This commit is contained in:
2025-07-02 21:55:07 +09:00
commit fa63330e69
855 changed files with 432271 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
"use strict"
var m = require("./index")
if (typeof module !== "undefined") module["exports"] = m
else window.m = m

View File

@@ -0,0 +1,8 @@
"use strict"
var hyperscript = require("./render/hyperscript")
hyperscript.trust = require("./render/trust")
hyperscript.fragment = require("./render/fragment")
module.exports = hyperscript

View File

@@ -0,0 +1,26 @@
"use strict"
var hyperscript = require("./hyperscript")
var request = require("./request")
var mountRedraw = require("./mount-redraw")
var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
m.Fragment = "["
m.mount = mountRedraw.mount
m.route = require("./route")
m.render = require("./render")
m.redraw = mountRedraw.redraw
m.request = request.request
m.jsonp = request.jsonp
m.parseQueryString = require("./querystring/parse")
m.buildQueryString = require("./querystring/build")
m.parsePathname = require("./pathname/parse")
m.buildPathname = require("./pathname/build")
m.vnode = require("./render/vnode")
m.PromisePolyfill = require("./promise/polyfill")
m.censor = require("./util/censor")
module.exports = m

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
"use strict"
var render = require("./render")
module.exports = require("./api/mount-redraw")(render, typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : null, typeof console !== "undefined" ? console : null)

View File

@@ -0,0 +1,3 @@
"use strict"
module.exports = require("./mount-redraw").mount

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Leo Horie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,667 @@
ospec [![npm Version](https://img.shields.io/npm/v/ospec.svg)](https://www.npmjs.com/package/ospec) [![npm License](https://img.shields.io/npm/l/ospec.svg)](https://www.npmjs.com/package/ospec)
=====
[About](#about) | [Usage](#usage) | [CLI](#command-line-interface) | [API](#api) | [Goals](#goals)
Noiseless testing framework
## About
- ~360 LOC including the CLI runner
- terser and faster test code than with mocha, jasmine or tape
- test code reads like bullet points
- assertion code follows [SVO](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object) structure in present tense for terseness and readability
- supports:
- test grouping
- assertions
- spies
- `equals`, `notEquals`, `deepEquals` and `notDeepEquals` assertion types
- `before`/`after`/`beforeEach`/`afterEach` hooks
- test exclusivity (i.e. `.only`)
- async tests and hooks
- explicitly regulates test-space configuration to encourage focus on testing, and to provide uniform test suites across projects
## Usage
### Single tests
Both tests and assertions are declared via the `o` function. Tests should have a description and a body function. A test may have one or more assertions. Assertions should appear inside a test's body function and compare two values.
```javascript
var o = require("module/talk/bundle/mithril-2.2.2/ospec/ospec")
o("addition", function () {
o(1 + 1).equals(2)
})
o("subtraction", function () {
o(1 - 1).notEquals(2)
})
```
Assertions may have descriptions:
```javascript
o("addition", function() {
o(1 + 1).equals(2)("addition should work")
/* in ES6, the following syntax is also possible
o(1 + 1).equals(2) `addition should work`
*/
})
/* for a failing test, an assertion with a description outputs this:
addition should work
1 should equal 2
Error
at stacktrace/goes/here.js:1:1
*/
```
### Grouping tests
Tests may be organized into logical groups using `o.spec`
```javascript
o.spec("math", function() {
o("addition", function() {
o(1 + 1).equals(2)
})
o("subtraction", function() {
o(1 - 1).notEquals(2)
})
})
```
Group names appear as a breadcrumb trail in test descriptions: `math > addition: 2 should equal 2`
### Nested test groups
Groups can be nested to further organize test groups. Note that tests cannot be nested inside other tests.
```javascript
o.spec("math", function() {
o.spec("arithmetics", function() {
o("addition", function() {
o(1 + 1).equals(2)
})
o("subtraction", function() {
o(1 - 1).notEquals(2)
})
})
})
```
### Callback test
The `o.spy()` method can be used to create a stub function that keeps track of its call count and received parameters
```javascript
// code to be tested
function call(cb, arg) {cb(arg)}
// test suite
var o = require("ospec")
o.spec("call()", function() {
o("works", function() {
var spy = o.spy()
call(spy, 1)
o(spy.callCount).equals(1)
o(spy.args[0]).equals(1)
o(spy.calls[0]).deepEquals([1])
})
})
```
A spy can also wrap other functions, like a decorator:
```javascript
// code to be tested
var count = 0
function inc() {
count++
}
// test suite
var o = require("ospec")
o.spec("call()", function() {
o("works", function() {
var spy = o.spy(inc)
spy()
o(count).equals(1)
})
})
```
### Asynchronous tests
If a test body function declares a named argument, the test is assumed to be asynchronous, and the argument is a function that must be called exactly one time to signal that the test has completed. As a matter of convention, this argument is typically named `done`.
```javascript
o("setTimeout calls callback", function(done) {
setTimeout(done, 10)
})
```
Alternativly you can return a promise or even use an async function in tests:
```javascript
o("promise test", function() {
return new Promise(function(resolve) {
setTimeout(resolve, 10)
})
})
```
```javascript
o("promise test", async function() {
await someOtherAsyncFunction()
})
```
#### Timeout delays
By default, asynchronous tests time out after 200ms. You can change that default for the current test suite and
its children by using the `o.specTimeout(delay)` function.
```javascript
o.spec("a spec that must timeout quickly", function(done, timeout) {
// wait 20ms before bailing out of the tests of this suite and
// its descendants
o.specTimeout(20)
o("some test", function(done) {
setTimeout(done, 10) // this will pass
})
o.spec("a child suite where the delay also applies", function () {
o("some test", function(done) {
setTimeout(done, 30) // this will time out.
})
})
})
o.spec("a spec that uses the default delay", function() {
// ...
})
```
This can also be changed on a per-test basis using the `o.timeout(delay)` function from within a test:
```javascript
o("setTimeout calls callback", function(done, timeout) {
o.timeout(500) // wait 500ms before bailing out of the test
setTimeout(done, 300)
})
```
Note that the `o.timeout` function call must be the first statement in its test. It also works with Promise-returning tests:
```javascript
o("promise test", function() {
o.timeout(1000)
return someOtherAsyncFunctionThatTakes900ms()
})
```
```javascript
o("promise test", async function() {
o.timeout(1000)
await someOtherAsyncFunctionThatTakes900ms()
})
```
Asynchronous tests generate an assertion that succeeds upon calling `done` or fails on timeout with the error message `async test timed out`.
### `before`, `after`, `beforeEach`, `afterEach` hooks
These hooks can be declared when it's necessary to setup and clean up state for a test or group of tests. The `before` and `after` hooks run once each per test group, whereas the `beforeEach` and `afterEach` hooks run for every test.
```javascript
o.spec("math", function() {
var acc
o.beforeEach(function() {
acc = 0
})
o("addition", function() {
acc += 1
o(acc).equals(1)
})
o("subtraction", function() {
acc -= 1
o(acc).equals(-1)
})
})
```
It's strongly recommended to ensure that `beforeEach` hooks always overwrite all shared variables, and avoid `if/else` logic, memoization, undo routines inside `beforeEach` hooks.
### Asynchronous hooks
Like tests, hooks can also be asynchronous. Tests that are affected by asynchronous hooks will wait for the hooks to complete before running.
```javascript
o.spec("math", function() {
var acc
o.beforeEach(function(done) {
setTimeout(function() {
acc = 0
done()
})
})
// tests only run after async hooks complete
o("addition", function() {
acc += 1
o(acc).equals(1)
})
o("subtraction", function() {
acc -= 1
o(acc).equals(-1)
})
})
```
### Running only some tests
One or more tests can be temporarily made to run exclusively by calling `o.only()` instead of `o`. This is useful when troubleshooting regressions, to zero-in on a failing test, and to avoid saturating console log w/ irrelevant debug information.
```javascript
o.spec("math", function() {
// will not run
o("addition", function() {
o(1 + 1).equals(2)
})
// this test will be run, regardless of how many groups there are
o.only("subtraction", function() {
o(1 - 1).notEquals(2)
})
// will not run
o("multiplication", function() {
o(2 * 2).equals(4)
})
// this test will be run, regardless of how many groups there are
o.only("division", function() {
o(6 / 2).notEquals(2)
})
})
```
### Running the test suite
```javascript
// define a test
o("addition", function() {
o(1 + 1).equals(2)
})
// run the suite
o.run()
```
### Running test suites concurrently
The `o.new()` method can be used to create new instances of ospec, which can be run in parallel. Note that each instance will report independently, and there's no aggregation of results.
```javascript
var _o = o.new('optional name')
_o("a test", function() {
_o(1).equals(1)
})
_o.run()
```
## Command Line Interface
Create a script in your package.json:
```
"scripts": {
"test": "ospec",
...
}
```
...and run it from the command line:
```
$ npm test
```
**NOTE:** `o.run()` is automatically called by the cli - no need to call it in your test code.
### CLI Options
Running ospec without arguments is equivalent to running `ospec '**/tests/**/*.js'`. In english, this tells ospec to evaluate all `*.js` files in any sub-folder named `tests/` (the `node_modules` folder is always excluded).
If you wish to change this behavior, just provide one or more glob match patterns:
```
ospec '**/spec/**/*.js' '**/*.spec.js'
```
You can also provide ignore patterns (note: always add `--ignore` AFTER match patterns):
```
ospec --ignore 'folder1/**' 'folder2/**'
```
Finally, you may choose to load files or modules before any tests run (**note:** always add `--require` AFTER match patterns):
```
ospec --require esm
```
Here's an example of mixing them all together:
```
ospec '**/*.test.js' --ignore 'folder1/**' --require esm ./my-file.js
```
### Run ospec directly from the command line:
ospec comes with an executable named `ospec`. npm auto-installs local binaries to `./node_modules/.bin/`. You can run ospec by running `./node_modules/.bin/ospec` from your project root, but there are more convenient methods to do so that we will soon describe.
ospec doesn't work when installed globally (`npm install -g`). Using global scripts is generally a bad idea since you can end up with different, incompatible versions of the same package installed locally and globally.
Here are different ways of running ospec from the command line. This knowledge applies to not just ospec, but any locally installed npm binary.
#### npx
If you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder.
#### npm-run
If you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder.
Otherwise, to work around this limitation, you can use [`npm-run`](https://www.npmjs.com/package/npm-run) which enables one to run the binaries of locally installed packages.
```
npm install npm-run -g
```
Then, from a project that has ospec installed as a (dev) dependency:
```
npm-run ospec
```
#### PATH
If you understand how your system's PATH works (e.g. for [OSX](https://coolestguidesontheplanet.com/add-shell-path-osx/)), then you can add the following to your PATH...
```
export PATH=./node_modules/.bin:$PATH
```
...and you'll be able to run `ospec` without npx, npm, etc. This one-time setup will also work with other binaries across all your node projects, as long as you run binaries from the root of your projects.
---
## API
Square brackets denote optional arguments
### void o.spec(String title, Function tests)
Defines a group of tests. Groups are optional
---
### void o(String title, Function([Function done [, Function timeout]]) assertions)
Defines a test.
If an argument is defined for the `assertions` function, the test is deemed to be asynchronous, and the argument is required to be called exactly one time.
---
### Assertion o(any value)
Starts an assertion. There are six types of assertion: `equals`, `notEquals`, `deepEquals`, `notDeepEquals`, `throws`, `notThrows`.
Assertions have this form:
```javascript
o(actualValue).equals(expectedValue)
```
As a matter of convention, the actual value should be the first argument and the expected value should be the second argument in an assertion.
Assertions can also accept an optional description curried parameter:
```javascript
o(actualValue).equals(expectedValue)("this is a description for this assertion")
```
Assertion descriptions can be simplified using ES6 tagged template string syntax:
```javascript
o(actualValue).equals(expectedValue) `this is a description for this assertion`
```
#### Function(String description) o(any value).equals(any value)
Asserts that two values are strictly equal (`===`)
#### Function(String description) o(any value).notEquals(any value)
Asserts that two values are strictly not equal (`!==`)
#### Function(String description) o(any value).deepEquals(any value)
Asserts that two values are recursively equal
#### Function(String description) o(any value).notDeepEquals(any value)
Asserts that two values are not recursively equal
#### Function(String description) o(Function fn).throws(Object constructor)
Asserts that a function throws an instance of the provided constructo
#### Function(String description) o(Function fn).throws(String message)
Asserts that a function throws an Error with the provided message
#### Function(String description) o(Function fn).notThrows(Object constructor)
Asserts that a function does not throw an instance of the provided constructor
#### Function(String description) o(Function fn).notThrows(String message)
Asserts that a function does not throw an Error with the provided message
---
### void o.before(Function([Function done [, Function timeout]]) setup)
Defines code to be run at the beginning of a test group
If an argument is defined for the `setup` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time.
---
### void o.after(Function([Function done [, Function timeout]]) teardown)
Defines code to be run at the end of a test group
If an argument is defined for the `teardown` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time.
---
### void o.beforeEach(Function([Function done [, Function timeout]]) setup)
Defines code to be run before each test in a group
If an argument is defined for the `setup` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time.
---
### void o.afterEach(Function([Function done [, Function timeout]]) teardown)
Defines code to be run after each test in a group
If an argument is defined for the `teardown` function, this hook is deemed to be asynchronous, and the argument is required to be called exactly one time.
---
### void o.only(String title, Function([Function done [, Function timeout]]) assertions)
Declares that only a single test should be run, instead of all of them
---
### Function o.spy([Function fn])
Returns a function that records the number of times it gets called, and its arguments
#### Number o.spy().callCount
The number of times the function has been called
#### Array<any> o.spy().args
The arguments that were passed to the function in the last time it was called
---
### void o.run([Function reporter])
Runs the test suite. By default passing test results are printed using
`console.log` and failing test results are printed using `console.error`.
If you have custom continuous integration needs then you can use a
reporter to process [test result data](#result-data) yourself.
If running in Node.js, ospec will call `process.exit` after reporting
results by default. If you specify a reporter, ospec will not do this
and allow your reporter to respond to results in its own way.
---
### Number o.report(results)
The default reporter used by `o.run()` when none are provided. Returns the number of failures, doesn't exit Node.js by itself. It expects an array of [test result data](#result-data) as argument.
---
### Function o.new()
Returns a new instance of ospec. Useful if you want to run more than one test suite concurrently
```javascript
var $o = o.new()
$o("a test", function() {
$o(1).equals(1)
})
$o.run()
```
---
## Result data
Test results are available by reference for integration purposes. You
can use custom reporters in `o.run()` to process these results.
```javascript
o.run(function(results) {
// results is an array
results.forEach(function(result) {
// ...
})
})
```
---
### Boolean|Null result.pass
- `true` if the assertion passed.
- `false` if the assertion failed.
- `null` if the assertion was incomplete (`o("partial assertion) // and that's it`).
---
### Error result.error
The `Error` object explaining the reason behind a failure. If the assertion failed, the stack will point to the actuall error. If the assertion did pass or was incomplete, this field is identical to `result.testError`.
---
### Error result.testError
An `Error` object whose stack points to the test definition that wraps the assertion. Useful as a fallback because in some async cases the main may not point to test code.
---
### String result.message
If an exception was thrown inside the corresponding test, this will equal that Error's `message`. Otherwise, this will be a preformatted message in [SVO form](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object). More specifically, `${subject}\n${verb}\n${object}`.
As an example, the following test's result message will be `"false\nshould equal\ntrue"`.
```javascript
o.spec("message", function() {
o(false).equals(true)
})
```
If you specify an assertion description, that description will appear two lines above the subject.
```javascript
o.spec("message", function() {
o(false).equals(true)("Candyland") // result.message === "Candyland\n\nfalse\nshould equal\ntrue"
})
```
---
### String result.context
A `>`-separated string showing the structure of the test specification.
In the below example, `result.context` would be `testing > rocks`.
```javascript
o.spec("testing", function() {
o.spec("rocks", function() {
o(false).equals(true)
})
})
```
---
## Goals
- Do the most common things that the mocha/chai/sinon triad does without having to install 3 different libraries and several dozen dependencies
- Disallow configuration in test-space:
- Disallow ability to pick between API styles (BDD/TDD/Qunit, assert/should/expect, etc)
- Disallow ability to add custom assertion types
- Provide a default simple reporter
- Make assertion code terse, readable and self-descriptive
- Have as few assertion types as possible for a workable usage pattern
Explicitly disallowing modularity and configuration in test-space has a few benefits:
- tests always look the same, even across different projects and teams
- single source of documentation for entire testing API
- no need to hunt down plugins to figure out what they do, especially if they replace common JavaScript idioms with fuzzy spoken language constructs (e.g. what does `.is()` do?)
- no need to pollute project-space with ad-hoc configuration code
- discourages side-tracking and yak-shaving

View File

@@ -0,0 +1,110 @@
# Change log for ospec
- [Upcoming](#upcoming)
- [4.0.1](#401)
- [4.0.0](#400)
- [3.1.0](#310)
- [3.0.1](#301)
- [3.0.0](#300)
- [2.1.0](#210)
- [2.0.0](#200)
- [1.4.1](#141)
- [1.4.0](#140)
- [1.3 and earlier](#13-and-earlier)
### Upcoming...
### 4.0.1
_2019-08-18_
- Fix `require` with relative paths
### 4.0.0
_2019-07-24_
- Pull ESM support out
### 3.1.0
_2019-02-07_
- ospec: Test results now include `.message` and `.context` regardless of whether the test passed or failed. (#2227 @robertakarobin)
<!-- Add new lines here. Version number will be decided later -->
- Add `spy.calls` array property to get the `this` and `arguments` values for any arbitrary call. (#2221 [@dead-claudia](https://github.com/dead-claudia))
- Added `.throws` and `.notThrows` assertions to ospec. (#2255 @robertakarobin)
- Update `glob` dependency.
### 3.0.1
_2018-06-30_
#### Bug fix
- Move `glob` from `devDependencies` to `dependencies`, fix the test runner ([#2186](https://github.com/MithrilJS/mithril.js/pull/2186) [@porsager](https://github.com/porsager)
### 3.0.0
_2018-06-26_
#### Breaking
- Better input checking to prevent misuses of the library. Misues of the library will now throw errors, rather than report failures. This may uncover bugs in your test suites. Since it is potentially a disruptive update this change triggers a semver major bump. ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- Change the reserved character for hooks and test suite meta-information from `"__"` to `"\x01"`. Tests whose name start with `"\0x01"` will be rejected ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
#### Features
- Give async timeout a stack trace that points to the problematic test ([#2154](https://github.com/MithrilJS/mithril.js/pull/2154) [@gilbert](github.com/gilbert), [#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- deprecate the `timeout` parameter in async tests in favour of `o.timeout()` for setting the timeout delay. The `timeout` parameter still works for v3, and will be removed in v4 ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- add `o.defaultTimeout()` for setting the the timeout delay for the current spec and its children ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- adds the possibility to select more than one test with o.only ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171))
#### Bug fixes
- Detect duplicate calls to `done()` properly [#2162](https://github.com/MithrilJS/mithril.js/issues/2162) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- Don't try to report internal errors as assertion failures, throw them instead ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- Don't ignore, silently, tests whose name start with the test suite meta-information sequence (was `"__"` up to this version) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- Fix the `done()` call detection logic [#2158](https://github.com/MithrilJS/mithril.js/issues/2158) and assorted fixes (accept non-English names, tolerate comments) ([#2167](https://github.com/MithrilJS/mithril.js/pull/2167))
- Catch exceptions thrown in synchronous tests and report them as assertion failures ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171))
- Fix a stack overflow when using `o.only()` with a large test suite ([#2171](https://github.com/MithrilJS/mithril.js/pull/2171))
### 2.1.0
_2018-05-25_
#### Features
- Pinpoint the `o.only()` call site ([#2157](https://github.com/MithrilJS/mithril.js/pull/2157))
- Improved wording, spacing and color-coding of report messages and errors ([#2147](https://github.com/MithrilJS/mithril.js/pull/2147), [@maranomynet](https://github.com/maranomynet))
#### Bug fixes
- Convert the exectuable back to plain ES5 [#2160](https://github.com/MithrilJS/mithril.js/issues/2160) ([#2161](https://github.com/MithrilJS/mithril.js/pull/2161))
### 2.0.0
_2018-05-09_
- Added `--require` feature to the ospec executable ([#2144](https://github.com/MithrilJS/mithril.js/pull/2144), [@gilbert](https://github.com/gilbert))
- In Node.js, ospec only uses colors when the output is sent to a terminal ([#2143](https://github.com/MithrilJS/mithril.js/pull/2143))
- the CLI runner now accepts globs as arguments ([#2141](https://github.com/MithrilJS/mithril.js/pull/2141), [@maranomynet](https://github.com/maranomynet))
- Added support for custom reporters ([#2020](https://github.com/MithrilJS/mithril.js/pull/2020), [@zyrolasting](https://github.com/zyrolasting))
- Make ospec more [Flems](https://flems.io)-friendly ([#2034](https://github.com/MithrilJS/mithril.js/pull/2034))
- Works either as a global or in CommonJS environments
- the o.run() report is always printed asynchronously (it could be synchronous before if none of the tests were async).
- Properly point to the assertion location of async errors [#2036](https://github.com/MithrilJS/mithril.js/issues/2036)
- expose the default reporter as `o.report(results)`
- Don't try to access the stack traces in IE9
### 1.4.1
_2018-05-03_
- Identical to v1.4.0, but with UNIX-style line endings so that BASH is happy.
### 1.4.0
_2017-12-01_
- Added support for async functions and promises in tests ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928), [@StephanHoyer](https://github.com/StephanHoyer))
- Error handling for async tests with `done` callbacks supports error as first argument ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928))
- Error messages which include newline characters do not swallow the stack trace [#1495](https://github.com/MithrilJS/mithril.js/issues/1495) ([#1984](https://github.com/MithrilJS/mithril.js/pull/1984), [@RodericDay](https://github.com/RodericDay))
### 1.3 and earlier
- Log using util.inspect to show object content instead of "[object Object]" ([#1661](https://github.com/MithrilJS/mithril.js/issues/1661), [@porsager](https://github.com/porsager))
- Shell command: Ignore hidden directories and files ([#1855](https://github.com/MithrilJS/mithril.js/pull/1855) [@pdfernhout)](https://github.com/pdfernhout))
- Library: Add the possibility to name new test suites ([#1529](https://github.com/MithrilJS/mithril.js/pull/1529))

View File

@@ -0,0 +1,397 @@
"use strict"
;(function(m) {
if (typeof module !== "undefined") module["exports"] = m()
else window.o = m()
})(function init(name) {
console.warn(
"Please switch to the `ospec` package to remove this warning and see " +
"the most recent features. Using the `ospec` bundled within Mithril.js " +
"is deprecated, and it will be removed in the next major release."
)
var spec = {}, subjects = [], results, only = [], ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty
var ospecFileName = getStackName(ensureStackTrace(new Error), /[\/\\](.*?):\d+:\d+/), timeoutStackName
var globalTimeout = noTimeoutRightNow
var currentTestError = null
if (name != null) spec[name] = ctx = {}
try {throw new Error} catch (e) {
var ospecFileName = e.stack && (/[\/\\](.*?):\d+:\d+/).test(e.stack) ? e.stack.match(/[\/\\](.*?):\d+:\d+/)[1] : null
}
function o(subject, predicate) {
if (predicate === undefined) {
if (!isRunning()) throw new Error("Assertions should not occur outside test definitions.")
return new Assert(subject)
} else {
if (isRunning()) throw new Error("Test definitions and hooks shouldn't be nested. To group tests, use 'o.spec()'.")
subject = String(subject)
if (subject.charCodeAt(0) === 1) throw new Error("test names starting with '\\x01' are reserved for internal use.")
ctx[unique(subject)] = new Task(predicate, ensureStackTrace(new Error))
}
}
o.before = hook("\x01before")
o.after = hook("\x01after")
o.beforeEach = hook("\x01beforeEach")
o.afterEach = hook("\x01afterEach")
o.specTimeout = function (t) {
if (isRunning()) throw new Error("o.specTimeout() can only be called before o.run().")
if (hasOwn.call(ctx, "\x01specTimeout")) throw new Error("A default timeout has already been defined in this context.")
if (typeof t !== "number") throw new Error("o.specTimeout() expects a number as argument.")
ctx["\x01specTimeout"] = t
}
o.new = init
o.spec = function(subject, predicate) {
var parent = ctx
ctx = ctx[unique(subject)] = {}
predicate()
ctx = parent
}
o.only = function(subject, predicate, silent) {
if (!silent) console.log(
highlight("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, args: spy.args})
spy.callCount++
if (fn) return fn.apply(this, arguments)
}
if (fn)
Object.defineProperties(spy, {
length: {value: fn.length},
name: {value: fn.name}
})
spy.args = []
spy.calls = []
spy.callCount = 0
return spy
}
o.cleanStackTrace = function(error) {
// For IE 10+ in quirks mode, and IE 9- in any mode, errors don't have a stack
if (error.stack == null) return ""
var i = 0, header = error.message ? error.name + ": " + error.message : error.name, stack
// some environments add the name and message to the stack trace
if (error.stack.indexOf(header) === 0) {
stack = error.stack.slice(header.length).split(/\r?\n/)
stack.shift() // drop the initial empty string
} else {
stack = error.stack.split(/\r?\n/)
}
if (ospecFileName == null) return stack.join("\n")
// skip ospec-related entries on the stack
while (stack[i] != null && stack[i].indexOf(ospecFileName) !== -1) i++
// now we're in user code (or past the stack end)
return stack[i]
}
o.timeout = function(n) {
globalTimeout(n)
}
o.run = function(reporter) {
results = []
start = new Date
test(spec, [], [], new Task(function() {
setTimeout(function () {
timeoutStackName = getStackName({stack: o.cleanStackTrace(ensureStackTrace(new Error))}, /([\w \.]+?:\d+:\d+)/)
if (typeof reporter === "function") reporter(results)
else {
var errCount = o.report(results)
if (hasProcess && errCount !== 0) process.exit(1) // eslint-disable-line no-process-exit
}
})
}, null), 200 /*default timeout delay*/)
function test(spec, pre, post, finalize, defaultDelay) {
if (hasOwn.call(spec, "\x01specTimeout")) defaultDelay = spec["\x01specTimeout"]
pre = [].concat(pre, spec["\x01beforeEach"] || [])
post = [].concat(spec["\x01afterEach"] || [], post)
series([].concat(spec["\x01before"] || [], Object.keys(spec).reduce(function(tasks, key) {
if (key.charCodeAt(0) !== 1 && (only.length === 0 || only.indexOf(spec[key].fn) !== -1 || !(spec[key] instanceof Task))) {
tasks.push(new Task(function(done) {
o.timeout(Infinity)
subjects.push(key)
var pop = new Task(function pop() {subjects.pop(), done()}, null)
if (spec[key] instanceof Task) series([].concat(pre, spec[key], post, pop), defaultDelay)
else test(spec[key], pre, post, pop, defaultDelay)
}, null))
}
return tasks
}, []), spec["\x01after"] || [], finalize), defaultDelay)
}
function series(tasks, defaultDelay) {
var cursor = 0
next()
function next() {
if (cursor === tasks.length) return
var task = tasks[cursor++]
var fn = task.fn
currentTestError = task.err
var timeout = 0, delay = defaultDelay, s = new Date
var current = cursor
var arg
globalTimeout = setDelay
var isDone = false
// public API, may only be called once from use code (or after returned Promise resolution)
function done(err) {
if (!isDone) isDone = true
else throw new Error("'" + arg + "()' should only be called once.")
if (timeout === undefined) console.warn("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms\n" + o.cleanStackTrace(task.err))
finalizeAsync(err)
}
// for internal use only
function finalizeAsync(err) {
if (err == null) {
if (task.err != null) succeed(new Assert)
} else {
if (err instanceof Error) fail(new Assert, err.message, err)
else fail(new Assert, String(err), null)
}
if (timeout !== undefined) timeout = clearTimeout(timeout)
if (current === cursor) next()
}
function startTimer() {
timeout = setTimeout(function() {
timeout = undefined
finalizeAsync("async test timed out after " + delay + "ms")
}, Math.min(delay, 2147483647))
}
function setDelay (t) {
if (typeof t !== "number") throw new Error("timeout() and o.timeout() expect a number as argument.")
delay = t
}
if (fn.length > 0) {
var body = fn.toString()
arg = (body.match(/^(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*=>/) || body.match(/\((?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*[,\)]/) || []).pop()
if (body.indexOf(arg) === body.lastIndexOf(arg)) {
var e = new Error
e.stack = "'" + arg + "()' should be called at least once\n" + o.cleanStackTrace(task.err)
throw e
}
try {
fn(done, setDelay)
}
catch (e) {
if (task.err != null) finalizeAsync(e)
// The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown.
else throw e
}
if (timeout === 0) {
startTimer()
}
} else {
try{
var p = fn()
if (p && p.then) {
startTimer()
p.then(function() { done() }, done)
} else {
nextTickish(next)
}
} catch (e) {
if (task.err != null) finalizeAsync(e)
// The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown.
else throw e
}
}
globalTimeout = noTimeoutRightNow
}
}
}
function unique(subject) {
if (hasOwn.call(ctx, subject)) {
console.warn("A test or a spec named '" + subject + "' was already defined.")
while (hasOwn.call(ctx, subject)) subject += "*"
}
return subject
}
function hook(name) {
return function(predicate) {
if (ctx[name]) throw new Error(name.slice(1) + " should be defined outside of a loop or inside a nested test group.")
ctx[name] = new Task(predicate, ensureStackTrace(new Error))
}
}
define("equals", "should equal", function(a, b) {return a === b})
define("notEquals", "should not equal", function(a, b) {return a !== b})
define("deepEquals", "should deep equal", deepEqual)
define("notDeepEquals", "should not deep equal", function(a, b) {return !deepEqual(a, b)})
define("throws", "should throw a", throws)
define("notThrows", "should not throw a", function(a, b) {return !throws(a, b)})
function isArguments(a) {
if ("callee" in a) {
for (var i in a) if (i === "callee") return false
return true
}
}
function deepEqual(a, b) {
if (a === b) return true
if (a === null ^ b === null || a === undefined ^ b === undefined) return false // eslint-disable-line no-bitwise
if (typeof a === "object" && typeof b === "object") {
var aIsArgs = isArguments(a), bIsArgs = isArguments(b)
if (a.constructor === Object && b.constructor === Object && !aIsArgs && !bIsArgs) {
for (var i in a) {
if ((!(i in b)) || !deepEqual(a[i], b[i])) return false
}
for (var i in b) {
if (!(i in a)) return false
}
return true
}
if (a.length === b.length && (a instanceof Array && b instanceof Array || aIsArgs && bIsArgs)) {
var aKeys = Object.getOwnPropertyNames(a), bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) return false
for (var i = 0; i < aKeys.length; i++) {
if (!hasOwn.call(b, aKeys[i]) || !deepEqual(a[aKeys[i]], b[aKeys[i]])) return false
}
return true
}
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
if (typeof Buffer === "function" && a instanceof Buffer && b instanceof Buffer) {
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
if (a.valueOf() === b.valueOf()) return true
}
return false
}
function throws(a, b){
try{
a()
}catch(e){
if(typeof b === "string"){
return (e.message === b)
}else{
return (e instanceof b)
}
}
return false
}
function isRunning() {return results != null}
function Assert(value) {
this.value = value
this.i = results.length
results.push({pass: null, context: "", message: "Incomplete assertion in the test definition starting at...", error: currentTestError, testError: currentTestError})
}
function Task(fn, err) {
this.fn = fn
this.err = err
}
function define(name, verb, compare) {
Assert.prototype[name] = function assert(value) {
var self = this
var message = serialize(self.value) + "\n " + verb + "\n" + serialize(value)
if (compare(self.value, value)) succeed(self, message)
else fail(self, message)
var result = results[self.i]
return function(message) {
if (!result.pass) {
result.message = message + "\n\n" + result.message
}
}
}
}
function succeed(assertion, message) {
results[assertion.i].pass = true
results[assertion.i].context = subjects.join(" > ")
results[assertion.i].message = message
}
function fail(assertion, message, error) {
results[assertion.i].pass = false
results[assertion.i].context = subjects.join(" > ")
results[assertion.i].message = message
results[assertion.i].error = error != null ? error : ensureStackTrace(new Error)
}
function serialize(value) {
if (hasProcess) return require("util").inspect(value) // eslint-disable-line global-require
if (value === null || (typeof value === "object" && !(value instanceof Array)) || typeof value === "number") return String(value)
else if (typeof value === "function") return value.name || "<anonymous function>"
try {return JSON.stringify(value)} catch (e) {return String(value)}
}
function noTimeoutRightNow() {
throw new Error("o.timeout must be called snchronously from within a test definition or a hook.")
}
var colorCodes = {
red: "31m",
red2: "31;1m",
green: "32;1m"
}
function highlight(message, color) {
var code = colorCodes[color] || colorCodes.red;
return hasProcess ? (process.stdout.isTTY ? "\x1b[" + code + message + "\x1b[0m" : message) : "%c" + message + "%c "
}
function cStyle(color, bold) {
return hasProcess||!color ? "" : "color:"+color+(bold ? ";font-weight:bold" : "")
}
function ensureStackTrace(error) {
// mandatory to get a stack in IE 10 and 11 (and maybe other envs?)
if (error.stack === undefined) try { throw error } catch(e) {return e}
else return error
}
function getStackName(e, exp) {
return e.stack && exp.test(e.stack) ? e.stack.match(exp)[1] : null
}
o.report = function (results) {
var errCount = 0
for (var i = 0, r; r = results[i]; i++) {
if (r.pass == null) {
r.testError.stack = r.message + "\n" + o.cleanStackTrace(r.testError)
r.testError.message = r.message
throw r.testError
}
if (!r.pass) {
var stackTrace = o.cleanStackTrace(r.error)
var couldHaveABetterStackTrace = !stackTrace || timeoutStackName != null && stackTrace.indexOf(timeoutStackName) !== -1
if (couldHaveABetterStackTrace) stackTrace = r.testError != null ? o.cleanStackTrace(r.testError) : r.error.stack || ""
console.error(
(hasProcess ? "\n" : "") +
highlight(r.context + ":", "red2") + "\n" +
highlight(r.message, "red") +
(stackTrace ? "\n" + stackTrace + "\n" : ""),
cStyle("black", true), "", // reset to default
cStyle("red"), cStyle("black")
)
errCount++
}
}
var pl = results.length === 1 ? "" : "s"
var resultSummary = (errCount === 0) ?
highlight((pl ? "All " : "The ") + results.length + " assertion" + pl + " passed", "green"):
highlight(errCount + " out of " + results.length + " assertion" + pl + " failed", "red2")
var runningTime = " in " + Math.round(Date.now() - start) + "ms"
console.log(
(hasProcess ? "\n" : "") +
(name ? name + ": " : "") + resultSummary + runningTime,
cStyle((errCount === 0 ? "green" : "red"), true), ""
)
return errCount
}
if (hasProcess) {
nextTickish = process.nextTick
} else {
nextTickish = function fakeFastNextTick(next) {
if (stack++ < 5000) next()
else setTimeout(next, stack = 0)
}
}
return o
})

View File

@@ -0,0 +1,19 @@
{
"name": "ospec",
"version": "4.0.1",
"description": "Noiseless testing framework",
"main": "ospec.js",
"directories": {
"test": "tests"
},
"keywords": [ "testing" ],
"author": "Leo Horie <leohorie@hotmail.com>",
"license": "MIT",
"bin": {
"ospec": "./bin/ospec"
},
"repository": "MithrilJS/mithril.js",
"dependencies": {
"glob": "^7.1.3"
}
}

View File

@@ -0,0 +1,66 @@
{
"name": "mithril",
"version": "2.2.2",
"description": "A framework for building brilliant applications",
"author": "Leo Horie",
"license": "MIT",
"unpkg": "mithril.min.js",
"repository": "github:MithrilJS/mithril.js",
"scripts": {
"precommit": "lint-staged",
"watch": "run-p watch:**",
"watch:js": "node scripts/bundler browser.js -output mithril.js -watch",
"watch:docs": "node scripts/generate-docs --watch",
"watch:docs-lint": "node scripts/lint-docs --watch",
"build": "run-p build:browser build:min build:stream-min",
"build:browser": "node scripts/bundler browser.js -output mithril.js",
"build:docs": "node scripts/generate-docs",
"build:min": "node scripts/bundler browser.js -output mithril.min.js -minify -save",
"build:stream-min": "node scripts/minify-stream",
"cleanup:lint": "rimraf .eslintcache .lint-docs-cache",
"lint": "run-s -cn lint:**",
"lint:js": "eslint --cache",
"lint:docs": "node scripts/lint-docs --cache",
"perf": "node performance/test-perf.js",
"pretest": "npm run lint",
"test": "run-s test:js",
"test:js": "ospec",
"cover": "istanbul cover --print both ospec/bin/ospec"
},
"devDependencies": {
"@alrra/travis-scripts": "^3.0.1",
"@babel/parser": "^7.7.5",
"benchmark": "^2.1.4",
"chokidar": "^3.2.1",
"escape-string-regexp": "^2.0.0",
"eslint": "^8.9.0",
"gh-pages": "^2.1.1",
"glob": "^7.1.4",
"html-minifier": "^4.0.0",
"istanbul": "^0.4.5",
"lint-staged": "^12.3.4",
"locater": "^1.3.0",
"marked": "^4.0.10",
"minimist": "^1.2.0",
"npm-run-all": "^4.1.5",
"ospec": "^4.0.1",
"pinpoint": "^1.1.0",
"request": "^2.88.0",
"request-promise-native": "^1.0.7",
"rimraf": "^3.0.0",
"semver": "^6.3.0",
"terser": "^4.3.4"
},
"bin": {
"ospec": "./ospec/bin/ospec"
},
"lint-staged": {
"*.js": [
"eslint . --fix",
"git add"
]
},
"dependencies": {
"ospec": "4.0.0"
}
}

View File

@@ -0,0 +1,43 @@
"use strict"
var buildQueryString = require("../querystring/build")
var assign = require("../util/assign")
// Returns `path` from `template` + `params`
module.exports = function(template, params) {
if ((/:([^\/\.-]+)(\.{3})?:/).test(template)) {
throw new SyntaxError("Template parameter names must be separated by either a '/', '-', or '.'.")
}
if (params == null) return template
var queryIndex = template.indexOf("?")
var hashIndex = template.indexOf("#")
var queryEnd = hashIndex < 0 ? template.length : hashIndex
var pathEnd = queryIndex < 0 ? queryEnd : queryIndex
var path = template.slice(0, pathEnd)
var query = {}
assign(query, params)
var resolved = path.replace(/:([^\/\.-]+)(\.{3})?/g, function(m, key, variadic) {
delete query[key]
// If no such parameter exists, don't interpolate it.
if (params[key] == null) return m
// Escape normal parameters, but not variadic ones.
return variadic ? params[key] : encodeURIComponent(String(params[key]))
})
// In case the template substitution adds new query/hash parameters.
var newQueryIndex = resolved.indexOf("?")
var newHashIndex = resolved.indexOf("#")
var newQueryEnd = newHashIndex < 0 ? resolved.length : newHashIndex
var newPathEnd = newQueryIndex < 0 ? newQueryEnd : newQueryIndex
var result = resolved.slice(0, newPathEnd)
if (queryIndex >= 0) result += template.slice(queryIndex, queryEnd)
if (newQueryIndex >= 0) result += (queryIndex < 0 ? "?" : "&") + resolved.slice(newQueryIndex, newQueryEnd)
var querystring = buildQueryString(query)
if (querystring) result += (queryIndex < 0 && newQueryIndex < 0 ? "?" : "&") + querystring
if (hashIndex >= 0) result += template.slice(hashIndex)
if (newHashIndex >= 0) result += (hashIndex < 0 ? "" : "&") + resolved.slice(newHashIndex)
return result
}

View File

@@ -0,0 +1,43 @@
"use strict"
var parsePathname = require("./parse")
// Compiles a template into a function that takes a resolved path (without query
// strings) and returns an object containing the template parameters with their
// parsed values. This expects the input of the compiled template to be the
// output of `parsePathname`. Note that it does *not* remove query parameters
// specified in the template.
module.exports = function(template) {
var templateData = parsePathname(template)
var templateKeys = Object.keys(templateData.params)
var keys = []
var regexp = new RegExp("^" + templateData.path.replace(
// I escape literal text so people can use things like `:file.:ext` or
// `:lang-:locale` in routes. This is all merged into one pass so I
// don't also accidentally escape `-` and make it harder to detect it to
// ban it from template parameters.
/:([^\/.-]+)(\.{3}|\.(?!\.)|-)?|[\\^$*+.()|\[\]{}]/g,
function(m, key, extra) {
if (key == null) return "\\" + m
keys.push({k: key, r: extra === "..."})
if (extra === "...") return "(.*)"
if (extra === ".") return "([^/]+)\\."
return "([^/]+)" + (extra || "")
}
) + "$")
return function(data) {
// First, check the params. Usually, there isn't any, and it's just
// checking a static set.
for (var i = 0; i < templateKeys.length; i++) {
if (templateData.params[templateKeys[i]] !== data.params[templateKeys[i]]) return false
}
// If no interpolations exist, let's skip all the ceremony
if (!keys.length) return regexp.test(data.path)
var values = regexp.exec(data.path)
if (values == null) return false
for (var i = 0; i < keys.length; i++) {
data.params[keys[i].k] = keys[i].r ? values[i + 1] : decodeURIComponent(values[i + 1])
}
return true
}
}

View File

@@ -0,0 +1,24 @@
"use strict"
var parseQueryString = require("../querystring/parse")
// Returns `{path, params}` from `url`
module.exports = function(url) {
var queryIndex = url.indexOf("?")
var hashIndex = url.indexOf("#")
var queryEnd = hashIndex < 0 ? url.length : hashIndex
var pathEnd = queryIndex < 0 ? queryEnd : queryIndex
var path = url.slice(0, pathEnd).replace(/\/{2,}/g, "/")
if (!path) path = "/"
else {
if (path[0] !== "/") path = "/" + path
if (path.length > 1 && path[path.length - 1] === "/") path = path.slice(0, -1)
}
return {
path: path,
params: queryIndex < 0
? {}
: parseQueryString(url.slice(queryIndex + 1, queryEnd)),
}
}

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../node_modules/lodash/lodash.js"></script>
<script src="../node_modules/benchmark/benchmark.js"></script>
<script src="../mithril.js"></script>
<script src="test-perf.js"></script>
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,493 @@
"use strict"
/* Based off of preact's perf tests, so including their MIT license */
/*
The MIT License (MIT)
Copyright (c) 2017 Jason Miller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Note: this tests against the generated bundle in browsers, but it tests
// against `index.js` in Node. Please do keep that in mind while testing.
//
// Mithril.js and Benchmark.js are loaded globally via bundle in the browser, so
// this doesn't require a CommonJS sham polyfill.
// I add it globally just so it's visible in the tests.
/* global m, rootElem: true */
// set up browser env on before running tests
var isDOM = typeof window !== "undefined"
var Benchmark
if (isDOM) {
Benchmark = window.Benchmark
window.rootElem = null
} else {
/* eslint-disable global-require */
global.window = require("../test-utils/browserMock")()
global.document = window.document
// We're benchmarking renders, not our throttling.
global.requestAnimationFrame = function () {
throw new Error("This should never be called.")
}
global.m = require("../index.js")
global.rootElem = null
Benchmark = require("benchmark")
/* eslint-enable global-require */
}
function cycleRoot() {
if (rootElem) document.body.removeChild(rootElem)
document.body.appendChild(rootElem = document.createElement("div"))
}
// Initialize benchmark suite
Benchmark.options.async = true
Benchmark.options.initCount = 10
Benchmark.options.minSamples = 40
if (isDOM) {
// Wait long enough for the browser to actually commit the DOM changes to
// the screen before moving on to the next cycle, so things are at least
// reasonably fresh each cycle.
Benchmark.options.delay = 1 / 30 /* frames per second */
}
var suite = new Benchmark.Suite("Mithril.js perf", {
onStart: function () {
this.start = Date.now()
},
onCycle: function (e) {
console.log(e.target.toString())
cycleRoot()
},
onComplete: function () {
console.log("Completed perf tests in " + (Date.now() - this.start) + "ms")
},
onError: function (e) {
console.error(e)
},
})
// eslint-disable-next-line no-unused-vars
var xsuite = {add: function(name) { console.log("skipping " + name) }}
suite.add("construct large vnode tree", {
setup: function () {
this.fields = []
for(var i=100; i--;) {
this.fields.push((i * 999).toString(36))
}
},
fn: function () {
m(".foo.bar[data-foo=bar]", {p: 2},
m("header",
m("h1.asdf", "a ", "b", " c ", 0, " d"),
m("nav",
m("a[href=/foo]", "Foo"),
m("a[href=/bar]", "Bar")
)
),
m("main",
m("form",
{onSubmit: function () {}},
m("input[type=checkbox][checked]"),
m("input[type=checkbox]"),
m("fieldset",
this.fields.map(function (field) {
return m("label",
field,
":",
m("input", {placeholder: field})
)
})
),
m("button-bar",
m("button",
{style: "width:10px; height:10px; border:1px solid #FFF;"},
"Normal CSS"
),
m("button",
{style: "top:0 ; right: 20"},
"Poor CSS"
),
m("button",
{style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true},
"Poorer CSS"
),
m("button",
{style: {margin: 0, padding: "10px", overflow: "visible"}},
"Object CSS"
)
)
)
)
)
},
})
suite.add("rerender identical vnode", {
setup: function () {
this.cached = m(".foo.bar[data-foo=bar]", {p: 2},
m("header",
m("h1.asdf", "a ", "b", " c ", 0, " d"),
m("nav",
m("a", {href: "/foo"}, "Foo"),
m("a", {href: "/bar"}, "Bar")
)
),
m("main",
m("form", {onSubmit: function () {}},
m("input", {type: "checkbox", checked: true}),
m("input", {type: "checkbox", checked: false}),
m("fieldset",
m("label",
m("input", {type: "radio", checked: true})
),
m("label",
m("input", {type: "radio"})
)
),
m("button-bar",
m("button",
{style: "width:10px; height:10px; border:1px solid #FFF;"},
"Normal CSS"
),
m("button",
{style: "top:0 ; right: 20"},
"Poor CSS"
),
m("button",
{style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true},
"Poorer CSS"
),
m("button",
{style: {margin: 0, padding: "10px", overflow: "visible"}},
"Object CSS"
)
)
)
)
)
},
fn: function () {
m.render(rootElem, this.cached)
},
})
suite.add("rerender same tree", {
fn: function () {
m.render(rootElem, m(".foo.bar[data-foo=bar]", {p: 2},
m("header",
m("h1.asdf", "a ", "b", " c ", 0, " d"),
m("nav",
m("a", {href: "/foo"}, "Foo"),
m("a", {href: "/bar"}, "Bar")
)
),
m("main",
m("form", {onSubmit: function () {}},
m("input", {type: "checkbox", checked: true}),
m("input", {type: "checkbox", checked: false}),
m("fieldset",
m("label",
m("input", {type: "radio", checked: true})
),
m("label",
m("input", {type: "radio"})
)
),
m("button-bar",
m("button",
{style: "width:10px; height:10px; border:1px solid #FFF;"},
"Normal CSS"
),
m("button",
{style: "top:0 ; right: 20"},
"Poor CSS"
),
m("button",
{style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true},
"Poorer CSS"
),
m("button",
{style: {margin: 0, padding: "10px", overflow: "visible"}},
"Object CSS"
)
)
)
)
))
},
})
suite.add("add large nested tree", {
setup: function () {
var fields = []
for(var i=100; i--;) {
fields.push((i * 999).toString(36))
}
var NestedHeader = {
view: function () {
return m("header",
m("h1.asdf", "a ", "b", " c ", 0, " d"),
m("nav",
m("a", {href: "/foo"}, "Foo"),
m("a", {href: "/bar"}, "Bar")
)
)
}
}
var NestedForm = {
view: function () {
return m("form", {onSubmit: function () {}},
m("input[type=checkbox][checked]"),
m("input[type=checkbox]", {checked: false}),
m("fieldset",
m("label",
m("input[type=radio][checked]")
),
m("label",
m("input[type=radio]")
)
),
m("fieldset",
fields.map(function (field) {
return m("label",
field,
":",
m("input", {placeholder: field})
)
})
),
m(NestedButtonBar, null)
)
}
}
var NestedButtonBar = {
view: function () {
return m(".button-bar",
m(NestedButton,
{style: "width:10px; height:10px; border:1px solid #FFF;"},
"Normal CSS"
),
m(NestedButton,
{style: "top:0 ; right: 20"},
"Poor CSS"
),
m(NestedButton,
{style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true},
"Poorer CSS"
),
m(NestedButton,
{style: {margin: 0, padding: "10px", overflow: "visible"}},
"Object CSS"
)
)
}
}
var NestedButton = {
view: function (vnode) {
return m("button", m.censor(vnode.attrs), vnode.children)
}
}
var NestedMain = {
view: function () {
return m(NestedForm)
}
}
this.NestedRoot = {
view: function () {
return m("div.foo.bar[data-foo=bar]",
{p: 2},
m(NestedHeader),
m(NestedMain)
)
}
}
},
fn: function () {
m.render(rootElem, m(this.NestedRoot))
},
})
suite.add("mutate styles/properties", {
setup: function () {
function get(obj, i) { return obj[i % obj.length] }
var counter = 0
var classes = ["foo", "foo bar", "", "baz-bat", null, "fooga", null, null, undefined]
var styles = []
var multivalue = ["0 1px", "0 0 1px 0", "0", "1px", "20px 10px", "7em 5px", "1px 0 5em 2px"]
var stylekeys = [
["left", function (c) { return c % 3 ? c + "px" : c }],
["top", function (c) { return c % 2 ? c + "px" : c }],
["margin", function (c) { return get(multivalue, c).replace("1px", c+"px") }],
["padding", function (c) { return get(multivalue, c) }],
["position", function (c) { return c%5 ? c%2 ? "absolute" : "relative" : null }],
["display", function (c) { return c%10 ? c%2 ? "block" : "inline" : "none" }],
["color", function (c) { return ("rgba(" + (c%255) + ", " + (255 - c%255) + ", " + (50+c%150) + ", " + (c%50/50) + ")") }],
["border", function (c) { return c%5 ? (c%10) + "px " + (c%2?"solid":"dotted") + " " + stylekeys[6][1](c) : "" }]
]
var i, j, style, conf
for (i=0; i<1000; i++) {
style = {}
for (j=0; j<i%10; j++) {
conf = get(stylekeys, ++counter)
style[conf[0]] = conf[1](counter)
}
styles[i] = style
}
var count = 0
this.app = function () {
var vnodes = []
for (var index = ++count, last = index + 300; index < last; index++) {
vnodes.push(
m("div.booga",
{
class: get(classes, index),
"data-index": index,
title: index.toString(36)
},
m("input.dooga", {type: "checkbox", checked: index % 3 === 0}),
m("input", {value: "test " + Math.floor(index / 4), disabled: index % 10 ? null : true}),
m("div", {class: get(classes, index * 11)},
m("p", {style: get(styles, index)}, "p1"),
m("p", {style: get(styles, index + 1)}, "p2"),
m("p", {style: get(styles, index * 2)}, "p3"),
m("p.zooga", {style: get(styles, index * 3 + 1), className: get(classes, index * 7)}, "p4")
)
)
)
}
return vnodes
}
},
fn: function () {
m.render(rootElem, this.app())
},
})
suite.add("repeated add/removal", {
setup: function () {
var RepeatedHeader = {
view: function () {
return m("header",
m("h1.asdf", "a ", "b", " c ", 0, " d"),
m("nav",
m("a", {href: "/foo"}, "Foo"),
m("a", {href: "/bar"}, "Bar")
)
)
}
}
var RepeatedForm = {
view: function () {
return m("form", {onSubmit: function () {}},
m("input", {type: "checkbox", checked: true}),
m("input", {type: "checkbox", checked: false}),
m("fieldset",
m("label",
m("input", {type: "radio", checked: true})
),
m("label",
m("input", {type: "radio"})
)
),
m(RepeatedButtonBar, null)
)
}
}
var RepeatedButtonBar = {
view: function () {
return m(".button-bar",
m(RepeatedButton,
{style: "width:10px; height:10px; border:1px solid #FFF;"},
"Normal CSS"
),
m(RepeatedButton,
{style: "top:0 ; right: 20"},
"Poor CSS"
),
m(RepeatedButton,
{style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true},
"Poorer CSS"
),
m(RepeatedButton,
{style: {margin: 0, padding: "10px", overflow: "visible"}},
"Object CSS"
)
)
}
}
var RepeatedButton = {
view: function (vnode) {
return m("button", vnode.attrs, vnode.children)
}
}
var RepeatedMain = {
view: function () {
return m(RepeatedForm)
}
}
this.RepeatedRoot = {
view: function () {
return m("div.foo.bar[data-foo=bar]",
{p: 2},
m(RepeatedHeader, null),
m(RepeatedMain, null)
)
}
}
},
fn: function () {
m.render(rootElem, [m(this.RepeatedRoot)])
m.render(rootElem, [])
},
})
if (isDOM) {
window.onload = function () {
cycleRoot()
suite.run()
}
} else {
cycleRoot()
suite.run()
}

View File

@@ -0,0 +1,15 @@
"use strict"
module.exports = {
"extends": "../.eslintrc.js",
"env": {
"browser": null,
"es6": null,
},
"parserOptions": {
"ecmaVersion": 5,
},
"rules": {
"no-process-env": "off",
},
};

View File

@@ -0,0 +1,112 @@
"use strict"
/** @constructor */
var PromisePolyfill = function(executor) {
if (!(this instanceof PromisePolyfill)) throw new Error("Promise must be called with 'new'.")
if (typeof executor !== "function") throw new TypeError("executor must be a function.")
var self = this, resolvers = [], rejectors = [], resolveCurrent = handler(resolvers, true), rejectCurrent = handler(rejectors, false)
var instance = self._instance = {resolvers: resolvers, rejectors: rejectors}
var callAsync = typeof setImmediate === "function" ? setImmediate : setTimeout
function handler(list, shouldAbsorb) {
return function execute(value) {
var then
try {
if (shouldAbsorb && value != null && (typeof value === "object" || typeof value === "function") && typeof (then = value.then) === "function") {
if (value === self) throw new TypeError("Promise can't be resolved with itself.")
executeOnce(then.bind(value))
}
else {
callAsync(function() {
if (!shouldAbsorb && list.length === 0) console.error("Possible unhandled promise rejection:", value)
for (var i = 0; i < list.length; i++) list[i](value)
resolvers.length = 0, rejectors.length = 0
instance.state = shouldAbsorb
instance.retry = function() {execute(value)}
})
}
}
catch (e) {
rejectCurrent(e)
}
}
}
function executeOnce(then) {
var runs = 0
function run(fn) {
return function(value) {
if (runs++ > 0) return
fn(value)
}
}
var onerror = run(rejectCurrent)
try {then(run(resolveCurrent), onerror)} catch (e) {onerror(e)}
}
executeOnce(executor)
}
PromisePolyfill.prototype.then = function(onFulfilled, onRejection) {
var self = this, instance = self._instance
function handle(callback, list, next, state) {
list.push(function(value) {
if (typeof callback !== "function") next(value)
else try {resolveNext(callback(value))} catch (e) {if (rejectNext) rejectNext(e)}
})
if (typeof instance.retry === "function" && state === instance.state) instance.retry()
}
var resolveNext, rejectNext
var promise = new PromisePolyfill(function(resolve, reject) {resolveNext = resolve, rejectNext = reject})
handle(onFulfilled, instance.resolvers, resolveNext, true), handle(onRejection, instance.rejectors, rejectNext, false)
return promise
}
PromisePolyfill.prototype.catch = function(onRejection) {
return this.then(null, onRejection)
}
PromisePolyfill.prototype.finally = function(callback) {
return this.then(
function(value) {
return PromisePolyfill.resolve(callback()).then(function() {
return value
})
},
function(reason) {
return PromisePolyfill.resolve(callback()).then(function() {
return PromisePolyfill.reject(reason);
})
}
)
}
PromisePolyfill.resolve = function(value) {
if (value instanceof PromisePolyfill) return value
return new PromisePolyfill(function(resolve) {resolve(value)})
}
PromisePolyfill.reject = function(value) {
return new PromisePolyfill(function(resolve, reject) {reject(value)})
}
PromisePolyfill.all = function(list) {
return new PromisePolyfill(function(resolve, reject) {
var total = list.length, count = 0, values = []
if (list.length === 0) resolve([])
else for (var i = 0; i < list.length; i++) {
(function(i) {
function consume(value) {
count++
values[i] = value
if (count === total) resolve(values)
}
if (list[i] != null && (typeof list[i] === "object" || typeof list[i] === "function") && typeof list[i].then === "function") {
list[i].then(consume, reject)
}
else consume(list[i])
})(i)
}
})
}
PromisePolyfill.race = function(list) {
return new PromisePolyfill(function(resolve, reject) {
for (var i = 0; i < list.length; i++) {
list[i].then(resolve, reject)
}
})
}
module.exports = PromisePolyfill

View File

@@ -0,0 +1,22 @@
/* global window */
"use strict"
var PromisePolyfill = require("./polyfill")
if (typeof window !== "undefined") {
if (typeof window.Promise === "undefined") {
window.Promise = PromisePolyfill
} else if (!window.Promise.prototype.finally) {
window.Promise.prototype.finally = PromisePolyfill.prototype.finally
}
module.exports = window.Promise
} else if (typeof global !== "undefined") {
if (typeof global.Promise === "undefined") {
global.Promise = PromisePolyfill
} else if (!global.Promise.prototype.finally) {
global.Promise.prototype.finally = PromisePolyfill.prototype.finally
}
module.exports = global.Promise
} else {
module.exports = PromisePolyfill
}

View File

@@ -0,0 +1,26 @@
"use strict"
module.exports = function(object) {
if (Object.prototype.toString.call(object) !== "[object Object]") return ""
var args = []
for (var key in object) {
destructure(key, object[key])
}
return args.join("&")
function destructure(key, value) {
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
destructure(key + "[" + i + "]", value[i])
}
}
else if (Object.prototype.toString.call(value) === "[object Object]") {
for (var i in value) {
destructure(key + "[" + i + "]", value[i])
}
}
else args.push(encodeURIComponent(key) + (value != null && value !== "" ? "=" + encodeURIComponent(value) : ""))
}
}

View File

@@ -0,0 +1,51 @@
"use strict"
function decodeURIComponentSave(str) {
try {
return decodeURIComponent(str)
} catch(err) {
return str
}
}
module.exports = function(string) {
if (string === "" || string == null) return {}
if (string.charAt(0) === "?") string = string.slice(1)
var entries = string.split("&"), counters = {}, data = {}
for (var i = 0; i < entries.length; i++) {
var entry = entries[i].split("=")
var key = decodeURIComponentSave(entry[0])
var value = entry.length === 2 ? decodeURIComponentSave(entry[1]) : ""
if (value === "true") value = true
else if (value === "false") value = false
var levels = key.split(/\]\[?|\[/)
var cursor = data
if (key.indexOf("[") > -1) levels.pop()
for (var j = 0; j < levels.length; j++) {
var level = levels[j], nextLevel = levels[j + 1]
var isNumber = nextLevel == "" || !isNaN(parseInt(nextLevel, 10))
if (level === "") {
var key = levels.slice(0, j).join()
if (counters[key] == null) {
counters[key] = Array.isArray(cursor) ? cursor.length : 0
}
level = counters[key]++
}
// Disallow direct prototype pollution
else if (level === "__proto__") break
if (j === levels.length - 1) cursor[level] = value
else {
// Read own properties exclusively to disallow indirect
// prototype pollution
var desc = Object.getOwnPropertyDescriptor(cursor, level)
if (desc != null) desc = desc.value
if (desc == null) cursor[level] = desc = isNumber ? [] : {}
cursor = desc
}
}
}
return data
}

View File

@@ -0,0 +1,3 @@
"use strict"
module.exports = require("./mount-redraw").redraw

View File

@@ -0,0 +1,3 @@
"use strict"
module.exports = require("./render/render")(typeof window !== "undefined" ? window : null)

View File

@@ -0,0 +1,12 @@
"use strict"
var Vnode = require("./vnode")
var hyperscriptVnode = require("./hyperscriptVnode")
module.exports = function() {
var vnode = hyperscriptVnode.apply(0, arguments)
vnode.tag = "["
vnode.children = Vnode.normalizeChildren(vnode.children)
return vnode
}

View File

@@ -0,0 +1,93 @@
"use strict"
var Vnode = require("./vnode")
var hyperscriptVnode = require("./hyperscriptVnode")
var hasOwn = require("../util/hasOwn")
var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g
var selectorCache = {}
function isEmpty(object) {
for (var key in object) if (hasOwn.call(object, key)) return false
return true
}
function compileSelector(selector) {
var match, tag = "div", classes = [], attrs = {}
while (match = selectorParser.exec(selector)) {
var type = match[1], value = match[2]
if (type === "" && value !== "") tag = value
else if (type === "#") attrs.id = value
else if (type === ".") classes.push(value)
else if (match[3][0] === "[") {
var attrValue = match[6]
if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\")
if (match[4] === "class") classes.push(attrValue)
else attrs[match[4]] = attrValue === "" ? attrValue : attrValue || true
}
}
if (classes.length > 0) attrs.className = classes.join(" ")
return selectorCache[selector] = {tag: tag, attrs: attrs}
}
function execSelector(state, vnode) {
var attrs = vnode.attrs
var hasClass = hasOwn.call(attrs, "class")
var className = hasClass ? attrs.class : attrs.className
vnode.tag = state.tag
vnode.attrs = {}
if (!isEmpty(state.attrs) && !isEmpty(attrs)) {
var newAttrs = {}
for (var key in attrs) {
if (hasOwn.call(attrs, key)) newAttrs[key] = attrs[key]
}
attrs = newAttrs
}
for (var key in state.attrs) {
if (hasOwn.call(state.attrs, key) && key !== "className" && !hasOwn.call(attrs, key)){
attrs[key] = state.attrs[key]
}
}
if (className != null || state.attrs.className != null) attrs.className =
className != null
? state.attrs.className != null
? String(state.attrs.className) + " " + String(className)
: className
: state.attrs.className != null
? state.attrs.className
: null
if (hasClass) attrs.class = null
for (var key in attrs) {
if (hasOwn.call(attrs, key) && key !== "key") {
vnode.attrs = attrs
break
}
}
return vnode
}
function hyperscript(selector) {
if (selector == null || typeof selector !== "string" && typeof selector !== "function" && typeof selector.view !== "function") {
throw Error("The selector must be either a string or a component.");
}
var vnode = hyperscriptVnode.apply(1, arguments)
if (typeof selector === "string") {
vnode.children = Vnode.normalizeChildren(vnode.children)
if (selector !== "[") return execSelector(selectorCache[selector] || compileSelector(selector), vnode)
}
vnode.tag = selector
return vnode
}
module.exports = hyperscript

View File

@@ -0,0 +1,53 @@
"use strict"
var Vnode = require("./vnode")
// Call via `hyperscriptVnode.apply(startOffset, arguments)`
//
// The reason I do it this way, forwarding the arguments and passing the start
// offset in `this`, is so I don't have to create a temporary array in a
// performance-critical path.
//
// In native ES6, I'd instead add a final `...args` parameter to the
// `hyperscript` and `fragment` factories and define this as
// `hyperscriptVnode(...args)`, since modern engines do optimize that away. But
// ES5 (what Mithril.js requires thanks to IE support) doesn't give me that luxury,
// and engines aren't nearly intelligent enough to do either of these:
//
// 1. Elide the allocation for `[].slice.call(arguments, 1)` when it's passed to
// another function only to be indexed.
// 2. Elide an `arguments` allocation when it's passed to any function other
// than `Function.prototype.apply` or `Reflect.apply`.
//
// In ES6, it'd probably look closer to this (I'd need to profile it, though):
// module.exports = function(attrs, ...children) {
// if (attrs == null || typeof attrs === "object" && attrs.tag == null && !Array.isArray(attrs)) {
// if (children.length === 1 && Array.isArray(children[0])) children = children[0]
// } else {
// children = children.length === 0 && Array.isArray(attrs) ? attrs : [attrs, ...children]
// attrs = undefined
// }
//
// if (attrs == null) attrs = {}
// return Vnode("", attrs.key, attrs, children)
// }
module.exports = function() {
var attrs = arguments[this], start = this + 1, children
if (attrs == null) {
attrs = {}
} else if (typeof attrs !== "object" || attrs.tag != null || Array.isArray(attrs)) {
attrs = {}
start = this
}
if (arguments.length === start + 1) {
children = arguments[start]
if (!Array.isArray(children)) children = [children]
} else {
children = []
while (start < arguments.length) children.push(arguments[start++])
}
return Vnode("", attrs.key, attrs, children)
}

View File

@@ -0,0 +1,983 @@
"use strict"
var Vnode = require("./vnode")
module.exports = function($window) {
var $doc = $window && $window.document
var currentRedraw
var nameSpace = {
svg: "http://www.w3.org/2000/svg",
math: "http://www.w3.org/1998/Math/MathML"
}
function getNameSpace(vnode) {
return vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag]
}
//sanity check to discourage people from doing `vnode.state = ...`
function checkState(vnode, original) {
if (vnode.state !== original) throw new Error("'vnode.state' must not be modified.")
}
//Note: the hook is passed as the `this` argument to allow proxying the
//arguments without requiring a full array allocation to do so. It also
//takes advantage of the fact the current `vnode` is the first argument in
//all lifecycle methods.
function callHook(vnode) {
var original = vnode.state
try {
return this.apply(original, arguments)
} finally {
checkState(vnode, original)
}
}
// IE11 (at least) throws an UnspecifiedError when accessing document.activeElement when
// inside an iframe. Catch and swallow this error, and heavy-handidly return null.
function activeElement() {
try {
return $doc.activeElement
} catch (e) {
return null
}
}
//create
function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) {
for (var i = start; i < end; i++) {
var vnode = vnodes[i]
if (vnode != null) {
createNode(parent, vnode, hooks, ns, nextSibling)
}
}
}
function createNode(parent, vnode, hooks, ns, nextSibling) {
var tag = vnode.tag
if (typeof tag === "string") {
vnode.state = {}
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
switch (tag) {
case "#": createText(parent, vnode, nextSibling); break
case "<": createHTML(parent, vnode, ns, nextSibling); break
case "[": createFragment(parent, vnode, hooks, ns, nextSibling); break
default: createElement(parent, vnode, hooks, ns, nextSibling)
}
}
else createComponent(parent, vnode, hooks, ns, nextSibling)
}
function createText(parent, vnode, nextSibling) {
vnode.dom = $doc.createTextNode(vnode.children)
insertNode(parent, vnode.dom, nextSibling)
}
var possibleParents = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"}
function createHTML(parent, vnode, ns, nextSibling) {
var match = vnode.children.match(/^\s*?<(\w+)/im) || []
// not using the proper parent makes the child element(s) vanish.
// var div = document.createElement("div")
// div.innerHTML = "<td>i</td><td>j</td>"
// console.log(div.innerHTML)
// --> "ij", no <td> in sight.
var temp = $doc.createElement(possibleParents[match[1]] || "div")
if (ns === "http://www.w3.org/2000/svg") {
temp.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\">" + vnode.children + "</svg>"
temp = temp.firstChild
} else {
temp.innerHTML = vnode.children
}
vnode.dom = temp.firstChild
vnode.domSize = temp.childNodes.length
// Capture nodes to remove, so we don't confuse them.
vnode.instance = []
var fragment = $doc.createDocumentFragment()
var child
while (child = temp.firstChild) {
vnode.instance.push(child)
fragment.appendChild(child)
}
insertNode(parent, fragment, nextSibling)
}
function createFragment(parent, vnode, hooks, ns, nextSibling) {
var fragment = $doc.createDocumentFragment()
if (vnode.children != null) {
var children = vnode.children
createNodes(fragment, children, 0, children.length, hooks, null, ns)
}
vnode.dom = fragment.firstChild
vnode.domSize = fragment.childNodes.length
insertNode(parent, fragment, nextSibling)
}
function createElement(parent, vnode, hooks, ns, nextSibling) {
var tag = vnode.tag
var attrs = vnode.attrs
var is = attrs && attrs.is
ns = getNameSpace(vnode) || ns
var element = ns ?
is ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) :
is ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag)
vnode.dom = element
if (attrs != null) {
setAttrs(vnode, attrs, ns)
}
insertNode(parent, element, nextSibling)
if (!maybeSetContentEditable(vnode)) {
if (vnode.children != null) {
var children = vnode.children
createNodes(element, children, 0, children.length, hooks, null, ns)
if (vnode.tag === "select" && attrs != null) setLateSelectAttrs(vnode, attrs)
}
}
}
function initComponent(vnode, hooks) {
var sentinel
if (typeof vnode.tag.view === "function") {
vnode.state = Object.create(vnode.tag)
sentinel = vnode.state.view
if (sentinel.$$reentrantLock$$ != null) return
sentinel.$$reentrantLock$$ = true
} else {
vnode.state = void 0
sentinel = vnode.tag
if (sentinel.$$reentrantLock$$ != null) return
sentinel.$$reentrantLock$$ = true
vnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function") ? new vnode.tag(vnode) : vnode.tag(vnode)
}
initLifecycle(vnode.state, vnode, hooks)
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode))
if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
sentinel.$$reentrantLock$$ = null
}
function createComponent(parent, vnode, hooks, ns, nextSibling) {
initComponent(vnode, hooks)
if (vnode.instance != null) {
createNode(parent, vnode.instance, hooks, ns, nextSibling)
vnode.dom = vnode.instance.dom
vnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0
}
else {
vnode.domSize = 0
}
}
//update
/**
* @param {Element|Fragment} parent - the parent element
* @param {Vnode[] | null} old - the list of vnodes of the last `render()` call for
* this part of the tree
* @param {Vnode[] | null} vnodes - as above, but for the current `render()` call.
* @param {Function[]} hooks - an accumulator of post-render hooks (oncreate/onupdate)
* @param {Element | null} nextSibling - the next DOM node if we're dealing with a
* fragment that is not the last item in its
* parent
* @param {'svg' | 'math' | String | null} ns) - the current XML namespace, if any
* @returns void
*/
// This function diffs and patches lists of vnodes, both keyed and unkeyed.
//
// We will:
//
// 1. describe its general structure
// 2. focus on the diff algorithm optimizations
// 3. discuss DOM node operations.
// ## Overview:
//
// The updateNodes() function:
// - deals with trivial cases
// - determines whether the lists are keyed or unkeyed based on the first non-null node
// of each list.
// - diffs them and patches the DOM if needed (that's the brunt of the code)
// - manages the leftovers: after diffing, are there:
// - old nodes left to remove?
// - new nodes to insert?
// deal with them!
//
// The lists are only iterated over once, with an exception for the nodes in `old` that
// are visited in the fourth part of the diff and in the `removeNodes` loop.
// ## Diffing
//
// Reading https://github.com/localvoid/ivi/blob/ddc09d06abaef45248e6133f7040d00d3c6be853/packages/ivi/src/vdom/implementation.ts#L617-L837
// may be good for context on longest increasing subsequence-based logic for moving nodes.
//
// In order to diff keyed lists, one has to
//
// 1) match nodes in both lists, per key, and update them accordingly
// 2) create the nodes present in the new list, but absent in the old one
// 3) remove the nodes present in the old list, but absent in the new one
// 4) figure out what nodes in 1) to move in order to minimize the DOM operations.
//
// To achieve 1) one can create a dictionary of keys => index (for the old list), then iterate
// over the new list and for each new vnode, find the corresponding vnode in the old list using
// the map.
// 2) is achieved in the same step: if a new node has no corresponding entry in the map, it is new
// and must be created.
// For the removals, we actually remove the nodes that have been updated from the old list.
// The nodes that remain in that list after 1) and 2) have been performed can be safely removed.
// The fourth step is a bit more complex and relies on the longest increasing subsequence (LIS)
// algorithm.
//
// the longest increasing subsequence is the list of nodes that can remain in place. Imagine going
// from `1,2,3,4,5` to `4,5,1,2,3` where the numbers are not necessarily the keys, but the indices
// corresponding to the keyed nodes in the old list (keyed nodes `e,d,c,b,a` => `b,a,e,d,c` would
// match the above lists, for example).
//
// In there are two increasing subsequences: `4,5` and `1,2,3`, the latter being the longest. We
// can update those nodes without moving them, and only call `insertNode` on `4` and `5`.
//
// @localvoid adapted the algo to also support node deletions and insertions (the `lis` is actually
// the longest increasing subsequence *of old nodes still present in the new list*).
//
// It is a general algorithm that is fireproof in all circumstances, but it requires the allocation
// and the construction of a `key => oldIndex` map, and three arrays (one with `newIndex => oldIndex`,
// the `LIS` and a temporary one to create the LIS).
//
// So we cheat where we can: if the tails of the lists are identical, they are guaranteed to be part of
// the LIS and can be updated without moving them.
//
// If two nodes are swapped, they are guaranteed not to be part of the LIS, and must be moved (with
// the exception of the last node if the list is fully reversed).
//
// ## Finding the next sibling.
//
// `updateNode()` and `createNode()` expect a nextSibling parameter to perform DOM operations.
// When the list is being traversed top-down, at any index, the DOM nodes up to the previous
// vnode reflect the content of the new list, whereas the rest of the DOM nodes reflect the old
// list. The next sibling must be looked for in the old list using `getNextSibling(... oldStart + 1 ...)`.
//
// In the other scenarios (swaps, upwards traversal, map-based diff),
// the new vnodes list is traversed upwards. The DOM nodes at the bottom of the list reflect the
// bottom part of the new vnodes list, and we can use the `v.dom` value of the previous node
// as the next sibling (cached in the `nextSibling` variable).
// ## DOM node moves
//
// In most scenarios `updateNode()` and `createNode()` perform the DOM operations. However,
// this is not the case if the node moved (second and fourth part of the diff algo). We move
// the old DOM nodes before updateNode runs because it enables us to use the cached `nextSibling`
// variable rather than fetching it using `getNextSibling()`.
//
// The fourth part of the diff currently inserts nodes unconditionally, leading to issues
// like #1791 and #1999. We need to be smarter about those situations where adjascent old
// nodes remain together in the new list in a way that isn't covered by parts one and
// three of the diff algo.
function updateNodes(parent, old, vnodes, hooks, nextSibling, ns) {
if (old === vnodes || old == null && vnodes == null) return
else if (old == null || old.length === 0) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns)
else if (vnodes == null || vnodes.length === 0) removeNodes(parent, old, 0, old.length)
else {
var isOldKeyed = old[0] != null && old[0].key != null
var isKeyed = vnodes[0] != null && vnodes[0].key != null
var start = 0, oldStart = 0
if (!isOldKeyed) while (oldStart < old.length && old[oldStart] == null) oldStart++
if (!isKeyed) while (start < vnodes.length && vnodes[start] == null) start++
if (isOldKeyed !== isKeyed) {
removeNodes(parent, old, oldStart, old.length)
createNodes(parent, vnodes, start, vnodes.length, hooks, nextSibling, ns)
} else if (!isKeyed) {
// Don't index past the end of either list (causes deopts).
var commonLength = old.length < vnodes.length ? old.length : vnodes.length
// Rewind if necessary to the first non-null index on either side.
// We could alternatively either explicitly create or remove nodes when `start !== oldStart`
// but that would be optimizing for sparse lists which are more rare than dense ones.
start = start < oldStart ? start : oldStart
for (; start < commonLength; start++) {
o = old[start]
v = vnodes[start]
if (o === v || o == null && v == null) continue
else if (o == null) createNode(parent, v, hooks, ns, getNextSibling(old, start + 1, nextSibling))
else if (v == null) removeNode(parent, o)
else updateNode(parent, o, v, hooks, getNextSibling(old, start + 1, nextSibling), ns)
}
if (old.length > commonLength) removeNodes(parent, old, start, old.length)
if (vnodes.length > commonLength) createNodes(parent, vnodes, start, vnodes.length, hooks, nextSibling, ns)
} else {
// keyed diff
var oldEnd = old.length - 1, end = vnodes.length - 1, map, o, v, oe, ve, topSibling
// bottom-up
while (oldEnd >= oldStart && end >= start) {
oe = old[oldEnd]
ve = vnodes[end]
if (oe.key !== ve.key) break
if (oe !== ve) updateNode(parent, oe, ve, hooks, nextSibling, ns)
if (ve.dom != null) nextSibling = ve.dom
oldEnd--, end--
}
// top-down
while (oldEnd >= oldStart && end >= start) {
o = old[oldStart]
v = vnodes[start]
if (o.key !== v.key) break
oldStart++, start++
if (o !== v) updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), ns)
}
// swaps and list reversals
while (oldEnd >= oldStart && end >= start) {
if (start === end) break
if (o.key !== ve.key || oe.key !== v.key) break
topSibling = getNextSibling(old, oldStart, nextSibling)
moveNodes(parent, oe, topSibling)
if (oe !== v) updateNode(parent, oe, v, hooks, topSibling, ns)
if (++start <= --end) moveNodes(parent, o, nextSibling)
if (o !== ve) updateNode(parent, o, ve, hooks, nextSibling, ns)
if (ve.dom != null) nextSibling = ve.dom
oldStart++; oldEnd--
oe = old[oldEnd]
ve = vnodes[end]
o = old[oldStart]
v = vnodes[start]
}
// bottom up once again
while (oldEnd >= oldStart && end >= start) {
if (oe.key !== ve.key) break
if (oe !== ve) updateNode(parent, oe, ve, hooks, nextSibling, ns)
if (ve.dom != null) nextSibling = ve.dom
oldEnd--, end--
oe = old[oldEnd]
ve = vnodes[end]
}
if (start > end) removeNodes(parent, old, oldStart, oldEnd + 1)
else if (oldStart > oldEnd) createNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns)
else {
// inspired by ivi https://github.com/ivijs/ivi/ by Boris Kaul
var originalNextSibling = nextSibling, vnodesLength = end - start + 1, oldIndices = new Array(vnodesLength), li=0, i=0, pos = 2147483647, matched = 0, map, lisIndices
for (i = 0; i < vnodesLength; i++) oldIndices[i] = -1
for (i = end; i >= start; i--) {
if (map == null) map = getKeyMap(old, oldStart, oldEnd + 1)
ve = vnodes[i]
var oldIndex = map[ve.key]
if (oldIndex != null) {
pos = (oldIndex < pos) ? oldIndex : -1 // becomes -1 if nodes were re-ordered
oldIndices[i-start] = oldIndex
oe = old[oldIndex]
old[oldIndex] = null
if (oe !== ve) updateNode(parent, oe, ve, hooks, nextSibling, ns)
if (ve.dom != null) nextSibling = ve.dom
matched++
}
}
nextSibling = originalNextSibling
if (matched !== oldEnd - oldStart + 1) removeNodes(parent, old, oldStart, oldEnd + 1)
if (matched === 0) createNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns)
else {
if (pos === -1) {
// the indices of the indices of the items that are part of the
// longest increasing subsequence in the oldIndices list
lisIndices = makeLisIndices(oldIndices)
li = lisIndices.length - 1
for (i = end; i >= start; i--) {
v = vnodes[i]
if (oldIndices[i-start] === -1) createNode(parent, v, hooks, ns, nextSibling)
else {
if (lisIndices[li] === i - start) li--
else moveNodes(parent, v, nextSibling)
}
if (v.dom != null) nextSibling = vnodes[i].dom
}
} else {
for (i = end; i >= start; i--) {
v = vnodes[i]
if (oldIndices[i-start] === -1) createNode(parent, v, hooks, ns, nextSibling)
if (v.dom != null) nextSibling = vnodes[i].dom
}
}
}
}
}
}
}
function updateNode(parent, old, vnode, hooks, nextSibling, ns) {
var oldTag = old.tag, tag = vnode.tag
if (oldTag === tag) {
vnode.state = old.state
vnode.events = old.events
if (shouldNotUpdate(vnode, old)) return
if (typeof oldTag === "string") {
if (vnode.attrs != null) {
updateLifecycle(vnode.attrs, vnode, hooks)
}
switch (oldTag) {
case "#": updateText(old, vnode); break
case "<": updateHTML(parent, old, vnode, ns, nextSibling); break
case "[": updateFragment(parent, old, vnode, hooks, nextSibling, ns); break
default: updateElement(old, vnode, hooks, ns)
}
}
else updateComponent(parent, old, vnode, hooks, nextSibling, ns)
}
else {
removeNode(parent, old)
createNode(parent, vnode, hooks, ns, nextSibling)
}
}
function updateText(old, vnode) {
if (old.children.toString() !== vnode.children.toString()) {
old.dom.nodeValue = vnode.children
}
vnode.dom = old.dom
}
function updateHTML(parent, old, vnode, ns, nextSibling) {
if (old.children !== vnode.children) {
removeHTML(parent, old)
createHTML(parent, vnode, ns, nextSibling)
}
else {
vnode.dom = old.dom
vnode.domSize = old.domSize
vnode.instance = old.instance
}
}
function updateFragment(parent, old, vnode, hooks, nextSibling, ns) {
updateNodes(parent, old.children, vnode.children, hooks, nextSibling, ns)
var domSize = 0, children = vnode.children
vnode.dom = null
if (children != null) {
for (var i = 0; i < children.length; i++) {
var child = children[i]
if (child != null && child.dom != null) {
if (vnode.dom == null) vnode.dom = child.dom
domSize += child.domSize || 1
}
}
if (domSize !== 1) vnode.domSize = domSize
}
}
function updateElement(old, vnode, hooks, ns) {
var element = vnode.dom = old.dom
ns = getNameSpace(vnode) || ns
if (vnode.tag === "textarea") {
if (vnode.attrs == null) vnode.attrs = {}
}
updateAttrs(vnode, old.attrs, vnode.attrs, ns)
if (!maybeSetContentEditable(vnode)) {
updateNodes(element, old.children, vnode.children, hooks, null, ns)
}
}
function updateComponent(parent, old, vnode, hooks, nextSibling, ns) {
vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode))
if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
updateLifecycle(vnode.state, vnode, hooks)
if (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)
if (vnode.instance != null) {
if (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling)
else updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, ns)
vnode.dom = vnode.instance.dom
vnode.domSize = vnode.instance.domSize
}
else if (old.instance != null) {
removeNode(parent, old.instance)
vnode.dom = undefined
vnode.domSize = 0
}
else {
vnode.dom = old.dom
vnode.domSize = old.domSize
}
}
function getKeyMap(vnodes, start, end) {
var map = Object.create(null)
for (; start < end; start++) {
var vnode = vnodes[start]
if (vnode != null) {
var key = vnode.key
if (key != null) map[key] = start
}
}
return map
}
// Lifted from ivi https://github.com/ivijs/ivi/
// takes a list of unique numbers (-1 is special and can
// occur multiple times) and returns an array with the indices
// of the items that are part of the longest increasing
// subsequence
var lisTemp = []
function makeLisIndices(a) {
var result = [0]
var u = 0, v = 0, i = 0
var il = lisTemp.length = a.length
for (var i = 0; i < il; i++) lisTemp[i] = a[i]
for (var i = 0; i < il; ++i) {
if (a[i] === -1) continue
var j = result[result.length - 1]
if (a[j] < a[i]) {
lisTemp[i] = j
result.push(i)
continue
}
u = 0
v = result.length - 1
while (u < v) {
// Fast integer average without overflow.
// eslint-disable-next-line no-bitwise
var c = (u >>> 1) + (v >>> 1) + (u & v & 1)
if (a[result[c]] < a[i]) {
u = c + 1
}
else {
v = c
}
}
if (a[i] < a[result[u]]) {
if (u > 0) lisTemp[i] = result[u - 1]
result[u] = i
}
}
u = result.length
v = result[u - 1]
while (u-- > 0) {
result[u] = v
v = lisTemp[v]
}
lisTemp.length = 0
return result
}
function getNextSibling(vnodes, i, nextSibling) {
for (; i < vnodes.length; i++) {
if (vnodes[i] != null && vnodes[i].dom != null) return vnodes[i].dom
}
return nextSibling
}
// This covers a really specific edge case:
// - Parent node is keyed and contains child
// - Child is removed, returns unresolved promise in `onbeforeremove`
// - Parent node is moved in keyed diff
// - Remaining children still need moved appropriately
//
// Ideally, I'd track removed nodes as well, but that introduces a lot more
// complexity and I'm not exactly interested in doing that.
function moveNodes(parent, vnode, nextSibling) {
var frag = $doc.createDocumentFragment()
moveChildToFrag(parent, frag, vnode)
insertNode(parent, frag, nextSibling)
}
function moveChildToFrag(parent, frag, vnode) {
// Dodge the recursion overhead in a few of the most common cases.
while (vnode.dom != null && vnode.dom.parentNode === parent) {
if (typeof vnode.tag !== "string") {
vnode = vnode.instance
if (vnode != null) continue
} else if (vnode.tag === "<") {
for (var i = 0; i < vnode.instance.length; i++) {
frag.appendChild(vnode.instance[i])
}
} else if (vnode.tag !== "[") {
// Don't recurse for text nodes *or* elements, just fragments
frag.appendChild(vnode.dom)
} else if (vnode.children.length === 1) {
vnode = vnode.children[0]
if (vnode != null) continue
} else {
for (var i = 0; i < vnode.children.length; i++) {
var child = vnode.children[i]
if (child != null) moveChildToFrag(parent, frag, child)
}
}
break
}
}
function insertNode(parent, dom, nextSibling) {
if (nextSibling != null) parent.insertBefore(dom, nextSibling)
else parent.appendChild(dom)
}
function maybeSetContentEditable(vnode) {
if (vnode.attrs == null || (
vnode.attrs.contenteditable == null && // attribute
vnode.attrs.contentEditable == null // property
)) return false
var children = vnode.children
if (children != null && children.length === 1 && children[0].tag === "<") {
var content = children[0].children
if (vnode.dom.innerHTML !== content) vnode.dom.innerHTML = content
}
else if (children != null && children.length !== 0) throw new Error("Child node of a contenteditable must be trusted.")
return true
}
//remove
function removeNodes(parent, vnodes, start, end) {
for (var i = start; i < end; i++) {
var vnode = vnodes[i]
if (vnode != null) removeNode(parent, vnode)
}
}
function removeNode(parent, vnode) {
var mask = 0
var original = vnode.state
var stateResult, attrsResult
if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeremove === "function") {
var result = callHook.call(vnode.state.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") {
mask = 1
stateResult = result
}
}
if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") {
var result = callHook.call(vnode.attrs.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") {
// eslint-disable-next-line no-bitwise
mask |= 2
attrsResult = result
}
}
checkState(vnode, original)
// If we can, try to fast-path it and avoid all the overhead of awaiting
if (!mask) {
onremove(vnode)
removeChild(parent, vnode)
} else {
if (stateResult != null) {
var next = function () {
// eslint-disable-next-line no-bitwise
if (mask & 1) { mask &= 2; if (!mask) reallyRemove() }
}
stateResult.then(next, next)
}
if (attrsResult != null) {
var next = function () {
// eslint-disable-next-line no-bitwise
if (mask & 2) { mask &= 1; if (!mask) reallyRemove() }
}
attrsResult.then(next, next)
}
}
function reallyRemove() {
checkState(vnode, original)
onremove(vnode)
removeChild(parent, vnode)
}
}
function removeHTML(parent, vnode) {
for (var i = 0; i < vnode.instance.length; i++) {
parent.removeChild(vnode.instance[i])
}
}
function removeChild(parent, vnode) {
// Dodge the recursion overhead in a few of the most common cases.
while (vnode.dom != null && vnode.dom.parentNode === parent) {
if (typeof vnode.tag !== "string") {
vnode = vnode.instance
if (vnode != null) continue
} else if (vnode.tag === "<") {
removeHTML(parent, vnode)
} else {
if (vnode.tag !== "[") {
parent.removeChild(vnode.dom)
if (!Array.isArray(vnode.children)) break
}
if (vnode.children.length === 1) {
vnode = vnode.children[0]
if (vnode != null) continue
} else {
for (var i = 0; i < vnode.children.length; i++) {
var child = vnode.children[i]
if (child != null) removeChild(parent, child)
}
}
}
break
}
}
function onremove(vnode) {
if (typeof vnode.tag !== "string" && typeof vnode.state.onremove === "function") callHook.call(vnode.state.onremove, vnode)
if (vnode.attrs && typeof vnode.attrs.onremove === "function") callHook.call(vnode.attrs.onremove, vnode)
if (typeof vnode.tag !== "string") {
if (vnode.instance != null) onremove(vnode.instance)
} else {
var children = vnode.children
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i]
if (child != null) onremove(child)
}
}
}
}
//attrs
function setAttrs(vnode, attrs, ns) {
// If you assign an input type that is not supported by IE 11 with an assignment expression, an error will occur.
//
// Also, the DOM does things to inputs based on the value, so it needs set first.
// See: https://github.com/MithrilJS/mithril.js/issues/2622
if (vnode.tag === "input" && attrs.type != null) vnode.dom.setAttribute("type", attrs.type)
var isFileInput = attrs != null && vnode.tag === "input" && attrs.type === "file"
for (var key in attrs) {
setAttr(vnode, key, null, attrs[key], ns, isFileInput)
}
}
function setAttr(vnode, key, old, value, ns, isFileInput) {
if (key === "key" || key === "is" || value == null || isLifecycleMethod(key) || (old === value && !isFormAttribute(vnode, key)) && typeof value !== "object" || key === "type" && vnode.tag === "input") return
if (key[0] === "o" && key[1] === "n") return updateEvent(vnode, key, value)
if (key.slice(0, 6) === "xlink:") vnode.dom.setAttributeNS("http://www.w3.org/1999/xlink", key.slice(6), value)
else if (key === "style") updateStyle(vnode.dom, old, value)
else if (hasPropertyKey(vnode, key, ns)) {
if (key === "value") {
// Only do the coercion if we're actually going to check the value.
/* eslint-disable no-implicit-coercion */
//setting input[value] to same value by typing on focused element moves cursor to end in Chrome
//setting input[type=file][value] to same value causes an error to be generated if it's non-empty
if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === "" + value && (isFileInput || vnode.dom === activeElement())) return
//setting select[value] to same value while having select open blinks select dropdown in Chrome
if (vnode.tag === "select" && old !== null && vnode.dom.value === "" + value) return
//setting option[value] to same value while having select open blinks select dropdown in Chrome
if (vnode.tag === "option" && old !== null && vnode.dom.value === "" + value) return
//setting input[type=file][value] to different value is an error if it's non-empty
// Not ideal, but it at least works around the most common source of uncaught exceptions for now.
if (isFileInput && "" + value !== "") { console.error("`value` is read-only on file inputs!"); return }
/* eslint-enable no-implicit-coercion */
}
vnode.dom[key] = value
} else {
if (typeof value === "boolean") {
if (value) vnode.dom.setAttribute(key, "")
else vnode.dom.removeAttribute(key)
}
else vnode.dom.setAttribute(key === "className" ? "class" : key, value)
}
}
function removeAttr(vnode, key, old, ns) {
if (key === "key" || key === "is" || old == null || isLifecycleMethod(key)) return
if (key[0] === "o" && key[1] === "n") updateEvent(vnode, key, undefined)
else if (key === "style") updateStyle(vnode.dom, old, null)
else if (
hasPropertyKey(vnode, key, ns)
&& key !== "className"
&& key !== "title" // creates "null" as title
&& !(key === "value" && (
vnode.tag === "option"
|| vnode.tag === "select" && vnode.dom.selectedIndex === -1 && vnode.dom === activeElement()
))
&& !(vnode.tag === "input" && key === "type")
) {
vnode.dom[key] = null
} else {
var nsLastIndex = key.indexOf(":")
if (nsLastIndex !== -1) key = key.slice(nsLastIndex + 1)
if (old !== false) vnode.dom.removeAttribute(key === "className" ? "class" : key)
}
}
function setLateSelectAttrs(vnode, attrs) {
if ("value" in attrs) {
if(attrs.value === null) {
if (vnode.dom.selectedIndex !== -1) vnode.dom.value = null
} else {
var normalized = "" + attrs.value // eslint-disable-line no-implicit-coercion
if (vnode.dom.value !== normalized || vnode.dom.selectedIndex === -1) {
vnode.dom.value = normalized
}
}
}
if ("selectedIndex" in attrs) setAttr(vnode, "selectedIndex", null, attrs.selectedIndex, undefined)
}
function updateAttrs(vnode, old, attrs, ns) {
if (old && old === attrs) {
console.warn("Don't reuse attrs object, use new object for every redraw, this will throw in next major")
}
if (attrs != null) {
// If you assign an input type that is not supported by IE 11 with an assignment expression, an error will occur.
//
// Also, the DOM does things to inputs based on the value, so it needs set first.
// See: https://github.com/MithrilJS/mithril.js/issues/2622
if (vnode.tag === "input" && attrs.type != null) vnode.dom.setAttribute("type", attrs.type)
var isFileInput = vnode.tag === "input" && attrs.type === "file"
for (var key in attrs) {
setAttr(vnode, key, old && old[key], attrs[key], ns, isFileInput)
}
}
var val
if (old != null) {
for (var key in old) {
if (((val = old[key]) != null) && (attrs == null || attrs[key] == null)) {
removeAttr(vnode, key, val, ns)
}
}
}
}
function isFormAttribute(vnode, attr) {
return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === activeElement() || vnode.tag === "option" && vnode.dom.parentNode === $doc.activeElement
}
function isLifecycleMethod(attr) {
return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate"
}
function hasPropertyKey(vnode, key, ns) {
// Filter out namespaced keys
return ns === undefined && (
// If it's a custom element, just keep it.
vnode.tag.indexOf("-") > -1 || vnode.attrs != null && vnode.attrs.is ||
// If it's a normal element, let's try to avoid a few browser bugs.
key !== "href" && key !== "list" && key !== "form" && key !== "width" && key !== "height"// && key !== "type"
// Defer the property check until *after* we check everything.
) && key in vnode.dom
}
//style
var uppercaseRegex = /[A-Z]/g
function toLowerCase(capital) { return "-" + capital.toLowerCase() }
function normalizeKey(key) {
return key[0] === "-" && key[1] === "-" ? key :
key === "cssFloat" ? "float" :
key.replace(uppercaseRegex, toLowerCase)
}
function updateStyle(element, old, style) {
if (old === style) {
// Styles are equivalent, do nothing.
} else if (style == null) {
// New style is missing, just clear it.
element.style.cssText = ""
} else if (typeof style !== "object") {
// New style is a string, let engine deal with patching.
element.style.cssText = style
} else if (old == null || typeof old !== "object") {
// `old` is missing or a string, `style` is an object.
element.style.cssText = ""
// Add new style properties
for (var key in style) {
var value = style[key]
if (value != null) element.style.setProperty(normalizeKey(key), String(value))
}
} else {
// Both old & new are (different) objects.
// Update style properties that have changed
for (var key in style) {
var value = style[key]
if (value != null && (value = String(value)) !== String(old[key])) {
element.style.setProperty(normalizeKey(key), value)
}
}
// Remove style properties that no longer exist
for (var key in old) {
if (old[key] != null && style[key] == null) {
element.style.removeProperty(normalizeKey(key))
}
}
}
}
// Here's an explanation of how this works:
// 1. The event names are always (by design) prefixed by `on`.
// 2. The EventListener interface accepts either a function or an object
// with a `handleEvent` method.
// 3. The object does not inherit from `Object.prototype`, to avoid
// any potential interference with that (e.g. setters).
// 4. The event name is remapped to the handler before calling it.
// 5. In function-based event handlers, `ev.target === this`. We replicate
// that below.
// 6. In function-based event handlers, `return false` prevents the default
// action and stops event propagation. We replicate that below.
function EventDict() {
// Save this, so the current redraw is correctly tracked.
this._ = currentRedraw
}
EventDict.prototype = Object.create(null)
EventDict.prototype.handleEvent = function (ev) {
var handler = this["on" + ev.type]
var result
if (typeof handler === "function") result = handler.call(ev.currentTarget, ev)
else if (typeof handler.handleEvent === "function") handler.handleEvent(ev)
if (this._ && ev.redraw !== false) (0, this._)()
if (result === false) {
ev.preventDefault()
ev.stopPropagation()
}
}
//event
function updateEvent(vnode, key, value) {
if (vnode.events != null) {
vnode.events._ = currentRedraw
if (vnode.events[key] === value) return
if (value != null && (typeof value === "function" || typeof value === "object")) {
if (vnode.events[key] == null) vnode.dom.addEventListener(key.slice(2), vnode.events, false)
vnode.events[key] = value
} else {
if (vnode.events[key] != null) vnode.dom.removeEventListener(key.slice(2), vnode.events, false)
vnode.events[key] = undefined
}
} else if (value != null && (typeof value === "function" || typeof value === "object")) {
vnode.events = new EventDict()
vnode.dom.addEventListener(key.slice(2), vnode.events, false)
vnode.events[key] = value
}
}
//lifecycle
function initLifecycle(source, vnode, hooks) {
if (typeof source.oninit === "function") callHook.call(source.oninit, vnode)
if (typeof source.oncreate === "function") hooks.push(callHook.bind(source.oncreate, vnode))
}
function updateLifecycle(source, vnode, hooks) {
if (typeof source.onupdate === "function") hooks.push(callHook.bind(source.onupdate, vnode))
}
function shouldNotUpdate(vnode, old) {
do {
if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") {
var force = callHook.call(vnode.attrs.onbeforeupdate, vnode, old)
if (force !== undefined && !force) break
}
if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeupdate === "function") {
var force = callHook.call(vnode.state.onbeforeupdate, vnode, old)
if (force !== undefined && !force) break
}
return false
} while (false); // eslint-disable-line no-constant-condition
vnode.dom = old.dom
vnode.domSize = old.domSize
vnode.instance = old.instance
// One would think having the actual latest attributes would be ideal,
// but it doesn't let us properly diff based on our current internal
// representation. We have to save not only the old DOM info, but also
// the attributes used to create it, as we diff *that*, not against the
// DOM directly (with a few exceptions in `setAttr`). And, of course, we
// need to save the children and text as they are conceptually not
// unlike special "attributes" internally.
vnode.attrs = old.attrs
vnode.children = old.children
vnode.text = old.text
return true
}
var currentDOM
return function(dom, vnodes, redraw) {
if (!dom) throw new TypeError("DOM element being rendered to does not exist.")
if (currentDOM != null && dom.contains(currentDOM)) {
throw new TypeError("Node is currently being rendered to and thus is locked.")
}
var prevRedraw = currentRedraw
var prevDOM = currentDOM
var hooks = []
var active = activeElement()
var namespace = dom.namespaceURI
currentDOM = dom
currentRedraw = typeof redraw === "function" ? redraw : undefined
try {
// First time rendering into a node clears it out
if (dom.vnodes == null) dom.textContent = ""
vnodes = Vnode.normalizeChildren(Array.isArray(vnodes) ? vnodes : [vnodes])
updateNodes(dom, dom.vnodes, vnodes, hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? undefined : namespace)
dom.vnodes = vnodes
// `document.activeElement` can return null: https://html.spec.whatwg.org/multipage/interaction.html#dom-document-activeelement
if (active != null && activeElement() !== active && typeof active.focus === "function") active.focus()
for (var i = 0; i < hooks.length; i++) hooks[i]()
} finally {
currentRedraw = prevRedraw
currentDOM = prevDOM
}
}
}

View File

@@ -0,0 +1,8 @@
"use strict"
var Vnode = require("./vnode")
module.exports = function(html) {
if (html == null) html = ""
return Vnode("<", undefined, undefined, html, undefined, undefined)
}

View File

@@ -0,0 +1,35 @@
"use strict"
function Vnode(tag, key, attrs, children, text, dom) {
return {tag: tag, key: key, attrs: attrs, children: children, text: text, dom: dom, domSize: undefined, state: undefined, events: undefined, instance: undefined}
}
Vnode.normalize = function(node) {
if (Array.isArray(node)) return Vnode("[", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined)
if (node == null || typeof node === "boolean") return null
if (typeof node === "object") return node
return Vnode("#", undefined, undefined, String(node), undefined, undefined)
}
Vnode.normalizeChildren = function(input) {
var children = []
if (input.length) {
var isKeyed = input[0] != null && input[0].key != null
// Note: this is a *very* perf-sensitive check.
// Fun fact: merging the loop like this is somehow faster than splitting
// it, noticeably so.
for (var i = 1; i < input.length; i++) {
if ((input[i] != null && input[i].key != null) !== isKeyed) {
throw new TypeError(
isKeyed && (input[i] != null || typeof input[i] === "boolean")
? "In fragments, vnodes must either all have keys or none have keys. You may wish to consider using an explicit keyed empty fragment, m.fragment({key: ...}), instead of a hole."
: "In fragments, vnodes must either all have keys or none have keys."
)
}
}
for (var i = 0; i < input.length; i++) {
children[i] = Vnode.normalize(input[i])
}
}
return children
}
module.exports = Vnode

View File

@@ -0,0 +1,6 @@
"use strict"
var PromisePolyfill = require("./promise/promise")
var mountRedraw = require("./mount-redraw")
module.exports = require("./request/request")(typeof window !== "undefined" ? window : null, PromisePolyfill, mountRedraw.redraw)

View File

@@ -0,0 +1,5 @@
"use strict"
var mountRedraw = require("./mount-redraw")
module.exports = require("./api/router")(typeof window !== "undefined" ? window : null, mountRedraw)

View File

@@ -0,0 +1,3 @@
"use strict"
module.exports = require("./stream/stream")

View File

@@ -0,0 +1,10 @@
// This exists so I'm only saving it once.
"use strict"
var hasOwn = require("./hasOwn")
module.exports = Object.assign || function(target, source) {
for (var key in source) {
if (hasOwn.call(source, key)) target[key] = source[key]
}
}

View File

@@ -0,0 +1,48 @@
"use strict"
// Note: this is mildly perf-sensitive.
//
// It does *not* use `delete` - dynamic `delete`s usually cause objects to bail
// out into dictionary mode and just generally cause a bunch of optimization
// issues within engines.
//
// Ideally, I would've preferred to do this, if it weren't for the optimization
// issues:
//
// ```js
// const hasOwn = require("./hasOwn")
// const magic = [
// "key", "oninit", "oncreate", "onbeforeupdate", "onupdate",
// "onbeforeremove", "onremove",
// ]
// module.exports = (attrs, extras) => {
// const result = Object.assign(Object.create(null), attrs)
// for (const key of magic) delete result[key]
// if (extras != null) for (const key of extras) delete result[key]
// return result
// }
// ```
var hasOwn = require("./hasOwn")
// Words in RegExp literals are sometimes mangled incorrectly by the internal bundler, so use RegExp().
var magic = new RegExp("^(?:key|oninit|oncreate|onbeforeupdate|onupdate|onbeforeremove|onremove)$")
module.exports = function(attrs, extras) {
var result = {}
if (extras != null) {
for (var key in attrs) {
if (hasOwn.call(attrs, key) && !magic.test(key) && extras.indexOf(key) < 0) {
result[key] = attrs[key]
}
}
} else {
for (var key in attrs) {
if (hasOwn.call(attrs, key) && !magic.test(key)) {
result[key] = attrs[key]
}
}
}
return result
}

View File

@@ -0,0 +1,4 @@
// This exists so I'm only saving it once.
"use strict"
module.exports = {}.hasOwnProperty