Merge branch 'next' into iss-1798

This commit is contained in:
Pierre-Yves Gérardy 2018-05-04 14:08:39 +02:00 committed by GitHub
commit 4818109c9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
107 changed files with 9687 additions and 1550 deletions

3
.babelrc Normal file
View file

@ -0,0 +1,3 @@
// This is solely to avoid https://github.com/danger/danger-js/issues/261
// and should be fine to remove before much longer
{}

View file

@ -1,7 +1,7 @@
.vscode .vscode/
/coverage coverage/
/docs/lib docs/lib/
/examples examples/
/mithril.js /mithril.js
/mithril.min.js /mithril.min.js
/node_modules node_modules/

View file

@ -4,7 +4,7 @@ module.exports = {
"commonjs": true, "commonjs": true,
"es6": true, "es6": true,
"node": true "node": true
}, },
"extends": "eslint:recommended", "extends": "eslint:recommended",
"rules": { "rules": {
"accessor-pairs": "error", "accessor-pairs": "error",

2
.gitattributes vendored
View file

@ -1,3 +1,5 @@
* text=auto * text=auto
/mithril.js binary /mithril.js binary
/mithril.min.js binary /mithril.min.js binary
/package-lock.json binary
/yarn.lock binary

9
.github/CODEOWNERS vendored Normal file
View file

@ -0,0 +1,9 @@
.travis.yml @tivac
package.json @tivac
.npmignore @tivac
.eslintrc.js @tivac
.eslintignore @tivac
README.md @tivac
docs/ @tivac
performance/ @tivac
render/ @pygy

32
.github/ISSUE_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,32 @@
<!--- Provide a general summary of the issue in the Title above -->
## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->
## Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change -->
## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1.
2.
3.
4.
## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Version used:
* Browser Name and version:
* Operating System and version (desktop or mobile):
* Link to your project:

31
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,31 @@
<!--- Provide a general summary of your changes in the Title above -->
## Description
<!--- Describe your changes in detail -->
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
<!--- If it fixes an open issue, please link to the issue here. -->
## How Has This Been Tested?
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation change
## Checklist:
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
- [ ] I have updated `docs/change-log.md`

View file

@ -6,3 +6,4 @@
.gitignore .gitignore
.travis.yml .travis.yml
CONTRIBUTING.md CONTRIBUTING.md
yarn.lock

View file

@ -13,10 +13,15 @@ cache:
# Custom install step so the travis-only stuff doesn't need to be in package.json # Custom install step so the travis-only stuff doesn't need to be in package.json
install: install:
- npm install - npm install
- npm install @alrra/travis-scripts@^3.0.1 gh-pages@^0.12.0 # This is to prevent lint-staged/prettier from running on the bundles
- npm rm husky
# Bundle before running tests so the bundle is always up-to-date # Run danger, build bundles (so they're always up to date)
before_script: npm run build before_script:
- npx danger run
- npm run build-browser
# Pass -save so it'll update the readme as well
- npm run build-min -- -save
# Run tests, lint, and then check for perf regressions # Run tests, lint, and then check for perf regressions
script: script:
@ -44,7 +49,7 @@ after_success:
# this doesn't have the built-in branch protection like commit-changes # this doesn't have the built-in branch protection like commit-changes
if [ "$TRAVIS_EVENT_TYPE" == "push" ] && \ if [ "$TRAVIS_EVENT_TYPE" == "push" ] && \
[ "$TRAVIS_BRANCH" == "master" ] && \ [ "$TRAVIS_BRANCH" == "master" ] && \
[ "$TRAVIS_REPO_SLUG" == "lhorie/mithril.js" ] [ "$TRAVIS_REPO_SLUG" == "MithrilJS/mithril.js" ]
then then
# Generate docs # Generate docs
npm run gendocs npm run gendocs
@ -59,7 +64,7 @@ after_success:
$(npm bin)/gh-pages \ $(npm bin)/gh-pages \
--dist ./dist \ --dist ./dist \
--add \ --add \
--repo "git@github.com:lhorie/mithril.js.git" \ --repo "git@github.com:MithrilJS/mithril.js.git" \
--message "Generated docs for commit $TRAVIS_COMMIT [skip ci]" --message "Generated docs for commit $TRAVIS_COMMIT [skip ci]"
else else
echo "Not submitting documentation updates" echo "Not submitting documentation updates"
@ -83,8 +88,7 @@ deploy:
skip_cleanup: true skip_cleanup: true
on: on:
tags: true tags: true
repo: lhorie/mithril.js repo: MithrilJS/mithril.js
branch: master
- provider: npm - provider: npm
skip_cleanup: true skip_cleanup: true
@ -93,5 +97,4 @@ deploy:
secure: ADElvD1oxn9GfEG7dDOggX96b36A/cGEybovAc0221CCKzv5kWCavMrtxneiJYI6N/n24abSlbM90vMfU84FEzH0Ev28dGVokRP4ad6VRkISszKlYVEP8Lds4QxfKh78jZlUxmxM0B3vmQ1kYJbTBqp3ICtaJ5ptEQHWhrLtxnc= secure: ADElvD1oxn9GfEG7dDOggX96b36A/cGEybovAc0221CCKzv5kWCavMrtxneiJYI6N/n24abSlbM90vMfU84FEzH0Ev28dGVokRP4ad6VRkISszKlYVEP8Lds4QxfKh78jZlUxmxM0B3vmQ1kYJbTBqp3ICtaJ5ptEQHWhrLtxnc=
on: on:
tags: true tags: true
repo: lhorie/mithril.js repo: MithrilJS/mithril.js
branch: master

316
README.md
View file

@ -1,267 +1,61 @@
# Introduction mithril.js [![NPM Version](https://img.shields.io/npm/v/mithril.svg)](https://www.npmjs.com/package/mithril) [![NPM License](https://img.shields.io/npm/l/mithril.svg)](https://www.npmjs.com/package/mithril) [![NPM Downloads](https://img.shields.io/npm/dm/mithril.svg)](https://www.npmjs.com/package/mithril)
==========
<p align="center">
<a href="https://travis-ci.org/MithrilJS/mithril.js">
<img src="https://img.shields.io/travis/MithrilJS/mithril.js/next.svg" alt="Build Status">
</a>
<a href="https://gitter.im/mithriljs/mithril.js">
<img src="https://img.shields.io/gitter/room/mithriljs/mithril.js.svg" alt="Gitter" />
</a>
</p>
- [What is Mithril?](#what-is-mithril) - [What is Mithril?](#what-is-mithril)
- [Getting started](#getting-started) - [Installation](#installation)
- [Hello world](#hello-world) - [Documentation](#documentation)
- [DOM elements](#dom-elements) - [Getting Help](#getting-help)
- [Components](#components) - [Contributing](#contributing)
- [Routing](#routing)
- [XHR](#xhr) ## What is Mithril?
A modern client-side Javascript framework for building Single Page Applications. It's small (<!-- size -->8.30 KB<!-- /size --> gzipped), fast and provides routing and XHR utilities out of the box.
Mithril is used by companies like Vimeo and Nike, and open source platforms like Lichess 👍.
Browsers all the way back to IE9 are supported, no polyfills required 👌.
## Installation
### CDN
```html
<script src="https://unpkg.com/mithril"></script>
```
### npm
```bash
$ npm install mithril
```
The ["Getting started" guide](https://mithril.js.org/#getting-started) is a good place to start learning how to use mithril.
## Documentation
Documentation lives on [mithril.js.org](https://mithril.js.org).
You may be interested in the [API Docs](https://mithril.js.org/api.html), a [Simple Application](https://mithril.js.org/simple-application.html), or perhaps some [Examples](https://mithril.js.org/examples.html).
## Getting Help
Mithril has an active & welcoming community on [Gitter](https://gitter.im/mithriljs/mithril.js), or feel free to ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/mithril.js) using the `mithril.js` tag.
## Contributing
There's a [Contributing FAQ](https://mithril.js.org/contributing.html) on the mithril site that hopefully helps, but if not definitely hop into the [Gitter Room](https://gitter.im/mithriljs/mithril.js) and ask away!
--- ---
### What is Mithril? Thanks for reading!
Mithril is a modern client-side Javascript framework for building Single Page Applications. 🎁
It's small (< 8kb gzip), fast and provides routing and XHR utilities out of the box.
<div style="display:flex;margin:0 0 30px;">
<div style="width:50%;">
<h5>Download size</h5>
<small>Mithril (8kb)</small>
<div style="animation:grow 0.08s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:4%;"></div>
<small style="color:#aaa;">Vue + Vue-Router + Vuex + fetch (40kb)</small>
<div style="animation:grow 0.4s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:20%"></div>
<small style="color:#aaa;">React + React-Router + Redux + fetch (64kb)</small>
<div style="animation:grow 0.64s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:32%"></div>
<small style="color:#aaa;">Angular (135kb)</small>
<div style="animation:grow 1.35s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:68%"></div>
</div>
<div style="width:50%;">
<h5>Performance</h5>
<small>Mithril (6.4ms)</small>
<div style="animation:grow 0.64s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:24%;"></div>
<small style="color:#aaa;">Vue (9.8ms)</small>
<div style="animation:grow 0.98s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:40%"></div>
<small style="color:#aaa;">React (12.1ms)</small>
<div style="animation:grow 1.21s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:48%"></div>
<small style="color:#aaa;">Angular (11.5ms)</small>
<div style="animation:grow 1.15s;background:#1e5799;height:3px;margin:0 10px 10px 0;transform-origin:0;width:44%"></div>
</div>
</div>
Mithril is used by companies like Vimeo and Nike, and open source platforms like Lichess.
If you are an experienced developer and want to know how Mithril compares to other frameworks, see the [framework comparison](http://mithril.js.org/framework-comparison.html) page.
Mithril supports browsers all the way back to IE9, no polyfills required.
---
### Getting started
The easiest way to try out Mithril is to include it from a CDN, and follow this tutorial. It'll cover the majority of the API surface (including routing and XHR) but it'll only take 10 minutes.
Let's create an HTML file to follow along:
```markup
<body>
<script src="//unpkg.com/mithril/mithril.js"></script>
<script>
var root = document.body
// your code goes here!
</script>
</body>
```
---
### Hello world
Let's start as small as we can: render some text on screen. Copy the code below into your file (and by copy, I mean type it out - you'll learn better)
```javascript
var root = document.body
m.render(root, "Hello world")
```
Now, let's change the text to something else. Add this line of code under the previous one:
```javascript
m.render(root, "My first app")
```
As you can see, you use the same code to both create and update HTML. Mithril automatically figures out the most efficient way of updating the text, rather than blindly recreating it from scratch.
---
### DOM elements
Let's wrap our text in an `<h1>` tag.
```javascript
m.render(root, m("h1", "My first app"))
```
The `m()` function can be used to describe any HTML structure you want. So if you need to add a class to the `<h1>`:
```javascript
m("h1", {class: "title"}, "My first app")
```
If you want to have multiple elements:
```javascript
[
m("h1", {class: "title"}, "My first app"),
m("button", "A button"),
]
```
And so on:
```javascript
m("main", [
m("h1", {class: "title"}, "My first app"),
m("button", "A button"),
])
```
Note: If you prefer `<html>` syntax, [it's possible to use it via a Babel plugin](http://mithril.js.org/jsx.html).
```jsx
// HTML syntax via Babel's JSX plugin
<main>
<h1 class="title">My first app</h1>
<button>A button</button>
</main>
```
---
### Components
A Mithril component is just an object with a `view` function. Here's the code above as a component:
```javascript
var Hello = {
view: function() {
return m("main", [
m("h1", {class: "title"}, "My first app"),
m("button", "A button"),
])
}
}
```
To activate the component, we use `m.mount`.
```javascript
m.mount(root, Hello)
```
As you would expect, doing so creates this markup:
```markup
<main>
<h1 class="title">My first app</h1>
<button>A button</button>
</main>
```
The `m.mount` function is similar to `m.render`, but instead of rendering some HTML only once, it activates Mithril's auto-redrawing system. To understand what that means, let's add some events:
```javascript
var count = 0 // added a variable
var Hello = {
view: function() {
return m("main", [
m("h1", {class: "title"}, "My first app"),
// changed the next line
m("button", {onclick: function() {count++}}, count + " clicks"),
])
}
}
m.mount(root, Hello)
```
We defined an `onclick` event on the button, which increments a variable `count` (which was declared at the top). We are now also rendering the value of that variable in the button label.
You can now update the label of the button by clicking the button. Since we used `m.mount`, you don't need to manually call `m.render` to apply the changes in the `count` variable to the HTML; Mithril does it for you.
If you're wondering about performance, it turns out Mithril is very fast at rendering updates, because it only touches the parts of the DOM it absolutely needs to. So in our example above, when you click the button, the text in it is the only part of the DOM Mithril actually updates.
---
### Routing
Routing just means going from one screen to another in an application with several screens.
Let's add a splash page that appears before our click counter. First we create a component for it:
```javascript
var Splash = {
view: function() {
return m("a", {href: "#!/hello"}, "Enter!")
}
}
```
As you can see, this component simply renders a link to `#!/hello`. The `#!` part is known as a hashbang, and it's a common convention used in Single Page Applications to indicate that the stuff after it (the `/hello` part) is a route path.
Now that we going to have more than one screen, we use `m.route` instead of `m.mount`.
```javascript
m.route(root, "/splash", {
"/splash": Splash,
"/hello": Hello,
})
```
The `m.route` function still has the same auto-redrawing functionality that `m.mount` does, and it also enables URL awareness; in other words, it lets Mithril know what to do when it sees a `#!` in the URL.
The `"/splash"` right after `root` means that's the default route, i.e. if the hashbang in the URL doesn't point to one of the defined routes (`/splash` and `/hello`, in our case), then Mithril redirects to the default route. So if you open the page in a browser and your URL is `http://localhost`, then you get redirected to `http://localhost/#!/splash`.
Also, as you would expect, clicking on the link on the splash page takes you to the click counter screen we created earlier. Notice that now your URL will point to `http://localhost/#!/hello`. You can navigate back and forth to the splash page using the browser's back and next button.
---
### XHR
Basically, XHR is just a way to talk to a server.
Let's change our click counter to make it save data on a server. For the server, we'll use [REM](http://rem-rest-api.herokuapp.com), a mock REST API designed for toy apps like this tutorial.
First we create a function that calls `m.request`. The `url` specifies an endpoint that represents a resource, the `method` specifies the type of action we're taking (typically the `PUT` method [upserts](https://en.wiktionary.org/wiki/upsert)), `data` is the payload that we're sending to the endpoint and `withCredentials` means to enable cookies (a requirement for the REM API to work)
```javascript
var count = 0
var increment = function() {
m.request({
method: "PUT",
url: "//rem-rest-api.herokuapp.com/api/tutorial/1",
data: {count: count + 1},
withCredentials: true,
})
.then(function(data) {
count = parseInt(data.count)
})
}
```
Calling the increment function [upserts](https://en.wiktionary.org/wiki/upsert) an object `{count: 1}` to the `/api/tutorial/1` endpoint. This endpoint returns an object with the same `count` value that was sent to it. Notice that the `count` variable is only updated after the request completes, and it's updated with the response value from the server now.
Let's replace the event handler in the component to call the `increment` function instead of incrementing the `count` variable directly:
```javascript
var Hello = {
view: function() {
return m("main", [
m("h1", {class: "title"}, "My first app"),
m("button", {onclick: increment}, count + " clicks"),
])
}
}
```
Clicking the button should now update the count.
---
We covered how to create and update HTML, how to create components, routes for a Single Page Application, and interacted with a server via XHR.
This should be enough to get you started writing the frontend for a real application. Now that you are comfortable with the basics of the Mithril API, [be sure to check out the simple application tutorial](http://mithril.js.org/simple-application.html), which walks you through building a realistic application.

View file

@ -16,6 +16,6 @@ module.exports = function(redrawService) {
redrawService.render(root, Vnode(component)) redrawService.render(root, Vnode(component))
} }
redrawService.subscribe(root, run) redrawService.subscribe(root, run)
redrawService.redraw() run()
} }
} }

View file

@ -4,44 +4,48 @@ var coreRenderer = require("../render/render")
function throttle(callback) { function throttle(callback) {
//60fps translates to 16.6ms, round it down since setTimeout requires int //60fps translates to 16.6ms, round it down since setTimeout requires int
var time = 16 var delay = 16
var last = 0, pending = null var last = 0, pending = null
var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout
return function() { return function() {
var now = Date.now() var elapsed = Date.now() - last
if (last === 0 || now - last >= time) { if (pending === null) {
last = now
callback()
}
else if (pending === null) {
pending = timeout(function() { pending = timeout(function() {
pending = null pending = null
callback() callback()
last = Date.now() last = Date.now()
}, time - (now - last)) }, delay - elapsed)
} }
} }
} }
module.exports = function($window) {
module.exports = function($window, throttleMock) {
var renderService = coreRenderer($window) var renderService = coreRenderer($window)
renderService.setEventCallback(function(e) { renderService.setEventCallback(function(e) {
if (e.redraw !== false) redraw() if (e.redraw === false) e.redraw = undefined
else redraw()
}) })
var callbacks = [] var callbacks = []
var rendering = false
function subscribe(key, callback) { function subscribe(key, callback) {
unsubscribe(key) unsubscribe(key)
callbacks.push(key, throttle(callback)) callbacks.push(key, callback)
} }
function unsubscribe(key) { function unsubscribe(key) {
var index = callbacks.indexOf(key) var index = callbacks.indexOf(key)
if (index > -1) callbacks.splice(index, 2) if (index > -1) callbacks.splice(index, 2)
} }
function redraw() { function sync() {
for (var i = 1; i < callbacks.length; i += 2) { if (rendering) throw new Error("Nested m.redraw.sync() call")
callbacks[i]() rendering = true
} for (var i = 1; i < callbacks.length; i+=2) try {callbacks[i]()} catch (e) {if (typeof console !== "undefined") console.error(e)}
rendering = false
} }
var redraw = (throttleMock || throttle)(sync)
redraw.sync = sync
return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render} return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render}
} }

View file

@ -11,9 +11,14 @@ module.exports = function($window, redrawService) {
var render, component, attrs, currentPath, lastUpdate var render, component, attrs, currentPath, lastUpdate
var route = function(root, defaultRoute, routes) { var route = function(root, defaultRoute, routes) {
if (root == null) throw new Error("Ensure the DOM element that was passed to `m.route` is not undefined") if (root == null) throw new Error("Ensure the DOM element that was passed to `m.route` is not undefined")
var run = function() { function run() {
if (render != null) redrawService.render(root, render(Vnode(component, attrs.key, attrs))) if (render != null) redrawService.render(root, render(Vnode(component, attrs.key, attrs)))
} }
var redraw = function() {
run()
redraw = redrawService.redraw
}
redrawService.subscribe(root, run)
var bail = function(path) { var bail = function(path) {
if (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true}) if (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true})
else throw new Error("Could not resolve default route " + defaultRoute) else throw new Error("Could not resolve default route " + defaultRoute)
@ -24,7 +29,7 @@ module.exports = function($window, redrawService) {
component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div" component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div"
attrs = params, currentPath = path, lastUpdate = null attrs = params, currentPath = path, lastUpdate = null
render = (routeResolver.render || identity).bind(routeResolver) render = (routeResolver.render || identity).bind(routeResolver)
run() redraw()
} }
if (payload.view || typeof payload === "function") update({}, payload) if (payload.view || typeof payload === "function") update({}, payload)
else { else {
@ -36,16 +41,18 @@ module.exports = function($window, redrawService) {
else update(payload, "div") else update(payload, "div")
} }
}, bail) }, bail)
redrawService.subscribe(root, run)
} }
route.set = function(path, data, options) { route.set = function(path, data, options) {
if (lastUpdate != null) options = {replace: true} if (lastUpdate != null) {
options = options || {}
options.replace = true
}
lastUpdate = null lastUpdate = null
routeService.setPath(path, data, options) routeService.setPath(path, data, options)
} }
route.get = function() {return currentPath} route.get = function() {return currentPath}
route.prefix = function(prefix) {routeService.prefix = prefix} route.prefix = function(prefix) {routeService.prefix = prefix}
route.link = function(vnode) { var link = function(options, vnode) {
vnode.dom.setAttribute("href", routeService.prefix + vnode.attrs.href) vnode.dom.setAttribute("href", routeService.prefix + vnode.attrs.href)
vnode.dom.onclick = function(e) { vnode.dom.onclick = function(e) {
if (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return if (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return
@ -53,9 +60,13 @@ module.exports = function($window, redrawService) {
e.redraw = false e.redraw = false
var href = this.getAttribute("href") var href = this.getAttribute("href")
if (href.indexOf(routeService.prefix) === 0) href = href.slice(routeService.prefix.length) if (href.indexOf(routeService.prefix) === 0) href = href.slice(routeService.prefix.length)
route.set(href, undefined, undefined) route.set(href, undefined, options)
} }
} }
route.link = function(args) {
if (args.tag == null) return link.bind(link, args)
return link({}, args)
}
route.param = function(key) { route.param = function(key) {
if(typeof attrs !== "undefined" && typeof key !== "undefined") return attrs[key] if(typeof attrs !== "undefined" && typeof key !== "undefined") return attrs[key]
return attrs return attrs

View file

@ -13,8 +13,8 @@
<script src="../../test-utils/pushStateMock.js"></script> <script src="../../test-utils/pushStateMock.js"></script>
<script src="../../test-utils/xhrMock.js"></script> <script src="../../test-utils/xhrMock.js"></script>
<script src="../../test-utils/browserMock.js"></script> <script src="../../test-utils/browserMock.js"></script>
<script src="../../test-utils/component.js"></script> <script src="../../test-utils/components.js"></script>
<script src="../../test-utils/throttleMock.js"></script>
<script src="../../promise/promise.js"></script> <script src="../../promise/promise.js"></script>
<script src="../../render/vnode.js"></script> <script src="../../render/vnode.js"></script>
<script src="../../render/trust.js"></script> <script src="../../render/trust.js"></script>
@ -28,7 +28,6 @@
<script src="../../api/redraw.js"></script> <script src="../../api/redraw.js"></script>
<script src="../../api/mount.js"></script> <script src="../../api/mount.js"></script>
<script src="../../api/router.js"></script> <script src="../../api/router.js"></script>
<script src="./test-redraw.js"></script> <script src="./test-redraw.js"></script>
<script src="./test-mount.js"></script> <script src="./test-mount.js"></script>
<script src="./test-router.js"></script> <script src="./test-router.js"></script>

View file

@ -3,24 +3,27 @@
var o = require("../../ospec/ospec") var o = require("../../ospec/ospec")
var components = require("../../test-utils/components") var components = require("../../test-utils/components")
var domMock = require("../../test-utils/domMock") var domMock = require("../../test-utils/domMock")
var throttleMocker = require("../../test-utils/throttleMock")
var m = require("../../render/hyperscript") var m = require("../../render/hyperscript")
var coreRenderer = require("../../render/render")
var apiRedraw = require("../../api/redraw") var apiRedraw = require("../../api/redraw")
var apiMounter = require("../../api/mount") var apiMounter = require("../../api/mount")
o.spec("mount", function() { o.spec("mount", function() {
var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, mount, render, throttleMock
var $window, root, redrawService, mount, render
o.beforeEach(function() { o.beforeEach(function() {
$window = domMock() $window = domMock()
throttleMock = throttleMocker()
root = $window.document.body root = $window.document.body
redrawService = apiRedraw($window, throttleMock.throttle)
redrawService = apiRedraw($window)
mount = apiMounter(redrawService) mount = apiMounter(redrawService)
render = coreRenderer($window).render render = redrawService.render
})
o.afterEach(function() {
o(throttleMock.queueLength()).equals(0)
}) })
o("throws on invalid component", function() { o("throws on invalid component", function() {
@ -47,7 +50,7 @@ o.spec("mount", function() {
o(threw).equals(true) o(threw).equals(true)
}) })
o("renders into `root`", function() { o("renders into `root` synchronoulsy", function() {
mount(root, createComponent({ mount(root, createComponent({
view : function() { view : function() {
return m("div") return m("div")
@ -69,7 +72,37 @@ o.spec("mount", function() {
o(root.childNodes.length).equals(0) o(root.childNodes.length).equals(0)
}) })
o("redraws on events", function(done) { o("Mounting a second root doesn't cause the first one to redraw", function() {
var view = o.spy(function() {
return m("div")
})
render(root, [
m("#child0"),
m("#child1")
])
mount(root.childNodes[0], createComponent({
view : view
}))
o(root.firstChild.nodeName).equals("DIV")
o(view.callCount).equals(1)
mount(root.childNodes[1], createComponent({
view : function() {
return m("div")
}
}))
o(view.callCount).equals(1)
throttleMock.fire()
o(view.callCount).equals(1)
})
o("redraws on events", function() {
var onupdate = o.spy() var onupdate = o.spy()
var oninit = o.spy() var oninit = o.spy()
var onclick = o.spy() var onclick = o.spy()
@ -97,17 +130,12 @@ o.spec("mount", function() {
o(onclick.args[0].type).equals("click") o(onclick.args[0].type).equals("click")
o(onclick.args[0].target).equals(root.firstChild) o(onclick.args[0].target).equals(root.firstChild)
// Wrapped to give time for the rate-limited redraw to fire throttleMock.fire()
setTimeout(function() {
o(onupdate.callCount).equals(1)
done() o(onupdate.callCount).equals(1)
}, FRAME_BUDGET)
}) })
o("redraws several mount points on events", function(done, timeout) { o("redraws several mount points on events", function() {
timeout(60)
var onupdate0 = o.spy() var onupdate0 = o.spy()
var oninit0 = o.spy() var oninit0 = o.spy()
var onclick0 = o.spy() var onclick0 = o.spy()
@ -154,26 +182,26 @@ o.spec("mount", function() {
o(onclick0.callCount).equals(1) o(onclick0.callCount).equals(1)
o(onclick0.this).equals(root.childNodes[0].firstChild) o(onclick0.this).equals(root.childNodes[0].firstChild)
setTimeout(function() { throttleMock.fire()
o(onupdate0.callCount).equals(1)
o(onupdate1.callCount).equals(1)
root.childNodes[1].firstChild.dispatchEvent(e) o(onupdate0.callCount).equals(1)
o(onclick1.callCount).equals(1) o(onupdate1.callCount).equals(1)
o(onclick1.this).equals(root.childNodes[1].firstChild)
setTimeout(function() { root.childNodes[1].firstChild.dispatchEvent(e)
o(onupdate0.callCount).equals(2)
o(onupdate1.callCount).equals(2)
done() o(onclick1.callCount).equals(1)
}, FRAME_BUDGET) o(onclick1.this).equals(root.childNodes[1].firstChild)
}, FRAME_BUDGET)
throttleMock.fire()
o(onupdate0.callCount).equals(2)
o(onupdate1.callCount).equals(2)
}) })
o("event handlers can skip redraw", function(done) { o("event handlers can skip redraw", function() {
var onupdate = o.spy() var onupdate = o.spy(function(){
throw new Error("This shouldn't have been called")
})
var oninit = o.spy() var oninit = o.spy()
var e = $window.document.createEvent("MouseEvents") var e = $window.document.createEvent("MouseEvents")
@ -195,15 +223,12 @@ o.spec("mount", function() {
o(oninit.callCount).equals(1) o(oninit.callCount).equals(1)
// Wrapped to ensure no redraw fired throttleMock.fire()
setTimeout(function() {
o(onupdate.callCount).equals(0)
done() o(onupdate.callCount).equals(0)
}, FRAME_BUDGET)
}) })
o("redraws when the render function is run", function(done) { o("redraws when the render function is run", function() {
var onupdate = o.spy() var onupdate = o.spy()
var oninit = o.spy() var oninit = o.spy()
@ -221,17 +246,12 @@ o.spec("mount", function() {
redrawService.redraw() redrawService.redraw()
// Wrapped to give time for the rate-limited redraw to fire throttleMock.fire()
setTimeout(function() {
o(onupdate.callCount).equals(1)
done() o(onupdate.callCount).equals(1)
}, FRAME_BUDGET)
}) })
o("throttles", function(done, timeout) { o("throttles", function() {
timeout(200)
var i = 0 var i = 0
mount(root, createComponent({view: function() {i++}})) mount(root, createComponent({view: function() {i++}}))
var before = i var before = i
@ -243,12 +263,11 @@ o.spec("mount", function() {
var after = i var after = i
setTimeout(function(){ throttleMock.fire()
o(before).equals(1) // mounts synchronously
o(after).equals(1) // throttles rest o(before).equals(1) // mounts synchronously
o(i).equals(2) o(after).equals(1) // throttles rest
done() o(i).equals(2)
},40)
}) })
}) })
}) })

View file

@ -2,6 +2,7 @@
var o = require("../../ospec/ospec") var o = require("../../ospec/ospec")
var domMock = require("../../test-utils/domMock") var domMock = require("../../test-utils/domMock")
var throttleMocker = require("../../test-utils/throttleMock")
var apiRedraw = require("../../api/redraw") var apiRedraw = require("../../api/redraw")
o.spec("redrawService", function() { o.spec("redrawService", function() {
@ -17,7 +18,9 @@ o.spec("redrawService", function() {
redrawService.redraw() redrawService.redraw()
}) })
o("should run a single renderer entry", function(done) { o("honours throttleMock", function() {
var throttleMock = throttleMocker()
redrawService = apiRedraw(domMock(), throttleMock.throttle)
var spy = o.spy() var spy = o.spy()
redrawService.subscribe(root, spy) redrawService.subscribe(root, spy)
@ -26,15 +29,27 @@ o.spec("redrawService", function() {
redrawService.redraw() redrawService.redraw()
o(spy.callCount).equals(0)
throttleMock.fire()
o(spy.callCount).equals(1) o(spy.callCount).equals(1)
})
o("should run a single renderer entry", function(done) {
var spy = o.spy()
redrawService.subscribe(root, spy)
o(spy.callCount).equals(0)
redrawService.redraw() redrawService.redraw()
redrawService.redraw() redrawService.redraw()
redrawService.redraw() redrawService.redraw()
o(spy.callCount).equals(1) o(spy.callCount).equals(0)
setTimeout(function() { setTimeout(function() {
o(spy.callCount).equals(2) o(spy.callCount).equals(1)
done() done()
}, 20) }, 20)
@ -54,27 +69,29 @@ o.spec("redrawService", function() {
redrawService.redraw() redrawService.redraw()
o(spy1.callCount).equals(1) o(spy1.callCount).equals(0)
o(spy2.callCount).equals(1) o(spy2.callCount).equals(0)
o(spy3.callCount).equals(1) o(spy3.callCount).equals(0)
redrawService.redraw() redrawService.redraw()
o(spy1.callCount).equals(1) o(spy1.callCount).equals(0)
o(spy2.callCount).equals(1) o(spy2.callCount).equals(0)
o(spy3.callCount).equals(1) o(spy3.callCount).equals(0)
setTimeout(function() { setTimeout(function() {
o(spy1.callCount).equals(2) o(spy1.callCount).equals(1)
o(spy2.callCount).equals(2) o(spy2.callCount).equals(1)
o(spy3.callCount).equals(2) o(spy3.callCount).equals(1)
done() done()
}, 20) }, 20)
}) })
o("should stop running after unsubscribe", function() { o("should stop running after unsubscribe", function(done) {
var spy = o.spy() var spy = o.spy(function() {
throw new Error("This shouldn't have been called")
})
redrawService.subscribe(root, spy) redrawService.subscribe(root, spy)
redrawService.unsubscribe(root, spy) redrawService.unsubscribe(root, spy)
@ -82,9 +99,33 @@ o.spec("redrawService", function() {
redrawService.redraw() redrawService.redraw()
o(spy.callCount).equals(0) o(spy.callCount).equals(0)
setTimeout(function() {
o(spy.callCount).equals(0)
done()
}, 20)
}) })
o("does nothing on invalid unsubscribe", function() { o("should stop running after unsubscribe, even if it occurs after redraw is requested", function(done) {
var spy = o.spy(function() {
throw new Error("This shouldn't have been called")
})
redrawService.subscribe(root, spy)
redrawService.redraw()
redrawService.unsubscribe(root, spy)
o(spy.callCount).equals(0)
setTimeout(function() {
o(spy.callCount).equals(0)
done()
}, 20)
})
o("does nothing on invalid unsubscribe", function(done) {
var spy = o.spy() var spy = o.spy()
redrawService.subscribe(root, spy) redrawService.subscribe(root, spy)
@ -92,6 +133,39 @@ o.spec("redrawService", function() {
redrawService.redraw() redrawService.redraw()
o(spy.callCount).equals(1) setTimeout(function() {
o(spy.callCount).equals(1)
done()
}, 20)
})
o("redraw.sync() redraws all roots synchronously", function() {
var el1 = $document.createElement("div")
var el2 = $document.createElement("div")
var el3 = $document.createElement("div")
var spy1 = o.spy()
var spy2 = o.spy()
var spy3 = o.spy()
redrawService.subscribe(el1, spy1)
redrawService.subscribe(el2, spy2)
redrawService.subscribe(el3, spy3)
o(spy1.callCount).equals(0)
o(spy2.callCount).equals(0)
o(spy3.callCount).equals(0)
redrawService.redraw.sync()
o(spy1.callCount).equals(1)
o(spy2.callCount).equals(1)
o(spy3.callCount).equals(1)
redrawService.redraw.sync()
o(spy1.callCount).equals(2)
o(spy2.callCount).equals(2)
o(spy3.callCount).equals(2)
}) })
}) })

View file

@ -3,6 +3,7 @@
var o = require("../../ospec/ospec") var o = require("../../ospec/ospec")
var callAsync = require("../../test-utils/callAsync") var callAsync = require("../../test-utils/callAsync")
var browserMock = require("../../test-utils/browserMock") var browserMock = require("../../test-utils/browserMock")
var throttleMocker = require("../../test-utils/throttleMock")
var m = require("../../render/hyperscript") var m = require("../../render/hyperscript")
var callAsync = require("../../test-utils/callAsync") var callAsync = require("../../test-utils/callAsync")
@ -14,19 +15,23 @@ o.spec("route", function() {
void [{protocol: "http:", hostname: "localhost"}, {protocol: "file:", hostname: "/"}].forEach(function(env) { void [{protocol: "http:", hostname: "localhost"}, {protocol: "file:", hostname: "/"}].forEach(function(env) {
void ["#", "?", "", "#!", "?!", "/foo"].forEach(function(prefix) { void ["#", "?", "", "#!", "?!", "/foo"].forEach(function(prefix) {
o.spec("using prefix `" + prefix + "` starting on " + env.protocol + "//" + env.hostname, function() { o.spec("using prefix `" + prefix + "` starting on " + env.protocol + "//" + env.hostname, function() {
var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, route, throttleMock
var $window, root, redrawService, route
o.beforeEach(function() { o.beforeEach(function() {
$window = browserMock(env) $window = browserMock(env)
throttleMock = throttleMocker()
root = $window.document.body root = $window.document.body
redrawService = apiRedraw($window) redrawService = apiRedraw($window, throttleMock.throttle)
route = apiRouter($window, redrawService) route = apiRouter($window, redrawService)
route.prefix(prefix) route.prefix(prefix)
}) })
o.afterEach(function() {
o(throttleMock.queueLength()).equals(0)
})
o("throws on invalid `root` DOM node", function() { o("throws on invalid `root` DOM node", function() {
var threw = false var threw = false
try { try {
@ -50,7 +55,7 @@ o.spec("route", function() {
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
}) })
o("routed mount points can redraw synchronously (POJO component)", function() { o("routed mount points only redraw asynchronously (POJO component)", function() {
var view = o.spy() var view = o.spy()
$window.location.href = prefix + "/" $window.location.href = prefix + "/"
@ -60,11 +65,14 @@ o.spec("route", function() {
redrawService.redraw() redrawService.redraw()
o(view.callCount).equals(2) o(view.callCount).equals(1)
throttleMock.fire()
o(view.callCount).equals(2)
}) })
o("routed mount points can redraw synchronously (constructible component)", function() { o("routed mount points only redraw asynchronously (constructible component)", function() {
var view = o.spy() var view = o.spy()
var Cmp = function(){} var Cmp = function(){}
@ -77,11 +85,14 @@ o.spec("route", function() {
redrawService.redraw() redrawService.redraw()
o(view.callCount).equals(2) o(view.callCount).equals(1)
throttleMock.fire()
o(view.callCount).equals(2)
}) })
o("routed mount points can redraw synchronously (closure component)", function() { o("routed mount points only redraw asynchronously (closure component)", function() {
var view = o.spy() var view = o.spy()
function Cmp() {return {view: view}} function Cmp() {return {view: view}}
@ -93,8 +104,11 @@ o.spec("route", function() {
redrawService.redraw() redrawService.redraw()
o(view.callCount).equals(2) o(view.callCount).equals(1)
throttleMock.fire()
o(view.callCount).equals(2)
}) })
o("default route doesn't break back button", function(done) { o("default route doesn't break back button", function(done) {
@ -160,11 +174,12 @@ o.spec("route", function() {
o(oninit.callCount).equals(1) o(oninit.callCount).equals(1)
redrawService.redraw() redrawService.redraw()
throttleMock.fire()
o(onupdate.callCount).equals(1) o(onupdate.callCount).equals(1)
}) })
o("redraws on events", function(done) { o("redraws on events", function() {
var onupdate = o.spy() var onupdate = o.spy()
var oninit = o.spy() var oninit = o.spy()
var onclick = o.spy() var onclick = o.spy()
@ -194,12 +209,9 @@ o.spec("route", function() {
o(onclick.args[0].type).equals("click") o(onclick.args[0].type).equals("click")
o(onclick.args[0].target).equals(root.firstChild) o(onclick.args[0].target).equals(root.firstChild)
// Wrapped to give time for the rate-limited redraw to fire
callAsync(function() {
o(onupdate.callCount).equals(1)
done() throttleMock.fire()
}) o(onupdate.callCount).equals(1)
}) })
o("event handlers can skip redraw", function(done) { o("event handlers can skip redraw", function(done) {
@ -224,9 +236,11 @@ o.spec("route", function() {
} }
}) })
o(oninit.callCount).equals(1)
root.firstChild.dispatchEvent(e) root.firstChild.dispatchEvent(e)
o(oninit.callCount).equals(1) o(e.redraw).notEquals(false)
// Wrapped to ensure no redraw fired // Wrapped to ensure no redraw fired
callAsync(function() { callAsync(function() {
@ -267,6 +281,36 @@ o.spec("route", function() {
o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test") o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test")
}) })
o("passes options on route.link", function() {
var opts = {}
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
$window.location.href = prefix + "/"
route(root, "/", {
"/" : {
view: function() {
return m("a", {
href: "/test",
oncreate: route.link(opts)
})
}
},
"/test" : {
view : function() {
return m("div")
}
}
})
route.set = o.spy(route.set)
root.firstChild.dispatchEvent(e)
o(route.set.callCount).equals(1)
o(route.set.args[2]).equals(opts)
})
o("accepts RouteResolver with onmatch that returns Component", function(done) { o("accepts RouteResolver with onmatch that returns Component", function(done) {
var matchCount = 0 var matchCount = 0
var renderCount = 0 var renderCount = 0
@ -500,7 +544,10 @@ o.spec("route", function() {
o(oninit.callCount).equals(1) o(oninit.callCount).equals(1)
route.set("/def") route.set("/def")
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(oninit.callCount).equals(2) o(oninit.callCount).equals(2)
done() done()
}) })
}) })
@ -536,23 +583,28 @@ o.spec("route", function() {
route(root, "/a", { route(root, "/a", {
"/a" : { "/a" : {
render: function() { render: function() {
return m("div") return m("div", m("p"))
}, },
}, },
"/b" : { "/b" : {
render: function() { render: function() {
return m("div") return m("div", m("a"))
}, },
}, },
}) })
var dom = root.firstChild var dom = root.firstChild
var child = dom.firstChild
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
route.set("/b") route.set("/b")
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(root.firstChild).equals(dom) o(root.firstChild).equals(dom)
o(root.firstChild.firstChild).notEquals(child)
done() done()
}) })
@ -586,6 +638,7 @@ o.spec("route", function() {
o(renderCount).equals(1) o(renderCount).equals(1)
redrawService.redraw() redrawService.redraw()
throttleMock.fire()
o(matchCount).equals(1) o(matchCount).equals(1)
o(renderCount).equals(2) o(renderCount).equals(2)
@ -621,6 +674,7 @@ o.spec("route", function() {
o(renderCount).equals(1) o(renderCount).equals(1)
redrawService.redraw() redrawService.redraw()
throttleMock.fire()
o(matchCount).equals(1) o(matchCount).equals(1)
o(renderCount).equals(2) o(renderCount).equals(2)
@ -665,7 +719,7 @@ o.spec("route", function() {
route(root, "/a", { route(root, "/a", {
"/a" : { "/a" : {
onmatch: function() { onmatch: function() {
route.set("/b") route.set("/b", {}, {state: {a: 5}})
}, },
render: render render: render
}, },
@ -684,6 +738,7 @@ o.spec("route", function() {
o(view.callCount).equals(1) o(view.callCount).equals(1)
o(root.childNodes.length).equals(1) o(root.childNodes.length).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o($window.history.state).deepEquals({a: 5})
done() done()
}) })
@ -815,10 +870,14 @@ o.spec("route", function() {
}) })
callAsync(function() { callAsync(function() {
throttleMock.fire()
route.set("/b") route.set("/b")
callAsync(function() { callAsync(function() {
callAsync(function() { callAsync(function() {
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(render.callCount).equals(0) o(render.callCount).equals(0)
o(component.view.callCount).equals(2) o(component.view.callCount).equals(2)
@ -939,6 +998,7 @@ o.spec("route", function() {
o(onmatch.callCount).equals(1) o(onmatch.callCount).equals(1)
redrawService.redraw() redrawService.redraw()
throttleMock.fire()
o(view.callCount).equals(2) o(view.callCount).equals(2)
o(onmatch.callCount).equals(1) o(onmatch.callCount).equals(1)
@ -1017,6 +1077,8 @@ o.spec("route", function() {
}) })
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(onmatch.callCount).equals(1) o(onmatch.callCount).equals(1)
o(render.callCount).equals(1) o(render.callCount).equals(1)
@ -1024,6 +1086,8 @@ o.spec("route", function() {
callAsync(function() { callAsync(function() {
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(onmatch.callCount).equals(2) o(onmatch.callCount).equals(2)
o(render.callCount).equals(2) o(render.callCount).equals(2)
@ -1074,9 +1138,15 @@ o.spec("route", function() {
route.set("/b") route.set("/b")
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(root.firstChild.nodeName).equals("B")
route.set("/a") route.set("/a")
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(root.firstChild.nodeName).equals("A") o(root.firstChild.nodeName).equals("A")
done() done()
@ -1141,7 +1211,9 @@ o.spec("route", function() {
route.set("/b") route.set("/b")
// setting the route is asynchronous
callAsync(function() { callAsync(function() {
throttleMock.fire()
o(spy.callCount).equals(1) o(spy.callCount).equals(1)
done() done()
@ -1181,9 +1253,7 @@ o.spec("route", function() {
}) })
}) })
o("throttles", function(done, timeout) { o("throttles", function() {
timeout(200)
var i = 0 var i = 0
$window.location.href = prefix + "/" $window.location.href = prefix + "/"
route(root, "/", { route(root, "/", {
@ -1197,12 +1267,11 @@ o.spec("route", function() {
redrawService.redraw() redrawService.redraw()
var after = i var after = i
setTimeout(function() { throttleMock.fire()
o(before).equals(1) // routes synchronously
o(after).equals(2) // redraws synchronously o(before).equals(1) // routes synchronously
o(i).equals(3) // throttles rest o(after).equals(1) // redraws asynchronously
done() o(i).equals(2)
}, FRAME_BUDGET * 2)
}) })
o("m.route.param is available outside of route handlers", function(done) { o("m.route.param is available outside of route handlers", function(done) {

View file

@ -5,7 +5,7 @@ var fs = require("fs");
var bundle = require("./bundle") var bundle = require("./bundle")
var minify = require("./minify") var minify = require("./minify")
var aliases = {o: "output", m: "minify", w: "watch", a: "aggressive"} var aliases = {o: "output", m: "minify", w: "watch", a: "aggressive", s: "save"}
var params = {} var params = {}
var args = process.argv.slice(2), command = null var args = process.argv.slice(2), command = null
for (var i = 0; i < args.length; i++) { for (var i = 0; i < args.length; i++) {
@ -27,8 +27,6 @@ function add(value) {
bundle(params.input, params.output, {watch: params.watch}) bundle(params.input, params.output, {watch: params.watch})
if (params.minify) { if (params.minify) {
minify(params.output, params.output, {watch: params.watch, advanced: params.aggressive}, function(stats) { minify(params.output, params.output, {watch: params.watch, advanced: params.aggressive}, function(stats) {
var readme, kb;
function format(n) { function format(n) {
return n.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") return n.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
} }
@ -36,14 +34,16 @@ if (params.minify) {
console.log("Original size: " + format(stats.originalGzipSize) + " bytes gzipped (" + format(stats.originalSize) + " bytes uncompressed)") console.log("Original size: " + format(stats.originalGzipSize) + " bytes gzipped (" + format(stats.originalSize) + " bytes uncompressed)")
console.log("Compiled size: " + format(stats.compressedGzipSize) + " bytes gzipped (" + format(stats.compressedSize) + " bytes uncompressed)") console.log("Compiled size: " + format(stats.compressedGzipSize) + " bytes gzipped (" + format(stats.compressedSize) + " bytes uncompressed)")
readme = fs.readFileSync("./README.md", "utf8") if (params.save) {
kb = stats.compressedGzipSize / 1024 var readme = fs.readFileSync("./README.md", "utf8")
var kb = stats.compressedGzipSize / 1000
fs.writeFileSync("./README.md", fs.writeFileSync("./README.md",
readme.replace( readme.replace(
/(<!-- size -->)(.+?)(<!-- \/size -->)/, /(<!-- size -->)(.+?)(<!-- \/size -->)/,
"$1" + (kb % 1 ? kb.toFixed(2) : kb) + " KB$3" "$1" + (kb % 1 ? kb.toFixed(2) : kb) + " KB$3"
)
) )
) }
}) })
} }

View file

@ -1,6 +1,6 @@
"use strict" "use strict"
var http = require("http") var http = require("https")
var querystring = require("querystring") var querystring = require("querystring")
var fs = require("fs") var fs = require("fs")
@ -22,7 +22,6 @@ module.exports = function(input, output, options, done) {
var response = "" var response = ""
var req = http.request({ var req = http.request({
method: "POST", method: "POST",
protocol: "http:",
hostname: "closure-compiler.appspot.com", hostname: "closure-compiler.appspot.com",
path: "/compile", path: "/compile",
headers: { headers: {
@ -33,8 +32,16 @@ module.exports = function(input, output, options, done) {
res.on("data", function(chunk) { res.on("data", function(chunk) {
response += chunk.toString() response += chunk.toString()
}) })
res.on("end", function() { res.on("end", function() {
var results = JSON.parse(response) try {
var results = JSON.parse(response)
} catch(e) {
console.error(response);
throw e;
}
if (results.errors) { if (results.errors) {
for (var i = 0; i < results.errors.length; i++) console.log(results.errors[i]) for (var i = 0; i < results.errors.length; i++) console.log(results.errors[i])
} }

View file

@ -5,7 +5,7 @@ var bundle = require("../bundle")
var fs = require("fs") var fs = require("fs")
var ns = "bundler/tests/" var ns = "./"
function read(filepath) { function read(filepath) {
try {return fs.readFileSync(ns + filepath, "utf8")} catch (e) {/* ignore */} try {return fs.readFileSync(ns + filepath, "utf8")} catch (e) {/* ignore */}
} }

60
dangerfile.js Normal file
View file

@ -0,0 +1,60 @@
/* global danger warn fail */
"use strict";
var fs = require("fs"),
path = require("path"),
locater = require("locater"),
pinpoint = require("pinpoint"),
dedent = require("dedent");
// Various views of changed/added files
var jsfiles = danger.git.created_files
.concat(danger.git.modified_files)
.filter((file) => path.extname(file) === ".js"),
changelog = danger.git.modified_files.find((file) =>
file === "docs/change-log.md"
),
appfiles = jsfiles.filter((file) =>
file.indexOf("tests/") === -1
);
function link(file, anchor, text) {
var repo = danger.github.pr.head.repo.html_url,
ref = danger.github.pr.head.ref;
return danger.utils.href(`${repo}/blob/${ref}/${file}${anchor || ""}`, file || text);
}
// All PRs should be targeted against `next`
if(danger.github.pr.base.ref !== "next") {
warn("PRs should be based on `next`, rebase before submitting please");
}
// Any non-test JS changes should probably have a change-log entry
if(appfiles.length && !changelog) {
warn(dedent(`
Please add an entry to ${link("docs/change-log.md")}.
`))
}
// Call out if `o.only(...)` was left in
jsfiles
.filter((file) => file.indexOf("tests/") > -1)
// Have to exclude test-ospec.js because it specifically has a purposeful "o.only" in it
.filter((file) => file.indexOf("test-ospec") === -1)
.forEach((file) => {
var code = fs.readFileSync(file, "utf8"),
locs = locater.find("o.only", code);
locs.forEach((loc) =>
fail(dedent(`
Please remove the \`o.only\` from ${link(file, `#L${loc.line}`)}.
<pre lang="javascript">
${pinpoint(code, {line: loc.line, column : loc.cursor})}
</pre>
`))
)
});

View file

@ -102,4 +102,4 @@ Note that the `onbeforeremove` hook only fires on the element that loses its `pa
When creating animations, it's recommended that you only use the `opacity` and `transform` CSS rules, since these can be hardware-accelerated by modern browsers and yield better performance than animating `top`, `left`, `width`, and `height`. When creating animations, it's recommended that you only use the `opacity` and `transform` CSS rules, since these can be hardware-accelerated by modern browsers and yield better performance than animating `top`, `left`, `width`, and `height`.
It's also recommended that you avoid the `box-shadow` rule and selectors like `:nth-child`, since these are also resource intensive options. If you want to animate a `box-shadow`, consider [putting the `box-shadow` rule on a pseudo element, and animate that element's opacity instead](http://tobiasahlin.com/blog/how-to-animate-box-shadow/). Other things that can be expensive include large or dynamically scaled images and overlapping elements with different `position` values (e.g. an absolute postioned element over a fixed element). It's also recommended that you avoid the `box-shadow` rule and selectors like `:nth-child`, since these are also resource intensive options. If you want to animate a `box-shadow`, consider [putting the `box-shadow` rule on a pseudo element, and animate that element's opacity instead](http://tobiasahlin.com/blog/how-to-animate-box-shadow/). Other things that can be expensive include large or dynamically scaled images and overlapping elements with different `position` values (e.g. an absolute positioned element over a fixed element).

View file

@ -1,5 +1,11 @@
# Change log # Change log
- [v2.0.0](#v200-wip)
- [v1.1.6](#v116)
- [v1.1.5](#v115)
- [v1.1.4](#v114)
- [v1.1.3](#v113)
- [v1.1.2](#v112)
- [v1.1.1](#v111) - [v1.1.1](#v111)
- [v1.1.0](#v110) - [v1.1.0](#v110)
- [v1.0.1](#v101) - [v1.0.1](#v101)
@ -8,14 +14,137 @@
--- ---
### v2.0.0 (WIP)
#### Breaking changes
- API: `m.redraw()` is always asynchronous ([#1592](https://github.com/MithrilJS/mithril.js/pull/1592))
- API: `m.mount()` will only render its own root when called, it will not trigger a `redraw()` ([#1592](https://github.com/MithrilJS/mithril.js/pull/1592))
- API: Assigning to `vnode.state` (as in `vnode.state = ...`) is no longer supported. Instead, an error is thrown if `vnode.state` changes upon the invocation of a lifecycle hook.
- API: `m.request` will no longer reject the Promise on server errors (eg. status >= 400) if the caller supplies an `extract` callback. This gives applications more control over handling server responses.
#### News
- API: Introduction of `m.redraw.sync()` ([#1592](https://github.com/MithrilJS/mithril.js/pull/1592))
- API: Event handlers may also be objects with `handleEvent` methods ([#1939](https://github.com/MithrilJS/mithril.js/issues/1939)).
- API: `m.route.link` accepts an optional `options` object ([#1930](https://github.com/MithrilJS/mithril.js/pull/1930))
- API: `m.request` supports `timeout` as attr - ([#1966](https://github.com/MithrilJS/mithril.js/pull/1966))
- Mocks: add limited support for the DOMParser API ([#2097](https://github.com/MithrilJS/mithril.js/pull/2097))
- API: add support for raw SVG in `m.trust()` string ([#2097](https://github.com/MithrilJS/mithril.js/pull/2097))
- Internals: remove the DOM nodes recycling pool ([#2122](https://github.com/MithrilJS/mithril.js/pull/2122))
#### Bug fixes
- API: `m.route.set()` causes all mount points to be redrawn ([#1592](https://github.com/MithrilJS/mithril.js/pull/1592))
- render/attrs: Using style objects in hyperscript calls will now properly diff style properties from one render to another as opposed to re-writing all element style properties every render.
- render/attrs: `xlink:href` attributes are now correctly removed
- render/attrs: fix element value don't change if new value is undefined [#2082](https://github.com/MithrilJS/mithril.js/issues/2082)
(https://github.com/MithrilJS/mithril.js/pull/2130)
- render/core: Render state correctly on select change event [#1916](https://github.com/MithrilJS/mithril.js/issues/1916) ([#1918](https://github.com/MithrilJS/mithril.js/pull/1918) [@robinchew](https://github.com/robinchew), [#2052](https://github.com/MithrilJS/mithril.js/pull/2052))
- render/core: fix various updateNodes/removeNodes issues when the pool and fragments are involved [#1990](https://github.com/MithrilJS/mithril.js/issues/1990), [#1991](https://github.com/MithrilJS/mithril.js/issues/1991), [#2003](https://github.com/MithrilJS/mithril.js/issues/2003), [#2021](https://github.com/MithrilJS/mithril.js/pull/2021)
- render/core: fix crashes when the keyed vnodes with the same `key` had different `tag` values [#2128](https://github.com/MithrilJS/mithril.js/issues/2128) [@JacksonJN](https://github.com/JacksonJN) ([#2130](https://github.com/MithrilJS/mithril.js/pull/2130))
- render/core: fix cached nodes behavior in some keyed diff scenarios [#2132](https://github.com/MithrilJS/mithril.js/issues/2132) ([#2130](https://github.com/MithrilJS/mithril.js/pull/2130))
- render/events: `addEventListener` and `removeEventListener` are always used to manage event subscriptions, preventing external interference.
- render/events: Event listeners allocate less memory, swap at low cost, and are properly diffed now when rendered via `m.mount()`/`m.redraw()`.
- render/events: `Object.prototype` properties can no longer interfere with event listener calls.
- render/events: Event handlers, when set to literally `undefined` (or any non-function), are now correctly removed.
- render/hooks: fixed an ommission that caused `oninit` to be called unnecessarily in some cases [#1992](https://github.com/MithrilJS/mithril.js/issues/1992)
- docs: fix typo ([#2104](https://github.com/MithrilJS/mithril.js/pull/2104) [@mikeyb](https://github.com/mikeyb))
---
### v1.1.7
- Promise polyfill implementation separated from polyfilling logic.
- `PromisePolyfill` is now available on the exported/global `m`.
---
### v1.1.6
- core: render() function can no longer prevent from changing `document.activeElement` in lifecycle hooks ([#1988](https://github.com/MithrilJS/mithril.js/pull/1988), [@purplecode](https://github.com/purplecode))
- core: don't call `onremove` on the children of components that return null from the view [#1921](https://github.com/MithrilJS/mithril.js/issues/1921) [@octavore](https://github.com/octavore) ([#1922](https://github.com/MithrilJS/mithril.js/pull/1922))
- hypertext: correct handling of shared attributes object passed to `m()`. Will copy attributes when it's necessary [#1941](https://github.com/MithrilJS/mithril.js/issues/1941) [@s-ilya](https://github.com/s-ilya) ([#1942](https://github.com/MithrilJS/mithril.js/pull/1942))
#### Ospec improvements
- ospec v1.4.0
- 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))
- ospec v2.0.0 (to be released)
- Added support for custom reporters ([#2009](https://github.com/MithrilJS/mithril.js/pull/2020))
- 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
---
### v1.1.5
- API: If a user sets the Content-Type header within a request's options, that value will be the entire header value rather than being appended to the default value ([#1924](https://github.com/MithrilJS/mithril.js/pull/1924))
---
### v1.1.4
#### Bug fixes:
- Fix IE bug where active element is null causing render function to throw error ([#1943](https://github.com/MithrilJS/mithril.js/pull/1943), [@JacksonJN](https://github.com/JacksonJN))
#### Ospec improvements:
- 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))
---
### v1.1.3
#### Bug fixes:
- move out npm dependencies added by mistake
---
### v1.1.2
#### Bug fixes:
- core: Namespace fixes [#1819](https://github.com/MithrilJS/mithril.js/issues/1819), ([#1825](https://github.com/MithrilJS/mithril.js/pull/1825) [@SamuelTilly](https://github.com/SamuelTilly)), [#1820](https://github.com/MithrilJS/mithril.js/issues/1820) ([#1864](https://github.com/MithrilJS/mithril.js/pull/1864)), [#1872](https://github.com/MithrilJS/mithril.js/issues/1872) ([#1873](https://github.com/MithrilJS/mithril.js/pull/1873))
- core: Fix select option to allow empty string value [#1814](https://github.com/MithrilJS/mithril.js/issues/1814) ([#1828](https://github.com/MithrilJS/mithril.js/pull/1828) [@spacejack](https://github.com/spacejack))
- core: Reset e.redraw when it was set to `false` [#1850](https://github.com/MithrilJS/mithril.js/issues/1850) ([#1890](https://github.com/MithrilJS/mithril.js/pull/1890))
- core: differentiate between `{ value: "" }` and `{ value: 0 }` for form elements [#1595 comment](https://github.com/MithrilJS/mithril.js/pull/1595#issuecomment-304071453) ([#1862](https://github.com/MithrilJS/mithril.js/pull/1862))
- core: Don't reset the cursor of textareas in IE10 when setting an identical `value` [#1870](https://github.com/MithrilJS/mithril.js/issues/1870) ([#1871](https://github.com/MithrilJS/mithril.js/pull/1871))
- hypertext: Correct handling of `[value=""]` ([#1843](https://github.com/MithrilJS/mithril.js/issues/1843), [@CreaturesInUnitards](https://github.com/CreaturesInUnitards))
- router: Don't overwrite the options object when redirecting from `onmatch with m.route.set()` [#1857](https://github.com/MithrilJS/mithril.js/issues/1857) ([#1889](https://github.com/MithrilJS/mithril.js/pull/1889))
- stream: Move the "use strict" directive inside the IIFE [#1831](https://github.com/MithrilJS/mithril.js/issues/1831) ([#1893](https://github.com/MithrilJS/mithril.js/pull/1893))
#### Ospec improvements:
- 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))
#### Docs / Repo maintenance:
Our thanks to [@0joshuaolson1](https://github.com/0joshuaolson1), [@ACXgit](https://github.com/ACXgit), [@cavemansspa](https://github.com/cavemansspa), [@CreaturesInUnitards](https://github.com/CreaturesInUnitards), [@dlepaux](https://github.com/dlepaux), [@isaaclyman](https://github.com/isaaclyman), [@kevinkace](https://github.com/kevinkace), [@micellius](https://github.com/micellius), [@spacejack](https://github.com/spacejack) and [@yurivish](https://github.com/yurivish)
#### Other:
- Addition of a performance regression test suite ([#1789](https://github.com/MithrilJS/mithril.js/issues/1789))
---
### v1.1.1 ### v1.1.1
#### Bug fixes #### Bug fixes
- hyperscript: Allow `0` as the second argument to `m()` - [#1752](https://github.com/lhorie/mithril.js/issues/1752) / [#1753](https://github.com/lhorie/mithril.js/pull/1753) ([@StephanHoyer](https://github.com/StephanHoyer)) - hyperscript: Allow `0` as the second argument to `m()` - [#1752](https://github.com/MithrilJS/mithril.js/issues/1752) / [#1753](https://github.com/MithrilJS/mithril.js/pull/1753) ([@StephanHoyer](https://github.com/StephanHoyer))
- hyperscript: restore `attrs.class` handling to what it was in v1.0.1 - [#1764](https://github.com/lhorie/mithril.js/issues/1764) / [#1769](https://github.com/lhorie/mithril.js/pull/1769) - hyperscript: restore `attrs.class` handling to what it was in v1.0.1 - [#1764](https://github.com/MithrilJS/mithril.js/issues/1764) / [#1769](https://github.com/MithrilJS/mithril.js/pull/1769)
- documentation improvements ([@JAForbes](https://github.com/JAForbes), [@smuemd](https://github.com/smuemd), [@hankeypancake](https://github.com/hankeypancake)) - documentation improvements ([@JAForbes](https://github.com/JAForbes), [@smuemd](https://github.com/smuemd), [@hankeypancake](https://github.com/hankeypancake))
---
### v1.1.0 ### v1.1.0
#### News #### News
@ -26,10 +155,10 @@
#### Bug fixes #### Bug fixes
- fix IE11 input[type] error - [#1610](https://github.com/lhorie/mithril.js/issues/1610) - fix IE11 input[type] error - [#1610](https://github.com/MithrilJS/mithril.js/issues/1610)
- apply [#1609](https://github.com/lhorie/mithril.js/issues/1609) to unkeyed children case - apply [#1609](https://github.com/MithrilJS/mithril.js/issues/1609) to unkeyed children case
- fix abort detection [#1612](https://github.com/lhorie/mithril.js/issues/1612) - fix abort detection [#1612](https://github.com/MithrilJS/mithril.js/issues/1612)
- fix input value focus issue when value is loosely equal to old value [#1593](https://github.com/lhorie/mithril.js/issues/1593) - fix input value focus issue when value is loosely equal to old value [#1593](https://github.com/MithrilJS/mithril.js/issues/1593)
--- ---
@ -37,12 +166,12 @@
#### News #### News
- performance improvements in IE [#1598](https://github.com/lhorie/mithril.js/pull/1598) - performance improvements in IE [#1598](https://github.com/MithrilJS/mithril.js/pull/1598)
#### Bug fixes #### Bug fixes
- prevent infinite loop in non-existent default route - [#1579](https://github.com/lhorie/mithril.js/issues/1579) - prevent infinite loop in non-existent default route - [#1579](https://github.com/MithrilJS/mithril.js/issues/1579)
- call correct lifecycle methods on children of recycled keyed vnodes - [#1609](https://github.com/lhorie/mithril.js/issues/1609) - call correct lifecycle methods on children of recycled keyed vnodes - [#1609](https://github.com/MithrilJS/mithril.js/issues/1609)
--- ---
@ -155,7 +284,7 @@ m("div", {
// Called after the node is updated // Called after the node is updated
onupdate : function(vnode) { /*...*/ }, onupdate : function(vnode) { /*...*/ },
// Called before the node is removed, return a Promise that resolves when // Called before the node is removed, return a Promise that resolves when
// ready for the node to be removed from the DOM // ready for the node to be removed from the DOM
onbeforeremove : function(vnode) { /*...*/ }, onbeforeremove : function(vnode) { /*...*/ },
// Called before the node is removed, but after onbeforeremove calls done() // Called before the node is removed, but after onbeforeremove calls done()
onremove : function(vnode) { /*...*/ } onremove : function(vnode) { /*...*/ }
@ -472,9 +601,9 @@ In `v0.2.x` reading route params was entirely handled through `m.route.param()`.
```javascript ```javascript
m.route(document.body, "/booga", { m.route(document.body, "/booga", {
"/:attr" : { "/:attr" : {
controller : function() { controller : function() {
m.route.param("attr") // "booga" m.route.param("attr") // "booga"
}, },
view : function() { view : function() {
m.route.param("attr") // "booga" m.route.param("attr") // "booga"
} }
@ -489,11 +618,11 @@ m.route(document.body, "/booga", {
"/:attr" : { "/:attr" : {
oninit : function(vnode) { oninit : function(vnode) {
vnode.attrs.attr // "booga" vnode.attrs.attr // "booga"
m.route.param("attr") // "booga" m.route.param("attr") // "booga"
}, },
view : function(vnode) { view : function(vnode) {
vnode.attrs.attr // "booga" vnode.attrs.attr // "booga"
m.route.param("attr") // "booga" m.route.param("attr") // "booga"
} }
} }
}) })
@ -531,14 +660,14 @@ It is no longer possible to prevent unmounting via `onunload`'s `e.preventDefaul
```javascript ```javascript
var Component = { var Component = {
controller: function() { controller: function() {
this.onunload = function(e) { this.onunload = function(e) {
if (condition) e.preventDefault() if (condition) e.preventDefault()
} }
}, },
view: function() { view: function() {
return m("a[href=/]", {config: m.route}) return m("a[href=/]", {config: m.route})
} }
} }
``` ```
@ -546,9 +675,9 @@ var Component = {
```javascript ```javascript
var Component = { var Component = {
view: function() { view: function() {
return m("a", {onclick: function() {if (!condition) m.route.set("/")}}) return m("a", {onclick: function() {if (!condition) m.route.set("/")}})
} }
} }
``` ```
@ -562,14 +691,14 @@ Components no longer call `this.onunload` when they are being removed. They now
```javascript ```javascript
var Component = { var Component = {
controller: function() { controller: function() {
this.onunload = function(e) { this.onunload = function(e) {
// ... // ...
} }
}, },
view: function() { view: function() {
// ... // ...
} }
} }
``` ```
@ -577,12 +706,12 @@ var Component = {
```javascript ```javascript
var Component = { var Component = {
onremove : function() { onremove : function() {
// ... // ...
} }
view: function() { view: function() {
// ... // ...
} }
} }
``` ```
@ -598,13 +727,13 @@ In addition, requests no longer have `m.startComputation`/`m.endComputation` sem
```javascript ```javascript
var data = m.request({ var data = m.request({
method: "GET", method: "GET",
url: "https://api.github.com/", url: "https://api.github.com/",
initialValue: [], initialValue: [],
}) })
setTimeout(function() { setTimeout(function() {
console.log(data()) console.log(data())
}, 1000) }, 1000)
``` ```
@ -613,15 +742,15 @@ setTimeout(function() {
```javascript ```javascript
var data = [] var data = []
m.request({ m.request({
method: "GET", method: "GET",
url: "https://api.github.com/", url: "https://api.github.com/",
}) })
.then(function (responseBody) { .then(function (responseBody) {
data = responseBody data = responseBody
}) })
setTimeout(function() { setTimeout(function() {
console.log(data) // note: not a getter-setter console.log(data) // note: not a getter-setter
}, 1000) }, 1000)
``` ```
@ -653,11 +782,11 @@ greetAsync()
```javascript ```javascript
var greetAsync = function() { var greetAsync = function() {
return new Promise(function(resolve){ return new Promise(function(resolve){
setTimeout(function() { setTimeout(function() {
resolve("hello") resolve("hello")
}, 1000) }, 1000)
}) })
} }
greetAsync() greetAsync()
@ -679,7 +808,7 @@ m.sync([
m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }), m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }),
]) ])
.then(function (users) { .then(function (users) {
console.log("Contributors:", users[0].name, "and", users[1].name) console.log("Contributors:", users[0].name, "and", users[1].name)
}) })
``` ```
@ -691,7 +820,7 @@ Promise.all([
m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }), m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }),
]) ])
.then(function (users) { .then(function (users) {
console.log("Contributors:", users[0].name, "and", users[1].name) console.log("Contributors:", users[0].name, "and", users[1].name)
}) })
``` ```
@ -706,7 +835,7 @@ In `v0.2.x`, the `xlink` namespace was the only supported attribute namespace, a
```javascript ```javascript
m("svg", m("svg",
// the `href` attribute is namespaced automatically // the `href` attribute is namespaced automatically
m("image[href='image.gif']") m("image[href='image.gif']")
) )
``` ```
@ -715,7 +844,7 @@ m("svg",
```javascript ```javascript
m("svg", m("svg",
// User-specified namespace on the `href` attribute // User-specified namespace on the `href` attribute
m("image[xlink:href='image.gif']") m("image[xlink:href='image.gif']")
) )
``` ```

74
docs/code-of-conduct.md Normal file
View file

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [github@patcavit.com](mailto:github@patcavit.com?subject=Mithril%20Code%20of%20Conduct). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View file

@ -61,6 +61,9 @@ var ComponentWithHooks = {
oncreate: function(vnode) { oncreate: function(vnode) {
console.log("DOM created") console.log("DOM created")
}, },
onbeforeupdate: function(vnode, old) {
return true
},
onupdate: function(vnode) { onupdate: function(vnode) {
console.log("DOM updated") console.log("DOM updated")
}, },
@ -74,9 +77,6 @@ var ComponentWithHooks = {
onremove: function(vnode) { onremove: function(vnode) {
console.log("removing DOM element") console.log("removing DOM element")
}, },
onbeforeupdate: function(vnode, old) {
return true
},
view: function(vnode) { view: function(vnode) {
return "hello" return "hello"
} }
@ -177,7 +177,7 @@ They can be consumed in the same way regular components can.
m.render(document.body, m(closureComponent)) m.render(document.body, m(closureComponent))
// EXAMPLE: via m.mount // EXAMPLE: via m.mount
m.mount(document.body, closuresComponent) m.mount(document.body, closureComponent)
// EXAMPLE: via m.route // EXAMPLE: via m.route
m.route(document.body, "/", { m.route(document.body, "/", {
@ -316,7 +316,7 @@ var Login = {
Normally, in the context of a larger application, a login component like the one above exists alongside components for user registration and password recovery. Imagine that we want to be able to prepopulate the email field when navigating from the login screen to the registration or password recovery screens (or vice versa), so that the user doesn't need to re-type their email if they happened to fill the wrong page (or maybe you want to bump the user to the registration form if a username is not found). Normally, in the context of a larger application, a login component like the one above exists alongside components for user registration and password recovery. Imagine that we want to be able to prepopulate the email field when navigating from the login screen to the registration or password recovery screens (or vice versa), so that the user doesn't need to re-type their email if they happened to fill the wrong page (or maybe you want to bump the user to the registration form if a username is not found).
Right away, we see that sharing the `username` and `password` fields from this component to another is difficult. This is because the fat component encapsulates its our state, which by definition makes this state difficult to access from outside. Right away, we see that sharing the `username` and `password` fields from this component to another is difficult. This is because the fat component encapsulates its state, which by definition makes this state difficult to access from outside.
It makes more sense to refactor this component and pull the state code out of the component and into the application's data layer. This can be as simple as creating a new module: It makes more sense to refactor this component and pull the state code out of the component and into the application's data layer. This can be as simple as creating a new module:

View file

@ -4,7 +4,7 @@
## How do I go about contributing ideas or new features? ## How do I go about contributing ideas or new features?
Create an [issue thread on Github](https://github.com/lhorie/mithril.js/issues/new) to suggest your idea so the community can discuss it. Create an [issue thread on GitHub](https://github.com/MithrilJS/mithril.js/issues/new) to suggest your idea so the community can discuss it.
If the consensus is that it's a good idea, the fastest way to get it into a release is to send a pull request. Without a PR, the time to implement the feature will depend on the bandwidth of the development team and its list of priorities. If the consensus is that it's a good idea, the fastest way to get it into a release is to send a pull request. Without a PR, the time to implement the feature will depend on the bandwidth of the development team and its list of priorities.
@ -20,12 +20,14 @@ Ideally, the best way to report bugs is to provide a small snippet of code where
To send a pull request: To send a pull request:
- fork the repo (button at the top right in Github) - fork the repo (button at the top right in GitHub)
- clone the forked repo to your computer (green button in Github) - clone the forked repo to your computer (green button in GitHub)
- Switch to the `next` branch (run `git checkout next`)
- create a feature branch (run `git checkout -b the-feature-branch-name`) - create a feature branch (run `git checkout -b the-feature-branch-name`)
- make your changes - make your changes
- run the tests (run `npm t`) - run the tests (run `npm test`)
- submit a pull request (go to the pull requests tab in Github, click the green button and select your feature branch) - push your changes to your fork
- submit a pull request (go to the pull requests tab in GitHub, click the green button and select your feature branch)

View file

@ -87,7 +87,7 @@ Nowadays there are [a lot of CSS-in-JS libraries with various degrees of robustn
The main problem with many of these libraries is that even though they require a non-trivial amount of transpiler tooling and configuration, they also require sacrificing code readability in order to work, e.g. `<a class={classnames(styles.button, styles.danger)}></a>` vs `<a class="button danger"></a>` (or `m("a.button.danger")` if we're using hyperscript). The main problem with many of these libraries is that even though they require a non-trivial amount of transpiler tooling and configuration, they also require sacrificing code readability in order to work, e.g. `<a class={classnames(styles.button, styles.danger)}></a>` vs `<a class="button danger"></a>` (or `m("a.button.danger")` if we're using hyperscript).
Often sacrifices also need to be made at time of debugging, when mapping rendered CSS class names back to their source. Often all you get in browser developer tools is a class like `button_fvp6zc2gdj35evhsl73ffzq_0 danger_fgdl0s2a5fmle5g56rbuax71_0` with useless source maps (or worse, entirely criptic class names). Often sacrifices also need to be made at time of debugging, when mapping rendered CSS class names back to their source. Often all you get in browser developer tools is a class like `button_fvp6zc2gdj35evhsl73ffzq_0 danger_fgdl0s2a5fmle5g56rbuax71_0` with useless source maps (or worse, entirely cryptic class names).
Another common issue is lack of support for less basic CSS features such as `@keyframes` and `@font-face`. Another common issue is lack of support for less basic CSS features such as `@keyframes` and `@font-face`.

View file

@ -5,7 +5,7 @@
--- ---
Mithril is written in ES5, and is fully compatible with ES6 as well. ES6 is a recent update to Javascript that introduces new syntax sugar for various common cases. It's not yet fully supported by all major browsers and it's not a requirement for writing application, but it may be pleasing to use depending on your team's preferences. Mithril is written in ES5, and is fully compatible with ES6 as well. ES6 is a recent update to Javascript that introduces new syntax sugar for various common cases. It's not yet fully supported by all major browsers and it's not a requirement for writing an application, but it may be pleasing to use depending on your team's preferences.
In some limited environments, it's possible to use a significant subset of ES6 directly without extra tooling (for example, in internal applications that do not support IE). However, for the vast majority of use cases, a compiler toolchain like [Babel](https://babeljs.io) is required to compile ES6 features down to ES5. In some limited environments, it's possible to use a significant subset of ES6 directly without extra tooling (for example, in internal applications that do not support IE). However, for the vast majority of use cases, a compiler toolchain like [Babel](https://babeljs.io) is required to compile ES6 features down to ES5.
@ -70,10 +70,12 @@ Create a `.babelrc` file:
Next, create a file called `webpack.config.js` Next, create a file called `webpack.config.js`
```javascript ```javascript
const path = require('path')
module.exports = { module.exports = {
entry: './src/index.js', entry: './src/index.js',
output: { output: {
path: './bin', path: path.resolve(__dirname, './bin'),
filename: 'app.js', filename: 'app.js',
}, },
module: { module: {

View file

@ -2,10 +2,10 @@
Here are some examples of Mithril in action Here are some examples of Mithril in action
- [Animation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/animation/mosaic.html) - [Animation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/animation/mosaic.html)
- [DBMonster](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html) - [DBMonster](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html)
- [Markdown Editor](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/editor/index.html) - [Markdown Editor](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/editor/index.html)
- SVG: [Clock](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/svg/clock.html), [Ring](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/svg/ring.html), [Tiger](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/svg/tiger.html) - SVG: [Clock](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/clock.html), [Ring](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/ring.html), [Tiger](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/tiger.html)
- [ThreadItJS](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/threaditjs/index.html) - [ThreadItJS](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/threaditjs/index.html)
- [TodoMVC](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/todomvc/index.html) - [TodoMVC](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/todomvc/index.html)

BIN
docs/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
docs/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

@ -74,7 +74,7 @@ What these numbers show is that not only does Mithril initializes significantly
Update performance can be even more important than first-render performance, since updates can happen many times while a Single Page Application is running. Update performance can be even more important than first-render performance, since updates can happen many times while a Single Page Application is running.
A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [React implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/react/index.html) and a [Mithril implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html). Sample results are shown below: A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [React implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/react/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Sample results are shown below:
React | Mithril React | Mithril
------- | ------- ------- | -------
@ -139,7 +139,7 @@ Also, remember that frameworks like Angular and Mithril are designed for non-tri
##### Update performance ##### Update performance
A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare an [Angular implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/angular/index.html) and a [Mithril implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below: A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare an [Angular implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/angular/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below:
Angular | Mithril Angular | Mithril
------- | ------- ------- | -------
@ -193,7 +193,7 @@ Library load times matter in applications that don't stay open for long periods
##### Update performance ##### Update performance
A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [Vue implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/vue/index.html) and a [Mithril implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below: A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [Vue implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/vue/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below:
Vue | Mithril Vue | Mithril
------ | ------- ------ | -------

View file

@ -12,9 +12,6 @@ try {fs.mkdirSync("./dist/archive/v" + version)} catch (e) {/* ignore */}
var guides = fs.readFileSync("docs/nav-guides.md", "utf-8") var guides = fs.readFileSync("docs/nav-guides.md", "utf-8")
var methods = fs.readFileSync("docs/nav-methods.md", "utf-8") var methods = fs.readFileSync("docs/nav-methods.md", "utf-8")
var index = fs.readFileSync("docs/index.md", "utf-8")
fs.writeFileSync("README.md", index.replace(/(\]\()(.+?)\.md(\))/g, "$1http://mithril.js.org/$2.html$3"), "utf-8")
generate("docs") generate("docs")
function generate(pathname) { function generate(pathname) {
@ -66,8 +63,9 @@ function generate(pathname) {
fs.writeFileSync("./dist/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") fs.writeFileSync("./dist/" + outputFilename.replace(/^docs\//, ""), html, "utf-8")
} }
else if (!pathname.match(/lint|generate/)) { else if (!pathname.match(/lint|generate/)) {
fs.writeFileSync("./dist/archive/v" + version + "/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, "utf-8"), "utf-8") var encoding = (/\.(ico|png)$/i).test(path.extname(pathname)) ? "binary" : "utf-8";
fs.writeFileSync("./dist/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, "utf-8"), "utf-8") fs.writeFileSync("./dist/archive/v" + version + "/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, encoding), encoding)
fs.writeFileSync("./dist/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, encoding), encoding)
} }
} }
} }

View file

@ -225,7 +225,7 @@ var Splash = {
As you can see, this component simply renders a link to `#!/hello`. The `#!` part is known as a hashbang, and it's a common convention used in Single Page Applications to indicate that the stuff after it (the `/hello` part) is a route path. As you can see, this component simply renders a link to `#!/hello`. The `#!` part is known as a hashbang, and it's a common convention used in Single Page Applications to indicate that the stuff after it (the `/hello` part) is a route path.
Now that we going to have more than one screen, we use `m.route` instead of `m.mount`. Now that we're going to have more than one screen, we use `m.route` instead of `m.mount`.
```javascript ```javascript
m.route(root, "/splash", { m.route(root, "/splash", {

View file

@ -2,6 +2,8 @@
- [CDN](#cdn) - [CDN](#cdn)
- [NPM](#npm) - [NPM](#npm)
- [Quick start with Webpack](#quick-start-with-webpack)
- [TypeScript](#typescript)
### CDN ### CDN
@ -15,30 +17,56 @@ If you're new to Javascript or just want a very simple setup to get your feet we
### NPM ### NPM
#### Quick start with Webpack
```bash ```bash
# 1) install $ npm install mithril --save
npm install mithril --save
npm install webpack --save
# 2) add this line into the scripts section in package.json
# "scripts": {
# "start": "webpack src/index.js bin/app.js --watch"
# }
# 3) create an `src/index.js` file
# 4) create an `index.html` file containing `<script src="bin/app.js"></script>`
# 5) run bundler
npm start
# 6) open `index.html` in the (default) browser
open index.html
``` ```
---
### Quick start with Webpack
1. Initialize the directory as an npm package
```bash
$ npm init --yes
```
2. install required tools
```bash
$ npm install mithril --save
$ npm install webpack webpack-cli --save-dev
```
3. Add a "start" entry to the scripts section in `package.json`.
```js
{
// ...
"scripts": {
"start": "webpack src/index.js --output bin/app.js -d --watch"
}
}
```
4. Create `src/index.js` file.
```js
import m from "mithril";
m.render(document.body, "hello world");
```
5. create `index.html`
```html
<!DOCTYPE html>
<body>
<script src="bin/app.js"></script>
</body>
```
6. run bundler
```bash
$ npm start
```
7. open `index.html` in a browser
#### Step by step #### Step by step
For production-level projects, the recommended way of installing Mithril is to use NPM. For production-level projects, the recommended way of installing Mithril is to use NPM.
@ -78,7 +106,7 @@ Most browser today do not natively support modularization systems (CommonJS or E
A popular way for creating a bundle is to setup an NPM script for [Webpack](https://webpack.js.org/). To install Webpack, run this from the command line: A popular way for creating a bundle is to setup an NPM script for [Webpack](https://webpack.js.org/). To install Webpack, run this from the command line:
```bash ```bash
npm install webpack --save-dev npm install webpack webpack-cli --save-dev
``` ```
Open the `package.json` that you created earlier, and add an entry to the `scripts` section: Open the `package.json` that you created earlier, and add an entry to the `scripts` section:
@ -87,7 +115,7 @@ Open the `package.json` that you created earlier, and add an entry to the `scrip
{ {
"name": "my-project", "name": "my-project",
"scripts": { "scripts": {
"start": "webpack src/index.js bin/app.js -d --watch" "start": "webpack src/index.js --output bin/app.js -d --watch"
} }
} }
``` ```
@ -149,8 +177,8 @@ If you open bin/app.js, you'll notice that the Webpack bundle is not minified, s
{ {
"name": "my-project", "name": "my-project",
"scripts": { "scripts": {
"start": "webpack src/index.js bin/app.js -d --watch", "start": "webpack src/index.js --output bin/app.js -d --watch",
"build": "webpack src/index.js bin/app.js -p", "build": "webpack src/index.js --output bin/app.js -p",
} }
} }
``` ```
@ -219,7 +247,7 @@ If you don't have the ability to run a bundler script due to company security po
<title>Hello world</title> <title>Hello world</title>
</head> </head>
<body> <body>
<script src="https://cdn.rawgit.com/lhorie/mithril.js/rewrite/mithril.js"></script> <script src="https://cdn.rawgit.com/MithrilJS/mithril.js/master/mithril.js"></script>
<script src="index.js"></script> <script src="index.js"></script>
</body> </body>
</html> </html>
@ -231,3 +259,15 @@ If you don't have the ability to run a bundler script due to company security po
// if a CommonJS environment is not detected, Mithril will be created in the global scope // if a CommonJS environment is not detected, Mithril will be created in the global scope
m.render(document.body, "hello world") m.render(document.body, "hello world")
``` ```
---
### TypeScript
TypeScript type definitions are available from DefinitelyTyped. They can be installed with:
```bash
$ npm install @types/mithril --save-dev
```
For example usage, to file issues or to discuss TypeScript related topics visit: https://github.com/MithrilJS/mithril.d.ts

57
docs/integrating-libs.md Normal file
View file

@ -0,0 +1,57 @@
# 3rd Party Integration
Integration with third party libraries or vanilla javascript code can be achieved via [lifecycle methods](lifecycle-methods.md).
## Example
```javascript
var FullCalendar = {
oncreate: function (vnode) {
console.log('FullCalendar::oncreate')
$(vnode.dom).fullCalendar({
// put your initial options and callbacks here
})
Object.assign(vnode.attrs.parentState, {fullCalendarEl: vnode.dom})
},
// Consider that the lib will modify this parent element in the DOM (e.g. add dependent class attribute and values).
// As long as you return the same view results here, mithril will not
// overwrite the actual DOM because it's always comparing old and new VDOM
// before applying DOM updates.
view: function (vnode) {
return m('div')
},
onbeforeremove: function (vnode) {
// Run any destroy / cleanup methods here.
//E.g. $(vnode.state.fullCalendarEl).fullCalendar('destroy')
}
}
m.mount(document.body, {
view: function (vnode) {
return [
m('h1', 'Calendar'),
m(FullCalendar, {parentState: vnode.state}),
m('button', {onclick: prev}, 'Mithril Button -'),
m('button', {onclick: next}, 'Mithril Button +')
]
function next() {
$(vnode.state.fullCalendarEl).fullCalendar('next')
}
function prev() {
$(vnode.state.fullCalendarEl).fullCalendar('prev')
}
}
})
```
Running example [flems: FullCalendar](https://flems.io/#0=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAGhAGMB7NYmBvAHigjQGsACAJxigBeADog4xAJ6w4hGDGKjuhfmBEgSxAA5xEAel3UAJmgBWcfNSi0ArobBQM-C7Sy6MJjAA9d7AEZxdMGsoKGoMWDRDR10AZnwAdnwABkDg0PCmKN58LA4LODhRAD4QAF8KdGxcRAIzShp6RmYagDdHbgAxNIBhDMj2wW5gYTQR4WJ6an4MRkRuILRqYgh6bgAKFrRaQxgASiGxhWI6NDhaWHwrAHM1gHIukN6oft5EREnpxlvdw-GAEg2Wx2+EMLl2+CCjz6WTWw1GR3G+m4mmsxG4EhsvG4HAgy3C3FommW9Dg3AwkW4YRCvgw1E4pNk-F+xFKP1G8PGAHlfCYYEt8BgChArmhAdsYALiMReOZNI4mMQAMrEGYwChDSFQJ6ZRwAUSgc024pBLlZh3KY3hLQgMAA7nMFksVmh1kadvs4eNxvxiNZeC6sHdDBAWt9zRRLeN6L4YGBaPx+FhaC0YA7rItiS6xe6DhziEiAErpsloCTcHbiXi0Mu6SmwcnWTTcHDEQjbBkwJzM-QAt0S8SqiE9aF6qDgzXal5B+DS6th+GlEaL9lYHI2BhrUHUaw4Bj4XzbCTqz3Ea12tMZ52uoF7XNe6XyP0u5DM8aB26EACMt3Vt0nWW+CM8zfNYHi1EdeGPOV+AYZVVUNG98AHRhWSA+8QNuXxUQmNAfzvBEjkmdg6TmTR+BaV8WV-ABZXFlGgbgACFsNWABaQDKPfLCpXoPCT3QnDLAgEjuDQGBPAUYCqO4W5aNbXgGOYniXQAannZkAF1IyOR1M1E8TiDWD1KN7RDkIlCcIP1cdhwiGFbjEiT1KOZdmV0q8yJgFojPw+9TONcyhyhOzRxs4KdV4O5PNDNl71chdLVZMoKhATAcDwfIECoE4mmIPAyg0qh2C4BAUEqdKalyeToHqP1yBqDRtD0XR000TgrmcVwqvoqAAAFP3wAaAFZdG6hSoHwOoqEkTRqhAOpynKuak13PKqDqvBGp0fRWvazrRpcBVeoAJkGgBOfBjoO1bJqykAZrmhaUrSx6AEdrE7CRat4er1ClJqdrQNqOroVwTHez7eriU7P10YNxF0cGPt4CRbvqB68Cepa8E1KkIu+36tua3aQZcVIQjxl4oYSZI4YgBHcYgtHpokWbMYQUoNNKIA)

View file

@ -39,7 +39,7 @@ When using JSX, it's possible to interpolate Javascript expressions within JSX t
var greeting = "Hello" var greeting = "Hello"
var url = "http://google.com" var url = "http://google.com"
var link = <a href={url}>{greeting + "!"}</a> var link = <a href={url}>{greeting + "!"}</a>
// yields <a href="http://google.com">Hello</a> // yields <a href="http://google.com">Hello!</a>
``` ```
Components can be used by using a convention of uppercasing the first letter of the component name: Components can be used by using a convention of uppercasing the first letter of the component name:
@ -98,7 +98,7 @@ npm install babel-core babel-loader babel-preset-es2015 babel-plugin-transform-r
Create a `.babelrc` file: Create a `.babelrc` file:
``` ```json
{ {
"presets": ["es2015"], "presets": ["es2015"],
"plugins": [ "plugins": [
@ -112,14 +112,16 @@ Create a `.babelrc` file:
Next, create a file called `webpack.config.js` Next, create a file called `webpack.config.js`
```javascript ```javascript
const path = require('path')
module.exports = { module.exports = {
entry: './src/index.js', entry: './src/index.js',
output: { output: {
path: './bin', path: path.resolve(__dirname, './bin'),
filename: 'app.js', filename: 'app.js',
}, },
module: { module: {
loaders: [{ rules: [{
test: /\.js$/, test: /\.js$/,
exclude: /node_modules/, exclude: /node_modules/,
loader: 'babel-loader' loader: 'babel-loader'
@ -128,6 +130,8 @@ module.exports = {
} }
``` ```
For those familiar with Webpack already, please note that adding the Babel options to the `babel-loader` section of your `webpack.config.js` will throw an error, so you need to include them in the separate `.babelrc` file.
This configuration assumes the source code file for the application entry point is in `src/index.js`, and this will output the bundle to `bin/app.js`. This configuration assumes the source code file for the application entry point is in `src/index.js`, and this will output the bundle to `bin/app.js`.
To run the bundler, setup an npm script. Open `package.json` and add this entry under `"scripts"`: To run the bundler, setup an npm script. Open `package.json` and add this entry under `"scripts"`:
@ -187,7 +191,7 @@ JSX is useful for teams where HTML is primarily written by someone without Javas
Hyperscript is the compiled representation of JSX. It's designed to be readable and can also be used as-is, instead of JSX (as is done in most of the documentation). Hyperscript tends to be terser than JSX for a couple of reasons: Hyperscript is the compiled representation of JSX. It's designed to be readable and can also be used as-is, instead of JSX (as is done in most of the documentation). Hyperscript tends to be terser than JSX for a couple of reasons:
- it does not require repeating the tag name in closing tags (e.g. `m("div")` vs `<div></div>`) - it does not require repeating the tag name in closing tags (e.g. `m("div")` vs `<div></div>`)
- static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `<div class="button"></div>` - static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `<a class="button"></a>`)
In addition, since hyperscript is plain Javascript, it's often more natural to indent than JSX: In addition, since hyperscript is plain Javascript, it's often more natural to indent than JSX:

View file

@ -180,7 +180,7 @@ m("div", [
#### Avoid passing model data directly to components if the model uses `key` as a data property #### Avoid passing model data directly to components if the model uses `key` as a data property
The `key` property may appear in your data model in a way that conflicts with Mithril's key logic. For example, a component may represent an entity whose `key` property is expected to change over time. This can lead to components receiving the wrong data, re-initialise, or change positions unexpectedly. If your data model uses the `key` property, make sure to wrap the data such that Mithril doesn't misinterpret it as a rendering instruction: The `key` property may appear in your data model in a way that conflicts with Mithril's key logic. For example, a component may represent an entity whose `key` property is expected to change over time. This can lead to components receiving the wrong data, re-initialize, or change positions unexpectedly. If your data model uses the `key` property, make sure to wrap the data such that Mithril doesn't misinterpret it as a rendering instruction:
```javascript ```javascript
// Data model // Data model

View file

@ -4,6 +4,7 @@
<title>Mithril.js</title> <title>Mithril.js</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" />
<link href="style.css" rel="stylesheet" /> <link href="style.css" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="32x32" href="favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</head> </head>
<body> <body>
@ -14,8 +15,8 @@
<nav> <nav>
<a href="index.html">Guide</a> <a href="index.html">Guide</a>
<a href="api.html">API</a> <a href="api.html">API</a>
<a href="https://gitter.im/lhorie/mithril.js">Chat</a> <a href="https://gitter.im/MithrilJS/mithril.js">Chat</a>
<a href="https://github.com/lhorie/mithril.js">Github</a> <a href="https://github.com/MithrilJS/mithril.js">GitHub</a>
</nav> </nav>
</section> </section>
</header> </header>

5
docs/learning-mithril.md Normal file
View file

@ -0,0 +1,5 @@
# Learning Resources
Links to Mithril learning content:
- [Mithril 0-60](https://scrimba.com/playlist/playlist-34)

View file

@ -35,12 +35,12 @@ m.mount(element, {view: function () {return m(Component, attrs)}})
### Signature ### Signature
`m.mount(element, component)` `m.mount(element, Component)`
Argument | Type | Required | Description Argument | Type | Required | Description
----------- | -------------------- | -------- | --- ----------- | -------------------- | -------- | ---
`element` | `Element` | Yes | A DOM element that will be the parent node to the subtree `element` | `Element` | Yes | A DOM element that will be the parent node to the subtree
`component` | `Component|null` | Yes | The [component](components.md) to be rendered. `null` unmounts the tree and cleans up internal state. `Component` | `Component|null` | Yes | The [component](components.md) to be rendered. `null` unmounts the tree and cleans up internal state.
**returns** | | | Returns nothing **returns** | | | Returns nothing
[How to read signatures](signatures.md) [How to read signatures](signatures.md)
@ -49,7 +49,9 @@ Argument | Type | Required | Description
### How it works ### How it works
Similar to [`m.render()`](render.md), the `m.mount()` method takes a component and mounts a corresponding DOM tree into `element`. If `element` already has a DOM tree mounted via a previous `m.mount()` call, the component is diffed against the previous vnode tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all. `m.mount(element, Component)`, when called renders the component into the element and subscribe the `(element, Component)` pair to the redraw subsystem. That tree will be re-rendered when [manual](redraw.md) or [automatic](autoredraw.md) redraws are triggered.
On redraw, the new vDOM tree is compared (or "diffed") with the old one, and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
#### Replace a component #### Replace a component
@ -73,7 +75,7 @@ In contrast, traversing a javascript data structure has a much more predictable
### Differences from m.render ### Differences from m.render
A component rendered via `m.mount` automatically auto-redraws in response to view events, `m.redraw()` calls or `m.request()` calls. Vnodes rendered via `m.render()` do not. A component rendered via `m.mount` [automatically redraws](autoredraw.md) in response to view events, `m.redraw()` calls or `m.request()` calls. Vnodes rendered via `m.render()` do not.
`m.mount()` is suitable for application developers integrating Mithril widgets into existing codebases where routing is handled by another library or framework, while still enjoying Mithril's auto-redrawing facilities. `m.mount()` is suitable for application developers integrating Mithril widgets into existing codebases where routing is handled by another library or framework, while still enjoying Mithril's auto-redrawing facilities.

View file

@ -1,7 +1,9 @@
- Tutorials - Getting Started
- [Installation](installation.md)
- [Introduction](index.md) - [Introduction](index.md)
- [Installation](installation.md)
- [Tutorial](simple-application.md) - [Tutorial](simple-application.md)
- [Learning Resources](learning-mithril.md)
- [Getting Help](support.md)
- Resources - Resources
- [JSX](jsx.md) - [JSX](jsx.md)
- [ES6](es6.md) - [ES6](es6.md)
@ -9,6 +11,7 @@
- [Animation](animation.md) - [Animation](animation.md)
- [Testing](testing.md) - [Testing](testing.md)
- [Examples](examples.md) - [Examples](examples.md)
- [3rd Party Integration](integrating-libs.md)
- Key concepts - Key concepts
- [Vnodes](vnodes.md) - [Vnodes](vnodes.md)
- [Components](components.md) - [Components](components.md)
@ -16,9 +19,10 @@
- [Keys](keys.md) - [Keys](keys.md)
- [Autoredraw system](autoredraw.md) - [Autoredraw system](autoredraw.md)
- Social - Social
- [Mithril Jobs](https://github.com/lhorie/mithril.js/wiki/JOBS) - [Mithril Jobs](https://github.com/MithrilJS/mithril.js/wiki/JOBS)
- [How to contribute](contributing.md) - [How to contribute](contributing.md)
- [Credits](credits.md) - [Credits](credits.md)
- [Code of Conduct](code-of-conduct.md)
- Misc - Misc
- [Framework comparison](framework-comparison.md) - [Framework comparison](framework-comparison.md)
- [Change log/Migration](change-log.md) - [Change log/Migration](change-log.md)

View file

@ -16,4 +16,4 @@
- Optional - Optional
- [Stream](stream.md) - [Stream](stream.md)
- Tooling - Tooling
- [Ospec](https://github.com/lhorie/mithril.js/blob/rewrite/ospec) - [Ospec](https://github.com/MithrilJS/mithril.js/blob/master/ospec)

View file

@ -26,6 +26,8 @@ A [ES6 Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/G
A Promise is a mechanism for working with asynchronous computations. A Promise is a mechanism for working with asynchronous computations.
Mithril provides a polyfill when the environment does not support Promises. The polyfill can also be referenced specifically via `m.PromisePolyfill`.
--- ---
### Signature ### Signature
@ -302,7 +304,7 @@ This example also illustrates another benefit of smaller functions: we reused th
### Why not callbacks ### Why not callbacks
Callbacks are another mechanism for working with asynchrounous computations, and are indeed more adequate to use if an asynchronous computation may occur more than one time (for example, an `onscroll` event handler). Callbacks are another mechanism for working with asynchronous computations, and are indeed more adequate to use if an asynchronous computation may occur more than one time (for example, an `onscroll` event handler).
However, for asynchronous computations that only occur once in response to an action, promises can be refactored more effectively, reducing code smells known as pyramids of doom (deeply nested series of callbacks with unmanaged state being used across several closure levels). However, for asynchronous computations that only occur once in response to an action, promises can be refactored more effectively, reducing code smells known as pyramids of doom (deeply nested series of callbacks with unmanaged state being used across several closure levels).

View file

@ -2,6 +2,8 @@
- [Description](#description) - [Description](#description)
- [Signature](#signature) - [Signature](#signature)
- [Static members](#static-members)
-[m.redraw.sync()](#mredrawsync)
- [How it works](#how-it-works) - [How it works](#how-it-works)
--- ---
@ -10,12 +12,10 @@
Updates the DOM after a change in the application data layer. Updates the DOM after a change in the application data layer.
You DON'T need to call it if data is modified within the execution context of an event handler defined in a Mithril view, or after request completion when using `m.request`/`m.jsonp`. You DON'T need to call it if data is modified within the execution context of an event handler defined in a Mithril view, or after request completion when using `m.request`/`m.jsonp`. The [autoredraw](autoredraw.md) system, which is built on top of `m.redraw()` will take care of it.
You DO need to call it in `setTimeout`/`setInterval`/`requestAnimationFrame` callbacks, or callbacks from 3rd party libraries. You DO need to call it in `setTimeout`/`setInterval`/`requestAnimationFrame` callbacks, or callbacks from 3rd party libraries.
Typically, `m.redraw` triggers an asynchronous redraws, but it may trigger synchronously if Mithril detects it's possible to improve performance by doing so (i.e. if no redraw was requested within the last animation frame). You should write code assuming that it always redraws asynchronously.
--- ---
### Signature ### Signature
@ -26,6 +26,16 @@ Argument | Type | Required | Description
----------- | -------------------- | -------- | --- ----------- | -------------------- | -------- | ---
**returns** | | | Returns nothing **returns** | | | Returns nothing
#### Static members
##### m.redraw.sync
`m.redraw.sync()`
Argument | Type | Required | Description
----------- | -------------------- | -------- | ---
**returns** | | | Returns nothing
--- ---
### How it works ### How it works
@ -34,4 +44,12 @@ When callbacks outside of Mithril run, you need to notify Mithril's rendering en
To trigger a redraw, call `m.redraw()`. Note that `m.redraw` only works if you used `m.mount` or `m.route`. If you rendered via `m.render`, you should use `m.render` to redraw. To trigger a redraw, call `m.redraw()`. Note that `m.redraw` only works if you used `m.mount` or `m.route`. If you rendered via `m.render`, you should use `m.render` to redraw.
You should not call m.redraw from a [lifecycle method](lifecycle-methods.md). Doing so will result in undefined behavior. `m.redraw()` always triggers an asynchronous redraws, whereas `m.redraw.sync()` triggers a synchronous one. `m.redraw()` is tied to `window.requestAnimationFrame()` (we provide a fallback for IE9). It will thus typically fire at most 60 times per second. It may fire faster if your monitor has a higher refresh rate.
`m.redraw.sync()` is mostly intended to make videos play work in iOS. That only works in response to user-triggered events. It comes with several caveat:
- You should not call `m.redraw.sync()` from a [lifecycle method](lifecycle-methods.md) or the `view()` method of a component. Doing so will result in undefined behavior (it throws an error when possible).
- `m.redraw.sync()` called from an event handler can cause the DOM to be modified while an event is bubbling. Depending on the structure of the old and new DOM trees, the event can finish the bubbling phase in the new tree and trigger unwanted handlers.
- It is not throttled. One call to `m.redraw.sync()` causes immediately one `m.render()` call per root registered with [`m.mount()`](mount.md) or [`m.route()`](route.md).
`m.redraw()` doesn't have any of those issues, you can call it from wherever you like.

View file

@ -1,5 +1,11 @@
# Mithril Release Processes # Mithril Release Processes
**Note** These steps all assume that `MithrilJS/mithril.js` is a git remote named `mithriljs`, adjust accordingly if that doesn't match your setup.
- [Releasing a new Mithril version](#releasing-a-new-mithril-version)
- [Updating mithril.js.org](#updating-mithriljsorg)
- [Releasing a new ospec version](#releasing-a-new-ospec-version)
## Releasing a new Mithril version ## Releasing a new Mithril version
### Prepare the release ### Prepare the release
@ -7,8 +13,8 @@
1. Ensure your local branch is up to date 1. Ensure your local branch is up to date
```bash ```bash
$ git co next $ git checkout next
$ git pull --rebase lhorie next $ git pull --rebase mithriljs next
``` ```
2. Determine patch level of the change 2. Determine patch level of the change
@ -22,8 +28,8 @@ $ git commit -m "Preparing for release"
# Push to your branch # Push to your branch
$ git push $ git push
# Push to lhorie/mithril.js # Push to MithrilJS/mithril.js
$ git push lhorie next $ git push mithriljs next
``` ```
### Merge from `next` to `master` ### Merge from `next` to `master`
@ -31,8 +37,8 @@ $ git push lhorie next
5. Switch to `master` and make sure it's up to date 5. Switch to `master` and make sure it's up to date
```bash ```bash
$ git co master $ git checkout master
$ git pull --rebase lhorie master $ git pull --rebase mithriljs master
``` ```
6. merge `next` on top of it 6. merge `next` on top of it
@ -53,10 +59,10 @@ $ npm test
8. `npm run release <major|minor|patch|semver>`, see the docs for [`npm version`](https://docs.npmjs.com/cli/version) 8. `npm run release <major|minor|patch|semver>`, see the docs for [`npm version`](https://docs.npmjs.com/cli/version)
9. The changes will be automatically pushed to your fork 9. The changes will be automatically pushed to your fork
10. Push the changes to `lhorie/mithril.js` 10. Push the changes to `MithrilJS/mithril.js`
```bash ```bash
$ git push lhorie master $ git push mithriljs master
``` ```
11. Travis will push the new release to npm & create a GitHub release 11. Travis will push the new release to npm & create a GitHub release
@ -68,8 +74,8 @@ This helps to ensure that the `version` field of `package.json` doesn't get out
12. Switch to `next` and make sure it's up to date 12. Switch to `next` and make sure it's up to date
```bash ```bash
$ git co next $ git checkout next
$ git pull --rebase lhorie next $ git pull --rebase mithriljs next
``` ```
13. Merge `master` back onto `next` 13. Merge `master` back onto `next`
@ -78,11 +84,11 @@ $ git pull --rebase lhorie next
$ git merge master $ git merge master
``` ```
14. Push the changes to your fork & `lhorie/mithril.js` 14. Push the changes to your fork & `MithrilJS/mithril.js`
```bash ```bash
$ git push $ git push
$ git push lhorie next $ git push mithriljs next
``` ```
### Update the GitHub release ### Update the GitHub release
@ -94,19 +100,77 @@ $ git push lhorie next
Fixes to documentation can land whenever, updates to the site are published via Travis. Fixes to documentation can land whenever, updates to the site are published via Travis.
```bash ```bash
# These steps assume that lhorie/mithril.js is a git remote named "lhorie" # These steps assume that MithrilJS/mithril.js is a git remote named "mithriljs"
# Ensure your next branch is up to date # Ensure your next branch is up to date
$ git co next $ git checkout next
$ git pull lhorie next $ git pull mithriljs next
# Splat the docs folder from next onto master # Splat the docs folder from next onto master
$ git co master $ git checkout master
$ git co next -- ./docs $ git checkout next -- ./docs
# Manually ensure that no new feature docs were added # Manually ensure that no new feature docs were added
$ git push lhorie $ git push mithriljs
``` ```
After the Travis build completes the updated docs should appear on https://mithril.js.org in a few minutes. After the Travis build completes the updated docs should appear on https://mithril.js.org in a few minutes.
## Releasing a new ospec version
1. Ensure your local branch is up to date
```bash
$ git checkout next
$ git pull --rebase mithriljs next
```
2. Determine patch level of the change
3. Update `version` field in `ospec/package.json` to match new version being prepared for release
4. Commit changes to `next`
```
$ git add .
$ git commit -m "chore(ospec): ospec@<version>"
# Push to your branch
$ git push
# Push to MithrilJS/mithril.js
$ git push mithriljs next
```
### Merge from `next` to `master`
5. Switch to `master` and make sure it's up to date
```bash
$ git checkout master
$ git pull --rebase mithriljs master
```
6. merge `next` on top of it
```bash
$ git checkout next -- ./ospec
$ git add .
$ git commit -m "chore(ospec): ospec@<version>"
```
7. Ensure the tests are passing!
### Publish the release
8. Push the changes to `MithrilJS/mithril.js`
```bash
$ git push mithriljs master
```
9. Publish the changes to npm **from the `/ospec` folder**. That bit is important to ensure you don't accidentally ship a new Mithril release!
```bash
$ cd ./ospec
$ npm publish
```

View file

@ -36,7 +36,7 @@ Argument | Type | Required | Description
### How it works ### How it works
The `m.render(element, vnodes)` method takes a virtual DOM tree (typically generated via the [`m()` hyperscript function](hyperscript.md), generates a DOM tree and mounts it on `element`. If `element` already has a DOM tree mounted via a previous `m.render()` call, `vnodes` is diffed against the previous `vnodes` tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all. The `m.render(element, vnodes)` method takes a virtual DOM tree (typically generated via the [`m()` hyperscript function](hyperscript.md)), generates a DOM tree and mounts it on `element`. If `element` already has a DOM tree mounted via a previous `m.render()` call, `vnodes` is diffed against the previous `vnodes` tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
`m.render` is synchronous. `m.render` is synchronous.
@ -68,4 +68,4 @@ Another difference is that `m.render` method expects a [vnode](vnodes.md) (or a
The `m.render` module is similar in scope to view libraries like Knockout, React and Vue. It is approximately 500 lines of code (3kb min+gzip) and implements a virtual DOM diffing engine with a modern search space reduction algorithm and DOM recycling, which translate to top-of-class performance, both in terms of initial page load and re-rendering. It has no dependencies on other parts of Mithril and can be used as a standalone library. The `m.render` module is similar in scope to view libraries like Knockout, React and Vue. It is approximately 500 lines of code (3kb min+gzip) and implements a virtual DOM diffing engine with a modern search space reduction algorithm and DOM recycling, which translate to top-of-class performance, both in terms of initial page load and re-rendering. It has no dependencies on other parts of Mithril and can be used as a standalone library.
Despite being incredibly small, the render module is fully functional and self-suficient. It supports everything you might expect: SVG, custom elements, and all valid attributes and events - without any weird case-sensitive edge cases or exceptions. Of course, it also fully supports [components](components.md) and [lifecycle methods](lifecycle-methods.md). Despite being incredibly small, the render module is fully functional and self-sufficient. It supports everything you might expect: SVG, custom elements, and all valid attributes and events - without any weird case-sensitive edge cases or exceptions. Of course, it also fully supports [components](components.md) and [lifecycle methods](lifecycle-methods.md).

View file

@ -49,12 +49,13 @@ Argument | Type | Required | Descr
`options.user` | `String` | No | A username for HTTP authorization. Defaults to `undefined`. `options.user` | `String` | No | A username for HTTP authorization. Defaults to `undefined`.
`options.password` | `String` | No | A password for HTTP authorization. Defaults to `undefined`. This option is provided for `XMLHttpRequest` compatibility, but you should avoid using it because it sends the password in plain text over the network. `options.password` | `String` | No | A password for HTTP authorization. Defaults to `undefined`. This option is provided for `XMLHttpRequest` compatibility, but you should avoid using it because it sends the password in plain text over the network.
`options.withCredentials` | `Boolean` | No | Whether to send cookies to 3rd party domains. Defaults to `false` `options.withCredentials` | `Boolean` | No | Whether to send cookies to 3rd party domains. Defaults to `false`
`options.timeout` | `Number` | No | The amount of milliseconds a request can take before automatically being [terminated](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout). Defaults to `undefined`.
`options.config` | `xhr = Function(xhr)` | No | Exposes the underlying XMLHttpRequest object for low-level configuration. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function). `options.config` | `xhr = Function(xhr)` | No | Exposes the underlying XMLHttpRequest object for low-level configuration. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function).
`options.headers` | `Object` | No | Headers to append to the request before sending it (applied right before `options.config`). `options.headers` | `Object` | No | Headers to append to the request before sending it (applied right before `options.config`).
`options.type` | `any = Function(any)` | No | A constructor to be applied to each object in the response. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function). `options.type` | `any = Function(any)` | No | A constructor to be applied to each object in the response. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function).
`options.serialize` | `string = Function(any)` | No | A serialization method to be applied to `data`. Defaults to `JSON.stringify`, or if `options.data` is an instance of [`FormData`](https://developer.mozilla.org/en/docs/Web/API/FormData), defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function) (i.e. `function(value) {return value}`). `options.serialize` | `string = Function(any)` | No | A serialization method to be applied to `data`. Defaults to `JSON.stringify`, or if `options.data` is an instance of [`FormData`](https://developer.mozilla.org/en/docs/Web/API/FormData), defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function) (i.e. `function(value) {return value}`).
`options.deserialize` | `any = Function(string)` | No | A deserialization method to be applied to the `xhr.responseText`. Defaults to a small wrapper around `JSON.parse` that returns `null` for empty responses. If `extract` is defined, `deserialize` will be skipped. `options.deserialize` | `any = Function(string)` | No | A deserialization method to be applied to the `xhr.responseText`. Defaults to a small wrapper around `JSON.parse` that returns `null` for empty responses. If `extract` is defined, `deserialize` will be skipped.
`options.extract` | `any = Function(xhr, options)` | No | A hook to specify how the XMLHttpRequest response should be read. Useful for processing response data, reading headers and cookies. By default this is a function that returns `xhr.responseText`, which is in turn passed to `deserialize`. If a custom `extract` callback is provided, the `xhr` parameter is the XMLHttpRequest instance used for the request, and `options` is the object that was passed to the `m.request` call. Additionally, `deserialize` will be skipped and the value returned from the extract callback will not automatically be parsed as JSON. `options.extract` | `any = Function(xhr, options)` | No | A hook to specify how the XMLHttpRequest response should be read. Useful for processing response data, reading headers and cookies. By default this is a function that returns `xhr.responseText`, which is in turn passed to `deserialize`. If a custom `extract` callback is provided, the `xhr` parameter is the XMLHttpRequest instance used for the request, and `options` is the object that was passed to the `m.request` call. Additionally, `deserialize` will be skipped and the value returned from the extract callback will be left as-is when the promise resolves. Furthermore, when an extract callback is provided, exceptions are *not* thrown when the server response status code indicates an error.
`options.useBody` | `Boolean` | No | Force the use of the HTTP body section for `data` in `GET` requests when set to `true`, or the use of querystring for other HTTP methods when set to `false`. Defaults to `false` for `GET` requests and `true` for other methods. `options.useBody` | `Boolean` | No | Force the use of the HTTP body section for `data` in `GET` requests when set to `true`, or the use of querystring for other HTTP methods when set to `false`. Defaults to `false` for `GET` requests and `true` for other methods.
`options.background` | `Boolean` | No | If `false`, redraws mounted components upon completion of the request. If `true`, it does not. Defaults to `false`. `options.background` | `Boolean` | No | If `false`, redraws mounted components upon completion of the request. If `true`, it does not. Defaults to `false`.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods **returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods
@ -77,10 +78,12 @@ m.request({
}) })
``` ```
A call to `m.request` return a [promise](promise.md) and trigger a redraw upon completion of its promise chain. A call to `m.request` returns a [promise](promise.md) and triggers a redraw upon completion of its promise chain.
By default, `m.request` assumes the response is in JSON format and parses it into a Javascript object (or array). By default, `m.request` assumes the response is in JSON format and parses it into a Javascript object (or array).
If the HTTP response status code indicates an error, the returned Promise will be rejected. Supplying an extract callback will prevent the promise rejection.
--- ---
### Typical usage ### Typical usage
@ -287,7 +290,7 @@ function upload(e) {
var data = new FormData() var data = new FormData()
for (var i = 0; i < files.length; i++) { for (var i = 0; i < files.length; i++) {
data.append("file" + i, file) data.append("file" + i, files[i])
} }
m.request({ m.request({
@ -329,7 +332,7 @@ function upload(e) {
url: "/api/v1/upload", url: "/api/v1/upload",
data: data, data: data,
config: function(xhr) { config: function(xhr) {
xhr.addEventListener("progress", function(e) { xhr.upload.addEventListener("progress", function(e) {
progress = e.loaded / e.total progress = e.loaded / e.total
m.redraw() // tell Mithril that data changed and a re-render is needed m.redraw() // tell Mithril that data changed and a re-render is needed
@ -426,7 +429,7 @@ m.request({
### Retrieving response details ### Retrieving response details
By default Mithril attempts to parse a response as JSON and returns `xhr.responseText`. It may be useful to inspect a server response in more detail, this can be accomplished by passing a custom `options.extract` function: By default Mithril attempts to parse `xhr.responseText` as JSON and returns the parsed object. It may be useful to inspect a server response in more detail and process it manually. This can be accomplished by passing a custom `options.extract` function:
```javascript ```javascript
m.request({ m.request({

View file

@ -65,7 +65,7 @@ Argument | Type | Required | D
##### m.route.set ##### m.route.set
Redirects to a matching route, or to the default route if no matching routes can be found. Redirects to a matching route, or to the default route if no matching routes can be found. Triggers an asynchronous redraw off all mount points.
`m.route.set(path, data, options)` `m.route.set(path, data, options)`
@ -104,27 +104,33 @@ Argument | Type | Required | Description
This function can be used as the `oncreate` (and `onupdate`) hook in a `m("a")` vnode: This function can be used as the `oncreate` (and `onupdate`) hook in a `m("a")` vnode:
```JS ```JS
m("a[href=/]", {oncreate: m.route.link})`. m("a[href=/]", {oncreate: m.route.link})
``` ```
Using `m.route.link` as a `oncreate` hook causes the link to behave as a router link (i.e. it navigates to the route specified in `href`, instead of nagivating away from the current page to the URL specified in `href`. Using `m.route.link` as a `oncreate` hook causes the link to behave as a router link (i.e. it navigates to the route specified in `href`, instead of navigating away from the current page to the URL specified in `href`.
If the `href` attribute is not static, the `onupdate` hook must also be set: If the `href` attribute is not static, the `onupdate` hook must also be set:
```JS ```JS
m("a", {href: someVariable, oncreate: m.route.link, onupdate: m.route.link})` m("a", {href: someVariable, oncreate: m.route.link, onupdate: m.route.link})
``` ```
`m.route.link(vnode)` `m.route.link` can also set the `options` passed to `m.route.set` when the link is clicked by calling the function in the lifecycle methods:
Argument | Type | Required | Description ```JS
----------------- | ----------- | -------- | --- m("a[href=/]", {oncreate: m.route.link({replace: true})})
`vnode` | `Vnode` | Yes | This method is meant to be used as or in conjunction with an `<a>` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md) ```
**returns** | | | Returns `undefined`
`m.route.link(args)`
Argument | Type | Required | Description
----------------- | ---------------| -------- | ---
`args` | `Vnode|Object` | Yes | This method is meant to be used as or in conjunction with an `<a>` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md)
**returns** | `function` | | Returns the onclick handler function for the component
##### m.route.param ##### m.route.param
Retrieves a route parameter. A route parameter is a key-value pair. Route parameters may come from a few different places: Retrieves a route parameter from the last fully resolved route. A route parameter is a key-value pair. Route parameters may come from a few different places:
- route interpolations (e.g. if a route is `/users/:id`, and it resolves to `/users/1`, the route parameter has a key `id` and value `"1"`) - route interpolations (e.g. if a route is `/users/:id`, and it resolves to `/users/1`, the route parameter has a key `id` and value `"1"`)
- router querystrings (e.g. if the path is `/users?page=1`, the route parameter has a key `page` and value `"1"`) - router querystrings (e.g. if the path is `/users?page=1`, the route parameter has a key `page` and value `"1"`)
@ -137,9 +143,11 @@ Argument | Type | Required | Description
`key` | `String` | No | A route parameter name (e.g. `id` in route `/users/:id`, or `page` in path `/users/1?page=3`, or a key in `history.state`) `key` | `String` | No | A route parameter name (e.g. `id` in route `/users/:id`, or `page` in path `/users/1?page=3`, or a key in `history.state`)
**returns** | `String|Object` | | Returns a value for the specified key. If a key is not specified, it returns an object that contains all the interpolation keys **returns** | `String|Object` | | Returns a value for the specified key. If a key is not specified, it returns an object that contains all the interpolation keys
Note that in the `onmatch` function of a RouteResolver, the new route hasn't yet been fully resolved, and `m.route.params()` will return the parameters of the previous route, if any. `onmatch` receives the parameters of the new route as an argument.
#### RouteResolver #### RouteResolver
A RouterResolver is an object that contains an `onmatch` method and/or a `render` method. Both methods are optional, but at least one must be present. A RouteResolver is not a component, and therefore it does NOT have lifecycle methods. As a rule of thumb, RouteResolvers should be in the same file as the `m.route` call, whereas component definitions should be in their own modules. A RouteResolver is an object that contains an `onmatch` method and/or a `render` method. Both methods are optional, but at least one must be present. A RouteResolver is not a component, and therefore it does NOT have lifecycle methods. As a rule of thumb, RouteResolvers should be in the same file as the `m.route` call, whereas component definitions should be in their own modules.
`routeResolver = {onmatch, render}` `routeResolver = {onmatch, render}`
@ -315,10 +323,24 @@ It's also possible to have variadic routes, i.e. a route with an argument that c
```javascript ```javascript
m.route(document.body, "/edit/pictures/image.jpg", { m.route(document.body, "/edit/pictures/image.jpg", {
"/files/:file...": Edit, "/edit/:file...": Edit,
}) })
``` ```
#### Handling 404s
For isomorphic / universal javascript app, an url param and a variadic route combined is very useful to display custom 404 error page.
In a case of 404 Not Found error, the server send back the custom page to client. When Mithril is loaded, it will redirect client to the default route because it can't know that route.
```javascript
m.route(document.body, "/", {
"/": homeComponent,
// [...]
"/:404...": errorPageComponent
});
```
#### History state #### History state
It's possible to take full advantage of the underlying `history.pushState` API to improve user's navigation experience. For example, an application could "remember" the state of a large form when the user leaves a page by navigating away, such that if the user pressed the back button in the browser, they'd have the form filled rather than a blank form. It's possible to take full advantage of the underlying `history.pushState` API to improve user's navigation experience. For example, an application could "remember" the state of a large form when the user leaves a page by navigating away, such that if the user pressed the back button in the browser, they'd have the form filled rather than a blank form.
@ -453,7 +475,7 @@ m.route(document.body, "/", {
}) })
``` ```
Note that in this case, if the Layout component the `oninit` and `oncreate` lifecycle methods would only fire on the Layout component on the first route change (assuming all routes use the same layout). Note that in this case, if the Layout component has `oninit` and `oncreate` lifecycle methods, they would only fire on the first route change (assuming all routes use the same layout).
To clarify the difference between the two examples, example 1 is equivalent to this code: To clarify the difference between the two examples, example 1 is equivalent to this code:
@ -492,7 +514,7 @@ In example 2, since `Layout` is the top-level component in both routes, the DOM
#### Authentication #### Authentication
The RouterResolver's `onmatch` hook can be used to run logic before the top level component in a route is initializated. The example below shows how to implement a login wall that prevents users from seeing the `/secret` page unless they login. The RouteResolver's `onmatch` hook can be used to run logic before the top level component in a route is initialized. The example below shows how to implement a login wall that prevents users from seeing the `/secret` page unless they login.
```javascript ```javascript
var isLoggedIn = false var isLoggedIn = false
@ -552,7 +574,7 @@ var Login = {
return m("form", [ return m("form", [
m("input[type=text]", {oninput: m.withAttr("value", Auth.setUsername), value: Auth.username}), m("input[type=text]", {oninput: m.withAttr("value", Auth.setUsername), value: Auth.username}),
m("input[type=password]", {oninput: m.withAttr("value", Auth.setPassword), value: Auth.password}), m("input[type=password]", {oninput: m.withAttr("value", Auth.setPassword), value: Auth.password}),
m("button[type=button]", {onclick: Auth.login, "Login") m("button[type=button]", {onclick: Auth.login}, "Login")
]) ])
} }
} }
@ -572,7 +594,7 @@ m.route(document.body, "/secret", {
#### Preloading data #### Preloading data
Typically, a component can load data upon initialization. Loading data this way renders the component twice (once upon routing, and once after the request completes). Typically, a component can load data upon initialization. Loading data this way renders the component twice. The first render pass occurs upon routing, and the second fires after the request completes. Take care to note that `loadUsers()` returns a Promise, but any Promise returned by `oninit` is currently ignored. The second render pass comes from the [`background` option for `m.request`](request.md).
```javascript ```javascript
var state = { var state = {

View file

@ -2,6 +2,8 @@
Let's develop a simple application that covers some of the major aspects of Single Page Applications Let's develop a simple application that covers some of the major aspects of Single Page Applications
An interactive running example can be seen here [flems: Simple Application](https://flems.io/#0=N4IgzgpgNhDGAuEAmIBcICGAHLA6AVmCADQgBmAljEagNqgB2GAthGiAKqQBOAsgPZJoBIqVj8GiSewBuGbgAIuERQF4FwADoMFuhVAph4qBbQC6xbXv38MSADKHjCsgFcGCChIAUASg1W1nrcEPCu3DrMuCEAjq4QRt5aOkGprPAAFoImmiAA4gCiACq5limp1uFQOSAZ8PBYYKgA9M0hzAC0IUYd2BS4GSr8ANau2HjizM19za48YKWBFXoA7hSZAMIhQpIUGFBNCvDc8WXLAL6+S0G4mRAM3m4e8F4P3a5Q8P7Jy9bK3LgDEYFOp3p9cEgMPAMNdrJdrucytdYOEQpITMBEdcoLYkCYnp4fBQkN9YcFQuFItEIHEEvAkmS0qEsniFLlCiUSIyglUanUGk1Wu0unTelh+oNuCMxjhcJNpuLZvNmrkFABqBTEs6-XRrTbbe4vfaHY6nbnw8o3O4PAkvHxgr4BS3Lf5y1GGkEKB3mq6WrEMa5gDAyCD49yEh6k53ksIRBRRWLxRI-HXx5nZNkgAAKHE52p1vMz-MaLTaEE63XgYolQ1G4zl-CmMzmKjAKpA6qUPDd3DR8FwWu51kh0JMrpRvcN+d+eoyW2Qhr2BxMpog07hvrh2nOIERjBYbHQ-0cRhEJBA4kkhtk8i7KhP8E9Kd0EgoDHWY+7OLsD+nMgoEArGGzyvH4TrLCEsaRN4uS4C23AdEC8ClHeAJIbgzDYI84Z2g88FRqmXoUnGzAwZgcE8IhTgdOs5YocAGQhGQNTNMg6ztp28EDkgxAKBIsAhFCobxtE-CuIggJvsMiIKFxlDcEYAByB6dqqqoalxUAYEpB6bhUlx6bo5zbruxD7qw7D-AAYvw3BRIQ56XlI8A3oo1m2cwT7XK+77OLaoEyAwggQN8rrfkg3iBcFuBQscYDcb4-rWP+gHARGYHPkEkGUvGZFkB59FDhUEhgK4ABGzAfi4OGgSF4GERUEC4FgIQhpIAAiEBkBgHz0oZDV-N2QYhn4RWpMZ0bjbxtBjbluRaWVwgLdAKG5FZFAKY+TCsLkvjrhUpG5G+WDiQODAnfAtDwAAnlgECqIgAAe8BmLQWBabAEBZFAQjcKo62bQo20QGYhWTb8PkXSYUSzgAgvU3BkXIUDxCh-k+Mj8Shd2E59rg8k6awnqYxAlz7TqJOfioPZ4wT8DKTt4MbuTQSHSAy1QICGCLVAq0gPY2lbQeu0s9YbPHadEuXe9GCfd9v2qALwLA6DJD1QNkPidDuBwwjSP7Kjavow8JPY9TuOGlzhMQMTBuk3ts3JXbVMAhbkhW-TwtM3oZOzWzZXifAEi4AH9QSFdt33aVFXrKrvG5AAysGEAi9yZj9RNO57iAwPsAL11if2DliBIzmuQo+eF15lopUB1UgRjQVCARFTZSRZGYW+XMF+JKEzd7uhs0wMgYfcrh947ehszCauZQNjFdSYADkzRIUvosQx4gmINrUriU1BgMMMk9GfHnDzLts3pxvg9kZAEYoVFQhyhkVBIGi-XWOnCImdnufoPWYuF5S7XnQAmQuTUWpdQoI9bwS8ADES9fTgP3t4JA-AUSsHdmVQQ10z6rycGDawuQCFGFyBibkaJfppVwhlWabdoKV3ErxUix4nC+E-j7BE04SFsXgM0VAxJyHqyyvcah9d0pPzqnPVuxFGEYB7vAFh3h3J2V4lImKCMwAcPNNw7cvhTLmUPCAOUYBRDAKvNIdAOCkB4LOhdYgIdA4SA0PldEQU7L7AUAARgAGxYEegoAAaioSETAADcmFuAAHM3wmAAEwAAYAkTW0N3KuwAomxIYKgbxyTAk9SDpEjAj0OhrCQJkXJiTqkBPCRNUeDBXAaCyXExJCg2kAGZ8l1O0Gk+CVFgTACQh0Iw10YCoCCgwCAxSYmtPaT47pWA7BIDfNE1AiSekMAoioAZVZaKeWAGVWWwxol7wYHieB3UrkYHCTg7g1DvEBIUGAfgBgkAKHgUgL54TxA4m4KgeBHSgXhJWWAGW11UBlRxLAYYMzsnrPmY8x64SllfNWagAAHE87xABWWpT0qxCHENwKErwJkSGmfU-pwz9moCyCGRQwACUdCJbZUlEhUDuF+ofSlvStkcw0KC8FkLoWwpaTktpbS8XIvqVLDQdyHlPJeW8j5XykC3Nsr9LodgKBzFQB02pODSlgAoAAL3RQqnZRqQWGGFVCjBYr5DwslQs2pqKVkMDWXk7F0rwnlMqXkxJABSTZTiw46EOcc05YlzkAogPGjV9yVC5KVa84kqrvmWoQiSlZeqDXIt+bZAFQKOk2rBVpCFb4eUdHtTCuFcy2neuRe69FTafG+uZaykluFyVTNDaHIOOT6UqHlVGs5FyIAYsnZOupu4LDsykjQegOcDzsEqpkbgVBzxVHYMWQUsxzonIbFMddjEqAAAFvG4Cvb45op7N2cyATdO67AHLnDMOcIAA)
First let's create an entry point for the application. Create a file `index.html`: First let's create an entry point for the application. Create a file `index.html`:
```markup ```markup
@ -136,6 +138,7 @@ By default, Mithril views are described using [hyperscript](hyperscript.md). Hyp
Let's use Mithril hyperscript to create a list of items. Hyperscript is the most idiomatic way of writing Mithril views, but [JSX is another popular alternative that you could explore](jsx.md) once you're more comfortable with the basics: Let's use Mithril hyperscript to create a list of items. Hyperscript is the most idiomatic way of writing Mithril views, but [JSX is another popular alternative that you could explore](jsx.md) once you're more comfortable with the basics:
```javascript ```javascript
// src/views/UserList.js
var m = require("mithril") var m = require("mithril")
var User = require("../models/User") var User = require("../models/User")
@ -392,8 +395,7 @@ var User = {
load: function(id) { load: function(id) {
return m.request({ return m.request({
method: "GET", method: "GET",
url: "https://rem-rest-api.herokuapp.com/api/users/:id", url: "https://rem-rest-api.herokuapp.com/api/users/" + id,
data: {id: id},
withCredentials: true, withCredentials: true,
}) })
.then(function(result) { .then(function(result) {
@ -508,8 +510,7 @@ var User = {
load: function(id) { load: function(id) {
return m.request({ return m.request({
method: "GET", method: "GET",
url: "https://rem-rest-api.herokuapp.com/api/users/:id", url: "https://rem-rest-api.herokuapp.com/api/users/" + id,
data: {id: id},
withCredentials: true, withCredentials: true,
}) })
.then(function(result) { .then(function(result) {
@ -520,7 +521,7 @@ var User = {
save: function() { save: function() {
return m.request({ return m.request({
method: "PUT", method: "PUT",
url: "https://rem-rest-api.herokuapp.com/api/users/:id", url: "https://rem-rest-api.herokuapp.com/api/users/" + User.current.id,
data: User.current, data: User.current,
withCredentials: true, withCredentials: true,
}) })
@ -541,6 +542,7 @@ Currently, we're only able to navigate back to the user list via the browser bac
Let's create a file `src/views/Layout.js`: Let's create a file `src/views/Layout.js`:
```javascript ```javascript
// src/views/Layout.js
var m = require("mithril") var m = require("mithril")
module.exports = { module.exports = {
@ -616,4 +618,4 @@ This concludes the tutorial.
In this tutorial, we went through the process of creating a very simple application where we can list users from a server and edit them individually. As an extra exercise, try to implement user creation and deletion on your own. In this tutorial, we went through the process of creating a very simple application where we can list users from a server and edit them individually. As an extra exercise, try to implement user creation and deletion on your own.
If you want to see more examples of Mithril code, check the [examples](examples.md) page. If you have questions, feel free to drop by the [Mithril chat room](https://gitter.im/lhorie/mithril.js). If you want to see more examples of Mithril code, check the [examples](examples.md) page. If you have questions, feel free to drop by the [Mithril chat room](https://gitter.im/MithrilJS/mithril.js).

View file

@ -9,10 +9,10 @@
- [Stream.scanMerge](#streamscanmerge) - [Stream.scanMerge](#streamscanmerge)
- [Stream.HALT](#streamhalt) - [Stream.HALT](#streamhalt)
- [Stream["fantasy-land/of"]](#streamfantasy-landof) - [Stream["fantasy-land/of"]](#streamfantasy-landof)
- [Instance members](#static-members) - [Instance members](#instance-members)
- [stream.map](#streammap) - [stream.map](#streammap)
- [stream.end](#streamend) - [stream.end](#streamend)
- [stream["fantasy-land/of"]](#streamfantasy-landof) - [stream["fantasy-land/of"]](#streamfantasy-landof-1)
- [stream["fantasy-land/map"]](#streamfantasy-landmap) - [stream["fantasy-land/map"]](#streamfantasy-landmap)
- [stream["fantasy-land/ap"]](#streamfantasy-landap) - [stream["fantasy-land/ap"]](#streamfantasy-landap)
- [Basic usage](#basic-usage) - [Basic usage](#basic-usage)
@ -120,11 +120,13 @@ Argument | Type | Required | Description
Creates a new stream with the results of calling the function on every value in the stream with an accumulator and the incoming value. Creates a new stream with the results of calling the function on every value in the stream with an accumulator and the incoming value.
Note that you can prevent dependent streams from being updated by returning the special value `stream.HALT` inside the accumulator function.
`stream = Stream.scan(fn, accumulator, stream)` `stream = Stream.scan(fn, accumulator, stream)`
Argument | Type | Required | Description Argument | Type | Required | Description
------------- | -------------------------------- | -------- | --- ------------- | -------------------------------- | -------- | ---
`fn` | `(accumulator, value) -> result` | Yes | A function that takes an accumulator and value parameter and returns a new accumulator value `fn` | `(accumulator, value) -> result \| HALT` | Yes | A function that takes an accumulator and value parameter and returns a new accumulator value
`accumulator` | `any` | Yes | The starting value for the accumulator `accumulator` | `any` | Yes | The starting value for the accumulator
`stream` | `Stream` | Yes | Stream containing the values `stream` | `Stream` | Yes | Stream containing the values
**returns** | `Stream` | | Returns a new stream containing the result **returns** | `Stream` | | Returns a new stream containing the result
@ -159,7 +161,7 @@ A special value that can be returned to stream callbacks to halt execution of do
This method is functionally identical to `stream`. It exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section. This method is functionally identical to `stream`. It exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section.
`stream = stream["fantasy-land/of"](value)` `stream = Stream["fantasy-land/of"](value)`
Argument | Type | Required | Description Argument | Type | Required | Description
----------- | -------------------- | -------- | --- ----------- | -------------------- | -------- | ---
@ -212,7 +214,7 @@ Creates a dependent stream whose value is set to the result of the callback func
This method exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section. This method exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section.
`dependentStream = stream()["fantasy-land/of"](callback)` `dependentStream = stream()["fantasy-land/map"](callback)`
Argument | Type | Required | Description Argument | Type | Required | Description
------------ | -------------------- | -------- | --- ------------ | -------------------- | -------- | ---
@ -384,7 +386,7 @@ var added = stream.combine(function(a, b) {
console.log(added()) // logs 12 console.log(added()) // logs 12
``` ```
A stream can depend on any number of streams and it's guaranteed to update atomically. For example, if a stream A has two dependent streams B and C, and a fourth stream D is dependent on both B and C, the stream D will only update once if the value of A changes. This guarantees that the callback for stream D is never called with unstable values such as when B has a new value but C has the old value. Atomicity also bring the performance benefits of not recomputing downstreams unnecessarily. A stream can depend on any number of streams and it's guaranteed to update atomically. For example, if a stream A has two dependent streams B and C, and a fourth stream D is dependent on both B and C, the stream D will only update once if the value of A changes. This guarantees that the callback for stream D is never called with unstable values such as when B has a new value but C has the old value. Atomicity also brings the performance benefits of not recomputing downstreams unnecessarily.
You can prevent dependent streams from being updated by returning the special value `stream.HALT` You can prevent dependent streams from being updated by returning the special value `stream.HALT`

View file

@ -1,4 +1,4 @@
body {-webkit-text-size-adjust: 100%;} body {background:white;-webkit-text-size-adjust: 100%;}
body,table,h5 {font:normal 16px 'Open Sans';} body,table,h5 {font:normal 16px 'Open Sans';}
header,main {margin:auto;max-width:1000px;} header,main {margin:auto;max-width:1000px;}
header section {position:absolute;width:250px;} header section {position:absolute;width:250px;}
@ -37,7 +37,7 @@ h2 a:visited,h3 a:visited,h4 a:visited,h5 a:visited {color:#000;text-decoration:
h2::before,h3::before,h4::before,h5::before {content:"#";position:absolute;left:-20px;visibility:hidden;} h2::before,h3::before,h4::before,h5::before {content:"#";position:absolute;left:-20px;visibility:hidden;}
h2:hover::before,h3:hover::before,h4:hover::before,h5:hover::before {visibility:visible;} h2:hover::before,h3:hover::before,h4:hover::before,h5:hover::before {visibility:visible;}
#signature + p code {padding:3px 10px;} #signature + p code {padding:3px 10px;}
h1 + ul {margin:40px 0 0 -270px;padding:0;position:absolute;width:250px;} h1 + ul {margin:40px 0 0 -270px;padding:0;position:absolute;width:250px;z-index:1;}
h1 + ul + hr {display:none;} h1 + ul + hr {display:none;}
h1 + ul li {list-style:none;margin:0;padding:0;} h1 + ul li {list-style:none;margin:0;padding:0;}
h1 + ul li:last-child {border-bottom:0;} h1 + ul li:last-child {border-bottom:0;}
@ -57,7 +57,7 @@ h1 + ul strong + ul {border-left:3px solid #1e5799;}
.hamburger:hover {text-decoration:none;} .hamburger:hover {text-decoration:none;}
main section {margin:0;} main section {margin:0;}
header section {margin:0 0 20px;position:static;width:auto;} header section {margin:0 0 20px;position:static;width:auto;}
h1 + ul {background:#eee;border:1px solid #ccc;box-sizing:border-box;display:none;height:100%;margin:0;overflow:auto;padding:20px;position:fixed;right:0;top:0;width:100%;} h1 + ul {background:#eee;border:1px solid #ccc;box-sizing:border-box;display:none;height:100%;margin:0;overflow:auto;padding:20px;position:fixed;right:0;top:0;width:100%;z-index:1}
h1 + ul + hr {display:block;} h1 + ul + hr {display:block;}
.navigating h1 + ul {display:block;} .navigating h1 + ul {display:block;}
.navigating {overflow:hidden;} .navigating {overflow:hidden;}

3
docs/support.md Normal file
View file

@ -0,0 +1,3 @@
# Getting Help
Mithril has an active & welcoming community on [Gitter](https://gitter.im/mithriljs/mithril.js), or feel free to ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/mithril.js) using the `mithril.js` tag.

View file

@ -1,6 +1,6 @@
# Testing # Testing
Mithril comes with a testing framework called [ospec](https://github.com/lhorie/mithril.js/tree/rewrite/ospec). What makes it different from most test frameworks is that it avoids all configurability for the sake of avoiding [yak shaving](http://catb.org/jargon/html/Y/yak-shaving.html) and [analysis paralysis](https://en.wikipedia.org/wiki/Analysis_paralysis). Mithril comes with a testing framework called [ospec](https://github.com/MithrilJS/mithril.js/tree/master/ospec). What makes it different from most test frameworks is that it avoids all configurability for the sake of avoiding [yak shaving](http://catb.org/jargon/html/Y/yak-shaving.html) and [analysis paralysis](https://en.wikipedia.org/wiki/Analysis_paralysis).
The easist way to setup the test runner is to create an NPM script for it. Open your project's `package.json` file and edit the `test` line under the `scripts` section: The easist way to setup the test runner is to create an NPM script for it. Open your project's `package.json` file and edit the `test` line under the `scripts` section:
@ -58,7 +58,7 @@ Generally speaking, there are two ways to write tests: upfront and after the fac
Writing tests upfront requires specifications to be frozen. Upfront tests are a great way of codifying the rules that a yet-to-be-implemented API must obey. However, writing tests upfront may not be a suitable strategy if you don't have a reasonable idea of what your project will look like, if the scope of the API is not well known or if it's likely to change (e.g. based on previous history at the company). Writing tests upfront requires specifications to be frozen. Upfront tests are a great way of codifying the rules that a yet-to-be-implemented API must obey. However, writing tests upfront may not be a suitable strategy if you don't have a reasonable idea of what your project will look like, if the scope of the API is not well known or if it's likely to change (e.g. based on previous history at the company).
Writing tests after the fact is a way to document the behavior of a system and avoid regressions. They are useful to ensure that obscure corner cases are not inadvertedly broken and that previously fixed bugs do not get re-introduced by unrelated changes. Writing tests after the fact is a way to document the behavior of a system and avoid regressions. They are useful to ensure that obscure corner cases are not inadvertently broken and that previously fixed bugs do not get re-introduced by unrelated changes.
--- ---
@ -74,7 +74,9 @@ var m = require("mithril")
module.exports = { module.exports = {
view: function() { view: function() {
return m("div", "Hello world") return m("div",
m("p", "Hello World")
)
} }
} }
``` ```
@ -90,7 +92,7 @@ o.spec("MyComponent", function() {
o(vnode.tag).equals("div") o(vnode.tag).equals("div")
o(vnode.children.length).equals(1) o(vnode.children.length).equals(1)
o(vnode.children[0].tag).equals("#") o(vnode.children[0].tag).equals("p")
o(vnode.children[0].children).equals("Hello world") o(vnode.children[0].children).equals("Hello world")
}) })
}) })

View file

@ -11,7 +11,7 @@
### Description ### Description
Turns an HTML string into unescaped HTML. **Do not use `m.trust` on unsanitized user input.** Turns an HTML or SVG string into unescaped HTML or SVG. **Do not use `m.trust` on unsanitized user input.**
Always try to use an [alternative method](#avoid-trusting-html) first, before considering using `m.trust`. Always try to use an [alternative method](#avoid-trusting-html) first, before considering using `m.trust`.
@ -23,7 +23,7 @@ Always try to use an [alternative method](#avoid-trusting-html) first, before co
Argument | Type | Required | Description Argument | Type | Required | Description
----------- | -------------------- | -------- | --- ----------- | -------------------- | -------- | ---
`html` | `String` | Yes | A string containing HTML text `html` | `String` | Yes | A string containing HTML or SVG text
**returns** | `Vnode` | | A trusted HTML [vnode](vnodes.md) that represents the input string **returns** | `Vnode` | | A trusted HTML [vnode](vnodes.md) that represents the input string
[How to read signatures](signatures.md) [How to read signatures](signatures.md)

View file

@ -21,11 +21,11 @@ It may seem wasteful to recreate vnodes so frequently, but as it turns out, mode
For that reason, Mithril uses a sophisticated and highly optimized virtual DOM diffing algorithm to minimize the amount of DOM updates. Mithril *also* generates carefully crafted vnode data structures that are compiled by Javascript engines for near-native data structure access performance. In addition, Mithril aggressively optimizes the function that creates vnodes as well. For that reason, Mithril uses a sophisticated and highly optimized virtual DOM diffing algorithm to minimize the amount of DOM updates. Mithril *also* generates carefully crafted vnode data structures that are compiled by Javascript engines for near-native data structure access performance. In addition, Mithril aggressively optimizes the function that creates vnodes as well.
The reason Mithril goes to such great lengths to support a rendering model that recreates the entire virtual DOM tree on every render is to provide [retained mode rendering](https://en.wikipedia.org/wiki/Retained_mode), a style of rendering that makes it drastically easier to manage UI complexity. The reason Mithril goes to such great lengths to support a rendering model that recreates the entire virtual DOM tree on every render is to provide a declarative [immediate mode](https://en.wikipedia.org/wiki/Immediate_mode_%28computer_graphics%29) API, a style of rendering that makes it drastically easier to manage UI complexity.
To illustrate why retained mode is so important, consider the DOM API and HTML. The DOM API is an [immediate mode](https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)) rendering system and requires writing out exact instructions to assemble a DOM tree procedurally. The imperative nature of the DOM API means you have many opportunities to micro-optimize your code, but it also means that you have more chances of introducing bugs and more chances to make code harder to understand. To illustrate why immediate mode is so important, consider the DOM API and HTML. The DOM API is an imperative [retained mode](https://en.wikipedia.org/wiki/Retained_mode) API and requires 1. writing out exact instructions to assemble a DOM tree procedurally, and 2. writing out other instructions to update that tree. The imperative nature of the DOM API means you have many opportunities to micro-optimize your code, but it also means that you have more chances of introducing bugs and more chances to make code harder to understand.
In contrast, HTML is a retained mode rendering system. With HTML, you can write a DOM tree in a far more natural and readable way, without worrying about forgetting to append a child to a parent, running into stack overflows when rendering extremely deep trees, etc. In contrast, HTML is closer to an immediate mode rendering system. With HTML, you can write a DOM tree in a far more natural and readable way, without worrying about forgetting to append a child to a parent, running into stack overflows when rendering extremely deep trees, etc.
Virtual DOM goes one step further than HTML by allowing you to write *dynamic* DOM trees without having to manually write multiple sets of DOM API calls to efficiently synchronize the UI to arbitrary data changes. Virtual DOM goes one step further than HTML by allowing you to write *dynamic* DOM trees without having to manually write multiple sets of DOM API calls to efficiently synchronize the UI to arbitrary data changes.
@ -74,7 +74,6 @@ Property | Type | Description
`dom` | `Element?` | Points to the element that corresponds to the vnode. This property is `undefined` in the `oninit` lifecycle method. In fragments and trusted HTML vnodes, `dom` points to the first element in the range. `dom` | `Element?` | Points to the element that corresponds to the vnode. This property is `undefined` in the `oninit` lifecycle method. In fragments and trusted HTML vnodes, `dom` points to the first element in the range.
`domSize` | `Number?` | This is only set in fragment and trusted HTML vnodes, and it's `undefined` in all other vnode types. It defines the number of DOM elements that the vnode represents (starting from the element referenced by the `dom` property). `domSize` | `Number?` | This is only set in fragment and trusted HTML vnodes, and it's `undefined` in all other vnode types. It defines the number of DOM elements that the vnode represents (starting from the element referenced by the `dom` property).
`state` | `Object?` | An object that is persisted between redraws. It is provided by the core engine when needed. In POJO component vnodes, the `state` inherits prototypically from the component object/class. In class component vnodes it is an instance of the class. In closure components it is the object returned by the closure. `state` | `Object?` | An object that is persisted between redraws. It is provided by the core engine when needed. In POJO component vnodes, the `state` inherits prototypically from the component object/class. In class component vnodes it is an instance of the class. In closure components it is the object returned by the closure.
`_state` | `Object?` | For components, a reference to the original `vnode.state` object, used to lookup the `view` and hooks. This property is only used internally by Mithril, do not use or modify it.
`events` | `Object?` | An object that is persisted between redraws and that stores event handlers so that they can be removed using the DOM API. The `events` property is `undefined` if there are no event handlers defined. This property is only used internally by Mithril, do not use or modify it. `events` | `Object?` | An object that is persisted between redraws and that stores event handlers so that they can be removed using the DOM API. The `events` property is `undefined` if there are no event handlers defined. This property is only used internally by Mithril, do not use or modify it.
`instance` | `Object?` | For components, a storage location for the value returned by the `view`. This property is only used internally by Mithril, do not use or modify it. `instance` | `Object?` | For components, a storage location for the value returned by the `view`. This property is only used internally by Mithril, do not use or modify it.
`skip` | `Boolean` | This property is only used internally by Mithril when diffing keyed lists, do not use or modify it. `skip` | `Boolean` | This property is only used internally by Mithril when diffing keyed lists, do not use or modify it.

View file

@ -62,7 +62,7 @@ var state = {
//view //view
var Todos = { var Todos = {
add: function(e) { add: function(e) {
if (e.keyCode === 13) { if (e.keyCode === 13 && e.target.value) {
state.dispatch("createTodo", [e.target.value]) state.dispatch("createTodo", [e.target.value])
e.target.value = "" e.target.value = ""
} }

View file

@ -17,5 +17,6 @@ m.parseQueryString = require("./querystring/parse")
m.buildQueryString = require("./querystring/build") m.buildQueryString = require("./querystring/build")
m.version = "bleeding-edge" m.version = "bleeding-edge"
m.vnode = require("./render/vnode") m.vnode = require("./render/vnode")
m.PromisePolyfill = require("./promise/polyfill")
module.exports = m module.exports = m

File diff suppressed because it is too large Load diff

88
mithril.min.js vendored
View file

@ -1,43 +1,45 @@
(function(){function B(b,d,f,g,e,n){return{tag:b,key:d,attrs:f,children:g,text:e,dom:n,domSize:void 0,state:void 0,_state:void 0,events:void 0,instance:void 0,skip:!1}}function C(b){var d=arguments[1],f=2,g;if(null==b||"string"!==typeof b&&"function"!==typeof b&&"function"!==typeof b.view)throw Error("The selector must be either a string or a component.");if("string"===typeof b){var e;if(!(e=M[b])){g="div";for(var n=[],k={};e=P.exec(b);){var q=e[1],m=e[2];""===q&&""!==m?g=m:"#"===q?k.id=m:"."===q? (function(){function x(a,d,e,f,k,l){return{tag:a,key:d,attrs:e,children:f,text:k,dom:l,domSize:void 0,state:void 0,events:void 0,instance:void 0,skip:!1}}function M(a){for(var d in a)if(C.call(a,d))return!1;return!0}function w(a){var d=arguments[1],e=2;if(null==a||"string"!==typeof a&&"function"!==typeof a&&"function"!==typeof a.view)throw Error("The selector must be either a string or a component.");if("string"===typeof a){var f;if(!(f=N[a])){var k="div";for(var l=[],m={};f=R.exec(a);){var p=f[1],
n.push(m):"["===e[3][0]&&((q=e[6])&&(q=q.replace(/\\(["'])/g,"$1").replace(/\\\\/g,"\\")),"class"===e[4]?n.push(q):k[e[4]]=q||!0)}0<n.length&&(k.className=n.join(" "));e=M[b]={tag:g,attrs:k}}}if(null==d)d={};else if("object"!==typeof d||null!=d.tag||Array.isArray(d))d={},f=1;if(arguments.length===f+1)g=arguments[f],Array.isArray(g)||(g=[g]);else for(g=[];f<arguments.length;)g.push(arguments[f++]);f=B.normalizeChildren(g);if("string"===typeof b){g=!1;var l,u,n=d.className||d["class"],a;for(a in e.attrs)N.call(e.attrs, u=f[2];""===p&&""!==u?k=u:"#"===p?m.id=u:"."===p?l.push(u):"["===f[3][0]&&((p=f[6])&&(p=p.replace(/\\(["'])/g,"$1").replace(/\\\\/g,"\\")),"class"===f[4]?l.push(p):m[f[4]]=""===p?p:p||!0)}0<l.length&&(m.className=l.join(" "));f=N[a]={tag:k,attrs:m}}}if(null==d)d={};else if("object"!==typeof d||null!=d.tag||Array.isArray(d))d={},e=1;if(arguments.length===e+1)k=arguments[e],Array.isArray(k)||(k=[k]);else for(k=[];e<arguments.length;)k.push(arguments[e++]);e=x.normalizeChildren(k);if("string"===typeof a){k=
a)&&(d[a]=e.attrs[a]);void 0!==n&&(void 0!==d["class"]&&(d["class"]=void 0,d.className=n),null!=e.attrs.className&&(d.className=e.attrs.className+" "+n));for(a in d)if(N.call(d,a)&&"key"!==a){g=!0;break}Array.isArray(f)&&1===f.length&&null!=f[0]&&"#"===f[0].tag?u=f[0].children:l=f;return B(e.tag,d.key,g?d:void 0,l,u)}return B(b,d.key,d,f)}function Q(b){var d=0,f=null,g="function"===typeof requestAnimationFrame?requestAnimationFrame:setTimeout;return function(){var e=Date.now();0===d||16<=e-d?(d=e, !1;var r,z;l=d.className||d["class"];if(!M(f.attrs)&&!M(d)){m={};for(var b in d)C.call(d,b)&&(m[b]=d[b]);d=m}for(b in f.attrs)C.call(f.attrs,b)&&(d[b]=f.attrs[b]);void 0!==l&&(void 0!==d["class"]&&(d["class"]=void 0,d.className=l),null!=f.attrs.className&&(d.className=f.attrs.className+" "+l));for(b in d)if(C.call(d,b)&&"key"!==b){k=!0;break}Array.isArray(e)&&1===e.length&&null!=e[0]&&"#"===e[0].tag?z=e[0].children:r=e;return x(f.tag,d.key,k?d:void 0,r,z)}return x(a,d.key,d,e)}function S(a){var d=
b()):null===f&&(f=g(function(){f=null;b();d=Date.now()},16-(e-d)))}}B.normalize=function(b){return Array.isArray(b)?B("[",void 0,void 0,B.normalizeChildren(b),void 0,void 0):null!=b&&"object"!==typeof b?B("#",void 0,void 0,!1===b?"":b,void 0,void 0):b};B.normalizeChildren=function(b){for(var d=0;d<b.length;d++)b[d]=B.normalize(b[d]);return b};var P=/(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g,M={},N={}.hasOwnProperty;C.trust=function(b){null==b&&(b="");return B("<", 0,e=null,f="function"===typeof requestAnimationFrame?requestAnimationFrame:setTimeout;return function(){var k=Date.now()-d;null===e&&(e=f(function(){e=null;a();d=Date.now()},16-k))}}x.normalize=function(a){return Array.isArray(a)?x("[",void 0,void 0,x.normalizeChildren(a),void 0,void 0):null!=a&&"object"!==typeof a?x("#",void 0,void 0,!1===a?"":a,void 0,void 0):a};x.normalizeChildren=function(a){for(var d=0;d<a.length;d++)a[d]=x.normalize(a[d]);return a};var R=/(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g,
void 0,void 0,b,void 0,void 0)};C.fragment=function(b,d){return B("[",b.key,b,B.normalizeChildren(d),void 0,void 0)};var x=function(b){function d(b,a){return function r(d){var k;try{if(!a||null==d||"object"!==typeof d&&"function"!==typeof d||"function"!==typeof(k=d.then))l(function(){a||0!==b.length||console.error("Possible unhandled promise rejection:",d);for(var f=0;f<b.length;f++)b[f](d);e.length=0;n.length=0;m.state=a;m.retry=function(){r(d)}});else{if(d===g)throw new TypeError("Promise can't be resolved w/ itself"); N={},C={}.hasOwnProperty;w.trust=function(a){null==a&&(a="");return x("<",void 0,void 0,a,void 0,void 0)};w.fragment=function(a,d){return x("[",a.key,a,x.normalizeChildren(d),void 0,void 0)};var n=function(a){function d(a,b){return function G(d){var h;try{if(!b||null==d||"object"!==typeof d&&"function"!==typeof d||"function"!==typeof(h=d.then))r(function(){b||0!==a.length||console.error("Possible unhandled promise rejection:",d);for(var e=0;e<a.length;e++)a[e](d);k.length=0;l.length=0;u.state=b;u.retry=
f(k.bind(d))}}catch(R){q(R)}}}function f(b){function a(a){return function(b){0<d++||a(b)}}var d=0,e=a(q);try{b(a(k),e)}catch(A){e(A)}}if(!(this instanceof x))throw Error("Promise must be called with `new`");if("function"!==typeof b)throw new TypeError("executor must be a function");var g=this,e=[],n=[],k=d(e,!0),q=d(n,!1),m=g._instance={resolvers:e,rejectors:n},l="function"===typeof setImmediate?setImmediate:setTimeout;f(b)};x.prototype.then=function(b,d){function f(b,d,f,k){d.push(function(a){if("function"!== function(){G(d)}});else{if(d===f)throw new TypeError("Promise can't be resolved w/ itself");e(h.bind(d))}}catch(T){p(T)}}}function e(a){function b(b){return function(a){0<d++||b(a)}}var d=0,e=b(p);try{a(b(m),e)}catch(G){e(G)}}if(!(this instanceof n))throw Error("Promise must be called with `new`");if("function"!==typeof a)throw new TypeError("executor must be a function");var f=this,k=[],l=[],m=d(k,!0),p=d(l,!1),u=f._instance={resolvers:k,rejectors:l},r="function"===typeof setImmediate?setImmediate:
typeof b)f(a);else try{e(b(a))}catch(w){n&&n(w)}});"function"===typeof g.retry&&k===g.state&&g.retry()}var g=this._instance,e,n,k=new x(function(b,d){e=b;n=d});f(b,g.resolvers,e,!0);f(d,g.rejectors,n,!1);return k};x.prototype["catch"]=function(b){return this.then(null,b)};x.resolve=function(b){return b instanceof x?b:new x(function(d){d(b)})};x.reject=function(b){return new x(function(d,f){f(b)})};x.all=function(b){return new x(function(d,f){var g=b.length,e=0,n=[];if(0===b.length)d([]);else for(var k= setTimeout;e(a)};n.prototype.then=function(a,d){function e(a,d,e,m){d.push(function(b){if("function"!==typeof a)e(b);else try{k(a(b))}catch(A){l&&l(A)}});"function"===typeof f.retry&&m===f.state&&f.retry()}var f=this._instance,k,l,m=new n(function(a,d){k=a;l=d});e(a,f.resolvers,k,!0);e(d,f.rejectors,l,!1);return m};n.prototype["catch"]=function(a){return this.then(null,a)};n.prototype["finally"]=function(a){return this.then(function(d){return n.resolve(a()).then(function(){return d})},function(d){return n.resolve(a()).then(function(){return n.reject(d)})})};
0;k<b.length;k++)(function(k){function m(b){e++;n[k]=b;e===g&&d(n)}null==b[k]||"object"!==typeof b[k]&&"function"!==typeof b[k]||"function"!==typeof b[k].then?m(b[k]):b[k].then(m,f)})(k)})};x.race=function(b){return new x(function(d,f){for(var g=0;g<b.length;g++)b[g].then(d,f)})};"undefined"!==typeof window?("undefined"===typeof window.Promise&&(window.Promise=x),x=window.Promise):"undefined"!==typeof global&&("undefined"===typeof global.Promise&&(global.Promise=x),x=global.Promise);var F=function(b){function d(b, n.resolve=function(a){return a instanceof n?a:new n(function(d){d(a)})};n.reject=function(a){return new n(function(d,e){e(a)})};n.all=function(a){return new n(function(d,e){var f=a.length,k=0,l=[];if(0===a.length)d([]);else for(var m=0;m<a.length;m++)(function(p){function u(a){k++;l[p]=a;k===f&&d(l)}null==a[p]||"object"!==typeof a[p]&&"function"!==typeof a[p]||"function"!==typeof a[p].then?u(a[p]):a[p].then(u,e)})(m)})};n.race=function(a){return new n(function(d,e){for(var f=0;f<a.length;f++)a[f].then(d,
g){if(Array.isArray(g))for(var e=0;e<g.length;e++)d(b+"["+e+"]",g[e]);else if("[object Object]"===Object.prototype.toString.call(g))for(e in g)d(b+"["+e+"]",g[e]);else f.push(encodeURIComponent(b)+(null!=g&&""!==g?"="+encodeURIComponent(g):""))}if("[object Object]"!==Object.prototype.toString.call(b))return"";var f=[],g;for(g in b)d(g,b[g]);return f.join("&")},S=/^file:\/\//i,K=function(b,d){function f(){function a(){0===--b&&"function"===typeof u&&u()}var b=0;return function A(d){var e=d.then;d.then= e)})};"undefined"!==typeof window?("undefined"===typeof window.Promise?window.Promise=n:window.Promise.prototype["finally"]||(window.Promise.prototype["finally"]=n.prototype["finally"]),n=window.Promise):"undefined"!==typeof global&&("undefined"===typeof global.Promise?global.Promise=n:global.Promise.prototype["finally"]||(global.Promise.prototype["finally"]=n.prototype["finally"]),n=global.Promise);var E=function(a){function d(a,f){if(Array.isArray(f))for(var k=0;k<f.length;k++)d(a+"["+k+"]",f[k]);
function(){b++;var f=e.apply(d,arguments);f.then(a,function(d){a();if(0===b)throw d;});return A(f)};return d}}function g(a,b){if("string"===typeof a){var d=a;a=b||{};null==a.url&&(a.url=d)}return a}function e(a,b){if(null==b)return a;for(var d=a.match(/:[^\/]+/gi)||[],e=0;e<d.length;e++){var f=d[e].slice(1);null!=b[f]&&(a=a.replace(d[e],b[f]))}return a}function n(a,b){var d=F(b);if(""!==d){var e=0>a.indexOf("?")?"?":"&";a+=e+d}return a}function k(a){try{return""!==a?JSON.parse(a):null}catch(w){throw Error(a); else if("[object Object]"===Object.prototype.toString.call(f))for(k in f)d(a+"["+k+"]",f[k]);else e.push(encodeURIComponent(a)+(null!=f&&""!==f?"="+encodeURIComponent(f):""))}if("[object Object]"!==Object.prototype.toString.call(a))return"";var e=[],f;for(f in a)d(f,a[f]);return e.join("&")},U=/^file:\/\//i,K=function(a,d){function e(){function b(){0===--a&&"function"===typeof z&&z()}var a=0;return function D(d){var e=d.then;d.then=function(){a++;var f=e.apply(d,arguments);f.then(b,function(d){b();
}}function q(a){return a.responseText}function m(a,b){if("function"===typeof a)if(Array.isArray(b))for(var d=0;d<b.length;d++)b[d]=new a(b[d]);else return new a(b);return b}var l=0,u;return{request:function(a,l){var u=f();a=g(a,l);var w=new d(function(d,f){null==a.method&&(a.method="GET");a.method=a.method.toUpperCase();var g="GET"===a.method||"TRACE"===a.method?!1:"boolean"===typeof a.useBody?a.useBody:!0;"function"!==typeof a.serialize&&(a.serialize="undefined"!==typeof FormData&&a.data instanceof if(0===a)throw d;});return D(f)};return d}}function f(b,a){if("string"===typeof b){var d=b;b=a||{};null==b.url&&(b.url=d)}return b}function k(b,a){if(null==a)return b;for(var d=b.match(/:[^\/]+/gi)||[],e=0;e<d.length;e++){var f=d[e].slice(1);null!=a[f]&&(b=b.replace(d[e],a[f]))}return b}function l(b,a){var d=E(a);if(""!==d){var e=0>b.indexOf("?")?"?":"&";b+=e+d}return b}function m(b){try{return""!==b?JSON.parse(b):null}catch(A){throw Error(b);}}function p(b){return b.responseText}function u(b,a){if("function"===
FormData?function(h){return h}:JSON.stringify);"function"!==typeof a.deserialize&&(a.deserialize=k);"function"!==typeof a.extract&&(a.extract=q);a.url=e(a.url,a.data);g?a.data=a.serialize(a.data):a.url=n(a.url,a.data);var l=new b.XMLHttpRequest,u=!1,w=l.abort;l.abort=function(){u=!0;w.call(l)};l.open(a.method,a.url,"boolean"===typeof a.async?a.async:!0,"string"===typeof a.user?a.user:void 0,"string"===typeof a.password?a.password:void 0);a.serialize===JSON.stringify&&g&&l.setRequestHeader("Content-Type", typeof b)if(Array.isArray(a))for(var d=0;d<a.length;d++)a[d]=new b(a[d]);else return new b(a);return a}var r=0,z;return{request:function(b,r){var h=e();b=f(b,r);var A=new d(function(d,e){null==b.method&&(b.method="GET");b.method=b.method.toUpperCase();var f="GET"===b.method||"TRACE"===b.method?!1:"boolean"===typeof b.useBody?b.useBody:!0;"function"!==typeof b.serialize&&(b.serialize="undefined"!==typeof FormData&&b.data instanceof FormData?function(b){return b}:JSON.stringify);"function"!==typeof b.deserialize&&
"application/json; charset=utf-8");a.deserialize===k&&l.setRequestHeader("Accept","application/json, text/*");a.withCredentials&&(l.withCredentials=a.withCredentials);for(var r in a.headers)({}).hasOwnProperty.call(a.headers,r)&&l.setRequestHeader(r,a.headers[r]);"function"===typeof a.config&&(l=a.config(l,a)||l);l.onreadystatechange=function(){if(!u&&4===l.readyState)try{var h=a.extract!==q?a.extract(l,a):a.deserialize(a.extract(l,a));if(200<=l.status&&300>l.status||304===l.status||S.test(a.url))d(m(a.type, (b.deserialize=m);"function"!==typeof b.extract&&(b.extract=p);b.url=k(b.url,b.data);f?b.data=b.serialize(b.data):b.url=l(b.url,b.data);var h=new a.XMLHttpRequest,r=!1,A=h.abort;h.abort=function(){r=!0;A.call(h)};h.open(b.method,b.url,"boolean"===typeof b.async?b.async:!0,"string"===typeof b.user?b.user:void 0,"string"===typeof b.password?b.password:void 0);b.serialize!==JSON.stringify||!f||b.headers&&b.headers.hasOwnProperty("Content-Type")||h.setRequestHeader("Content-Type","application/json; charset=utf-8");
h));else{var c=Error(l.responseText),p;for(p in h)c[p]=h[p];f(c)}}catch(v){f(v)}};g&&null!=a.data?l.send(a.data):l.send()});return!0===a.background?w:u(w)},jsonp:function(a,k){var u=f();a=g(a,k);var q=new d(function(d,f){var g=a.callbackName||"_mithril_"+Math.round(1E16*Math.random())+"_"+l++,k=b.document.createElement("script");b[g]=function(e){k.parentNode.removeChild(k);d(m(a.type,e));delete b[g]};k.onerror=function(){k.parentNode.removeChild(k);f(Error("JSONP request failed"));delete b[g]};null== b.deserialize!==m||b.headers&&b.headers.hasOwnProperty("Accept")||h.setRequestHeader("Accept","application/json, text/*");b.withCredentials&&(h.withCredentials=b.withCredentials);b.timeout&&(h.timeout=b.timeout);for(var z in b.headers)({}).hasOwnProperty.call(b.headers,z)&&h.setRequestHeader(z,b.headers[z]);"function"===typeof b.config&&(h=b.config(h,b)||h);h.onreadystatechange=function(){if(!r&&4===h.readyState)try{var a=b.extract!==p?b.extract(h,b):b.deserialize(b.extract(h,b));if(b.extract!==p||
a.data&&(a.data={});a.url=e(a.url,a.data);a.data[a.callbackKey||"callback"]=g;k.src=n(a.url,a.data);b.document.documentElement.appendChild(k)});return!0===a.background?q:u(q)},setCompletionCallback:function(a){u=a}}}(window,x),O=function(b){function d(h,c,p,a,b,d,e){for(;p<a;p++){var v=c[p];null!=v&&f(h,v,b,e,d)}}function f(h,c,p,a,b){var v=c.tag;if("string"===typeof v)switch(c.state={},null!=c.attrs&&C(c.attrs,c,p),v){case "#":return c.dom=D.createTextNode(c.children),l(h,c.dom,b),c.dom;case "<":return g(h, 200<=h.status&&300>h.status||304===h.status||U.test(b.url))d(u(b.type,a));else{var f=Error(h.responseText);f.code=h.status;f.response=a;e(f)}}catch(V){e(V)}};f&&null!=b.data?h.send(b.data):h.send()});return!0===b.background?A:h(A)},jsonp:function(b,p){var h=e();b=f(b,p);var m=new d(function(d,e){var f=b.callbackName||"_mithril_"+Math.round(1E16*Math.random())+"_"+r++,h=a.document.createElement("script");a[f]=function(e){h.parentNode.removeChild(h);d(u(b.type,e));delete a[f]};h.onerror=function(){h.parentNode.removeChild(h);
c,b);case "[":var k=D.createDocumentFragment();null!=c.children&&(v=c.children,d(k,v,0,v.length,p,null,a));c.dom=k.firstChild;c.domSize=k.childNodes.length;l(h,k,b);return k;default:var m=c.tag;switch(c.tag){case "svg":a="http://www.w3.org/2000/svg";break;case "math":a="http://www.w3.org/1998/Math/MathML"}var t=(v=c.attrs)&&v.is,m=a?t?D.createElementNS(a,m,{is:t}):D.createElementNS(a,m):t?D.createElement(m,{is:t}):D.createElement(m);c.dom=m;if(null!=v)for(k in t=a,v)A(c,k,null,v[k],t);l(h,m,b);null!= e(Error("JSONP request failed"));delete a[f]};null==b.data&&(b.data={});b.url=k(b.url,b.data);b.data[b.callbackKey||"callback"]=f;h.src=l(b.url,b.data);a.document.documentElement.appendChild(h)});return!0===b.background?m:h(m)},setCompletionCallback:function(b){z=b}}}(window,n),Q=function(a){function d(b,c){if(b.state!==c)throw Error("`vnode.state` must not be modified");}function e(b){var c=b.state;try{return this.apply(c,arguments)}finally{d(b,c)}}function f(b,c,g,a,d,e,f){for(;g<a;g++){var q=c[g];
c.attrs&&null!=c.attrs.contenteditable?u(c):(null!=c.text&&(""!==c.text?m.textContent=c.text:c.children=[B("#",void 0,void 0,c.text,void 0,void 0)]),null!=c.children&&(h=c.children,d(m,h,0,h.length,p,null,a),h=c.attrs,"select"===c.tag&&null!=h&&("value"in h&&A(c,"value",null,h.value,void 0),"selectedIndex"in h&&A(c,"selectedIndex",null,h.selectedIndex,void 0))));return m}else return e(c,p),null!=c.instance?(p=f(h,c.instance,p,a,b),c.dom=c.instance.dom,c.domSize=null!=c.dom?c.instance.domSize:0,l(h, null!=q&&k(b,q,d,f,e)}}function k(q,c,g,a,d){var h=c.tag;if("string"===typeof h)switch(c.state={},null!=c.attrs&&I(c.attrs,c,g),h){case "#":c.dom=y.createTextNode(c.children);z(q,c.dom,d);break;case "<":l(q,c,a,d);break;case "[":var u=y.createDocumentFragment();null!=c.children&&(h=c.children,f(u,h,0,h.length,g,null,a));c.dom=u.firstChild;c.domSize=u.childNodes.length;z(q,u,d);break;default:var t=c.tag,p=(h=c.attrs)&&h.is;t=(a=c.attrs&&c.attrs.xmlns||P[c.tag]||a)?p?y.createElementNS(a,t,{is:p}):y.createElementNS(a,
p,b),c=p):(c.domSize=0,c=J),c}function g(h,c,p){var a={caption:"table",thead:"table",tbody:"table",tfoot:"table",tr:"tbody",th:"tr",td:"tr",colgroup:"table",col:"colgroup"}[(c.children.match(/^\s*?<(\w+)/im)||[])[1]]||"div",a=D.createElement(a);a.innerHTML=c.children;c.dom=a.firstChild;c.domSize=a.childNodes.length;c=D.createDocumentFragment();for(var b;b=a.firstChild;)c.appendChild(b);l(h,c,p);return c}function e(h,c){var a;if("function"===typeof h.tag.view){h.state=Object.create(h.tag);a=h.state.view; t):p?y.createElement(t,{is:p}):y.createElement(t);c.dom=t;if(null!=h)for(u in p=a,h)D(c,u,null,h[u],p);z(q,t,d);null!=c.attrs&&null!=c.attrs.contenteditable?b(c):(null!=c.text&&(""!==c.text?t.textContent=c.text:c.children=[x("#",void 0,void 0,c.text,void 0,void 0)]),null!=c.children&&(q=c.children,f(t,q,0,q.length,g,null,a),g=c.attrs,"select"===c.tag&&null!=g&&("value"in g&&D(c,"value",null,g.value,void 0),"selectedIndex"in g&&D(c,"selectedIndex",null,g.selectedIndex,void 0))))}else{a:{if("function"===
if(null!=a.$$reentrantLock$$)return J;a.$$reentrantLock$$=!0}else{h.state=void 0;a=h.tag;if(null!=a.$$reentrantLock$$)return J;a.$$reentrantLock$$=!0;h.state=null!=h.tag.prototype&&"function"===typeof h.tag.prototype.view?new h.tag(h):h.tag(h)}h._state=h.state;null!=h.attrs&&C(h.attrs,h,c);C(h._state,h,c);h.instance=B.normalize(h._state.view.call(h.state,h));if(h.instance===h)throw Error("A view cannot return the vnode it received as argument");a.$$reentrantLock$$=null}function n(h,c,p,b,e,g,n){if(c!== typeof c.tag.view){c.state=Object.create(c.tag);u=c.state.view;if(null!=u.$$reentrantLock$$)break a;u.$$reentrantLock$$=!0}else{c.state=void 0;u=c.tag;if(null!=u.$$reentrantLock$$)break a;u.$$reentrantLock$$=!0;c.state=null!=c.tag.prototype&&"function"===typeof c.tag.prototype.view?new c.tag(c):c.tag(c)}null!=c.attrs&&I(c.attrs,c,g);I(c.state,c,g);c.instance=x.normalize(e.call(c.state.view,c));if(c.instance===c)throw Error("A view cannot return the vnode it received as argument");u.$$reentrantLock$$=
p&&(null!=c||null!=p))if(null==c)d(h,p,0,p.length,e,g,void 0);else if(null==p)a(c,0,c.length,p);else{if(c.length===p.length){for(var v=!1,t=0;t<p.length;t++)if(null!=p[t]&&null!=c[t]){v=null==p[t].key&&null==c[t].key;break}if(v){for(t=0;t<c.length;t++)c[t]!==p[t]&&(null==c[t]&&null!=p[t]?f(h,p[t],e,n,m(c,t+1,g)):null==p[t]?a(c,t,t+1,p):k(h,c[t],p[t],e,m(c,t+1,g),b,n));return}}if(!b)a:{if(null!=c.pool&&Math.abs(c.pool.length-p.length)<=Math.abs(c.length-p.length)&&(b=p[0]&&p[0].children&&p[0].children.length|| null}null!=c.instance?(k(q,c.instance,g,a,d),c.dom=c.instance.dom,c.domSize=null!=c.dom?c.instance.domSize:0):c.domSize=0}}function l(b,c,a,d){var q=c.children.match(/^\s*?<(\w+)/im)||[];q=y.createElement(E[q[1]]||"div");"http://www.w3.org/2000/svg"===a?(q.innerHTML='<svg xmlns="http://www.w3.org/2000/svg">'+c.children+"</svg>",q=q.firstChild):q.innerHTML=c.children;c.dom=q.firstChild;c.domSize=q.childNodes.length;for(c=y.createDocumentFragment();a=q.firstChild;)c.appendChild(a);z(b,c,d)}function m(b,
0,Math.abs((c.pool[0]&&c.pool[0].children&&c.pool[0].children.length||0)-b)<=Math.abs((c[0]&&c[0].children&&c[0].children.length||0)-b))){b=!0;break a}b=!1}if(b){var u=c.pool;c=c.concat(c.pool)}for(var t=v=0,w=c.length-1,y=p.length-1,G;w>=v&&y>=t;){var r=c[v],z=p[t];if(r!==z||b)if(null==r)v++;else if(null==z)t++;else if(r.key===z.key){var A=null!=u&&v>=c.length-u.length||null==u&&b;v++;t++;k(h,r,z,e,m(c,v,g),A,n);b&&r.tag===z.tag&&l(h,q(r),g)}else if(r=c[w],r!==z||b)if(null==r)w--;else if(null==z)t++; c,a,d,e,l){if(c!==a&&(null!=c||null!=a))if(null==c)f(b,a,0,a.length,d,e,l);else if(null==a)A(c,0,c.length);else{for(var q=0,g=0,t=!0,m=!0;g<c.length;g++)if(null!=c[g]){t=null!=c[g].key;break}for(;q<a.length;q++)if(null!=a[q]){m=null!=a[q].key;break}if(t!==m)A(c,g,c.length),f(b,a,q,a.length,d,e,l);else if(m){m=c.length-1;for(var B=a.length-1,n,v;m>=g&&B>=q;)if(v=c[g],t=a[q],null==v)g++;else if(null==t)q++;else if(v.key===t.key)g++,q++,v!==t&&p(b,v,t,d,r(c,g,e),l);else if(t=a[B],null==v)g++;else if(null==
else if(r.key===z.key)A=null!=u&&w>=c.length-u.length||null==u&&b,k(h,r,z,e,m(c,w+1,g),A,n),(b||t<y)&&l(h,q(r),m(c,v,g)),w--,t++;else break;else w--,t++;else v++,t++}for(;w>=v&&y>=t;){r=c[w];z=p[y];if(r!==z||b)if(null==r)w--;else{if(null!=z)if(r.key===z.key)A=null!=u&&w>=c.length-u.length||null==u&&b,k(h,r,z,e,m(c,w+1,g),A,n),b&&r.tag===z.tag&&l(h,q(r),g),null!=r.dom&&(g=r.dom),w--;else{if(!G){G=c;var r=w,A={},E;for(E=0;E<r;E++){var x=G[E];null!=x&&(x=x.key,null!=x&&(A[x]=E))}G=A}null!=z&&(r=G[z.key], t)B--;else if(v.key===t.key)g++,q<B--&&z(b,u(v),e),v!==t&&p(b,v,t,d,e,l),null!=t.dom&&(e=t.dom);else break;for(;m>=g&&B>=q;){v=c[m];t=a[B];if(null==v)m--;else{if(null!=t)if(v.key===t.key)v!==t&&p(b,v,t,d,e,l),null!=t.dom&&(e=t.dom),m--;else{if(null==n){n=c;v=g;for(var y=m,x={};v<y;v++){var w=n[v];null!=w&&(w=w.key,null!=w&&(x[w]=v))}n=x}null!=t&&(v=n[t.key],null==v?k(b,t,d,l,e):(v=c[v],z(b,u(v),e),v!==t&&p(b,v,t,d,e,l),v.skip=!0),null!=t.dom&&(e=t.dom))}B--}if(B<q)break}f(b,a,q,B+1,d,e,l);A(c,g,m+
null!=r?(A=c[r],k(h,A,z,e,m(c,w+1,g),b,n),l(h,q(A),g),c[r].skip=!0,null!=A.dom&&(g=A.dom)):g=f(h,z,e,void 0,g))}y--}else w--,y--;if(y<t)break}d(h,p,t,y+1,e,g,n);a(c,v,w+1,p)}}function k(h,c,a,b,d,m,l){var p=c.tag;if(p===a.tag){a.state=c.state;a._state=c._state;a.events=c.events;var v;if(v=!m){var r,z;null!=a.attrs&&"function"===typeof a.attrs.onbeforeupdate&&(r=a.attrs.onbeforeupdate.call(a.state,a,c));"string"!==typeof a.tag&&"function"===typeof a._state.onbeforeupdate&&(z=a._state.onbeforeupdate.call(a.state, 1)}else{m=c.length<a.length?c.length:a.length;for(q=q<g?q:g;q<m;q++)v=c[q],t=a[q],v===t||null==v&&null==t||(null==v?k(b,t,d,l,r(c,q+1,e)):null==t?h(v):p(b,v,t,d,r(c,q+1,e),l));c.length>m&&A(c,q,c.length);a.length>m&&f(b,a,q,a.length,d,e,l)}}}function p(a,c,g,d,f,r){var q=c.tag;if(q===g.tag){g.state=c.state;g.events=c.events;var t;var A;null!=g.attrs&&"function"===typeof g.attrs.onbeforeupdate&&(t=e.call(g.attrs.onbeforeupdate,g,c));"string"!==typeof g.tag&&"function"===typeof g.state.onbeforeupdate&&
a,c));void 0===r&&void 0===z||r||z?v=!1:(a.dom=c.dom,a.domSize=c.domSize,a.instance=c.instance,v=!0)}if(!v)if("string"===typeof p)switch(null!=a.attrs&&(m?(a.state={},C(a.attrs,a,b)):I(a.attrs,a,b)),p){case "#":c.children.toString()!==a.children.toString()&&(c.dom.nodeValue=a.children);a.dom=c.dom;break;case "<":c.children!==a.children?(q(c),g(h,a,d)):(a.dom=c.dom,a.domSize=c.domSize);break;case "[":n(h,c.children,a.children,m,b,d,l);c=0;b=a.children;a.dom=null;if(null!=b){for(m=0;m<b.length;m++){var y= (A=e.call(g.state.onbeforeupdate,g,c));void 0===t&&void 0===A||t||A?t=!1:(g.dom=c.dom,g.domSize=c.domSize,g.instance=c.instance,t=!0);if(!t)if("string"===typeof q)switch(null!=g.attrs&&J(g.attrs,g,d),q){case "#":c.children.toString()!==g.children.toString()&&(c.dom.nodeValue=g.children);g.dom=c.dom;break;case "<":c.children!==g.children?(u(c),l(a,g,r,f)):(g.dom=c.dom,g.domSize=c.domSize);break;case "[":m(a,c.children,g.children,d,f,r);c=0;d=g.children;g.dom=null;if(null!=d){for(var n=0;n<d.length;n++)r=
b[m];null!=y&&null!=y.dom&&(null==a.dom&&(a.dom=y.dom),c+=y.domSize||1)}1!==c&&(a.domSize=c)}break;default:h=l;d=a.dom=c.dom;switch(a.tag){case "svg":h="http://www.w3.org/2000/svg";break;case "math":h="http://www.w3.org/1998/Math/MathML"}"textarea"===a.tag&&(null==a.attrs&&(a.attrs={}),null!=a.text&&(a.attrs.value=a.text,a.text=void 0));l=c.attrs;p=a.attrs;v=h;if(null!=p)for(y in p)A(a,y,l&&l[y],p[y],v);if(null!=l)for(y in l)null!=p&&y in p||("className"===y&&(y="class"),"o"!==y[0]||"n"!==y[1]||E(y)? d[n],null!=r&&null!=r.dom&&(null==g.dom&&(g.dom=r.dom),c+=r.domSize||1);1!==c&&(g.domSize=c)}break;default:a=g.dom=c.dom;r=g.attrs&&g.attrs.xmlns||P[g.tag]||r;"textarea"===g.tag&&(null==g.attrs&&(g.attrs={}),null!=g.text&&(g.attrs.value=g.text,g.text=void 0));f=c.attrs;q=g.attrs;t=r;if(null!=q)for(n in q)D(g,n,f&&f[n],q[n],t);if(null!=f)for(n in f)null!=q&&n in q||("className"===n&&(n="class"),"o"!==n[0]||"n"!==n[1]||w(n)?"key"!==n&&g.dom.removeAttribute(n):O(g,n,void 0));null!=g.attrs&&null!=g.attrs.contenteditable?
"key"!==y&&a.dom.removeAttribute(y):x(a,y,void 0));null!=a.attrs&&null!=a.attrs.contenteditable?u(a):null!=c.text&&null!=a.text&&""!==a.text?c.text.toString()!==a.text.toString()&&(c.dom.firstChild.nodeValue=a.text):(null!=c.text&&(c.children=[B("#",void 0,void 0,c.text,void 0,c.dom.firstChild)]),null!=a.text&&(a.children=[B("#",void 0,void 0,a.text,void 0,void 0)]),n(d,c.children,a.children,m,b,null,h))}else{if(m)e(a,b);else{a.instance=B.normalize(a._state.view.call(a.state,a));if(a.instance===a)throw Error("A view cannot return the vnode it received as argument"); b(g):null!=c.text&&null!=g.text&&""!==g.text?c.text.toString()!==g.text.toString()&&(c.dom.firstChild.nodeValue=g.text):(null!=c.text&&(c.children=[x("#",void 0,void 0,c.text,void 0,c.dom.firstChild)]),null!=g.text&&(g.children=[x("#",void 0,void 0,g.text,void 0,void 0)]),m(a,c.children,g.children,d,null,r))}else{g.instance=x.normalize(e.call(g.state.view,g));if(g.instance===g)throw Error("A view cannot return the vnode it received as argument");null!=g.attrs&&J(g.attrs,g,d);J(g.state,g,d);null!=
null!=a.attrs&&I(a.attrs,a,b);I(a._state,a,b)}null!=a.instance?(null==c.instance?f(h,a.instance,b,l,d):k(h,c.instance,a.instance,b,d,m,l),a.dom=a.instance.dom,a.domSize=a.instance.domSize):null!=c.instance?(w(c.instance,null),a.dom=void 0,a.domSize=0):(a.dom=c.dom,a.domSize=c.domSize)}}else w(c,null),f(h,a,b,l,d)}function q(a){var c=a.domSize;if(null!=c||null==a.dom){var b=D.createDocumentFragment();if(0<c){for(a=a.dom;--c;)b.appendChild(a.nextSibling);b.insertBefore(a,b.firstChild)}return b}return a.dom} g.instance?(null==c.instance?k(a,g.instance,d,r,f):p(a,c.instance,g.instance,d,f,r),g.dom=g.instance.dom,g.domSize=g.instance.domSize):null!=c.instance?(h(c.instance),g.dom=void 0,g.domSize=0):(g.dom=c.dom,g.domSize=c.domSize)}}else h(c),k(a,g,d,r,f)}function u(a){var c=a.domSize;if(null!=c||null==a.dom){var b=y.createDocumentFragment();if(0<c){for(a=a.dom;--c;)b.appendChild(a.nextSibling);b.insertBefore(a,b.firstChild)}return b}return a.dom}function r(a,c,b){for(;c<a.length;c++)if(null!=a[c]&&null!=
function m(a,c,b){for(;c<a.length;c++)if(null!=a[c]&&null!=a[c].dom)return a[c].dom;return b}function l(a,c,b){b&&b.parentNode?a.insertBefore(c,b):a.appendChild(c)}function u(a){var c=a.children;if(null!=c&&1===c.length&&"<"===c[0].tag)c=c[0].children,a.dom.innerHTML!==c&&(a.dom.innerHTML=c);else if(null!=a.text||null!=c&&0!==c.length)throw Error("Child node of a contenteditable must be trusted");}function a(a,c,b,d){for(;c<b;c++){var h=a[c];null!=h&&(h.skip?h.skip=!1:w(h,d))}}function w(a,c){function b(){if(++d=== a[c].dom)return a[c].dom;return b}function z(a,c,b){null!=b?a.insertBefore(c,b):a.appendChild(c)}function b(a){var c=a.children;if(null!=c&&1===c.length&&"<"===c[0].tag)c=c[0].children,a.dom.innerHTML!==c&&(a.dom.innerHTML=c);else if(null!=a.text||null!=c&&0!==c.length)throw Error("Child node of a contenteditable must be trusted");}function A(a,c,b){for(;c<b;c++){var q=a[c];null!=q&&(q.skip?q.skip=!1:h(q))}}function h(a){function c(){if(++q===b&&(d(a,f),n(a),a.dom)){var c=a.domSize||1;if(1<c)for(var g=
h&&(r(a),a.dom)){var b=a.domSize||1;if(1<b)for(var e=a.dom;--b;){var g=e.nextSibling,f=g.parentNode;null!=f&&f.removeChild(g)}b=a.dom;e=b.parentNode;null!=e&&e.removeChild(b);if(b=null!=c&&null==a.domSize)b=a.attrs,b=!(null!=b&&(b.oncreate||b.onupdate||b.onbeforeremove||b.onremove));b&&"string"===typeof a.tag&&(c.pool?c.pool.push(a):c.pool=[a])}}var h=1,d=0;if(a.attrs&&"function"===typeof a.attrs.onbeforeremove){var e=a.attrs.onbeforeremove.call(a.state,a);null!=e&&"function"===typeof e.then&&(h++, a.dom;--c;){var e=g.nextSibling,h=e.parentNode;null!=h&&h.removeChild(e)}c=a.dom;g=c.parentNode;null!=g&&g.removeChild(c)}}var b=1,q=0,f=a.state;if(a.attrs&&"function"===typeof a.attrs.onbeforeremove){var h=e.call(a.attrs.onbeforeremove,a);null!=h&&"function"===typeof h.then&&(b++,h.then(c,c))}"string"!==typeof a.tag&&"function"===typeof a.state.onbeforeremove&&(h=e.call(a.state.onbeforeremove,a),null!=h&&"function"===typeof h.then&&(b++,h.then(c,c)));c()}function n(a){a.attrs&&"function"===typeof a.attrs.onremove&&
e.then(b,b))}"string"!==typeof a.tag&&"function"===typeof a._state.onbeforeremove&&(e=a._state.onbeforeremove.call(a.state,a),null!=e&&"function"===typeof e.then&&(h++,e.then(b,b)));b()}function r(a){a.attrs&&"function"===typeof a.attrs.onremove&&a.attrs.onremove.call(a.state,a);"string"!==typeof a.tag&&"function"===typeof a._state.onremove&&a._state.onremove.call(a.state,a);if(null!=a.instance)r(a.instance);else if(a=a.children,Array.isArray(a))for(var c=0;c<a.length;c++){var b=a[c];null!=b&&r(b)}} e.call(a.attrs.onremove,a);if("string"!==typeof a.tag)"function"===typeof a.state.onremove&&e.call(a.state.onremove,a),null!=a.instance&&n(a.instance);else if(a=a.children,Array.isArray(a))for(var c=0;c<a.length;c++){var b=a[c];null!=b&&n(b)}}function D(a,c,b,d,e){if("key"!==c&&"is"!==c&&!w(c)){if("o"===c[0]&&"n"===c[1])return O(a,c,d);if("undefined"===typeof d&&"value"===c&&b!==d)a.dom.value="";else if((b!==d||"value"===c||"checked"===c||"selectedIndex"===c||"selected"===c&&a.dom===y.activeElement||
function A(a,c,b,d,e){var h=a.dom;if("key"!==c&&"is"!==c&&(b!==d||"value"===c||"checked"===c||"selectedIndex"===c||"selected"===c&&a.dom===D.activeElement||"object"===typeof d)&&"undefined"!==typeof d&&!E(c)){var g=c.indexOf(":");if(-1<g&&"xlink"===c.substr(0,g))h.setAttributeNS("http://www.w3.org/1999/xlink",c.slice(g+1),d);else if("o"===c[0]&&"n"===c[1]&&"function"===typeof d)x(a,c,d);else if("style"===c)if(a=b,a===d&&(h.style.cssText="",a=null),null==d)h.style.cssText="";else if("string"===typeof d)h.style.cssText= "option"===a.tag&&a.dom.parentNode===y.activeElement||"object"===typeof d)&&void 0!==d){var g=a.dom;if("xlink:"===c.slice(0,6))g.setAttributeNS("http://www.w3.org/1999/xlink",c,d);else if("style"===c)if(a=b,null!=a&&null!=d&&"object"===typeof a&&"object"===typeof d&&d!==a){for(var f in d)d[f]!==a[f]&&(g.style[f]=d[f]);for(f in a)f in d||(g.style[f]="")}else if(a===d&&(g.style.cssText="",a=null),null==d)g.style.cssText="";else if("string"===typeof d)g.style.cssText=d;else for(f in"string"===typeof a&&
d;else{"string"===typeof a&&(h.style.cssText="");for(var f in d)h.style[f]=d[f];if(null!=a&&"string"!==typeof a)for(f in a)f in d||(h.style[f]="")}else c in h&&"href"!==c&&"list"!==c&&"form"!==c&&"width"!==c&&"height"!==c&&void 0===e&&!(a.attrs.is||-1<a.tag.indexOf("-"))?"input"===a.tag&&"value"===c&&a.dom.value==d&&a.dom===D.activeElement||"select"===a.tag&&"value"===c&&a.dom.value==d&&a.dom===D.activeElement||"option"===a.tag&&"value"===c&&a.dom.value==d||("input"===a.tag&&"type"===c?h.setAttribute(c, (g.style.cssText=""),d)g.style[f]=d[f];else if(c in g&&"href"!==c&&"list"!==c&&"form"!==c&&"width"!==c&&"height"!==c&&void 0===e&&!(a.attrs.is||-1<a.tag.indexOf("-"))){if("value"===c){f=""+d;if(("input"===a.tag||"textarea"===a.tag)&&a.dom.value===f&&a.dom===y.activeElement)return;if("select"===a.tag)if(null===d){if(-1===a.dom.selectedIndex&&a.dom===y.activeElement)return}else if(null!==b&&a.dom.value===f&&a.dom===y.activeElement)return;if("option"===a.tag&&null!=b&&a.dom.value===f)return}"input"===
d):h[c]=d):"boolean"===typeof d?d?h.setAttribute(c,""):h.removeAttribute(c):h.setAttribute("className"===c?"class":c,d)}}function E(a){return"oninit"===a||"oncreate"===a||"onupdate"===a||"onremove"===a||"onbeforeremove"===a||"onbeforeupdate"===a}function x(a,c,b){var d=a.dom,e="function"!==typeof F?b:function(a){var c=b.call(d,a);F.call(d,a);return c};if(c in d)d[c]="function"===typeof b?e:null;else{var h=c.slice(2);void 0===a.events&&(a.events={});a.events[c]!==e&&(null!=a.events[c]&&d.removeEventListener(h, a.tag&&"type"===c?g.setAttribute(c,d):g[c]=d}else"boolean"===typeof d?d?g.setAttribute(c,""):g.removeAttribute(c):g.setAttribute("className"===c?"class":c,d)}}}function w(a){return"oninit"===a||"oncreate"===a||"onupdate"===a||"onremove"===a||"onbeforeremove"===a||"onbeforeupdate"===a}function H(){}function O(a,c,b){null!=a.events?a.events[c]!==b&&(null==b||"function"!==typeof b&&"object"!==typeof b?(null!=a.events[c]&&a.dom.removeEventListener(c.slice(2),a.events,!1),a.events[c]=void 0):(null==a.events[c]&&
a.events[c],!1),"function"===typeof b&&(a.events[c]=e,d.addEventListener(h,a.events[c],!1)))}}function C(a,b,d){"function"===typeof a.oninit&&a.oninit.call(b.state,b);"function"===typeof a.oncreate&&d.push(a.oncreate.bind(b.state,b))}function I(a,b,d){"function"===typeof a.onupdate&&d.push(a.onupdate.bind(b.state,b))}var D=b.document,J=D.createDocumentFragment(),F;return{render:function(a,b){if(!a)throw Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.");var c= a.dom.addEventListener(c.slice(2),a.events,!1),a.events[c]=b)):null==b||"function"!==typeof b&&"object"!==typeof b||(a.events=new H,a.dom.addEventListener(c.slice(2),a.events,!1),a.events[c]=b)}function I(a,c,b){"function"===typeof a.oninit&&e.call(a.oninit,c);"function"===typeof a.oncreate&&b.push(e.bind(a.oncreate,c))}function J(a,c,b){"function"===typeof a.onupdate&&b.push(e.bind(a.onupdate,c))}var y=a.document;y.createDocumentFragment();var P={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},
[],d=D.activeElement;null==a.vnodes&&(a.textContent="");Array.isArray(b)||(b=[b]);n(a,a.vnodes,B.normalizeChildren(b),!1,c,null,void 0);a.vnodes=b;for(var e=0;e<c.length;e++)c[e]();D.activeElement!==d&&d.focus()},setEventCallback:function(a){return F=a}}},H=function(b){function d(b){b=g.indexOf(b);-1<b&&g.splice(b,2)}function f(){for(var b=1;b<g.length;b+=2)g[b]()}b=O(b);b.setEventCallback(function(b){!1!==b.redraw&&f()});var g=[];return{subscribe:function(b,f){d(b);g.push(b,Q(f))},unsubscribe:d, C,E={caption:"table",thead:"table",tbody:"table",tfoot:"table",tr:"tbody",th:"tr",td:"tr",colgroup:"table",col:"colgroup"};H.prototype=Object.create(null);H.prototype.handleEvent=function(a){var c=this["on"+a.type];"function"===typeof c?c.call(a.target,a):"function"===typeof c.handleEvent&&c.handleEvent(a);"function"===typeof C&&C.call(a.target,a)};return{render:function(a,c){if(!a)throw Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.");var b=[],d=y.activeElement,
redraw:f,render:b.render}}(window);K.setCompletionCallback(H.redraw);C.mount=function(b){return function(d,f){if(null===f)b.render(d,[]),b.unsubscribe(d);else{if(null==f.view&&"function"!==typeof f)throw Error("m.mount(element, component) expects a component, not a vnode");b.subscribe(d,function(){b.render(d,B(f))});b.redraw()}}}(H);var T=x,L=function(b){if(""===b||null==b)return{};"?"===b.charAt(0)&&(b=b.slice(1));b=b.split("&");for(var d={},f={},g=0;g<b.length;g++){var e=b[g].split("="),n=decodeURIComponent(e[0]), f=a.namespaceURI;null==a.vnodes&&(a.textContent="");Array.isArray(c)||(c=[c]);m(a,a.vnodes,x.normalizeChildren(c),b,null,"http://www.w3.org/1999/xhtml"===f?void 0:f);a.vnodes=c;null!=d&&y.activeElement!==d&&d.focus();for(d=0;d<b.length;d++)b[d]()},setEventCallback:function(a){return C=a}}},F=function(a,d){function e(a){a=l.indexOf(a);-1<a&&l.splice(a,2)}function f(){if(m)throw Error("Nested m.redraw.sync() call");m=!0;for(var a=1;a<l.length;a+=2)try{l[a]()}catch(r){"undefined"!==typeof console&&console.error(r)}m=
e=2===e.length?decodeURIComponent(e[1]):"";"true"===e?e=!0:"false"===e&&(e=!1);var k=n.split(/\]\[?|\[/),q=d;-1<n.indexOf("[")&&k.pop();for(var m=0;m<k.length;m++){var n=k[m],l=k[m+1],l=""==l||!isNaN(parseInt(l,10)),u=m===k.length-1;""===n&&(n=k.slice(0,m).join(),null==f[n]&&(f[n]=0),n=f[n]++);null==q[n]&&(q[n]=u?e:l?[]:{});q=q[n]}}return d},U=function(b){function d(d){var e=b.location[d].replace(/(?:%[a-f89][a-f0-9])+/gim,decodeURIComponent);"pathname"===d&&"/"!==e[0]&&(e="/"+e);return e}function f(b){return function(){null== !1}var k=Q(a);k.setEventCallback(function(a){!1===a.redraw?a.redraw=void 0:p()});var l=[],m=!1,p=(d||S)(f);p.sync=f;return{subscribe:function(a,d){e(a);l.push(a,d)},unsubscribe:e,redraw:p,render:k.render}}(window);K.setCompletionCallback(F.redraw);w.mount=function(a){return function(d,e){if(null===e)a.render(d,[]),a.unsubscribe(d);else{if(null==e.view&&"function"!==typeof e)throw Error("m.mount(element, component) expects a component, not a vnode");var f=function(){a.render(d,x(e))};a.subscribe(d,
k&&(k=n(function(){k=null;b()}))}}function g(b,d,e){var a=b.indexOf("?"),g=b.indexOf("#"),f=-1<a?a:-1<g?g:b.length;if(-1<a){var a=L(b.slice(a+1,-1<g?g:b.length)),k;for(k in a)d[k]=a[k]}if(-1<g)for(k in d=L(b.slice(g+1)),d)e[k]=d[k];return b.slice(0,f)}var e="function"===typeof b.history.pushState,n="function"===typeof setImmediate?setImmediate:setTimeout,k,q={prefix:"#!",getPath:function(){switch(q.prefix.charAt(0)){case "#":return d("hash").slice(q.prefix.length);case "?":return d("search").slice(q.prefix.length)+ f);f()}}}(F);var W=n,L=function(a){if(""===a||null==a)return{};"?"===a.charAt(0)&&(a=a.slice(1));a=a.split("&");for(var d={},e={},f=0;f<a.length;f++){var k=a[f].split("="),l=decodeURIComponent(k[0]);k=2===k.length?decodeURIComponent(k[1]):"";"true"===k?k=!0:"false"===k&&(k=!1);var m=l.split(/\]\[?|\[/),p=d;-1<l.indexOf("[")&&m.pop();for(var u=0;u<m.length;u++){l=m[u];var r=m[u+1];r=""==r||!isNaN(parseInt(r,10));var n=u===m.length-1;""===l&&(l=m.slice(0,u).join(),null==e[l]&&(e[l]=0),l=e[l]++);null==
d("hash");default:return d("pathname").slice(q.prefix.length)+d("search")+d("hash")}},setPath:function(d,f,k){var a={},l={};d=g(d,a,l);if(null!=f){for(var m in f)a[m]=f[m];d=d.replace(/:([^\/]+)/g,function(b,d){delete a[d];return f[d]})}(m=F(a))&&(d+="?"+m);(l=F(l))&&(d+="#"+l);e?(l=k?k.state:null,m=k?k.title:null,b.onpopstate(),k&&k.replace?b.history.replaceState(l,m,q.prefix+d):b.history.pushState(l,m,q.prefix+d)):b.location.href=q.prefix+d},defineRoutes:function(d,k,n){function a(){var a=q.getPath(), p[l]&&(p[l]=n?k:r?[]:{});p=p[l]}}return d},X=function(a){function d(d){var f=a.location[d].replace(/(?:%[a-f89][a-f0-9])+/gim,decodeURIComponent);"pathname"===d&&"/"!==f[0]&&(f="/"+f);return f}function e(a){return function(){null==m&&(m=l(function(){m=null;a()}))}}function f(a,d,f){var b=a.indexOf("?"),e=a.indexOf("#"),h=-1<b?b:-1<e?e:a.length;if(-1<b){b=L(a.slice(b+1,-1<e?e:a.length));for(var k in b)d[k]=b[k]}if(-1<e)for(k in d=L(a.slice(e+1)),d)f[k]=d[k];return a.slice(0,h)}var k="function"===typeof a.history.pushState,
e={},f=g(a,e,e),l=b.history.state;if(null!=l)for(var m in l)e[m]=l[m];for(var u in d)if(l=new RegExp("^"+u.replace(/:[^\/]+?\.{3}/g,"(.*?)").replace(/:[^\/]+/g,"([^\\/]+)")+"/?$"),l.test(f)){f.replace(l,function(){for(var b=u.match(/:[^\/]+/g)||[],g=[].slice.call(arguments,1,-2),f=0;f<b.length;f++)e[b[f].replace(/:|\./g,"")]=decodeURIComponent(g[f]);k(d[u],e,a,u)});return}n(a,e)}e?b.onpopstate=f(a):"#"===q.prefix.charAt(0)&&(b.onhashchange=a);a()}};return q};C.route=function(b,d){var f=U(b),g=function(b){return b}, l="function"===typeof setImmediate?setImmediate:setTimeout,m,p={prefix:"#!",getPath:function(){switch(p.prefix.charAt(0)){case "#":return d("hash").slice(p.prefix.length);case "?":return d("search").slice(p.prefix.length)+d("hash");default:return d("pathname").slice(p.prefix.length)+d("search")+d("hash")}},setPath:function(d,e,m){var b={},l={};d=f(d,b,l);if(null!=e){for(var h in e)b[h]=e[h];d=d.replace(/:([^\/]+)/g,function(a,d){delete b[d];return e[d]})}(h=E(b))&&(d+="?"+h);(l=E(l))&&(d+="#"+l);
e,n,k,q,m,l=function(b,a,l){if(null==b)throw Error("Ensure the DOM element that was passed to `m.route` is not undefined");var u=function(){null!=e&&d.render(b,e(B(n,k.key,k)))},w=function(b){if(b!==a)f.setPath(a,null,{replace:!0});else throw Error("Could not resolve default route "+a);};f.defineRoutes(l,function(a,b,d){var f=m=function(a,l){f===m&&(n=null==l||"function"!==typeof l.view&&"function"!==typeof l?"div":l,k=b,q=d,m=null,e=(a.render||g).bind(a),u())};a.view||"function"===typeof a?f({}, k?(l=m?m.state:null,h=m?m.title:null,a.onpopstate(),m&&m.replace?a.history.replaceState(l,h,p.prefix+d):a.history.pushState(l,h,p.prefix+d)):a.location.href=p.prefix+d},defineRoutes:function(d,l,m){function b(){var b=p.getPath(),e={},k=f(b,e,e),n=a.history.state;if(null!=n)for(var u in n)e[u]=n[u];for(var r in d)if(n=new RegExp("^"+r.replace(/:[^\/]+?\.{3}/g,"(.*?)").replace(/:[^\/]+/g,"([^\\/]+)")+"/?$"),n.test(k)){k.replace(n,function(){for(var a=r.match(/:[^\/]+/g)||[],f=[].slice.call(arguments,
a):a.onmatch?T.resolve(a.onmatch(b,d)).then(function(b){f(a,b)},w):f(a,"div")},w);d.subscribe(b,u)};l.set=function(b,a,d){null!=m&&(d={replace:!0});m=null;f.setPath(b,a,d)};l.get=function(){return q};l.prefix=function(b){f.prefix=b};l.link=function(b){b.dom.setAttribute("href",f.prefix+b.attrs.href);b.dom.onclick=function(a){a.ctrlKey||a.metaKey||a.shiftKey||2===a.which||(a.preventDefault(),a.redraw=!1,a=this.getAttribute("href"),0===a.indexOf(f.prefix)&&(a=a.slice(f.prefix.length)),l.set(a,void 0, 1,-2),h=0;h<a.length;h++)e[a[h].replace(/:|\./g,"")]=decodeURIComponent(f[h]);l(d[r],e,b,r)});return}m(b,e)}k?a.onpopstate=e(b):"#"===p.prefix.charAt(0)&&(a.onhashchange=b);b()}};return p};w.route=function(a,d){var e=X(a),f=function(a){return a},k,l,m,p,n,r=function(a,r,h){function b(){null!=k&&d.render(a,k(x(l,m.key,m)))}if(null==a)throw Error("Ensure the DOM element that was passed to `m.route` is not undefined");var u=function(){b();u=d.redraw};d.subscribe(a,b);var w=function(a){if(a!==r)e.setPath(r,
void 0))}};l.param=function(b){return"undefined"!==typeof k&&"undefined"!==typeof b?k[b]:k};return l}(window,H);C.withAttr=function(b,d,f){return function(g){d.call(f||this,b in g.currentTarget?g.currentTarget[b]:g.currentTarget.getAttribute(b))}};var V=O(window);C.render=V.render;C.redraw=H.redraw;C.request=K.request;C.jsonp=K.jsonp;C.parseQueryString=L;C.buildQueryString=F;C.version="1.1.1";C.vnode=B;"undefined"!==typeof module?module.exports=C:window.m=C})(); null,{replace:!0});else throw Error("Could not resolve default route "+r);};e.defineRoutes(h,function(a,b,d){var e=n=function(a,h){e===n&&(l=null==h||"function"!==typeof h.view&&"function"!==typeof h?"div":h,m=b,p=d,n=null,k=(a.render||f).bind(a),u())};a.view||"function"===typeof a?e({},a):a.onmatch?W.resolve(a.onmatch(b,d)).then(function(b){e(a,b)},w):e(a,"div")},w)};r.set=function(a,d,f){null!=n&&(f=f||{},f.replace=!0);n=null;e.setPath(a,d,f)};r.get=function(){return p};r.prefix=function(a){e.prefix=
a};var w=function(a,d){d.dom.setAttribute("href",e.prefix+d.attrs.href);d.dom.onclick=function(b){b.ctrlKey||b.metaKey||b.shiftKey||2===b.which||(b.preventDefault(),b.redraw=!1,b=this.getAttribute("href"),0===b.indexOf(e.prefix)&&(b=b.slice(e.prefix.length)),r.set(b,void 0,a))}};r.link=function(a){return null==a.tag?w.bind(w,a):w({},a)};r.param=function(a){return"undefined"!==typeof m&&"undefined"!==typeof a?m[a]:m};return r}(window,F);w.withAttr=function(a,d,e){return function(f){d.call(e||this,
a in f.currentTarget?f.currentTarget[a]:f.currentTarget.getAttribute(a))}};var Y=Q(window);w.render=Y.render;w.redraw=F.redraw;w.request=K.request;w.jsonp=K.jsonp;w.parseQueryString=L;w.buildQueryString=E;w.version="1.1.3";w.vnode=x;w.PromisePolyfill=n;"undefined"!==typeof module?module.exports=w:window.m=w})();

21
ospec/LICENSE Normal file
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

@ -1,15 +1,13 @@
# ospec 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) | [API](#api) | [Goals](#goals) [About](#about) | [Usage](#usage) | [API](#api) | [Goals](#goals)
Noiseless testing framework Noiseless testing framework
Version: 1.2.3
License: MIT
## About ## About
- ~180 LOC - ~330 LOC including the CLI runner
- terser and faster test code than with mocha, jasmine or tape - terser and faster test code than with mocha, jasmine or tape
- test code reads like bullet points - test code reads like bullet points
- assertion code follows [SVO](https://en.wikipedia.org/wiki/Subjectverbobject) structure in present tense for terseness and readability - assertion code follows [SVO](https://en.wikipedia.org/wiki/Subjectverbobject) structure in present tense for terseness and readability
@ -21,7 +19,7 @@ License: MIT
- `before`/`after`/`beforeEach`/`afterEach` hooks - `before`/`after`/`beforeEach`/`afterEach` hooks
- test exclusivity (i.e. `.only`) - test exclusivity (i.e. `.only`)
- async tests and hooks - async tests and hooks
- explicitly disallows test-space configuration to encourage focus on testing, and to provide uniform test suites across projects - explicitly regulates test-space configuration to encourage focus on testing, and to provide uniform test suites across projects
## Usage ## Usage
@ -150,6 +148,22 @@ o("setTimeout calls callback", function(done) {
}) })
``` ```
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()
})
```
By default, asynchronous tests time out after 20ms. This can be changed on a per-test basis using the `timeout` argument: By default, asynchronous tests time out after 20ms. This can be changed on a per-test basis using the `timeout` argument:
```javascript ```javascript
@ -160,7 +174,22 @@ o("setTimeout calls callback", function(done, timeout) {
}) })
``` ```
Note that the `timeout` function call must be the first statement in its test. Note that the `timeout` function call must be the first statement in its test. This currently does not work for promise tests. You can combine both methods to do this:
```javascript
o("promise test", function(done, timeout) {
timeout(1000)
someOtherAsyncFunctionThatTakes900ms().then(done)
})
```
```javascript
o("promise test", async function(done, timeout) {
timeout(1000)
await someOtherAsyncFunctionThatTakes900ms()
done()
})
```
Asynchronous tests generate an assertion that succeeds upon calling `done` or fails on timeout with the error message `async test timed out`. Asynchronous tests generate an assertion that succeeds upon calling `done` or fails on timeout with the error message `async test timed out`.
@ -252,7 +281,7 @@ o.run()
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. 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 ```javascript
var _o = o.new() var _o = o.new('optional name')
_o("a test", function() { _o("a test", function() {
_o(1).equals(1) _o(1).equals(1)
}) })
@ -282,7 +311,9 @@ ospec will automatically evaluate all `*.js` files in any folder named `/tests`.
Ospec doesn't work when installed globally. 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. Ospec doesn't work when installed globally. 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.
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. 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 npm install npm-run -g
@ -408,9 +439,24 @@ The arguments that were passed to the function in the last time it was called
--- ---
### void o.run() ### void o.run([Function reporter])
Runs the test suite 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.
--- ---
@ -426,6 +472,74 @@ $o("a test", function() {
$o.run() $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 result.pass
True if the test passed. **No other keys will exist on the result if this value is true.**
---
### Error result.error
The `Error` object explaining the reason behind a failure.
---
### 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 ## Goals
@ -433,8 +547,8 @@ $o.run()
- Do the most common things that the mocha/chai/sinon triad does without having to install 3 different libraries and several dozen dependencies - 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 configuration in test-space:
- Disallow ability to pick between API styles (BDD/TDD/Qunit, assert/should/expect, etc) - Disallow ability to pick between API styles (BDD/TDD/Qunit, assert/should/expect, etc)
- Disallow ability to pick between different reporters
- Disallow ability to add custom assertion types - Disallow ability to add custom assertion types
- Provide a default simple reporter
- Make assertion code terse, readable and self-descriptive - Make assertion code terse, readable and self-descriptive
- Have as few assertion types as possible for a workable usage pattern - Have as few assertion types as possible for a workable usage pattern

View file

@ -17,6 +17,7 @@ function traverseDirectory(pathname, callback) {
var promises = [] var promises = []
for (var i = 0; i < pathnames.length; i++) { for (var i = 0; i < pathnames.length; i++) {
if (pathnames[i] === "node_modules") continue if (pathnames[i] === "node_modules") continue
if (pathnames[i][0] === ".") continue
pathnames[i] = path.join(pathname, pathnames[i]) pathnames[i] = path.join(pathname, pathnames[i])
promises.push(traverseDirectory(pathnames[i], callback)) promises.push(traverseDirectory(pathnames[i], callback))
} }

View file

@ -1,9 +1,16 @@
/* eslint-disable no-bitwise, no-process-exit */ /* eslint-disable global-require, no-bitwise, no-process-exit */
"use strict" "use strict"
;(function(m) {
module.exports = new function init() { if (typeof module !== "undefined") module["exports"] = m()
else window.o = m()
})(function init(name) {
var spec = {}, subjects = [], results, only = null, ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty var spec = {}, subjects = [], results, only = null, ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty
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) { function o(subject, predicate) {
if (predicate === undefined) { if (predicate === undefined) {
if (results == null) throw new Error("Assertions should not occur outside test definitions") if (results == null) throw new Error("Assertions should not occur outside test definitions")
@ -47,10 +54,35 @@ module.exports = new function init() {
spy.callCount = 0 spy.callCount = 0
return spy return spy
} }
o.run = function() { 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].indexOf(ospecFileName) !== -1) i++
// now we're in user code
return stack[i]
}
o.run = function(reporter) {
results = [] results = []
start = new Date start = new Date
test(spec, [], [], report) test(spec, [], [], function() {
setTimeout(function () {
if (typeof reporter === "function") reporter(results)
else {
var errCount = o.report(results)
if (hasProcess && errCount !== 0) process.exit(1)
}
})
})
function test(spec, pre, post, finalize) { function test(spec, pre, post, finalize) {
pre = [].concat(pre, spec["__beforeEach"] || []) pre = [].concat(pre, spec["__beforeEach"] || [])
@ -82,41 +114,56 @@ module.exports = new function init() {
if (cursor === fns.length) return if (cursor === fns.length) return
var fn = fns[cursor++] var fn = fns[cursor++]
var timeout = 0, delay = 200, s = new Date
var isDone = false
function done(err) {
if (err) {
if (err instanceof Error) record(err.message, err)
else record(String(err))
subjects.pop()
next()
}
if (timeout !== undefined) {
timeout = clearTimeout(timeout)
if (delay !== Infinity) record(null)
if (!isDone) next()
else throw new Error("`" + arg + "()` should only be called once")
isDone = true
}
else console.log("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms")
}
function startTimer() {
timeout = setTimeout(function() {
timeout = undefined
record("async test timed out")
next()
}, Math.min(delay, 2147483647))
}
if (fn.length > 0) { if (fn.length > 0) {
var timeout = 0, delay = 200, s = new Date
var isDone = false
var body = fn.toString() var body = fn.toString()
var arg = (body.match(/\(([\w$]+)/) || body.match(/([\w$]+)\s*=>/) || []).pop() var arg = (body.match(/\(([\w$]+)/) || body.match(/([\w$]+)\s*=>/) || []).pop()
if (body.indexOf(arg) === body.lastIndexOf(arg)) throw new Error("`" + arg + "()` should be called at least once") if (body.indexOf(arg) === body.lastIndexOf(arg)) throw new Error("`" + arg + "()` should be called at least once")
try { try {
fn(function done() { fn(done, function(t) {delay = t})
if (timeout !== undefined) {
timeout = clearTimeout(timeout)
if (delay !== Infinity) record(null)
if (!isDone) next()
else throw new Error("`" + arg + "()` should only be called once")
isDone = true
}
else console.log("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms")
}, function(t) {delay = t})
} }
catch (e) { catch (e) {
if (e instanceof Error) record(e.message, e) done(e)
else record(String(e))
subjects.pop()
next()
} }
if (timeout === 0) { if (timeout === 0) {
timeout = setTimeout(function() { startTimer()
timeout = undefined
record("async test timed out")
next()
}, Math.min(delay, 2147483647))
} }
} }
else { else {
fn() var p = fn()
nextTickish(next) if (p && p.then) {
startTimer()
p.then(function() { done() }, done)
} else {
nextTickish(next)
}
} }
} }
} }
@ -200,11 +247,13 @@ module.exports = new function init() {
} }
result.context = subjects.join(" > ") result.context = subjects.join(" > ")
result.message = message result.message = message
result.error = error.stack result.error = error
} }
results.push(result) results.push(result)
} }
function serialize(value) { function serialize(value) {
if (hasProcess) return require("util").inspect(value)
if (value === null || (typeof value === "object" && !(value instanceof Array)) || typeof value === "number") return String(value) 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>" else if (typeof value === "function") return value.name || "<anonymous function>"
try {return JSON.stringify(value)} catch (e) {return String(value)} try {return JSON.stringify(value)} catch (e) {return String(value)}
@ -213,23 +262,24 @@ module.exports = new function init() {
return hasProcess ? "\x1b[31m" + message + "\x1b[0m" : "%c" + message + "%c " return hasProcess ? "\x1b[31m" + message + "\x1b[0m" : "%c" + message + "%c "
} }
function report() { o.report = function (results) {
var status = 0 var errCount = 0
for (var i = 0, r; r = results[i]; i++) { for (var i = 0, r; r = results[i]; i++) {
if (!r.pass) { if (!r.pass) {
var stackTrace = r.error.match(/^(?:(?!Error|[\/\\]ospec[\/\\]ospec\.js).)*$/m) var stackTrace = o.cleanStackTrace(r.error)
console.error(r.context + ":\n" + highlight(r.message) + (stackTrace ? "\n\n" + stackTrace + "\n\n" : ""), hasProcess ? "" : "color:red", hasProcess ? "" : "color:black") console.error(r.context + ":\n" + highlight(r.message) + (stackTrace ? "\n\n" + stackTrace + "\n\n" : ""), hasProcess ? "" : "color:red", hasProcess ? "" : "color:black")
status = 1 errCount++
} }
} }
console.log( console.log(
(name ? name + ": " : "") +
results.length + " assertions completed in " + Math.round(new Date - start) + "ms, " + results.length + " assertions completed in " + Math.round(new Date - start) + "ms, " +
"of which " + results.filter(function(result){return result.error}).length + " failed" "of which " + results.filter(function(result){return result.error}).length + " failed"
) )
if (hasProcess && status === 1) process.exit(1) return errCount
} }
if(hasProcess) { if (hasProcess) {
nextTickish = process.nextTick nextTickish = process.nextTick
} else { } else {
nextTickish = function fakeFastNextTick(next) { nextTickish = function fakeFastNextTick(next) {
@ -239,4 +289,4 @@ module.exports = new function init() {
} }
return o return o
} })

View file

@ -1,6 +1,6 @@
{ {
"name": "ospec", "name": "ospec",
"version": "1.2.3", "version": "1.4.0",
"description": "Noiseless testing framework", "description": "Noiseless testing framework",
"main": "ospec.js", "main": "ospec.js",
"directories": { "directories": {
@ -12,5 +12,5 @@
"bin": { "bin": {
"ospec": "./bin/ospec" "ospec": "./bin/ospec"
}, },
"repository": "lhorie/mithril.js#rewrite" "repository": "MithrilJS/mithril.js"
} }

View file

@ -18,6 +18,77 @@ new function(o) {
o.run() o.run()
}(o) }(o)
new function(o) {
var clone = o.new()
clone.spec("clone", function() {
clone("fail", function() {
clone(true).equals(false)
})
clone("pass", function() {
clone(true).equals(true)
})
})
// Predicate test passing on clone results
o.spec("reporting", function() {
o("reports per instance", function(done, timeout) {
timeout(100) // Waiting on clone
clone.run(function(results) {
o(typeof results).equals("object")
o("length" in results).equals(true)
o(results.length).equals(2)("Two results")
o("error" in results[0] && "pass" in results[0]).equals(true)("error and pass keys present in failing result")
o(!("error" in results[1]) && "pass" in results[1]).equals(true)("only pass key present in passing result")
o(results[0].pass).equals(false)("Test meant to fail has failed")
o(results[1].pass).equals(true)("Test meant to pass has passed")
done()
})
})
o("o.report() returns the number of failures", function () {
var log = console.log, error = console.error
console.log = o.spy()
console.error = o.spy()
function makeError(msg) {try{throw msg ? new Error(msg) : new Error} catch(e){return e}}
try {
var errCount = o.report([{pass: true}, {pass: true}])
o(errCount).equals(0)
o(console.log.callCount).equals(1)
o(console.error.callCount).equals(0)
errCount = o.report([
{pass: false, error: makeError("hey"), message: "hey"}
])
o(errCount).equals(1)
o(console.log.callCount).equals(2)
o(console.error.callCount).equals(1)
errCount = o.report([
{pass: false, error: makeError("hey"), message: "hey"},
{pass: true},
{pass: false, error: makeError("ho"), message: "ho"}
])
o(errCount).equals(2)
o(console.log.callCount).equals(3)
o(console.error.callCount).equals(3)
} catch (e) {
o(1).equals(0)("Error while testing the reporter")
}
console.log = log
console.error = error
})
})
}(o)
o.spec("ospec", function() { o.spec("ospec", function() {
o.spec("sync", function() { o.spec("sync", function() {
var a = 0, b = 0, illegalAssertionThrows = false var a = 0, b = 0, illegalAssertionThrows = false
@ -107,7 +178,7 @@ o.spec("ospec", function() {
o(output).deepEquals({tag: "div", children: children}) o(output).deepEquals({tag: "div", children: children})
}) })
}) })
o.spec("async", function() { o.spec("async callback", function() {
var a = 0, b = 0 var a = 0, b = 0
o.before(function(done) { o.before(function(done) {
@ -148,4 +219,63 @@ o.spec("ospec", function() {
}) })
}) })
}) })
o.spec("stack trace cleaner", function() {
o("handles line breaks", function() {
try {
throw new Error("line\nbreak")
} catch(error) {
var trace = o.cleanStackTrace(error)
o(trace).notEquals("break")
o(trace.includes("test-ospec.js")).equals(true)
}
})
})
o.spec("async promise", function() {
var a = 0, b = 0
function wrapPromise(fn) {
return new Promise((resolve, reject) => {
callAsync(() => {
try {
fn()
resolve()
} catch(e) {
reject(e)
}
})
})
}
o.before(function() {
return wrapPromise(() => {
a = 1
})
})
o.after(function() {
return wrapPromise(function() {
a = 0
})
})
o.beforeEach(function() {
return wrapPromise(function() {
b = 1
})
})
o.afterEach(function() {
return wrapPromise(function() {
b = 0
})
})
o("promise functions", function() {
return wrapPromise(function() {
o(a).equals(b)
o(a).equals(1)("a and b should be initialized")
})
})
})
}) })

4310
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,16 +1,17 @@
{ {
"name": "mithril", "name": "mithril",
"version": "1.1.1", "version": "1.1.3",
"description": "A framework for building brilliant applications", "description": "A framework for building brilliant applications",
"author": "Leo Horie", "author": "Leo Horie",
"license": "MIT", "license": "MIT",
"main": "mithril.js", "main": "mithril.js",
"repository": "lhorie/mithril.js", "repository": "MithrilJS/mithril.js",
"scripts": { "scripts": {
"dev": "node bundler/cli browser.js -o mithril.js -w", "dev": "node bundler/cli browser.js -output mithril.js -watch",
"build": "npm run build-browser & npm run build-min", "build": "npm run build-browser & npm run build-min",
"build-browser": "node bundler/cli browser.js -o mithril.js", "build-browser": "node bundler/cli browser.js -output mithril.js",
"build-min": "node bundler/cli browser.js -o mithril.min.js -m", "build-min": "node bundler/cli browser.js -output mithril.min.js -minify",
"precommit": "lint-staged",
"lintdocs": "node docs/lint", "lintdocs": "node docs/lint",
"gendocs": "node docs/generate", "gendocs": "node docs/generate",
"lint": "eslint . || true", "lint": "eslint . || true",
@ -25,13 +26,26 @@
"postversion": "git push --follow-tags" "postversion": "git push --follow-tags"
}, },
"devDependencies": { "devDependencies": {
"@alrra/travis-scripts": "^3.0.1",
"benchmark": "^2.1.4", "benchmark": "^2.1.4",
"danger": "^1.2.0",
"dedent": "^0.7.0",
"eslint": "^3.19.0", "eslint": "^3.19.0",
"gh-pages": "^0.12.0",
"istanbul": "^0.4.5", "istanbul": "^0.4.5",
"marked": "^0.3.6" "lint-staged": "^4.0.4",
"locater": "^1.3.0",
"marked": "^0.3.6",
"pinpoint": "^1.1.0"
}, },
"bin": { "bin": {
"ospec": "./ospec/bin/ospec", "ospec": "./ospec/bin/ospec"
"bundle": "./bundler/bin/bundle" },
} "lint-staged": {
"*.js": [
"eslint . --fix",
"git add"
]
},
"dependencies": {}
} }

View file

@ -70,7 +70,7 @@ suite.on("complete", function() {
suite.on("error", console.error.bind(console)) suite.on("error", console.error.bind(console))
suite.add({ suite.add({
name : "rerender without changes", name : "rerender identical vnode",
onStart : function() { onStart : function() {
this.vdom = m("div", {class: "foo bar", "data-foo": "bar", p: 2}, this.vdom = m("div", {class: "foo bar", "data-foo": "bar", p: 2},
m("header", m("header",
@ -119,6 +119,53 @@ suite.add({
} }
}) })
suite.add({
name : "rerender same tree",
fn : function() {
m.render(scratch, m("div", {class: "foo bar", "data-foo": "bar", p: 2},
m("header",
m("h1", {class: "asdf"}, "a ", "b", " c ", 0, " d"),
m("nav",
m("a", {href: "/foo"}, "Foo"),
m("a", {href: "/bar"}, "Bar")
)
),
m("main",
m("form", {onSubmit: function onSubmit() {}},
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({ suite.add({
name : "construct large VDOM tree", name : "construct large VDOM tree",
@ -311,16 +358,9 @@ var Root = {
} }
} }
suite.add({
name : "repeated trees (recycling)",
fn : function () {
m.render(scratch, [m(Root)])
m.render(scratch, [])
}
})
suite.add({ suite.add({
name : "repeated trees (no recycling)", name : "repeated trees",
fn : function () { fn : function () {
m.render(scratch, [m(Root)]) m.render(scratch, [m(Root)])
m.render(scratch, []) m.render(scratch, [])

112
promise/polyfill.js Normal file
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 w/ 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

@ -1,105 +1,20 @@
"use strict" "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 PromisePolyfill = require("./polyfill")
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 w/ 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.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)
}
})
}
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
if (typeof window.Promise === "undefined") window.Promise = PromisePolyfill 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 module.exports = window.Promise
} else if (typeof global !== "undefined") { } else if (typeof global !== "undefined") {
if (typeof global.Promise === "undefined") global.Promise = PromisePolyfill 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 module.exports = global.Promise
} else { } else {
module.exports = PromisePolyfill module.exports = PromisePolyfill

View file

@ -2,7 +2,7 @@
var o = require("../../ospec/ospec") var o = require("../../ospec/ospec")
var callAsync = require("../../test-utils/callAsync") var callAsync = require("../../test-utils/callAsync")
var Promise = require("../../promise/promise") var Promise = require("../../promise/polyfill")
o.spec("promise", function() { o.spec("promise", function() {
o.spec("constructor", function() { o.spec("constructor", function() {
@ -15,6 +15,7 @@ o.spec("promise", function() {
o("constructor has correct methods", function() { o("constructor has correct methods", function() {
o(typeof Promise.prototype.then).equals("function") o(typeof Promise.prototype.then).equals("function")
o(typeof Promise.prototype.catch).equals("function") o(typeof Promise.prototype.catch).equals("function")
o(typeof Promise.prototype.finally).equals("function")
o(typeof Promise.resolve).equals("function") o(typeof Promise.resolve).equals("function")
o(typeof Promise.reject).equals("function") o(typeof Promise.reject).equals("function")
o(typeof Promise.race).equals("function") o(typeof Promise.race).equals("function")
@ -53,6 +54,78 @@ o.spec("promise", function() {
o(value).equals(1) o(value).equals(1)
}).then(done) }).then(done)
}) })
o("finally lets a fulfilled value pass though", function(done) {
var promise = Promise.resolve(1)
var spy = o.spy(function(){return 2})
promise.finally(spy).then(function(value){
o(value).equals(1)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
o("finally lets a rejected reason pass though", function(done) {
var promise = Promise.reject(1)
var spy = o.spy(function(){return 2})
promise.finally(spy).catch(function(reason){
o(reason).equals(1)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
o("finally overrrides a fulfilled value when it throws", function(done) {
var promise = Promise.resolve(1)
var spy = o.spy(function(){throw 2})
promise.finally(spy).catch(function(reason){
o(reason).equals(2)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
o("finally overrrides a fulfilled value when it returns a rejected Promise", function(done) {
var promise = Promise.resolve(1)
var spy = o.spy(function(){return Promise.reject(2)})
promise.finally(spy).catch(function(reason){
o(reason).equals(2)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
o("finally overrrides a rejected reason when it throws", function(done) {
var promise = Promise.reject(1)
var spy = o.spy(function(){throw 2})
promise.finally(spy).catch(function(reason){
o(reason).equals(2)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
o("finally overrrides a rejected reason when it returns a rejected Promise", function(done) {
var promise = Promise.reject(1)
var spy = o.spy(function(){return Promise.reject(2)})
promise.finally(spy).catch(function(reason){
o(reason).equals(2)
o(spy.callCount).equals(1)
o(spy.args.length).equals(0)
o(spy.this).equals(undefined)
done()
})
})
}) })
o.spec("resolve", function() { o.spec("resolve", function() {
o("resolves once", function(done) { o("resolves once", function(done) {
@ -131,7 +204,7 @@ o.spec("promise", function() {
callAsync(function() {resolve(promise)}) callAsync(function() {resolve(promise)})
}) })
promise.then(null, done) promise.then(null, () => done())
}) })
o("non-function onFulfilled is ignored", function(done) { o("non-function onFulfilled is ignored", function(done) {
var promise = Promise.resolve(1) var promise = Promise.resolve(1)

View file

@ -6,6 +6,11 @@ var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["
var selectorCache = {} var selectorCache = {}
var hasOwn = {}.hasOwnProperty var hasOwn = {}.hasOwnProperty
function isEmpty(object) {
for (var key in object) if (hasOwn.call(object, key)) return false
return true
}
function compileSelector(selector) { function compileSelector(selector) {
var match, tag = "div", classes = [], attrs = {} var match, tag = "div", classes = [], attrs = {}
while (match = selectorParser.exec(selector)) { while (match = selectorParser.exec(selector)) {
@ -17,7 +22,7 @@ function compileSelector(selector) {
var attrValue = match[6] var attrValue = match[6]
if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\") if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\")
if (match[4] === "class") classes.push(attrValue) if (match[4] === "class") classes.push(attrValue)
else attrs[match[4]] = attrValue || true else attrs[match[4]] = attrValue === "" ? attrValue : attrValue || true
} }
} }
if (classes.length > 0) attrs.className = classes.join(" ") if (classes.length > 0) attrs.className = classes.join(" ")
@ -28,6 +33,18 @@ function execSelector(state, attrs, children) {
var hasAttrs = false, childList, text var hasAttrs = false, childList, text
var className = attrs.className || attrs.class var className = attrs.className || attrs.class
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) { for (var key in state.attrs) {
if (hasOwn.call(state.attrs, key)) { if (hasOwn.call(state.attrs, key)) {
attrs[key] = state.attrs[key] attrs[key] = state.attrs[key]

View file

@ -6,9 +6,36 @@ module.exports = function($window) {
var $doc = $window.document var $doc = $window.document
var $emptyFragment = $doc.createDocumentFragment() var $emptyFragment = $doc.createDocumentFragment()
var nameSpace = {
svg: "http://www.w3.org/2000/svg",
math: "http://www.w3.org/1998/Math/MathML"
}
var onevent var onevent
function setEventCallback(callback) {return onevent = callback} function setEventCallback(callback) {return onevent = callback}
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)
}
}
//create //create
function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) { function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) {
for (var i = start; i < end; i++) { for (var i = start; i < end; i++) {
@ -24,25 +51,33 @@ module.exports = function($window) {
vnode.state = {} vnode.state = {}
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks) if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
switch (tag) { switch (tag) {
case "#": return createText(parent, vnode, nextSibling) case "#": createText(parent, vnode, nextSibling); break
case "<": return createHTML(parent, vnode, nextSibling) case "<": createHTML(parent, vnode, ns, nextSibling); break
case "[": return createFragment(parent, vnode, hooks, ns, nextSibling) case "[": createFragment(parent, vnode, hooks, ns, nextSibling); break
default: return createElement(parent, vnode, hooks, ns, nextSibling) default: createElement(parent, vnode, hooks, ns, nextSibling)
} }
} }
else return createComponent(parent, vnode, hooks, ns, nextSibling) else createComponent(parent, vnode, hooks, ns, nextSibling)
} }
function createText(parent, vnode, nextSibling) { function createText(parent, vnode, nextSibling) {
vnode.dom = $doc.createTextNode(vnode.children) vnode.dom = $doc.createTextNode(vnode.children)
insertNode(parent, vnode.dom, nextSibling) insertNode(parent, vnode.dom, nextSibling)
return vnode.dom
} }
function createHTML(parent, vnode, 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) || [] var match = vnode.children.match(/^\s*?<(\w+)/im) || []
var parent1 = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"}[match[1]] || "div" // not using the proper parent makes the child element(s) vanish.
var temp = $doc.createElement(parent1) // var div = document.createElement("div")
// div.innerHTML = "<td>i</td><td>j</td>"
temp.innerHTML = vnode.children // 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.dom = temp.firstChild
vnode.domSize = temp.childNodes.length vnode.domSize = temp.childNodes.length
var fragment = $doc.createDocumentFragment() var fragment = $doc.createDocumentFragment()
@ -51,7 +86,6 @@ module.exports = function($window) {
fragment.appendChild(child) fragment.appendChild(child)
} }
insertNode(parent, fragment, nextSibling) insertNode(parent, fragment, nextSibling)
return fragment
} }
function createFragment(parent, vnode, hooks, ns, nextSibling) { function createFragment(parent, vnode, hooks, ns, nextSibling) {
var fragment = $doc.createDocumentFragment() var fragment = $doc.createDocumentFragment()
@ -62,18 +96,14 @@ module.exports = function($window) {
vnode.dom = fragment.firstChild vnode.dom = fragment.firstChild
vnode.domSize = fragment.childNodes.length vnode.domSize = fragment.childNodes.length
insertNode(parent, fragment, nextSibling) insertNode(parent, fragment, nextSibling)
return fragment
} }
function createElement(parent, vnode, hooks, ns, nextSibling) { function createElement(parent, vnode, hooks, ns, nextSibling) {
var tag = vnode.tag var tag = vnode.tag
switch (vnode.tag) {
case "svg": ns = "http://www.w3.org/2000/svg"; break
case "math": ns = "http://www.w3.org/1998/Math/MathML"; break
}
var attrs = vnode.attrs var attrs = vnode.attrs
var is = attrs && attrs.is var is = attrs && attrs.is
ns = getNameSpace(vnode) || ns
var element = ns ? var element = ns ?
is ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) : is ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) :
is ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag) is ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag)
@ -99,7 +129,6 @@ module.exports = function($window) {
setLateAttrs(vnode) setLateAttrs(vnode)
} }
} }
return element
} }
function initComponent(vnode, hooks) { function initComponent(vnode, hooks) {
var sentinel var sentinel
@ -115,147 +144,250 @@ module.exports = function($window) {
sentinel.$$reentrantLock$$ = true sentinel.$$reentrantLock$$ = true
vnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function") ? new vnode.tag(vnode) : vnode.tag(vnode) vnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function") ? new vnode.tag(vnode) : vnode.tag(vnode)
} }
vnode._state = vnode.state
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks) if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
initLifecycle(vnode._state, vnode, hooks) initLifecycle(vnode.state, vnode, hooks)
vnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode)) 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") if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
sentinel.$$reentrantLock$$ = null sentinel.$$reentrantLock$$ = null
} }
function createComponent(parent, vnode, hooks, ns, nextSibling) { function createComponent(parent, vnode, hooks, ns, nextSibling) {
initComponent(vnode, hooks) initComponent(vnode, hooks)
if (vnode.instance != null) { if (vnode.instance != null) {
var element = createNode(parent, vnode.instance, hooks, ns, nextSibling) createNode(parent, vnode.instance, hooks, ns, nextSibling)
vnode.dom = vnode.instance.dom vnode.dom = vnode.instance.dom
vnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0 vnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0
insertNode(parent, element, nextSibling)
return element
} }
else { else {
vnode.domSize = 0 vnode.domSize = 0
return $emptyFragment
} }
} }
//update //update
function updateNodes(parent, old, vnodes, recycling, hooks, nextSibling, ns) { /**
if (old === vnodes || old == null && vnodes == null) return * @param {Element|Fragment} parent - the parent element
else if (old == null) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, undefined) * @param {Vnode[] | null} old - the list of vnodes of the last `render()` call for
else if (vnodes == null) removeNodes(old, 0, old.length, vnodes) * this part of the tree
else { * @param {Vnode[] | null} vnodes - as above, but for the current `render()` call.
if (old.length === vnodes.length) { * @param {Function[]} hooks - an accumulator of post-render hooks (oncreate/onupdate)
var isUnkeyed = false * @param {Element | null} nextSibling - the next DOM node if we're dealing with a
for (var i = 0; i < vnodes.length; i++) { * fragment that is not the last item in its
if (vnodes[i] != null && old[i] != null) { * parent
isUnkeyed = vnodes[i].key == null && old[i].key == null * @param {'svg' | 'math' | String | null} ns) - the current XML namespace, if any
break * @returns void
} */
} // This function diffs and patches lists of vnodes, both keyed and unkeyed.
if (isUnkeyed) { //
for (var i = 0; i < old.length; i++) { // We will:
if (old[i] === vnodes[i]) continue //
else if (old[i] == null && vnodes[i] != null) createNode(parent, vnodes[i], hooks, ns, getNextSibling(old, i + 1, nextSibling)) // 1. describe its general structure
else if (vnodes[i] == null) removeNodes(old, i, i + 1, vnodes) // 2. focus on the diff algorithm optimizations
else updateNode(parent, old[i], vnodes[i], hooks, getNextSibling(old, i + 1, nextSibling), recycling, ns) // 3. discuss DOM node operations.
}
return // ## Overview:
} //
} // The updateNodes() function:
recycling = recycling || isRecyclable(old, vnodes) // - deals with trivial cases
if (recycling) { // - determines whether the lists are keyed or unkeyed based on the first non-null node
var pool = old.pool // of each list.
old = old.concat(old.pool) // - 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
//
// If one list is keyed and the other is unkeyed, the old is removed, and the new one is
// inserted (since the keys are guaranteed to differ).
//
// Then comes the unkeyed diff algo, and at last, the keyed diff algorithm that is split
// in four parts (simplifying a bit).
//
// The first part goes through both lists top-down as long as the nodes at each level have
// the same key.
//
// The second part deals with lists reversals, and traverses one list top-down and the other
// bottom-up (as long as the keys match).
//
// The third part goes through both lists bottom up as long as the keys match.
//
// The first and third sections allow us to deal efficiently with situations where one or
// more contiguous nodes were either inserted into, removed from or re-ordered in an otherwise
// sorted list. They may reduce the number of nodes to be processed in the fourth section.
//
// The fourth section does keyed diff for the situations not covered by the other three. It
// builds a {key: oldIndex} dictionary and uses it to find old nodes that match the keys of
// new ones.
// The nodes from the `old` array that have a match in the new `vnodes` one are marked as
// `vnode.skip: true`.
//
// If there are still nodes in the new `vnodes` array that haven't been matched to old ones,
// they are created.
// The range of old nodes that wasn't covered by the first three sections is passed to
// `removeNodes()`. Those nodes are removed unless marked as `.skip: true`.
//
// It should be noted that the description of the four sections above is not perfect, because those
// parts are actually implemented as only two loops, one for the first two parts, and one for
// the other two. I'm not sure it wins us anything except maybe a few bytes of file size.
// ## 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) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns)
else if (vnodes == null) removeNodes(old, 0, old.length)
else {
// default to keyed because, when either list is full of null nodes, it has fewer branches
var start = 0, oldStart = 0, isOldKeyed = true, isKeyed = true
for (; oldStart < old.length; oldStart++) {
if (old[oldStart] != null) {
isOldKeyed = old[oldStart].key != null
break
}
}
for (; start < vnodes.length; start++) {
if (vnodes[start] != null) {
isKeyed = vnodes[start].key != null
break
}
}
if (isOldKeyed !== isKeyed) {
removeNodes(old, oldStart, old.length)
createNodes(parent, vnodes, start, vnodes.length, hooks, nextSibling, ns)
return
}
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(o)
else updateNode(parent, o, v, hooks, getNextSibling(old, start + 1, nextSibling), ns)
}
if (old.length > commonLength) removeNodes(old, start, old.length)
if (vnodes.length > commonLength) createNodes(parent, vnodes, start, vnodes.length, hooks, nextSibling, ns)
return
}
// keyed diff
var oldEnd = old.length - 1, end = vnodes.length - 1, map, o, v
var oldStart = 0, start = 0, oldEnd = old.length - 1, end = vnodes.length - 1, map
while (oldEnd >= oldStart && end >= start) { while (oldEnd >= oldStart && end >= start) {
var o = old[oldStart], v = vnodes[start] // both top-down
if (o === v && !recycling) oldStart++, start++ o = old[oldStart]
else if (o == null) oldStart++ v = vnodes[start]
if (o == null) oldStart++
else if (v == null) start++ else if (v == null) start++
else if (o.key === v.key) { else if (o.key === v.key) {
var shouldRecycle = (pool != null && oldStart >= old.length - pool.length) || ((pool == null) && recycling)
oldStart++, start++ oldStart++, start++
updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), shouldRecycle, ns) if (o !== v) updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), ns)
if (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling) } else {
} // reversal: old top-down, new bottom-up
else { v = vnodes[end]
var o = old[oldEnd] if (o == null) oldStart++
if (o === v && !recycling) oldEnd--, start++ else if (v == null) end--
else if (o == null) oldEnd--
else if (v == null) start++
else if (o.key === v.key) { else if (o.key === v.key) {
var shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling) oldStart++
updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns) if (start < end--) insertNode(parent, toFragment(o), nextSibling)
if (recycling || start < end) insertNode(parent, toFragment(o), getNextSibling(old, oldStart, nextSibling)) if (o !== v) updateNode(parent, o, v, hooks, nextSibling, ns)
oldEnd--, start++ if (v.dom != null) nextSibling = v.dom
} }
else break else break
} }
} }
while (oldEnd >= oldStart && end >= start) { while (oldEnd >= oldStart && end >= start) {
var o = old[oldEnd], v = vnodes[end] // both bottom-up
if (o === v && !recycling) oldEnd--, end-- o = old[oldEnd]
else if (o == null) oldEnd-- v = vnodes[end]
if (o == null) oldEnd--
else if (v == null) end-- else if (v == null) end--
else if (o.key === v.key) { else if (o.key === v.key) {
var shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling) if (o !== v) updateNode(parent, o, v, hooks, nextSibling, ns)
updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns) if (v.dom != null) nextSibling = v.dom
if (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling)
if (o.dom != null) nextSibling = o.dom
oldEnd--, end-- oldEnd--, end--
} } else {
else { // old map-based, new bottom-up
if (!map) map = getKeyMap(old, oldEnd) if (map == null) {
// the last node can be left out of the map because it will be caught by the
// bottom-up part of the diff loop. If we were to refactor this to use distinct
// loops, we'd have to pass `oldEnd + 1` (or change `start < end` to `<=` in getKeyMap).
map = getKeyMap(old, oldStart, oldEnd)
}
if (v != null) { if (v != null) {
var oldIndex = map[v.key] var oldIndex = map[v.key]
if (oldIndex != null) { if (oldIndex == null) {
var movable = old[oldIndex] createNode(parent, v, hooks, ns, nextSibling)
var shouldRecycle = (pool != null && oldIndex >= old.length - pool.length) || ((pool == null) && recycling) if (v.dom != null) nextSibling = v.dom
updateNode(parent, movable, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns) } else {
insertNode(parent, toFragment(movable), nextSibling) o = old[oldIndex]
old[oldIndex].skip = true insertNode(parent, toFragment(o), nextSibling)
if (movable.dom != null) nextSibling = movable.dom if (o !== v) updateNode(parent, o, v, hooks, nextSibling, ns)
} o.skip = true
else { if (v.dom != null) nextSibling = v.dom
var dom = createNode(parent, v, hooks, undefined, nextSibling)
nextSibling = dom
} }
} }
end-- end--
} }
if (end < start) break if (end < start) break
} }
// deal with the leftovers.
createNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns) createNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns)
removeNodes(old, oldStart, oldEnd + 1, vnodes) removeNodes(old, oldStart, oldEnd + 1)
} }
} }
function updateNode(parent, old, vnode, hooks, nextSibling, recycling, ns) { function updateNode(parent, old, vnode, hooks, nextSibling, ns) {
var oldTag = old.tag, tag = vnode.tag var oldTag = old.tag, tag = vnode.tag
if (oldTag === tag) { if (oldTag === tag) {
vnode.state = old.state vnode.state = old.state
vnode._state = old._state
vnode.events = old.events vnode.events = old.events
if (!recycling && shouldNotUpdate(vnode, old)) return if (shouldNotUpdate(vnode, old)) return
if (typeof oldTag === "string") { if (typeof oldTag === "string") {
if (vnode.attrs != null) { if (vnode.attrs != null) {
if (recycling) { updateLifecycle(vnode.attrs, vnode, hooks)
vnode.state = {}
initLifecycle(vnode.attrs, vnode, hooks)
}
else updateLifecycle(vnode.attrs, vnode, hooks)
} }
switch (oldTag) { switch (oldTag) {
case "#": updateText(old, vnode); break case "#": updateText(old, vnode); break
case "<": updateHTML(parent, old, vnode, nextSibling); break case "<": updateHTML(parent, old, vnode, ns, nextSibling); break
case "[": updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns); break case "[": updateFragment(parent, old, vnode, hooks, nextSibling, ns); break
default: updateElement(old, vnode, recycling, hooks, ns) default: updateElement(old, vnode, hooks, ns)
} }
} }
else updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) else updateComponent(parent, old, vnode, hooks, nextSibling, ns)
} }
else { else {
removeNode(old, null) removeNode(old)
createNode(parent, vnode, hooks, ns, nextSibling) createNode(parent, vnode, hooks, ns, nextSibling)
} }
} }
@ -265,15 +397,15 @@ module.exports = function($window) {
} }
vnode.dom = old.dom vnode.dom = old.dom
} }
function updateHTML(parent, old, vnode, nextSibling) { function updateHTML(parent, old, vnode, ns, nextSibling) {
if (old.children !== vnode.children) { if (old.children !== vnode.children) {
toFragment(old) toFragment(old)
createHTML(parent, vnode, nextSibling) createHTML(parent, vnode, ns, nextSibling)
} }
else vnode.dom = old.dom, vnode.domSize = old.domSize else vnode.dom = old.dom, vnode.domSize = old.domSize
} }
function updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns) { function updateFragment(parent, old, vnode, hooks, nextSibling, ns) {
updateNodes(parent, old.children, vnode.children, recycling, hooks, nextSibling, ns) updateNodes(parent, old.children, vnode.children, hooks, nextSibling, ns)
var domSize = 0, children = vnode.children var domSize = 0, children = vnode.children
vnode.dom = null vnode.dom = null
if (children != null) { if (children != null) {
@ -287,12 +419,10 @@ module.exports = function($window) {
if (domSize !== 1) vnode.domSize = domSize if (domSize !== 1) vnode.domSize = domSize
} }
} }
function updateElement(old, vnode, recycling, hooks, ns) { function updateElement(old, vnode, hooks, ns) {
var element = vnode.dom = old.dom var element = vnode.dom = old.dom
switch (vnode.tag) { ns = getNameSpace(vnode) || ns
case "svg": ns = "http://www.w3.org/2000/svg"; break
case "math": ns = "http://www.w3.org/1998/Math/MathML"; break
}
if (vnode.tag === "textarea") { if (vnode.tag === "textarea") {
if (vnode.attrs == null) vnode.attrs = {} if (vnode.attrs == null) vnode.attrs = {}
if (vnode.text != null) { if (vnode.text != null) {
@ -310,26 +440,22 @@ module.exports = function($window) {
else { else {
if (old.text != null) old.children = [Vnode("#", undefined, undefined, old.text, undefined, old.dom.firstChild)] if (old.text != null) old.children = [Vnode("#", undefined, undefined, old.text, undefined, old.dom.firstChild)]
if (vnode.text != null) vnode.children = [Vnode("#", undefined, undefined, vnode.text, undefined, undefined)] if (vnode.text != null) vnode.children = [Vnode("#", undefined, undefined, vnode.text, undefined, undefined)]
updateNodes(element, old.children, vnode.children, recycling, hooks, null, ns) updateNodes(element, old.children, vnode.children, hooks, null, ns)
} }
} }
function updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) { function updateComponent(parent, old, vnode, hooks, nextSibling, ns) {
if (recycling) { vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode))
initComponent(vnode, hooks) if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
} else { if (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)
vnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode)) updateLifecycle(vnode.state, vnode, hooks)
if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
if (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)
updateLifecycle(vnode._state, vnode, hooks)
}
if (vnode.instance != null) { if (vnode.instance != null) {
if (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling) if (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling)
else updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, recycling, ns) else updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, ns)
vnode.dom = vnode.instance.dom vnode.dom = vnode.instance.dom
vnode.domSize = vnode.instance.domSize vnode.domSize = vnode.instance.domSize
} }
else if (old.instance != null) { else if (old.instance != null) {
removeNode(old.instance, null) removeNode(old.instance)
vnode.dom = undefined vnode.dom = undefined
vnode.domSize = 0 vnode.domSize = 0
} }
@ -338,24 +464,13 @@ module.exports = function($window) {
vnode.domSize = old.domSize vnode.domSize = old.domSize
} }
} }
function isRecyclable(old, vnodes) { function getKeyMap(vnodes, start, end) {
if (old.pool != null && Math.abs(old.pool.length - vnodes.length) <= Math.abs(old.length - vnodes.length)) { var map = {}
var oldChildrenLength = old[0] && old[0].children && old[0].children.length || 0 for (; start < end; start++) {
var poolChildrenLength = old.pool[0] && old.pool[0].children && old.pool[0].children.length || 0 var vnode = vnodes[start]
var vnodesChildrenLength = vnodes[0] && vnodes[0].children && vnodes[0].children.length || 0
if (Math.abs(poolChildrenLength - vnodesChildrenLength) <= Math.abs(oldChildrenLength - vnodesChildrenLength)) {
return true
}
}
return false
}
function getKeyMap(vnodes, end) {
var map = {}, i = 0
for (var i = 0; i < end; i++) {
var vnode = vnodes[i]
if (vnode != null) { if (vnode != null) {
var key = vnode.key var key = vnode.key
if (key != null) map[key] = i if (key != null) map[key] = start
} }
} }
return map return map
@ -381,7 +496,7 @@ module.exports = function($window) {
} }
function insertNode(parent, dom, nextSibling) { function insertNode(parent, dom, nextSibling) {
if (nextSibling && nextSibling.parentNode) parent.insertBefore(dom, nextSibling) if (nextSibling != null) parent.insertBefore(dom, nextSibling)
else parent.appendChild(dom) else parent.appendChild(dom)
} }
@ -395,26 +510,27 @@ module.exports = function($window) {
} }
//remove //remove
function removeNodes(vnodes, start, end, context) { function removeNodes(vnodes, start, end) {
for (var i = start; i < end; i++) { for (var i = start; i < end; i++) {
var vnode = vnodes[i] var vnode = vnodes[i]
if (vnode != null) { if (vnode != null) {
if (vnode.skip) vnode.skip = false if (vnode.skip) vnode.skip = false
else removeNode(vnode, context) else removeNode(vnode)
} }
} }
} }
function removeNode(vnode, context) { function removeNode(vnode) {
var expected = 1, called = 0 var expected = 1, called = 0
var original = vnode.state
if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") { if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") {
var result = vnode.attrs.onbeforeremove.call(vnode.state, vnode) var result = callHook.call(vnode.attrs.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") { if (result != null && typeof result.then === "function") {
expected++ expected++
result.then(continuation, continuation) result.then(continuation, continuation)
} }
} }
if (typeof vnode.tag !== "string" && typeof vnode._state.onbeforeremove === "function") { if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeremove === "function") {
var result = vnode._state.onbeforeremove.call(vnode.state, vnode) var result = callHook.call(vnode.state.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") { if (result != null && typeof result.then === "function") {
expected++ expected++
result.then(continuation, continuation) result.then(continuation, continuation)
@ -423,6 +539,7 @@ module.exports = function($window) {
continuation() continuation()
function continuation() { function continuation() {
if (++called === expected) { if (++called === expected) {
checkState(vnode, original)
onremove(vnode) onremove(vnode)
if (vnode.dom) { if (vnode.dom) {
var count = vnode.domSize || 1 var count = vnode.domSize || 1
@ -433,10 +550,6 @@ module.exports = function($window) {
} }
} }
removeNodeFromDOM(vnode.dom) removeNodeFromDOM(vnode.dom)
if (context != null && vnode.domSize == null && !hasIntegrationMethods(vnode.attrs) && typeof vnode.tag === "string") { //TODO test custom elements
if (!context.pool) context.pool = [vnode]
else context.pool.push(vnode)
}
} }
} }
} }
@ -446,10 +559,11 @@ module.exports = function($window) {
if (parent != null) parent.removeChild(node) if (parent != null) parent.removeChild(node)
} }
function onremove(vnode) { function onremove(vnode) {
if (vnode.attrs && typeof vnode.attrs.onremove === "function") vnode.attrs.onremove.call(vnode.state, vnode) if (vnode.attrs && typeof vnode.attrs.onremove === "function") callHook.call(vnode.attrs.onremove, vnode)
if (typeof vnode.tag !== "string" && typeof vnode._state.onremove === "function") vnode._state.onremove.call(vnode.state, vnode) if (typeof vnode.tag !== "string") {
if (vnode.instance != null) onremove(vnode.instance) if (typeof vnode.state.onremove === "function") callHook.call(vnode.state.onremove, vnode)
else { if (vnode.instance != null) onremove(vnode.instance)
} else {
var children = vnode.children var children = vnode.children
if (Array.isArray(children)) { if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) { for (var i = 0; i < children.length; i++) {
@ -467,21 +581,32 @@ module.exports = function($window) {
} }
} }
function setAttr(vnode, key, old, value, ns) { function setAttr(vnode, key, old, value, ns) {
var element = vnode.dom if (key === "key" || key === "is" || isLifecycleMethod(key)) return
if (key === "key" || key === "is" || (old === value && !isFormAttribute(vnode, key)) && typeof value !== "object" || typeof value === "undefined" || isLifecycleMethod(key)) return if (key[0] === "o" && key[1] === "n") return updateEvent(vnode, key, value)
var nsLastIndex = key.indexOf(":") if (typeof value === "undefined" && key === "value" && old !== value) {
if (nsLastIndex > -1 && key.substr(0, nsLastIndex) === "xlink") { vnode.dom.value = ""
element.setAttributeNS("http://www.w3.org/1999/xlink", key.slice(nsLastIndex + 1), value) return
} }
else if (key[0] === "o" && key[1] === "n" && typeof value === "function") updateEvent(vnode, key, value) if ((old === value && !isFormAttribute(vnode, key)) && typeof value !== "object" || value === undefined) return
var element = vnode.dom
if (key.slice(0, 6) === "xlink:") element.setAttributeNS("http://www.w3.org/1999/xlink", key, value)
else if (key === "style") updateStyle(element, old, value) else if (key === "style") updateStyle(element, old, value)
else if (key in element && !isAttribute(key) && ns === undefined && !isCustomElement(vnode)) { else if (key in element && !isAttribute(key) && ns === undefined && !isCustomElement(vnode)) {
//setting input[value] to same value by typing on focused element moves cursor to end in Chrome if (key === "value") {
if (vnode.tag === "input" && key === "value" && vnode.dom.value == value && vnode.dom === $doc.activeElement) return var normalized = "" + value // eslint-disable-line no-implicit-coercion
//setting select[value] to same value while having select open blinks select dropdown in Chrome //setting input[value] to same value by typing on focused element moves cursor to end in Chrome
if (vnode.tag === "select" && key === "value" && vnode.dom.value == value && vnode.dom === $doc.activeElement) return if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === normalized && vnode.dom === $doc.activeElement) return
//setting option[value] to same value while having select open blinks select dropdown in Chrome //setting select[value] to same value while having select open blinks select dropdown in Chrome
if (vnode.tag === "option" && key === "value" && vnode.dom.value == value) return if (vnode.tag === "select") {
if (value === null) {
if (vnode.dom.selectedIndex === -1 && vnode.dom === $doc.activeElement) return
} else {
if (old !== null && vnode.dom.value === normalized && vnode.dom === $doc.activeElement) 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 === normalized) return
}
// If you assign an input type that is not supported by IE 11 with an assignment expression, an error will occur. // If you assign an input type that is not supported by IE 11 with an assignment expression, an error will occur.
if (vnode.tag === "input" && key === "type") { if (vnode.tag === "input" && key === "type") {
element.setAttribute(key, value) element.setAttribute(key, value)
@ -521,7 +646,7 @@ module.exports = function($window) {
} }
} }
function isFormAttribute(vnode, attr) { function isFormAttribute(vnode, attr) {
return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === $doc.activeElement return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === $doc.activeElement || vnode.tag === "option" && vnode.dom.parentNode === $doc.activeElement
} }
function isLifecycleMethod(attr) { function isLifecycleMethod(attr) {
return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate" return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate"
@ -532,12 +657,21 @@ module.exports = function($window) {
function isCustomElement(vnode){ function isCustomElement(vnode){
return vnode.attrs.is || vnode.tag.indexOf("-") > -1 return vnode.attrs.is || vnode.tag.indexOf("-") > -1
} }
function hasIntegrationMethods(source) {
return source != null && (source.oncreate || source.onupdate || source.onbeforeremove || source.onremove)
}
//style //style
function updateStyle(element, old, style) { function updateStyle(element, old, style) {
if (old != null && style != null && typeof old === "object" && typeof style === "object" && style !== old) {
// Both old & new are (different) objects.
// Update style properties that have changed
for (var key in style) {
if (style[key] !== old[key]) element.style[key] = style[key]
}
// Remove style properties that no longer exist
for (var key in old) {
if (!(key in style)) element.style[key] = ""
}
return
}
if (old === style) element.style.cssText = "", old = null if (old === style) element.style.cssText = "", old = null
if (style == null) element.style.cssText = "" if (style == null) element.style.cssText = ""
else if (typeof style === "string") element.style.cssText = style else if (typeof style === "string") element.style.cssText = style
@ -546,47 +680,61 @@ module.exports = function($window) {
for (var key in style) { for (var key in style) {
element.style[key] = style[key] element.style[key] = style[key]
} }
if (old != null && typeof old !== "string") {
for (var key in old) {
if (!(key in style)) element.style[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.
function EventDict() {}
EventDict.prototype = Object.create(null)
EventDict.prototype.handleEvent = function (ev) {
var handler = this["on" + ev.type]
if (typeof handler === "function") handler.call(ev.target, ev)
else if (typeof handler.handleEvent === "function") handler.handleEvent(ev)
if (typeof onevent === "function") onevent.call(ev.target, ev)
}
//event //event
function updateEvent(vnode, key, value) { function updateEvent(vnode, key, value) {
var element = vnode.dom if (vnode.events != null) {
var callback = typeof onevent !== "function" ? value : function(e) { if (vnode.events[key] === value) return
var result = value.call(element, e) if (value != null && (typeof value === "function" || typeof value === "object")) {
onevent.call(element, e) if (vnode.events[key] == null) vnode.dom.addEventListener(key.slice(2), vnode.events, false)
return result vnode.events[key] = value
} } else {
if (key in element) element[key] = typeof value === "function" ? callback : null if (vnode.events[key] != null) vnode.dom.removeEventListener(key.slice(2), vnode.events, false)
else { vnode.events[key] = undefined
var eventName = key.slice(2)
if (vnode.events === undefined) vnode.events = {}
if (vnode.events[key] === callback) return
if (vnode.events[key] != null) element.removeEventListener(eventName, vnode.events[key], false)
if (typeof value === "function") {
vnode.events[key] = callback
element.addEventListener(eventName, vnode.events[key], false)
} }
} 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 //lifecycle
function initLifecycle(source, vnode, hooks) { function initLifecycle(source, vnode, hooks) {
if (typeof source.oninit === "function") source.oninit.call(vnode.state, vnode) if (typeof source.oninit === "function") callHook.call(source.oninit, vnode)
if (typeof source.oncreate === "function") hooks.push(source.oncreate.bind(vnode.state, vnode)) if (typeof source.oncreate === "function") hooks.push(callHook.bind(source.oncreate, vnode))
} }
function updateLifecycle(source, vnode, hooks) { function updateLifecycle(source, vnode, hooks) {
if (typeof source.onupdate === "function") hooks.push(source.onupdate.bind(vnode.state, vnode)) if (typeof source.onupdate === "function") hooks.push(callHook.bind(source.onupdate, vnode))
} }
function shouldNotUpdate(vnode, old) { function shouldNotUpdate(vnode, old) {
var forceVnodeUpdate, forceComponentUpdate var forceVnodeUpdate, forceComponentUpdate
if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") forceVnodeUpdate = vnode.attrs.onbeforeupdate.call(vnode.state, vnode, old) if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") {
if (typeof vnode.tag !== "string" && typeof vnode._state.onbeforeupdate === "function") forceComponentUpdate = vnode._state.onbeforeupdate.call(vnode.state, vnode, old) forceVnodeUpdate = callHook.call(vnode.attrs.onbeforeupdate, vnode, old)
}
if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeupdate === "function") {
forceComponentUpdate = callHook.call(vnode.state.onbeforeupdate, vnode, old)
}
if (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) { if (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) {
vnode.dom = old.dom vnode.dom = old.dom
vnode.domSize = old.domSize vnode.domSize = old.domSize
@ -600,15 +748,17 @@ module.exports = function($window) {
if (!dom) throw new Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.") if (!dom) throw new Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.")
var hooks = [] var hooks = []
var active = $doc.activeElement var active = $doc.activeElement
var namespace = dom.namespaceURI
// First time rendering into a node clears it out // First time rendering into a node clears it out
if (dom.vnodes == null) dom.textContent = "" if (dom.vnodes == null) dom.textContent = ""
if (!Array.isArray(vnodes)) vnodes = [vnodes] if (!Array.isArray(vnodes)) vnodes = [vnodes]
updateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), false, hooks, null, undefined) updateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? undefined : namespace)
dom.vnodes = vnodes dom.vnodes = vnodes
// document.activeElement can return null in IE https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
if (active != null && $doc.activeElement !== active) active.focus()
for (var i = 0; i < hooks.length; i++) hooks[i]() for (var i = 0; i < hooks.length; i++) hooks[i]()
if ($doc.activeElement !== active) active.focus()
} }
return {render: render, setEventCallback: setEventCallback} return {render: render, setEventCallback: setEventCallback}

View file

@ -11,6 +11,46 @@ o.spec("attributes", function() {
root = $window.document.body root = $window.document.body
render = vdom($window).render render = vdom($window).render
}) })
o.spec("basics", function() {
o("works (create/update/remove)", function() {
var a = {tag: "div", attrs: {}}
var b = {tag: "div", attrs: {id: "test"}}
var c = {tag: "div", attrs: {}}
render(root, [a]);
o(a.dom.hasAttribute("id")).equals(false)
render(root, [b]);
o(b.dom.getAttribute("id")).equals("test")
render(root, [c]);
o(c.dom.hasAttribute("id")).equals(false)
})
o("undefined attr is equivalent to a lack of attr", function() {
var a = {tag: "div", attrs: {id: undefined}}
var b = {tag: "div", attrs: {id: "test"}}
var c = {tag: "div", attrs: {id: undefined}}
render(root, [a]);
o(a.dom.hasAttribute("id")).equals(false)
render(root, [b]);
o(b.dom.hasAttribute("id")).equals(true)
o(b.dom.getAttribute("id")).equals("test")
render(root, [c]);
// #1804
// TODO: uncomment
// o(c.dom.hasAttribute("id")).equals(false)
})
})
o.spec("customElements", function(){ o.spec("customElements", function(){
o("when vnode is customElement, custom setAttribute called", function(){ o("when vnode is customElement, custom setAttribute called", function(){
@ -54,7 +94,7 @@ o.spec("attributes", function() {
render(root, [a]) render(root, [a])
o(a.dom.attributes["readonly"].nodeValue).equals("") o(a.dom.attributes["readonly"].value).equals("")
}) })
o("when input readonly is false, attribute is not present", function() { o("when input readonly is false, attribute is not present", function() {
var a = {tag: "input", attrs: {readonly: false}} var a = {tag: "input", attrs: {readonly: false}}
@ -96,6 +136,196 @@ o.spec("attributes", function() {
o(a.dom.attributes["checked"]).equals(undefined) o(a.dom.attributes["checked"]).equals(undefined)
}) })
}) })
o.spec("input.value", function() {
o("can be set as text", function() {
var a = {tag: "input", attrs: {value: "test"}}
render(root, [a]);
o(a.dom.value).equals("test")
})
o("a lack of attribute removes `value`", function() {
var a = {tag: "input", attrs: {}}
var b = {tag: "input", attrs: {value: "test"}}
// var c = {tag: "input", attrs: {}}
render(root, [a])
o(a.dom.value).equals("")
render(root, [b])
o(a.dom.value).equals("test")
// https://github.com/MithrilJS/mithril.js/issues/1804#issuecomment-304521235
// TODO: Uncomment
// render(root, [c])
// o(a.dom.value).equals("")
})
o("can be set as number", function() {
var a = {tag: "input", attrs: {value: 1}}
render(root, [a]);
o(a.dom.value).equals("1")
})
o("null becomes the empty string", function() {
var a = {tag: "input", attrs: {value: null}}
var b = {tag: "input", attrs: {value: "test"}}
var c = {tag: "input", attrs: {value: null}}
render(root, [a]);
o(a.dom.value).equals("")
o(a.dom.getAttribute("value")).equals(null)
render(root, [b]);
o(b.dom.value).equals("test")
o(b.dom.getAttribute("value")).equals(null)
render(root, [c]);
o(c.dom.value).equals("")
o(c.dom.getAttribute("value")).equals(null)
})
o("'' and 0 are different values", function() {
var a = {tag: "input", attrs: {value: 0}, children:[{tag:"#", children:""}]}
var b = {tag: "input", attrs: {value: ""}, children:[{tag:"#", children:""}]}
var c = {tag: "input", attrs: {value: 0}, children:[{tag:"#", children:""}]}
render(root, [a]);
o(a.dom.value).equals("0")
render(root, [b]);
o(b.dom.value).equals("")
// #1595 redux
render(root, [c]);
o(c.dom.value).equals("0")
})
o("isn't set when equivalent to the previous value and focused", function() {
var $window = domMock({spy: o.spy})
var root = $window.document.body
var render = vdom($window).render
var a = {tag: "input"}
var b = {tag: "input", attrs: {value: "1"}}
var c = {tag: "input", attrs: {value: "1"}}
var d = {tag: "input", attrs: {value: 1}}
var e = {tag: "input", attrs: {value: 2}}
render(root, [a])
var spies = $window.__getSpies(a.dom)
a.dom.focus()
o(spies.valueSetter.callCount).equals(0)
render(root, [b])
o(b.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [c])
o(c.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [d])
o(d.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [e])
o(d.dom.value).equals("2")
o(spies.valueSetter.callCount).equals(2)
})
})
o.spec("input.type", function() {
o("the input.type setter is never used", function() {
var $window = domMock({spy: o.spy})
var root = $window.document.body
var render = vdom($window).render
var a = {tag: "input", attrs: {type: "radio"}}
var b = {tag: "input", attrs: {type: "text"}}
var c = {tag: "input", attrs: {}}
render(root, [a])
var spies = $window.__getSpies(a.dom)
o(spies.typeSetter.callCount).equals(0)
o(a.dom.getAttribute("type")).equals("radio")
render(root, [b])
o(spies.typeSetter.callCount).equals(0)
o(b.dom.getAttribute("type")).equals("text")
render(root, [c])
o(spies.typeSetter.callCount).equals(0)
o(c.dom.hasAttribute("type")).equals(false)
})
})
o.spec("textarea.value", function() {
o("can be removed by not passing a value", function() {
var a = {tag: "textarea", attrs: {value:"x"}}
// var b = {tag: "textarea", attrs: {}}
render(root, [a])
o(a.dom.value).equals("x")
// https://github.com/MithrilJS/mithril.js/issues/1804#issuecomment-304521235
// TODO: Uncomment
// render(root, [b])
// o(b.dom.value).equals("")
})
o("isn't set when equivalent to the previous value and focused", function() {
var $window = domMock({spy: o.spy})
var root = $window.document.body
var render = vdom($window).render
var a = {tag: "textarea"}
var b = {tag: "textarea", attrs: {value: "1"}}
var c = {tag: "textarea", attrs: {value: "1"}}
var d = {tag: "textarea", attrs: {value: 1}}
var e = {tag: "textarea", attrs: {value: 2}}
render(root, [a])
var spies = $window.__getSpies(a.dom)
a.dom.focus()
o(spies.valueSetter.callCount).equals(0)
render(root, [b])
o(b.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [c])
o(c.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [d])
o(d.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [e])
o(d.dom.value).equals("2")
o(spies.valueSetter.callCount).equals(2)
})
})
o.spec("link href", function() { o.spec("link href", function() {
o("when link href is true, attribute is present", function() { o("when link href is true, attribute is present", function() {
var a = {tag: "a", attrs: {href: true}} var a = {tag: "a", attrs: {href: true}}
@ -118,7 +348,7 @@ o.spec("attributes", function() {
render(root, canvas) render(root, canvas)
o(canvas.dom.attributes["width"].nodeValue).equals("100%") o(canvas.dom.attributes["width"].value).equals("100%")
o(canvas.dom.width).equals(100) o(canvas.dom.width).equals(100)
}) })
}) })
@ -128,7 +358,231 @@ o.spec("attributes", function() {
render(root, [a]); render(root, [a]);
o(a.dom.attributes["class"].nodeValue).equals("test") o(a.dom.attributes["class"].value).equals("test")
})
})
o.spec("option.value", function() {
o("can be set as text", function() {
var a = {tag: "option", attrs: {value: "test"}}
render(root, [a]);
o(a.dom.value).equals("test")
})
o("can be set as number", function() {
var a = {tag: "option", attrs: {value: 1}}
render(root, [a]);
o(a.dom.value).equals("1")
})
o("null becomes 'null'", function() {
var a = {tag: "option", attrs: {value: null}}
var b = {tag: "option", attrs: {value: "test"}}
var c = {tag: "option", attrs: {value: null}}
render(root, [a]);
o(a.dom.value).equals("null")
o(a.dom.getAttribute("value")).equals("null")
render(root, [b]);
o(b.dom.value).equals("test")
o(b.dom.getAttribute("value")).equals("test")
render(root, [c]);
o(c.dom.value).equals("null")
o(c.dom.getAttribute("value")).equals("null")
})
o("'' and 0 are different values", function() {
var a = {tag: "option", attrs: {value: 0}, children:[{tag:"#", children:""}]}
var b = {tag: "option", attrs: {value: ""}, children:[{tag:"#", children:""}]}
var c = {tag: "option", attrs: {value: 0}, children:[{tag:"#", children:""}]}
render(root, [a]);
o(a.dom.value).equals("0")
render(root, [b]);
o(a.dom.value).equals("")
// #1595 redux
render(root, [c]);
o(c.dom.value).equals("0")
})
o("isn't set when equivalent to the previous value", function() {
var $window = domMock({spy: o.spy})
var root = $window.document.body
var render = vdom($window).render
var a = {tag: "option"}
var b = {tag: "option", attrs: {value: "1"}}
var c = {tag: "option", attrs: {value: "1"}}
var d = {tag: "option", attrs: {value: 1}}
var e = {tag: "option", attrs: {value: 2}}
render(root, [a])
var spies = $window.__getSpies(a.dom)
o(spies.valueSetter.callCount).equals(0)
render(root, [b])
o(b.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [c])
o(c.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [d])
o(d.dom.value).equals("1")
o(spies.valueSetter.callCount).equals(1)
render(root, [e])
o(d.dom.value).equals("2")
o(spies.valueSetter.callCount).equals(2)
})
})
o.spec("select.value", function() {
function makeSelect(value) {
var attrs = (arguments.length === 0) ? {} : {value: value}
return {tag: "select", attrs: attrs, children: [
{tag:"option", attrs: {value: "1"}},
{tag:"option", attrs: {value: "2"}},
{tag:"option", attrs: {value: "a"}},
{tag:"option", attrs: {value: "0"}},
{tag:"option", attrs: {value: ""}}
]}
}
/* FIXME
This incomplete test is meant for testing #1916.
However it cannot be completed until #1978 is addressed
which is a lack a working select.selected / option.selected
attribute. Ask isiahmeadows.
o("render select options", function() {
var select = {tag: "select", selectedIndex: 0, children: [
{tag:"option", attrs: {value: "1", selected: ""}}
]}
render(root, select)
})
*/
o("can be set as text", function() {
var a = makeSelect()
var b = makeSelect("2")
var c = makeSelect("a")
render(root, [a])
o(a.dom.value).equals("1")
o(a.dom.selectedIndex).equals(0)
render(root, [b])
o(b.dom.value).equals("2")
o(b.dom.selectedIndex).equals(1)
render(root, [c])
o(c.dom.value).equals("a")
o(c.dom.selectedIndex).equals(2)
})
o("setting null unsets the value", function() {
var a = makeSelect(null)
render(root, [a])
o(a.dom.value).equals("")
o(a.dom.selectedIndex).equals(-1)
})
o("values are type converted", function() {
var a = makeSelect(1)
var b = makeSelect(2)
render(root, [a])
o(a.dom.value).equals("1")
o(a.dom.selectedIndex).equals(0)
render(root, [b])
o(b.dom.value).equals("2")
o(b.dom.selectedIndex).equals(1)
})
o("'' and 0 are different values when focused", function() {
var a = makeSelect("")
var b = makeSelect(0)
render(root, [a])
a.dom.focus()
o(a.dom.value).equals("")
// #1595 redux
render(root, [b])
o(b.dom.value).equals("0")
})
o("'' and null are different values when focused", function() {
var a = makeSelect("")
var b = makeSelect(null)
var c = makeSelect("")
render(root, [a])
a.dom.focus()
o(a.dom.value).equals("")
o(a.dom.selectedIndex).equals(4)
render(root, [b])
o(b.dom.value).equals("")
o(b.dom.selectedIndex).equals(-1)
render(root, [c])
o(c.dom.value).equals("")
o(c.dom.selectedIndex).equals(4)
})
o("updates with the same value do not re-set the attribute if the select has focus", function() {
var $window = domMock({spy: o.spy})
var root = $window.document.body
var render = vdom($window).render
var a = makeSelect()
var b = makeSelect("1")
var c = makeSelect(1)
var d = makeSelect("2")
render(root, [a])
var spies = $window.__getSpies(a.dom)
a.dom.focus()
o(spies.valueSetter.callCount).equals(0)
o(a.dom.value).equals("1")
render(root, [b])
o(spies.valueSetter.callCount).equals(0)
o(b.dom.value).equals("1")
render(root, [c])
o(spies.valueSetter.callCount).equals(0)
o(c.dom.value).equals("1")
render(root, [d])
o(spies.valueSetter.callCount).equals(1)
o(d.dom.value).equals("2")
}) })
}) })
o.spec("contenteditable throws on untrusted children", function() { o.spec("contenteditable throws on untrusted children", function() {

View file

@ -30,7 +30,7 @@ o.spec("component", function() {
render(root, [node]) render(root, [node])
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("receives arguments", function() { o("receives arguments", function() {
@ -44,7 +44,7 @@ o.spec("component", function() {
render(root, [node]) render(root, [node])
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("updates", function() { o("updates", function() {
@ -57,7 +57,7 @@ o.spec("component", function() {
render(root, [{tag: component, attrs: {id: "c"}, text: "d"}]) render(root, [{tag: component, attrs: {id: "c"}, text: "d"}])
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("c") o(root.firstChild.attributes["id"].value).equals("c")
o(root.firstChild.firstChild.nodeValue).equals("d") o(root.firstChild.firstChild.nodeValue).equals("d")
}) })
o("updates root from null", function() { o("updates root from null", function() {
@ -400,7 +400,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("calls oninit when returning fragment", function() { o("calls oninit when returning fragment", function() {
@ -423,7 +423,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("calls oninit before view", function() { o("calls oninit before view", function() {
@ -479,7 +479,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("does not calls oncreate on redraw", function() { o("does not calls oncreate on redraw", function() {
@ -520,7 +520,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("calls onupdate", function() { o("calls onupdate", function() {
@ -546,7 +546,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("calls onupdate when returning fragment", function() { o("calls onupdate when returning fragment", function() {
@ -572,7 +572,7 @@ o.spec("component", function() {
o(called).equals(1) o(called).equals(1)
o(root.firstChild.nodeName).equals("DIV") o(root.firstChild.nodeName).equals("DIV")
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
o(root.firstChild.firstChild.nodeValue).equals("b") o(root.firstChild.firstChild.nodeValue).equals("b")
}) })
o("calls onremove", function() { o("calls onremove", function() {
@ -764,97 +764,6 @@ o.spec("component", function() {
o(attrs[hook].callCount).equals(methods[hook].callCount)(hook) o(attrs[hook].callCount).equals(methods[hook].callCount)(hook)
}) })
}) })
o("lifecycle timing megatest (for a single component with the state overwritten)", function() {
var methods = {
view: o.spy(function(vnode) {
o(vnode.state).equals(1)
return ""
})
}
var attrs = {}
var hooks = [
"oninit", "oncreate", "onbeforeupdate",
"onupdate", "onbeforeremove", "onremove"
]
hooks.forEach(function(hook) {
// the `attrs` hooks are called before the component ones
attrs[hook] = o.spy(function(vnode) {
o(vnode.state).equals(1)
o(attrs[hook].callCount).equals(methods[hook].callCount + 1)
})
methods[hook] = o.spy(function(vnode) {
o(vnode.state).equals(1)
o(attrs[hook].callCount).equals(methods[hook].callCount)
})
})
var attrsOninit = attrs.oninit
var methodsOninit = methods.oninit
attrs.oninit = o.spy(function(vnode){
vnode.state = 1
return attrsOninit.call(this, vnode)
})
methods.oninit = o.spy(function(vnode){
vnode.state = 1
return methodsOninit.call(this, vnode)
})
var component = createComponent(methods)
o(methods.view.callCount).equals(0)
o(methods.oninit.callCount).equals(0)
o(methods.oncreate.callCount).equals(0)
o(methods.onbeforeupdate.callCount).equals(0)
o(methods.onupdate.callCount).equals(0)
o(methods.onbeforeremove.callCount).equals(0)
o(methods.onremove.callCount).equals(0)
hooks.forEach(function(hook) {
o(attrs[hook].callCount).equals(methods[hook].callCount)(hook)
})
render(root, [{tag: component, attrs: attrs}])
o(methods.view.callCount).equals(1)
o(methods.oninit.callCount).equals(1)
o(methods.oncreate.callCount).equals(1)
o(methods.onbeforeupdate.callCount).equals(0)
o(methods.onupdate.callCount).equals(0)
o(methods.onbeforeremove.callCount).equals(0)
o(methods.onremove.callCount).equals(0)
hooks.forEach(function(hook) {
o(attrs[hook].callCount).equals(methods[hook].callCount)(hook)
})
render(root, [{tag: component, attrs: attrs}])
o(methods.view.callCount).equals(2)
o(methods.oninit.callCount).equals(1)
o(methods.oncreate.callCount).equals(1)
o(methods.onbeforeupdate.callCount).equals(1)
o(methods.onupdate.callCount).equals(1)
o(methods.onbeforeremove.callCount).equals(0)
o(methods.onremove.callCount).equals(0)
hooks.forEach(function(hook) {
o(attrs[hook].callCount).equals(methods[hook].callCount)(hook)
})
render(root, [])
o(methods.view.callCount).equals(2)
o(methods.oninit.callCount).equals(1)
o(methods.oncreate.callCount).equals(1)
o(methods.onbeforeupdate.callCount).equals(1)
o(methods.onupdate.callCount).equals(1)
o(methods.onbeforeremove.callCount).equals(1)
o(methods.onremove.callCount).equals(1)
hooks.forEach(function(hook) {
o(attrs[hook].callCount).equals(methods[hook].callCount)(hook)
})
})
o("hook state and arguments validation", function(){ o("hook state and arguments validation", function(){
var methods = { var methods = {
view: o.spy(function(vnode) { view: o.spy(function(vnode) {
@ -899,7 +808,7 @@ o.spec("component", function() {
o(methods[hook].args.length).equals(attrs[hook].args.length)(hook) o(methods[hook].args.length).equals(attrs[hook].args.length)(hook)
}) })
}) })
o("recycled components get a fresh state", function() { o("no recycling occurs (was: recycled components get a fresh state)", function() {
var step = 0 var step = 0
var firstState var firstState
var view = o.spy(function(vnode) { var view = o.spy(function(vnode) {
@ -918,7 +827,7 @@ o.spec("component", function() {
step = 1 step = 1
render(root, [{tag: "div", children: [{tag: component, key: 1}]}]) render(root, [{tag: "div", children: [{tag: component, key: 1}]}])
o(child).equals(root.firstChild.firstChild) o(child).notEquals(root.firstChild.firstChild) // this used to be a recycling pool test
o(view.callCount).equals(2) o(view.callCount).equals(2)
}) })
}) })

View file

@ -24,8 +24,8 @@ o.spec("createElement", function() {
render(root, [vnode]) render(root, [vnode])
o(vnode.dom.nodeName).equals("DIV") o(vnode.dom.nodeName).equals("DIV")
o(vnode.dom.attributes["id"].nodeValue).equals("a") o(vnode.dom.attributes["id"].value).equals("a")
o(vnode.dom.attributes["title"].nodeValue).equals("b") o(vnode.dom.attributes["title"].value).equals("b")
}) })
o("creates style", function() { o("creates style", function() {
var vnode = {tag: "div", attrs: {style: {backgroundColor: "red"}}} var vnode = {tag: "div", attrs: {style: {backgroundColor: "red"}}}
@ -48,28 +48,52 @@ o.spec("createElement", function() {
render(root, [vnode]) render(root, [vnode])
o(vnode.dom.nodeName).equals("DIV") o(vnode.dom.nodeName).equals("DIV")
o(vnode.dom.attributes["id"].nodeValue).equals("a") o(vnode.dom.attributes["id"].value).equals("a")
o(vnode.dom.attributes["title"].nodeValue).equals("b") o(vnode.dom.attributes["title"].value).equals("b")
o(vnode.dom.childNodes.length).equals(2) o(vnode.dom.childNodes.length).equals(2)
o(vnode.dom.childNodes[0].nodeName).equals("A") o(vnode.dom.childNodes[0].nodeName).equals("A")
o(vnode.dom.childNodes[1].nodeName).equals("B") o(vnode.dom.childNodes[1].nodeName).equals("B")
}) })
o("creates svg", function() { o("creates svg", function() {
var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", children: [{tag: "a", ns: "http://www.w3.org/2000/svg", attrs: {"xlink:href": "javascript:;"}}]} var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", children: [
{tag: "a", ns: "http://www.w3.org/2000/svg", attrs: {"xlink:href": "javascript:;"}},
{tag: "foreignObject", children: [{tag: "body", attrs: {xmlns: "http://www.w3.org/1999/xhtml"}}]}
]}
render(root, [vnode]) render(root, [vnode])
o(vnode.dom.nodeName).equals("svg") o(vnode.dom.nodeName).equals("svg")
o(vnode.dom.namespaceURI).equals("http://www.w3.org/2000/svg") o(vnode.dom.namespaceURI).equals("http://www.w3.org/2000/svg")
o(vnode.dom.firstChild.nodeName).equals("a") o(vnode.dom.firstChild.nodeName).equals("a")
o(vnode.dom.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") o(vnode.dom.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg")
o(vnode.dom.firstChild.attributes["href"].nodeValue).equals("javascript:;") o(vnode.dom.firstChild.attributes["xlink:href"].value).equals("javascript:;")
o(vnode.dom.firstChild.attributes["href"].namespaceURI).equals("http://www.w3.org/1999/xlink") o(vnode.dom.firstChild.attributes["xlink:href"].namespaceURI).equals("http://www.w3.org/1999/xlink")
o(vnode.dom.childNodes[1].nodeName).equals("foreignObject")
o(vnode.dom.childNodes[1].firstChild.nodeName).equals("body")
o(vnode.dom.childNodes[1].firstChild.namespaceURI).equals("http://www.w3.org/1999/xhtml")
}) })
o("sets attributes correctly for svg", function() { o("sets attributes correctly for svg", function() {
var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", attrs: {viewBox: "0 0 100 100"}} var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", attrs: {viewBox: "0 0 100 100"}}
render(root, [vnode]) render(root, [vnode])
o(vnode.dom.attributes["viewBox"].nodeValue).equals("0 0 100 100") o(vnode.dom.attributes["viewBox"].value).equals("0 0 100 100")
})
o("removes xlink:href", function() {
var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", children: [
{tag: "a", ns: "http://www.w3.org/2000/svg", attrs: {"xlink:href": "javascript:;"}}
]}
render(root, [vnode])
o(vnode.dom.nodeName).equals("svg")
o(vnode.dom.firstChild.attributes["xlink:href"].value).equals("javascript:;")
o(vnode.dom.firstChild.attributes["xlink:href"].namespaceURI).equals("http://www.w3.org/1999/xlink")
vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", children: [
{tag: "a", ns: "http://www.w3.org/2000/svg", attrs: {}}
]}
render(root, [vnode])
o(vnode.dom.nodeName).equals("svg")
o(vnode.dom.firstChild.attributes["xlink:href"]).equals(undefined)
}) })
o("creates mathml", function() { o("creates mathml", function() {
var vnode = {tag: "math", ns: "http://www.w3.org/1998/Math/MathML", children: [{tag: "mrow", ns: "http://www.w3.org/1998/Math/MathML"}]} var vnode = {tag: "math", ns: "http://www.w3.org/1998/Math/MathML", children: [{tag: "mrow", ns: "http://www.w3.org/1998/Math/MathML"}]}

View file

@ -31,7 +31,7 @@ o.spec("createHTML", function() {
o(vnode.dom).equals(null) o(vnode.dom).equals(null)
o(vnode.domSize).equals(0) o(vnode.domSize).equals(0)
}) })
o("handles multiple children", function() { o("handles multiple children in HTML", function() {
var vnode = {tag: "<", children: "<a></a><b></b>"} var vnode = {tag: "<", children: "<a></a><b></b>"}
render(root, [vnode]) render(root, [vnode])
@ -51,4 +51,34 @@ o.spec("createHTML", function() {
o(vnode.dom.nodeName).equals(tag.toUpperCase()) o(vnode.dom.nodeName).equals(tag.toUpperCase())
}) })
}) })
o("creates SVG", function() {
var vnode = {tag: "<", children: "<g></g>"}
render(root, [{tag:"svg", children: [vnode]}])
o(vnode.dom.nodeName).equals("g")
o(vnode.dom.namespaceURI).equals("http://www.w3.org/2000/svg")
})
o("creates text SVG", function() {
var vnode = {tag: "<", children: "a"}
render(root, [{tag:"svg", children: [vnode]}])
o(vnode.dom.nodeValue).equals("a")
})
o("handles empty SVG", function() {
var vnode = {tag: "<", children: ""}
render(root, [{tag:"svg", children: [vnode]}])
o(vnode.dom).equals(null)
o(vnode.domSize).equals(0)
})
o("handles multiple children in SVG", function() {
var vnode = {tag: "<", children: "<g></g><text></text>"}
render(root, [{tag:"svg", children: [vnode]}])
o(vnode.domSize).equals(2)
o(vnode.dom.nodeName).equals("g")
o(vnode.dom.namespaceURI).equals("http://www.w3.org/2000/svg")
o(vnode.dom.nextSibling.nodeName).equals("text")
o(vnode.dom.nextSibling.namespaceURI).equals("http://www.w3.org/2000/svg")
})
}) })

View file

@ -34,6 +34,26 @@ o.spec("event", function() {
o(onevent.args[0].target).equals(div.dom) o(onevent.args[0].target).equals(div.dom)
}) })
o("handles click EventListener object", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var div = {tag: "div", attrs: {onclick: listener}}
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
render(root, [div])
div.dom.dispatchEvent(e)
o(spy.callCount).equals(1)
o(spy.this).equals(listener)
o(spy.args[0].type).equals("click")
o(spy.args[0].target).equals(div.dom)
o(onevent.callCount).equals(1)
o(onevent.this).equals(div.dom)
o(onevent.args[0].type).equals("click")
o(onevent.args[0].target).equals(div.dom)
})
o("removes event", function() { o("removes event", function() {
var spy = o.spy() var spy = o.spy()
var vnode = {tag: "a", attrs: {onclick: spy}} var vnode = {tag: "a", attrs: {onclick: spy}}
@ -49,6 +69,129 @@ o.spec("event", function() {
o(spy.callCount).equals(0) o(spy.callCount).equals(0)
}) })
o("removes event when null", function() {
var spy = o.spy()
var vnode = {tag: "a", attrs: {onclick: spy}}
var updated = {tag: "a", attrs: {onclick: null}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes event when undefined", function() {
var spy = o.spy()
var vnode = {tag: "a", attrs: {onclick: spy}}
var updated = {tag: "a", attrs: {onclick: undefined}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes event added via addEventListener when null", function() {
var spy = o.spy()
var vnode = {tag: "a", attrs: {ontouchstart: spy}}
var updated = {tag: "a", attrs: {ontouchstart: null}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("TouchEvents")
e.initEvent("touchstart", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes event added via addEventListener", function() {
var spy = o.spy()
var vnode = {tag: "a", attrs: {ontouchstart: spy}}
var updated = {tag: "a", attrs: {}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("TouchEvents")
e.initEvent("touchstart", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes event added via addEventListener when undefined", function() {
var spy = o.spy()
var vnode = {tag: "a", attrs: {ontouchstart: spy}}
var updated = {tag: "a", attrs: {ontouchstart: undefined}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("TouchEvents")
e.initEvent("touchstart", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes EventListener object", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var vnode = {tag: "a", attrs: {onclick: listener}}
var updated = {tag: "a", attrs: {}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes EventListener object when null", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var vnode = {tag: "a", attrs: {onclick: listener}}
var updated = {tag: "a", attrs: {onclick: null}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("removes EventListener object when undefined", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var vnode = {tag: "a", attrs: {onclick: listener}}
var updated = {tag: "a", attrs: {onclick: undefined}}
render(root, [vnode])
render(root, [updated])
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
vnode.dom.dispatchEvent(e)
o(spy.callCount).equals(0)
})
o("fires onclick only once after redraw", function() { o("fires onclick only once after redraw", function() {
var spy = o.spy() var spy = o.spy()
var div = {tag: "div", attrs: {id: "a", onclick: spy}} var div = {tag: "div", attrs: {id: "a", onclick: spy}}
@ -69,7 +212,31 @@ o.spec("event", function() {
o(onevent.args[0].type).equals("click") o(onevent.args[0].type).equals("click")
o(onevent.args[0].target).equals(div.dom) o(onevent.args[0].target).equals(div.dom)
o(div.dom).equals(updated.dom) o(div.dom).equals(updated.dom)
o(div.dom.attributes["id"].nodeValue).equals("b") o(div.dom.attributes["id"].value).equals("b")
})
o("fires click EventListener object only once after redraw", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var div = {tag: "div", attrs: {id: "a", onclick: listener}}
var updated = {tag: "div", attrs: {id: "b", onclick: listener}}
var e = $window.document.createEvent("MouseEvents")
e.initEvent("click", true, true)
render(root, [div])
render(root, [updated])
div.dom.dispatchEvent(e)
o(spy.callCount).equals(1)
o(spy.this).equals(listener)
o(spy.args[0].type).equals("click")
o(spy.args[0].target).equals(div.dom)
o(onevent.callCount).equals(1)
o(onevent.this).equals(div.dom)
o(onevent.args[0].type).equals("click")
o(onevent.args[0].target).equals(div.dom)
o(div.dom).equals(updated.dom)
o(div.dom.attributes["id"].value).equals("b")
}) })
o("handles ontransitionend", function() { o("handles ontransitionend", function() {
@ -90,4 +257,24 @@ o.spec("event", function() {
o(onevent.args[0].type).equals("transitionend") o(onevent.args[0].type).equals("transitionend")
o(onevent.args[0].target).equals(div.dom) o(onevent.args[0].target).equals(div.dom)
}) })
o("handles transitionend EventListener object", function() {
var spy = o.spy()
var listener = {handleEvent: spy}
var div = {tag: "div", attrs: {ontransitionend: listener}}
var e = $window.document.createEvent("HTMLEvents")
e.initEvent("transitionend", true, true)
render(root, [div])
div.dom.dispatchEvent(e)
o(spy.callCount).equals(1)
o(spy.this).equals(listener)
o(spy.args[0].type).equals("transitionend")
o(spy.args[0].target).equals(div.dom)
o(onevent.callCount).equals(1)
o(onevent.this).equals(div.dom)
o(onevent.args[0].type).equals("transitionend")
o(onevent.args[0].target).equals(div.dom)
})
}) })

View file

@ -218,6 +218,18 @@ o.spec("hyperscript", function() {
o(vnode.tag).equals("div") o(vnode.tag).equals("div")
o(vnode.attrs.a).equals(true) o(vnode.attrs.a).equals(true)
}) })
o("handles explicit empty string value for input", function() {
var vnode = m('input[value=""]')
o(vnode.tag).equals("input")
o(vnode.attrs.value).equals("")
})
o("handles explicit empty string value for option", function() {
var vnode = m('option[value=""]')
o(vnode.tag).equals("option")
o(vnode.attrs.value).equals("")
})
}) })
o.spec("attrs", function() { o.spec("attrs", function() {
o("handles string attr", function() { o("handles string attr", function() {
@ -495,6 +507,23 @@ o.spec("hyperscript", function() {
o(vnode.children[0].tag).equals("i") o(vnode.children[0].tag).equals("i")
o(vnode.children[1].tag).equals("s") o(vnode.children[1].tag).equals("s")
}) })
o("handles shared attrs", function() {
var attrs = {a: "b"}
var nodeA = m(".a", attrs)
var nodeB = m(".b", attrs)
o(nodeA.attrs.className).equals("a")
o(nodeA.attrs.a).equals("b")
o(nodeB.attrs.className).equals("b")
o(nodeB.attrs.a).equals("b")
})
o("doesnt modify passed attributes object", function() {
var attrs = {a: "b"}
m(".a", attrs)
o(attrs).deepEquals({a: "b"})
})
o("handles fragment children without attr unwrapped", function() { o("handles fragment children without attr unwrapped", function() {
var vnode = m("div", [m("i")], [m("s")]) var vnode = m("div", [m("i")], [m("s")])

View file

@ -30,6 +30,16 @@ o.spec("form inputs", function() {
o($window.document.activeElement).equals(input.dom) o($window.document.activeElement).equals(input.dom)
}) })
o("maintains focus when changed manually in hook", function() {
var input = {tag: "input", attrs: {oncreate: function() {
input.dom.focus();
}}};
render(root, [input])
o($window.document.activeElement).equals(input.dom)
})
o("syncs input value if DOM value differs from vdom value", function() { o("syncs input value if DOM value differs from vdom value", function() {
var input = {tag: "input", attrs: {value: "aaa", oninput: function() {}}} var input = {tag: "input", attrs: {value: "aaa", oninput: function() {}}}
var updated = {tag: "input", attrs: {value: "aaa", oninput: function() {}}} var updated = {tag: "input", attrs: {value: "aaa", oninput: function() {}}}
@ -49,6 +59,16 @@ o.spec("form inputs", function() {
o(updated.dom.value).equals("aaa") o(updated.dom.value).equals("aaa")
}) })
o("clear element value if vdom value is set to undefined (aka removed)", function() {
var input = {tag: "input", attrs: {value: "aaa", oninput: function() {}}}
var updated = {tag: "input", attrs: {value: undefined, oninput: function() {}}}
render(root, [input])
render(root, [updated])
o(updated.dom.value).equals("")
})
o("syncs input checked attribute if DOM value differs from vdom value", function() { o("syncs input checked attribute if DOM value differs from vdom value", function() {
var input = {tag: "input", attrs: {type: "checkbox", checked: true, onclick: function() {}}} var input = {tag: "input", attrs: {type: "checkbox", checked: true, onclick: function() {}}}
var updated = {tag: "input", attrs: {type: "checkbox", checked: true, onclick: function() {}}} var updated = {tag: "input", attrs: {type: "checkbox", checked: true, onclick: function() {}}}
@ -80,6 +100,57 @@ o.spec("form inputs", function() {
o(select.dom.selectedIndex).equals(0) o(select.dom.selectedIndex).equals(0)
}) })
o("select option can have empty string value", function() {
var select = {tag: "select", children :[
{tag: "option", attrs: {value: ""}, text: "aaa"}
]}
render(root, [select])
o(select.dom.firstChild.value).equals("")
})
o("option value defaults to textContent unless explicitly set", function() {
var select = {tag: "select", children :[
{tag: "option", text: "aaa"}
]}
render(root, [select])
o(select.dom.firstChild.value).equals("aaa")
o(select.dom.value).equals("aaa")
//test that value changes when content changes
select = {tag: "select", children :[
{tag: "option", text: "bbb"}
]}
render(root, [select])
o(select.dom.firstChild.value).equals("bbb")
o(select.dom.value).equals("bbb")
//test that value can be set to "" in subsequent render
select = {tag: "select", children :[
{tag: "option", attrs: {value: ""}, text: "aaa"}
]}
render(root, [select])
o(select.dom.firstChild.value).equals("")
o(select.dom.value).equals("")
//test that value reverts to textContent when value omitted
select = {tag: "select", children :[
{tag: "option", text: "aaa"}
]}
render(root, [select])
o(select.dom.firstChild.value).equals("aaa")
o(select.dom.value).equals("aaa")
})
o("select yields invalid value without children", function() { o("select yields invalid value without children", function() {
var select = {tag: "select", attrs: {value: "a"}} var select = {tag: "select", attrs: {value: "a"}}

View file

@ -36,10 +36,7 @@ o.spec("onbeforeremove", function() {
o(update.callCount).equals(0) o(update.callCount).equals(0)
}) })
o("calls onbeforeremove when removing element", function(done) { o("calls onbeforeremove when removing element", function(done) {
var vnode = {tag: "div", attrs: { var vnode = {tag: "div", attrs: {onbeforeremove: remove}}
oninit: function() {vnode.state = {}},
onbeforeremove: remove
}}
render(root, [vnode]) render(root, [vnode])
render(root, []) render(root, [])
@ -47,6 +44,7 @@ o.spec("onbeforeremove", function() {
function remove(node) { function remove(node) {
o(node).equals(vnode) o(node).equals(vnode)
o(this).equals(vnode.state) o(this).equals(vnode.state)
o(this != null && typeof this === "object").equals(true)
o(root.childNodes.length).equals(1) o(root.childNodes.length).equals(1)
o(root.firstChild).equals(vnode.dom) o(root.firstChild).equals(vnode.dom)

View file

@ -21,7 +21,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
}) })
o("prevents update in text", function() { o("prevents update in text", function() {
@ -65,7 +65,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("accepts arguments for comparison", function() { o("accepts arguments for comparison", function() {
@ -86,7 +86,7 @@ o.spec("onbeforeupdate", function() {
} }
o(count).equals(1) o(count).equals(1)
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("is not called on creation", function() { o("is not called on creation", function() {
@ -129,7 +129,7 @@ o.spec("onbeforeupdate", function() {
render(root, temp) render(root, temp)
render(root, updated) render(root, updated)
o(vnodes[0].dom).equals(updated[0].dom) o(vnodes[0].dom).notEquals(updated[0].dom) // this used to be a recycling pool test
o(updated[0].dom.nodeName).equals("DIV") o(updated[0].dom.nodeName).equals("DIV")
o(onbeforeupdate.callCount).equals(0) o(onbeforeupdate.callCount).equals(0)
}) })
@ -167,7 +167,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("a") o(root.firstChild.attributes["id"].value).equals("a")
}) })
o("does not prevent update if returning true in component and true in vnode", function() { o("does not prevent update if returning true in component and true in vnode", function() {
@ -183,7 +183,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("does not prevent update if returning false in component but true in vnode", function() { o("does not prevent update if returning false in component but true in vnode", function() {
@ -199,7 +199,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("does not prevent update if returning true in component but false in vnode", function() { o("does not prevent update if returning true in component but false in vnode", function() {
@ -215,7 +215,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("does not prevent update if returning true from component", function() { o("does not prevent update if returning true from component", function() {
@ -231,7 +231,7 @@ o.spec("onbeforeupdate", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("accepts arguments for comparison in component", function() { o("accepts arguments for comparison in component", function() {
@ -258,7 +258,7 @@ o.spec("onbeforeupdate", function() {
} }
o(count).equals(1) o(count).equals(1)
o(root.firstChild.attributes["id"].nodeValue).equals("b") o(root.firstChild.attributes["id"].value).equals("b")
}) })
o("is not called on component creation", function() { o("is not called on component creation", function() {

View file

@ -199,4 +199,27 @@ o.spec("oninit", function() {
o(vnode.dom.oninit).equals(undefined) o(vnode.dom.oninit).equals(undefined)
o(vnode.dom.attributes["oninit"]).equals(undefined) o(vnode.dom.attributes["oninit"]).equals(undefined)
}) })
o("No spurious oninit calls in mapped keyed diff when the pool is involved (#1992)", function () {
var oninit1 = o.spy()
var oninit2 = o.spy()
var oninit3 = o.spy()
render(root, [
{tag: "p", key: 1, attrs: {oninit: oninit1}},
{tag: "p", key: 2, attrs: {oninit: oninit2}},
{tag: "p", key: 3, attrs: {oninit: oninit3}},
])
render(root, [
{tag: "p", key: 1, attrs: {oninit: oninit1}},
{tag: "p", key: 3, attrs: {oninit: oninit3}},
])
render(root, [
{tag: "p", key: 3, attrs: {oninit: oninit3}},
])
o(oninit1.callCount).equals(1)
o(oninit2.callCount).equals(1)
o(oninit3.callCount).equals(1)
})
}) })

View file

@ -89,8 +89,9 @@ o.spec("onremove", function() {
o(vnode.dom.onremove).equals(undefined) o(vnode.dom.onremove).equals(undefined)
o(vnode.dom.attributes["onremove"]).equals(undefined) o(vnode.dom.attributes["onremove"]).equals(undefined)
o(vnode.events).equals(undefined)
}) })
o("calls onremove on recycle", function() { o("calls onremove on keyed nodes", function() {
var remove = o.spy() var remove = o.spy()
var vnodes = [{tag: "div", key: 1}] var vnodes = [{tag: "div", key: 1}]
var temp = [{tag: "div", key: 2, attrs: {onremove: remove}}] var temp = [{tag: "div", key: 2, attrs: {onremove: remove}}]
@ -100,6 +101,7 @@ o.spec("onremove", function() {
render(root, temp) render(root, temp)
render(root, updated) render(root, updated)
o(vnodes[0].dom).notEquals(updated[0].dom) // this used to be a recycling pool test
o(remove.callCount).equals(1) o(remove.callCount).equals(1)
}) })
o("does not recycle when there's an onremove", function() { o("does not recycle when there's an onremove", function() {
@ -150,6 +152,68 @@ o.spec("onremove", function() {
o(spy.callCount).equals(1) o(spy.callCount).equals(1)
}) })
o("doesn't call onremove on children when the corresponding view returns null (after removing the parent)", function() {
var threw = false
var spy = o.spy()
var parent = createComponent({
view: function() {}
})
var child = createComponent({
view: function() {},
onremove: spy
})
render(root, {tag: parent, children: [child]})
try {
render(root, null)
} catch (e) {
threw = e
}
o(spy.callCount).equals(0)
o(threw).equals(false)
})
o("doesn't call onremove on children when the corresponding view returns null (after removing the children)", function() {
var threw = false
var spy = o.spy()
var parent = createComponent({
view: function() {}
})
var child = createComponent({
view: function() {},
onremove: spy
})
render(root, {tag: parent, children: [child]})
try {
render(root, {tag: parent})
} catch (e) {
threw = true
}
o(spy.callCount).equals(0)
o(threw).equals(false)
})
o("onremove doesn't fire on nodes that go from pool to pool (#1990)", function() {
var onremove = o.spy();
render(root, [m("div", m("div")), m("div", m("div", {onremove: onremove}))]);
render(root, [m("div", m("div"))]);
render(root, []);
o(onremove.callCount).equals(1)
})
o("doesn't fire when removing the children of a node that's brought back from the pool (#1991 part 2)", function() {
var onremove = o.spy()
var vnode = {tag: "div", key: 1, children: [{tag: "div", attrs: {onremove: onremove}}]}
var temp = {tag: "div", key: 2}
var updated = {tag: "div", key: 1, children: [{tag: "p"}]}
render(root, [vnode])
render(root, [temp])
render(root, [updated])
o(vnode.dom).notEquals(updated.dom) // this used to be a recycling pool test
o(onremove.callCount).equals(1)
})
}) })
}) })
}) })

View file

@ -170,9 +170,9 @@ o.spec("onupdate", function() {
function update(vnode) { function update(vnode) {
called = true called = true
o(vnode.dom.parentNode.attributes["id"].nodeValue).equals("11") o(vnode.dom.parentNode.attributes["id"].value).equals("11")
o(vnode.dom.attributes["id"].nodeValue).equals("22") o(vnode.dom.attributes["id"].value).equals("22")
o(vnode.dom.childNodes[0].attributes["id"].nodeValue).equals("33") o(vnode.dom.childNodes[0].attributes["id"].value).equals("33")
} }
o(called).equals(true) o(called).equals(true)
}) })

View file

@ -271,4 +271,32 @@ o.spec("render", function() {
o(updateA.callCount).equals(2) o(updateA.callCount).equals(2)
o(removeA.callCount).equals(1) o(removeA.callCount).equals(1)
}) })
o("svg namespace is preserved in keyed diff (#1820)", function(){
// note that this only exerciese one branch of the keyed diff algo
var svg = {tag:"svg", children: [
{tag:"g", key: 0},
{tag:"g", key: 1}
]}
render(root, [svg])
o(svg.dom.namespaceURI).equals("http://www.w3.org/2000/svg")
o(svg.dom.childNodes[0].namespaceURI).equals("http://www.w3.org/2000/svg")
o(svg.dom.childNodes[1].namespaceURI).equals("http://www.w3.org/2000/svg")
svg = {tag:"svg", children: [
{tag:"g", key: 1, attrs: {x: 1}},
{tag:"g", key: 2, attrs: {x: 2}}
]}
render(root, [svg])
o(svg.dom.namespaceURI).equals("http://www.w3.org/2000/svg")
o(svg.dom.childNodes[0].namespaceURI).equals("http://www.w3.org/2000/svg")
o(svg.dom.childNodes[1].namespaceURI).equals("http://www.w3.org/2000/svg")
})
o("the namespace of the root is passed to children", function() {
render(root, [{tag: "svg"}])
o(root.childNodes[0].namespaceURI).equals("http://www.w3.org/2000/svg")
render(root.childNodes[0], [{tag: "g"}])
o(root.childNodes[0].childNodes[0].namespaceURI).equals("http://www.w3.org/2000/svg")
})
}) })

View file

@ -21,7 +21,7 @@ o.spec("updateElement", function() {
o(updated.dom).equals(vnode.dom) o(updated.dom).equals(vnode.dom)
o(updated.dom).equals(root.firstChild) o(updated.dom).equals(root.firstChild)
o(updated.dom.attributes["id"].nodeValue).equals("c") o(updated.dom.attributes["id"].value).equals("c")
}) })
o("adds attr", function() { o("adds attr", function() {
var vnode = {tag: "a", attrs: {id: "b"}} var vnode = {tag: "a", attrs: {id: "b"}}
@ -32,7 +32,7 @@ o.spec("updateElement", function() {
o(updated.dom).equals(vnode.dom) o(updated.dom).equals(vnode.dom)
o(updated.dom).equals(root.firstChild) o(updated.dom).equals(root.firstChild)
o(updated.dom.attributes["title"].nodeValue).equals("d") o(updated.dom.attributes["title"].value).equals("d")
}) })
o("adds attr from empty attrs", function() { o("adds attr from empty attrs", function() {
var vnode = {tag: "a"} var vnode = {tag: "a"}
@ -43,7 +43,7 @@ o.spec("updateElement", function() {
o(updated.dom).equals(vnode.dom) o(updated.dom).equals(vnode.dom)
o(updated.dom).equals(root.firstChild) o(updated.dom).equals(root.firstChild)
o(updated.dom.attributes["title"].nodeValue).equals("d") o(updated.dom.attributes["title"].value).equals("d")
}) })
o("removes attr", function() { o("removes attr", function() {
var vnode = {tag: "a", attrs: {id: "b", title: "d"}} var vnode = {tag: "a", attrs: {id: "b", title: "d"}}
@ -192,6 +192,19 @@ o.spec("updateElement", function() {
o(updated.dom.style.backgroundColor).equals("") o(updated.dom.style.backgroundColor).equals("")
o(updated.dom.style.color).equals("gold") o(updated.dom.style.color).equals("gold")
}) })
o("does not re-render element styles for equivalent style objects", function() {
var style = {color: "gold"}
var vnode = {tag: "a", attrs: {style: style}}
render(root, [vnode])
root.firstChild.style.color = "red"
style = {color: "gold"}
var updated = {tag: "a", attrs: {style: style}}
render(root, [updated])
o(updated.dom.style.color).equals("red")
})
o("replaces el", function() { o("replaces el", function() {
var vnode = {tag: "a"} var vnode = {tag: "a"}
var updated = {tag: "b"} var updated = {tag: "b"}
@ -209,7 +222,7 @@ o.spec("updateElement", function() {
render(root, [vnode]) render(root, [vnode])
render(root, [updated]) render(root, [updated])
o(updated.dom.attributes["class"].nodeValue).equals("b") o(updated.dom.attributes["class"].value).equals("b")
}) })
o("updates svg child", function() { o("updates svg child", function() {
var vnode = {tag: "svg", children: [{ var vnode = {tag: "svg", children: [{
@ -224,7 +237,7 @@ o.spec("updateElement", function() {
o(updated.dom.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") o(updated.dom.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg")
}) })
o("restores correctly when recycling", function() { o("doesn't restore since we're not recycling", function() {
var vnode = {tag: "div", key: 1} var vnode = {tag: "div", key: 1}
var updated = {tag: "div", key: 2} var updated = {tag: "div", key: 2}
@ -237,9 +250,9 @@ o.spec("updateElement", function() {
var c = vnode.dom var c = vnode.dom
o(root.childNodes.length).equals(1) o(root.childNodes.length).equals(1)
o(a).equals(c) o(a).notEquals(c) // this used to be a recycling pool test
}) })
o("restores correctly when recycling via map", function() { o("doesn't restore since we're not recycling (via map)", function() {
var a = {tag: "div", key: 1} var a = {tag: "div", key: 1}
var b = {tag: "div", key: 2} var b = {tag: "div", key: 2}
var c = {tag: "div", key: 3} var c = {tag: "div", key: 3}
@ -256,6 +269,6 @@ o.spec("updateElement", function() {
var y = root.childNodes[1] var y = root.childNodes[1]
o(root.childNodes.length).equals(3) o(root.childNodes.length).equals(3)
o(x).equals(y) o(x).notEquals(y) // this used to be a recycling pool test
}) })
}) })

View file

@ -614,6 +614,38 @@ o.spec("updateNodes", function() {
o(updated[0].dom.nodeName).equals("I") o(updated[0].dom.nodeName).equals("I")
o(updated[0].dom).equals(root.childNodes[0]) o(updated[0].dom).equals(root.childNodes[0])
}) })
o("cached keyed nodes move when the list is reversed", function(){
var a = {tag: "a", key: "a"}
var b = {tag: "b", key: "b"}
var c = {tag: "c", key: "c"}
var d = {tag: "d", key: "d"}
render(root, [a, b, c, d])
render(root, [d, c, b, a])
o(root.childNodes.length).equals(4)
o(root.childNodes[0].nodeName).equals("D")
o(root.childNodes[1].nodeName).equals("C")
o(root.childNodes[2].nodeName).equals("B")
o(root.childNodes[3].nodeName).equals("A")
})
o("cached keyed nodes move when diffed via the map", function() {
var onupdate = o.spy()
var a = {tag: "a", key: "a", attrs: {onupdate: onupdate}}
var b = {tag: "b", key: "b", attrs: {onupdate: onupdate}}
var c = {tag: "c", key: "c", attrs: {onupdate: onupdate}}
var d = {tag: "d", key: "d", attrs: {onupdate: onupdate}}
render(root, [a, b, c, d])
render(root, [b, d, a, c])
o(root.childNodes.length).equals(4)
o(root.childNodes[0].nodeName).equals("B")
o(root.childNodes[1].nodeName).equals("D")
o(root.childNodes[2].nodeName).equals("A")
o(root.childNodes[3].nodeName).equals("C")
o(onupdate.callCount).equals(0)
})
o("removes then create different bigger", function() { o("removes then create different bigger", function() {
var vnodes = [{tag: "a", key: 1}, {tag: "b", key: 2}] var vnodes = [{tag: "a", key: 1}, {tag: "b", key: 2}]
var temp = [] var temp = []
@ -776,7 +808,7 @@ o.spec("updateNodes", function() {
o(root.childNodes[0].childNodes[1].childNodes.length).equals(1) o(root.childNodes[0].childNodes[1].childNodes.length).equals(1)
o(root.childNodes[1].childNodes.length).equals(0) o(root.childNodes[1].childNodes.length).equals(0)
}) })
o("recycles", function() { o("doesn't recycle", function() {
var vnodes = [{tag: "div", key: 1}] var vnodes = [{tag: "div", key: 1}]
var temp = [] var temp = []
var updated = [{tag: "div", key: 1}] var updated = [{tag: "div", key: 1}]
@ -785,10 +817,10 @@ o.spec("updateNodes", function() {
render(root, temp) render(root, temp)
render(root, updated) render(root, updated)
o(vnodes[0].dom).equals(updated[0].dom) o(vnodes[0].dom).notEquals(updated[0].dom) // this used to be a recycling pool test
o(updated[0].dom.nodeName).equals("DIV") o(updated[0].dom.nodeName).equals("DIV")
}) })
o("recycles when not keyed", function() { o("doesn't recycle when not keyed", function() {
var vnodes = [{tag: "div"}] var vnodes = [{tag: "div"}]
var temp = [] var temp = []
var updated = [{tag: "div"}] var updated = [{tag: "div"}]
@ -798,19 +830,22 @@ o.spec("updateNodes", function() {
render(root, updated) render(root, updated)
o(root.childNodes.length).equals(1) o(root.childNodes.length).equals(1)
o(vnodes[0].dom).equals(updated[0].dom) o(vnodes[0].dom).notEquals(updated[0].dom) // this used to be a recycling pool test
o(updated[0].dom.nodeName).equals("DIV") o(updated[0].dom.nodeName).equals("DIV")
}) })
o("recycles deep", function() { o("doesn't recycle deep", function() {
var vnodes = [{tag: "div", children: [{tag: "a", key: 1}]}] var vnodes = [{tag: "div", children: [{tag: "a", key: 1}]}]
var temp = [{tag: "div"}] var temp = [{tag: "div"}]
var updated = [{tag: "div", children: [{tag: "a", key: 1}]}] var updated = [{tag: "div", children: [{tag: "a", key: 1}]}]
render(root, vnodes) render(root, vnodes)
var oldChild = vnodes[0].dom.firstChild
render(root, temp) render(root, temp)
render(root, updated) render(root, updated)
o(vnodes[0].dom.firstChild).equals(updated[0].dom.firstChild) o(oldChild).notEquals(updated[0].dom.firstChild) // this used to be a recycling pool test
o(updated[0].dom.firstChild.nodeName).equals("A") o(updated[0].dom.firstChild.nodeName).equals("A")
}) })
o("mixed unkeyed tags are not broken by recycle", function() { o("mixed unkeyed tags are not broken by recycle", function() {
@ -839,6 +874,19 @@ o.spec("updateNodes", function() {
o(root.childNodes[0].nodeName).equals("A") o(root.childNodes[0].nodeName).equals("A")
o(root.childNodes[1].nodeName).equals("B") o(root.childNodes[1].nodeName).equals("B")
}) })
o("onremove doesn't fire from nodes in the pool (#1990)", function () {
var onremove = o.spy()
render(root, [
{tag: "div", children: [{tag: "div", attrs: {onremove: onremove}}]},
{tag: "div", children: [{tag: "div", attrs: {onremove: onremove}}]}
])
render(root, [
{tag: "div", children: [{tag: "div", attrs: {onremove: onremove}}]}
])
render(root,[])
o(onremove.callCount).equals(2)
})
o("cached, non-keyed nodes skip diff", function () { o("cached, non-keyed nodes skip diff", function () {
var onupdate = o.spy(); var onupdate = o.spy();
var cached = {tag:"a", attrs:{onupdate: onupdate}} var cached = {tag:"a", attrs:{onupdate: onupdate}}
@ -857,6 +905,72 @@ o.spec("updateNodes", function() {
o(onupdate.callCount).equals(0) o(onupdate.callCount).equals(0)
}) })
o("keyed cached elements are re-initialized when brought back from the pool (#2003)", function () {
var onupdate = o.spy()
var oncreate = o.spy()
var cached = {
tag: "B", key: 1, children: [
{tag: "A", attrs: {oncreate: oncreate, onupdate: onupdate}, text: "A"}
]
}
render(root, [{tag: "div", children: [cached]}])
render(root, [])
render(root, [{tag: "div", children: [cached]}])
o(oncreate.callCount).equals(2)
o(onupdate.callCount).equals(0)
})
o("unkeyed cached elements are re-initialized when brought back from the pool (#2003)", function () {
var onupdate = o.spy()
var oncreate = o.spy()
var cached = {
tag: "B", children: [
{tag: "A", attrs: {oncreate: oncreate, onupdate: onupdate}, text: "A"}
]
}
render(root, [{tag: "div", children: [cached]}])
render(root, [])
render(root, [{tag: "div", children: [cached]}])
o(oncreate.callCount).equals(2)
o(onupdate.callCount).equals(0)
})
o("keyed cached elements are re-initialized when brought back from nested pools (#2003)", function () {
var onupdate = o.spy()
var oncreate = o.spy()
var cached = {
tag: "B", key: 1, children: [
{tag: "A", attrs: {oncreate: oncreate, onupdate: onupdate}, text: "A"}
]
}
render(root, [{tag: "div", children: [cached]}])
render(root, [{tag: "div", children: []}])
render(root, [])
render(root, [{tag: "div", children: [cached]}])
o(oncreate.callCount).equals(2)
o(onupdate.callCount).equals(0)
})
o("unkeyed cached elements are re-initialized when brought back from nested pools (#2003)", function () {
var onupdate = o.spy()
var oncreate = o.spy()
var cached = {
tag: "B", children: [
{tag: "A", attrs: {oncreate: oncreate, onupdate: onupdate}, text: "A"}
]
}
render(root, [{tag: "div", children: [cached]}])
render(root, [{tag: "div", children: []}])
render(root, [])
render(root, [{tag: "div", children: [cached]}])
o(oncreate.callCount).equals(2)
o(onupdate.callCount).equals(0)
})
o("null stays in place", function() { o("null stays in place", function() {
var create = o.spy() var create = o.spy()
var update = o.spy() var update = o.spy()
@ -904,6 +1018,88 @@ o.spec("updateNodes", function() {
o(vnode.dom).notEquals(updated.dom) o(vnode.dom).notEquals(updated.dom)
}) })
o("don't add back elements from fragments that are restored from the pool #1991", function() {
render(root, [
{tag: "[", children: []},
{tag: "[", children: []}
])
render(root, [
{tag: "[", children: []},
{tag: "[", children: [{tag: "div"}]}
])
render(root, [
{tag: "[", children: [null]}
])
render(root, [
{tag: "[", children: []},
{tag: "[", children: []}
])
o(root.childNodes.length).equals(0)
})
o("don't add back elements from fragments that are being removed #1991", function() {
render(root, [
{tag: "[", children: []},
{tag: "p"},
])
render(root, [
{tag: "[", children: [{tag: "div", text: 5}]}
])
render(root, [
{tag: "[", children: []},
{tag: "[", children: []}
])
o(root.childNodes.length).equals(0)
})
o("handles null values in unkeyed lists of different length (#2003)", function() {
var oncreate = o.spy();
var onremove = o.spy();
var onupdate = o.spy();
function attrs() {
return {oncreate: oncreate, onremove: onremove, onupdate: onupdate}
}
render(root, [{tag: "div", attrs: attrs()}, null]);
render(root, [null, {tag: "div", attrs: attrs()}, null]);
o(oncreate.callCount).equals(2)
o(onremove.callCount).equals(1)
o(onupdate.callCount).equals(0)
})
o("supports changing the element of a keyed element in a list when traversed bottom-up", function() {
try {
render(root, [{tag: "a", key: 2}])
render(root, [{tag: "b", key: 1}, {tag: "b", key: 2}])
o(root.childNodes.length).equals(2)
o(root.childNodes[0].nodeName).equals("B")
o(root.childNodes[1].nodeName).equals("B")
} catch (e) {
o(e).equals(null)
}
})
o("supports changing the element of a keyed element in a list when looking up nodes using the map", function() {
try {
render(root, [{tag: "x", key: 1}, {tag: "y", key: 2}, {tag: "z", key: 3}])
render(root, [{tag: "b", key: 2}, {tag: "c", key: 1}, {tag: "d", key: 4}, {tag: "e", key: 3}])
o(root.childNodes.length).equals(4)
o(root.childNodes[0].nodeName).equals("B")
o(root.childNodes[1].nodeName).equals("C")
o(root.childNodes[2].nodeName).equals("D")
o(root.childNodes[3].nodeName).equals("E")
} catch (e) {
o(e).equals(null)
}
})
o("don't fetch the nextSibling from the pool", function() {
render(root, [{tag: "[", children: [{tag: "div", key: 1}, {tag: "div", key: 2}]}, {tag: "p"}])
render(root, [{tag: "[", children: []}, {tag: "p"}])
render(root, [{tag: "[", children: [{tag: "div", key: 2}, {tag: "div", key: 1}]}, {tag: "p"}])
o([].map.call(root.childNodes, function(el) {return el.nodeName})).deepEquals(["DIV", "DIV", "P"])
})
components.forEach(function(cmp){ components.forEach(function(cmp){
o.spec(cmp.kind, function(){ o.spec(cmp.kind, function(){
var createComponent = cmp.create var createComponent = cmp.create
@ -940,6 +1136,19 @@ o.spec("updateNodes", function() {
o(root.childNodes[0].nodeName).equals("A") o(root.childNodes[0].nodeName).equals("A")
o(root.childNodes[1].nodeName).equals("S") o(root.childNodes[1].nodeName).equals("S")
}) })
o("removing a component that returns a fragment doesn't throw (regression test for incidental bug introduced while debugging some Flems)", function() {
var component = createComponent({
view: function() {return {tag: "[", children:[{tag: "a"}, {tag: "b"}]}}
})
try {
render(root, [{tag: component}])
render(root, [])
o(root.childNodes.length).equals(0)
} catch (e) {
o(e).equals(null)
}
})
}) })
}) })
}) })

View file

@ -1,7 +1,7 @@
"use strict" "use strict"
function Vnode(tag, key, attrs, children, text, dom) { 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, _state: undefined, events: undefined, instance: undefined, skip: false} return {tag: tag, key: key, attrs: attrs, children: children, text: text, dom: dom, domSize: undefined, state: undefined, events: undefined, instance: undefined, skip: false}
} }
Vnode.normalize = function(node) { Vnode.normalize = function(node) {
if (Array.isArray(node)) return Vnode("[", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined) if (Array.isArray(node)) return Vnode("[", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined)

View file

@ -67,14 +67,16 @@ module.exports = function($window, Promise) {
xhr.open(args.method, args.url, typeof args.async === "boolean" ? args.async : true, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined) xhr.open(args.method, args.url, typeof args.async === "boolean" ? args.async : true, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined)
if (args.serialize === JSON.stringify && useBody) { if (args.serialize === JSON.stringify && useBody && !(args.headers && args.headers.hasOwnProperty("Content-Type"))) {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8") xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
} }
if (args.deserialize === deserialize) { if (args.deserialize === deserialize && !(args.headers && args.headers.hasOwnProperty("Accept"))) {
xhr.setRequestHeader("Accept", "application/json, text/*") xhr.setRequestHeader("Accept", "application/json, text/*")
} }
if (args.withCredentials) xhr.withCredentials = args.withCredentials if (args.withCredentials) xhr.withCredentials = args.withCredentials
if (args.timeout) xhr.timeout = args.timeout
for (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) { for (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) {
xhr.setRequestHeader(key, args.headers[key]) xhr.setRequestHeader(key, args.headers[key])
} }
@ -88,12 +90,13 @@ module.exports = function($window, Promise) {
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
try { try {
var response = (args.extract !== extract) ? args.extract(xhr, args) : args.deserialize(args.extract(xhr, args)) var response = (args.extract !== extract) ? args.extract(xhr, args) : args.deserialize(args.extract(xhr, args))
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) { if (args.extract !== extract || (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) {
resolve(cast(args.type, response)) resolve(cast(args.type, response))
} }
else { else {
var error = new Error(xhr.responseText) var error = new Error(xhr.responseText)
for (var key in response) error[key] = response[key] error.code = xhr.status
error.response = response
reject(error) reject(error)
} }
} }

View file

@ -230,7 +230,7 @@ o.spec("xhr", function() {
} }
}) })
xhr({method: "GET", url: "/item", deserialize: deserialize}).then(function(data) { xhr({method: "GET", url: "/item", deserialize: deserialize}).then(function(data) {
o(data).equals('{"test":123}') o(data).equals("{\"test\":123}")
}).then(done) }).then(done)
}) })
o("deserialize parameter works in POST", function(done) { o("deserialize parameter works in POST", function(done) {
@ -244,7 +244,7 @@ o.spec("xhr", function() {
} }
}) })
xhr({method: "POST", url: "/item", deserialize: deserialize}).then(function(data) { xhr({method: "POST", url: "/item", deserialize: deserialize}).then(function(data) {
o(data).equals('{"test":123}') o(data).equals("{\"test\":123}")
}).then(done) }).then(done)
}) })
o("extract parameter works in GET", function(done) { o("extract parameter works in GET", function(done) {
@ -258,7 +258,7 @@ o.spec("xhr", function() {
} }
}) })
xhr({method: "GET", url: "/item", extract: extract}).then(function(data) { xhr({method: "GET", url: "/item", extract: extract}).then(function(data) {
o(data).equals('{"test":123}') o(data).equals("{\"test\":123}")
}).then(done) }).then(done)
}) })
o("extract parameter works in POST", function(done) { o("extract parameter works in POST", function(done) {
@ -272,7 +272,7 @@ o.spec("xhr", function() {
} }
}) })
xhr({method: "POST", url: "/item", extract: extract}).then(function(data) { xhr({method: "POST", url: "/item", extract: extract}).then(function(data) {
o(data).equals('{"test":123}') o(data).equals("{\"test\":123}")
}).then(done) }).then(done)
}) })
o("ignores deserialize if extract is defined", function(done) { o("ignores deserialize if extract is defined", function(done) {
@ -435,6 +435,20 @@ o.spec("xhr", function() {
done() done()
}) })
}) })
o("set timeout to xhr instance", function() {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: ""}
}
})
return xhr({
method: "GET", url: "/item",
timeout: 42,
config: function(xhr) {
o(xhr.timeout).equals(42)
}
})
})
/*o("data maintains after interpolate", function() { /*o("data maintains after interpolate", function() {
mock.$defineRoutes({ mock.$defineRoutes({
"PUT /items/:x": function() { "PUT /items/:x": function() {
@ -458,9 +472,10 @@ o.spec("xhr", function() {
xhr({method: "GET", url: "/item"}).catch(function(e) { xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e instanceof Error).equals(true) o(e instanceof Error).equals(true)
o(e.message).equals(JSON.stringify({error: "error"})) o(e.message).equals(JSON.stringify({error: "error"}))
o(e.code).equals(500)
}).then(done) }).then(done)
}) })
o("extends Error with JSON response", function(done) { o("adds response to Error", function(done) {
mock.$defineRoutes({ mock.$defineRoutes({
"GET /item": function() { "GET /item": function() {
return {status: 500, responseText: JSON.stringify({message: "error", stack: "error on line 1"})} return {status: 500, responseText: JSON.stringify({message: "error", stack: "error on line 1"})}
@ -468,8 +483,8 @@ o.spec("xhr", function() {
}) })
xhr({method: "GET", url: "/item"}).catch(function(e) { xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e instanceof Error).equals(true) o(e instanceof Error).equals(true)
o(e.message).equals("error") o(e.response.message).equals("error")
o(e.stack).equals("error on line 1") o(e.response.stack).equals("error on line 1")
}).then(done) }).then(done)
}) })
o("rejects on non-JSON server error", function(done) { o("rejects on non-JSON server error", function(done) {
@ -518,5 +533,35 @@ o.spec("xhr", function() {
o(e instanceof Error).equals(true) o(e instanceof Error).equals(true)
}).then(done) }).then(done)
}) })
o("does not reject on status error code when extract provided", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: JSON.stringify({message: "error"})}
}
})
xhr({
method: "GET", url: "/item",
extract: function(xhr) {return JSON.parse(xhr.responseText)}
}).then(function(data) {
o(data.message).equals("error")
done()
})
})
o("rejects on error in extract", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr({
method: "GET", url: "/item",
extract: function() {throw new Error("error")}
}).catch(function(e) {
o(e instanceof Error).equals(true)
o(e.message).equals("error")
}).then(function() {
done()
})
})
}) })
}) })

21
stream/LICENSE Normal file
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.

6
stream/README.md Normal file
View file

@ -0,0 +1,6 @@
mithril-stream [![NPM Version](https://img.shields.io/npm/v/mithril-stream.svg)](https://www.npmjs.com/package/mithril-stream) [![NPM License](https://img.shields.io/npm/l/mithril-stream.svg)](https://www.npmjs.com/package/mithril-stream)
==============
Mithril's `m.stream` as a standalone module.
See [mithril.js.org/stream.html](https://mithril.js.org/stream.html) for docs/usage.

View file

@ -1,6 +1,6 @@
{ {
"name": "mithril-stream", "name": "mithril-stream",
"version": "1.0.0", "version": "1.1.0",
"description": "Streaming data, mithril-style", "description": "Streaming data, mithril-style",
"main": "stream.js", "main": "stream.js",
"directories": { "directories": {
@ -9,5 +9,5 @@
"keywords": [ "stream", "reactive", "data" ], "keywords": [ "stream", "reactive", "data" ],
"author": "Leo Horie <lhorie@hotmail.com>", "author": "Leo Horie <lhorie@hotmail.com>",
"license": "MIT", "license": "MIT",
"repository": "lhorie/mithril.js" "repository": "MithrilJS/mithril.js"
} }

View file

@ -1,6 +1,7 @@
"use strict" /* eslint-disable */
;(function() { ;(function() {
"use strict"
/* eslint-enable */
var guid = 0, HALT = {} var guid = 0, HALT = {}
function createStream() { function createStream() {
@ -116,7 +117,9 @@ function merge(streams) {
function scan(reducer, seed, stream) { function scan(reducer, seed, stream) {
var newStream = combine(function (s) { var newStream = combine(function (s) {
return seed = reducer(seed, s._state.value) var next = reducer(seed, s._state.value)
if (next !== HALT) return seed = next
return HALT
}, [stream]) }, [stream])
if (newStream._state.state === 0) newStream(seed) if (newStream._state.state === 0) newStream(seed)

View file

@ -8,11 +8,8 @@
<script src="../../ospec/ospec.js"></script> <script src="../../ospec/ospec.js"></script>
<script src="../../test-utils/callAsync.js"></script> <script src="../../test-utils/callAsync.js"></script>
<script src="../stream.js"></script> <script src="../stream.js"></script>
<script src="../scan.js"></script>
<script src="../scanMerge.js"></script>
<script src="test-stream.js"></script> <script src="test-stream.js"></script>
<script src="test-scanMerge.js"></script> <script src="test-scanMerge.js"></script>
<script src="test-scanMerge.js"></script>
<script>require("../../ospec/ospec").run()</script> <script>require("../../ospec/ospec").run()</script>
</body> </body>

View file

@ -30,4 +30,36 @@ o.spec("scan", function() {
o(result[2]).equals(undefined) o(result[2]).equals(undefined)
o(result[3]).deepEquals({a: 1}) o(result[3]).deepEquals({a: 1})
}) })
o("reducer can return HALT to prevent child updates", function() {
var count = 0
var action = stream()
var store = stream.scan(function (arr, value) {
switch (typeof value) {
case "number":
return arr.concat(value)
default:
return stream.HALT
}
}, [], action)
var child = store.map(function (p) {
count++
return p
})
var result
action(7)
action("11")
action(undefined)
action({a: 1})
result = child()
// check we got the expect result
o(result[0]).equals(7)
// check child received minimum # of updates
o(count).equals(2)
})
}) })

View file

@ -1,9 +1,66 @@
"use strict" "use strict"
module.exports = function() { /*
Known limitations:
- the innerHTML setter and the DOMParser only support a small subset of the true HTML/XML syntax.
- `option.selected` can't be set/read when the option doesn't have a `select` parent
- `element.attributes` is just a map of attribute names => Attr objects stubs
- ...
*/
/*
options:
- spy:(f: Function) => Function
*/
module.exports = function(options) {
options = options || {}
var spy = options.spy || function(f){return f}
var spymap = []
function registerSpies(element, spies) {
if(options.spy) {
var i = spymap.indexOf(element)
if (i === -1) {
spymap.push(element, spies)
} else {
var existing = spymap[i + 1]
for (var k in spies) existing[k] = spies[k]
}
}
}
function getSpies(element) {
if (element == null || typeof element !== "object") throw new Error("Element expected")
if(options.spy) return spymap[spymap.indexOf(element) + 1]
}
function isModernEvent(type) { function isModernEvent(type) {
return type === "transitionstart" || type === "transitionend" || type === "animationstart" || type === "animationend" return type === "transitionstart" || type === "transitionend" || type === "animationstart" || type === "animationend"
} }
function dispatchEvent(e) {
var stopped = false
e.stopImmediatePropagation = function() {
e.stopPropagation()
stopped = true
}
e.currentTarget = this
if (this._events[e.type] != null) {
for (var i = 0; i < this._events[e.type].handlers.length; i++) {
var useCapture = this._events[e.type].options[i].capture
if (useCapture && e.eventPhase < 3 || !useCapture && e.eventPhase > 1) {
var handler = this._events[e.type].handlers[i]
if (typeof handler === "function") try {handler.call(this, e)} catch(e) {setTimeout(function(){throw e})}
else try {handler.handleEvent(e)} catch(e) {setTimeout(function(){throw e})}
if (stopped) return
}
}
}
// this is inaccurate. Normally the event fires in definition order, including legacy events
// this would require getters/setters for each of them though and we haven't gotten around to
// adding them since it would be at a high perf cost or would entail some heavy refactoring of
// the mocks (prototypes instead of closures).
if (e.eventPhase > 1 && typeof this["on" + e.type] === "function" && !isModernEvent(e.type)) try {this["on" + e.type](e)} catch(e) {setTimeout(function(){throw e})}
}
function appendChild(child) { function appendChild(child) {
var ancestor = this var ancestor = this
while (ancestor !== child && ancestor !== null) ancestor = ancestor.parentNode while (ancestor !== child && ancestor !== null) ancestor = ancestor.parentNode
@ -44,6 +101,7 @@ module.exports = function() {
if (index > -1) this.childNodes.splice(index, 1) if (index > -1) this.childNodes.splice(index, 1)
if (reference === null) this.appendChild(child) if (reference === null) this.appendChild(child)
else { else {
if (index !== -1 && refIndex > index) refIndex--
if (child.nodeType === 11) { if (child.nodeType === 11) {
this.childNodes.splice.apply(this.childNodes, [refIndex, 0].concat(child.childNodes)) this.childNodes.splice.apply(this.childNodes, [refIndex, 0].concat(child.childNodes))
while (child.firstChild) { while (child.firstChild) {
@ -62,14 +120,26 @@ module.exports = function() {
} }
function getAttribute(name) { function getAttribute(name) {
if (this.attributes[name] == null) return null if (this.attributes[name] == null) return null
return this.attributes[name].nodeValue return this.attributes[name].value
} }
function setAttribute(name, value) { function setAttribute(name, value) {
var nodeValue = String(value) /*eslint-disable no-implicit-coercion*/
// this is the correct kind of conversion, passing a Symbol throws in browsers too.
var nodeValue = "" + value
/*eslint-enable no-implicit-coercion*/
this.attributes[name] = { this.attributes[name] = {
namespaceURI: null, namespaceURI: null,
get value() {return nodeValue},
set value(value) {
/*eslint-disable no-implicit-coercion*/
nodeValue = "" + value
/*eslint-enable no-implicit-coercion*/
},
get nodeValue() {return nodeValue}, get nodeValue() {return nodeValue},
set nodeValue(value) {nodeValue = String(value)}, set nodeValue(value) {
this.value = value
}
} }
} }
function setAttributeNS(ns, name, value) { function setAttributeNS(ns, name, value) {
@ -79,6 +149,9 @@ module.exports = function() {
function removeAttribute(name) { function removeAttribute(name) {
delete this.attributes[name] delete this.attributes[name]
} }
function hasAttribute(name) {
return name in this.attributes
}
var declListTokenizer = /;|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'/g var declListTokenizer = /;|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'/g
/** /**
* This will split a semicolon-separated CSS declaration list into an array of * This will split a semicolon-separated CSS declaration list into an array of
@ -111,9 +184,43 @@ module.exports = function() {
res.unshift(declList) res.unshift(declList)
return res return res
} }
function parseMarkup(value, root, voidElements, xmlns) {
var depth = 0, stack = [root]
value.replace(/<([a-z0-9\-]+?)((?:\s+?[^=]+?=(?:"[^"]*?"|'[^']*?'|[^\s>]*))*?)(\s*\/)?>|<\/([a-z0-9\-]+?)>|([^<]+)/g, function(match, startTag, attrs, selfClosed, endTag, text) {
if (startTag) {
var element = xmlns == null ? $window.document.createElement(startTag) : $window.document.createElementNS(xmlns, startTag)
attrs.replace(/\s+?([^=]+?)=(?:"([^"]*?)"|'([^']*?)'|([^\s>]*))/g, function(match, key, doubleQuoted, singleQuoted, unquoted) {
var keyParts = key.split(":")
var name = keyParts.pop()
var ns = keyParts[0]
var value = doubleQuoted || singleQuoted || unquoted || ""
if (ns != null) element.setAttributeNS(ns, name, value)
else element.setAttribute(name, value)
})
stack[depth].appendChild(element)
if (!selfClosed && voidElements.indexOf(startTag.toLowerCase()) < 0) stack[++depth] = element
}
else if (endTag) {
depth--
}
else if (text) {
stack[depth].appendChild($window.document.createTextNode(text)) // FIXME handle html entities
}
})
}
function DOMParser() {}
DOMParser.prototype.parseFromString = function(src, mime) {
if (mime !== "image/svg+xml") throw new Error("The DOMParser mock only supports the \"image/svg+xml\" MIME type")
var match = src.match(/^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg">(.*)<\/svg>$/)
if (!match) throw new Error("Please provide a bare SVG tag with the xmlns as only attribute")
var value = match[1]
var root = $window.document.createElementNS("http://www.w3.org/2000/svg", "svg")
parseMarkup(value, root, [], "http://www.w3.org/2000/svg")
return {documentElement: root}
}
var activeElement var activeElement
var $window = { var $window = {
DOMParser: DOMParser,
document: { document: {
createElement: function(tag) { createElement: function(tag) {
var cssText = "" var cssText = ""
@ -150,6 +257,7 @@ module.exports = function() {
appendChild: appendChild, appendChild: appendChild,
removeChild: removeChild, removeChild: removeChild,
insertBefore: insertBefore, insertBefore: insertBefore,
hasAttribute: hasAttribute,
getAttribute: getAttribute, getAttribute: getAttribute,
setAttribute: setAttribute, setAttribute: setAttribute,
setAttributeNS: setAttributeNS, setAttributeNS: setAttributeNS,
@ -171,30 +279,18 @@ module.exports = function() {
if (value !== "") this.appendChild($window.document.createTextNode(value)) if (value !== "") this.appendChild($window.document.createTextNode(value))
}, },
set innerHTML(value) { set innerHTML(value) {
var voidElements = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
while (this.firstChild) this.removeChild(this.firstChild) while (this.firstChild) this.removeChild(this.firstChild)
var match = value.match(/^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg">(.*)<\/svg>$/), root, ns
var stack = [this], depth = 0, voidElements = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"] if (match) {
value.replace(/<([a-z0-9\-]+?)((?:\s+?[^=]+?=(?:"[^"]*?"|'[^']*?'|[^\s>]*))*?)(\s*\/)?>|<\/([a-z0-9\-]+?)>|([^<]+)/g, function(match, startTag, attrs, selfClosed, endTag, text) { var value = match[1]
if (startTag) { root = $window.document.createElementNS("http://www.w3.org/2000/svg", "svg")
var element = $window.document.createElement(startTag) ns = "http://www.w3.org/2000/svg"
attrs.replace(/\s+?([^=]+?)=(?:"([^"]*?)"|'([^']*?)'|([^\s>]*))/g, function(match, key, doubleQuoted, singleQuoted, unquoted) { this.appendChild(root)
var keyParts = key.split(":") } else {
var name = keyParts.pop() root = this
var ns = keyParts[0] }
var value = doubleQuoted || singleQuoted || unquoted || "" parseMarkup(value, root, voidElements, ns)
if (ns != null) element.setAttributeNS(ns, name, value)
else element.setAttribute(name, value)
})
stack[depth].appendChild(element)
if (!selfClosed && voidElements.indexOf(startTag.toLowerCase()) < 0) stack[++depth] = element
}
else if (endTag) {
depth--
}
else if (text) {
stack[depth].appendChild($window.document.createTextNode(text)) // FIXME handle html entities
}
})
}, },
get style() { get style() {
return style return style
@ -204,40 +300,106 @@ module.exports = function() {
throw new Error("setting element.style is not portable") throw new Error("setting element.style is not portable")
}, },
get className() { get className() {
return this.attributes["class"] ? this.attributes["class"].nodeValue : "" return this.attributes["class"] ? this.attributes["class"].value : ""
}, },
set className(value) { set className(value) {
if (this.namespaceURI === "http://www.w3.org/2000/svg") throw new Error("Cannot set property className of SVGElement") if (this.namespaceURI === "http://www.w3.org/2000/svg") throw new Error("Cannot set property className of SVGElement")
else this.setAttribute("class", value) else this.setAttribute("class", value)
}, },
focus: function() {activeElement = this}, focus: function() {activeElement = this},
addEventListener: function(type, callback) { addEventListener: function(type, handler, options) {
if (events[type] == null) events[type] = [callback] if (arguments.length > 2) {
else events[type].push(callback) if (typeof options === "object" && options != null) throw new TypeError("NYI: addEventListener options")
else if (typeof options !== "boolean") throw new TypeError("boolean expected for useCapture")
else options = {capture: options}
} else {
options = {capture: false}
}
if (events[type] == null) events[type] = {handlers: [handler], options: [options]}
else {
var found = false
for (var i = 0; i < events[type].handlers.length; i++) {
if (events[type].handlers[i] === handler && events[type].options[i].capture === options.capture) {
found = true
break
}
}
if (!found) {
events[type].handlers.push(handler)
events[type].options.push(options)
}
}
}, },
removeEventListener: function(type, callback) { removeEventListener: function(type, handler, options) {
if (arguments.length > 2) {
if (typeof options === "object" && options != null) throw new TypeError("NYI: addEventListener options")
else if (typeof options !== "boolean") throw new TypeError("boolean expected for useCapture")
else options = {capture: options}
} else {
options = {capture: false}
}
if (events[type] != null) { if (events[type] != null) {
var index = events[type].indexOf(callback) for (var i = 0; i < events[type].handlers.length; i++) {
if (index > -1) events[type].splice(index, 1) if (events[type].handlers[i] === handler && events[type].options[i].capture === options.capture) {
events[type].handlers.splice(i, 1)
events[type].options.splice(i, 1)
break;
}
}
} }
}, },
dispatchEvent: function(e) { dispatchEvent: function(e) {
if (this.nodeName === "INPUT" && this.attributes["type"] != null && this.attributes["type"].nodeValue === "checkbox" && e.type === "click") { var parents = []
this.checked = !this.checked if (this.parentNode != null) {
var parent = this.parentNode
do {
parents.push(parent)
parent = parent.parentNode
} while (parent != null)
} }
e.target = this e.target = this
if (events[e.type] != null) { var prevented = false
for (var i = 0; i < events[e.type].length; i++) { e.preventDefault = function() {
events[e.type][i].call(this, e) prevented = true
}
var stopped = false
e.stopPropagation = function() {
stopped = true
}
e.eventPhase = 1
try {
for (var i = parents.length - 1; 0 <= i; i--) {
dispatchEvent.call(parents[i], e)
if (stopped) {
return
}
}
e.eventPhase = 2
dispatchEvent.call(this, e)
if (stopped) {
return
}
e.eventPhase = 3
for (var i = 0; i < parents.length; i++) {
dispatchEvent.call(parents[i], e)
if (stopped) {
return
}
}
} catch(e) {
throw e
} finally {
e.eventPhase = 0
if (!prevented) {
if (this.nodeName === "INPUT" && this.attributes["type"] != null && this.attributes["type"].value === "checkbox" && e.type === "click") {
this.checked = !this.checked
}
} }
} }
e.preventDefault = function() {
// TODO: should this do something?
}
if (typeof this["on" + e.type] === "function" && !isModernEvent(e.type)) this["on" + e.type](e)
}, },
onclick: null, onclick: null,
_events: events
} }
if (element.nodeName === "A") { if (element.nodeName === "A") {
@ -256,30 +418,73 @@ module.exports = function() {
enumerable: true, enumerable: true,
}) })
element.value = "" var value = ""
} var valueSetter = spy(function(v) {
/*eslint-disable no-implicit-coercion*/
if (element.nodeName === "TEXTAREA") { value = v === null ? "" : "" + v
var value /*eslint-enable no-implicit-coercion*/
})
Object.defineProperty(element, "value", { Object.defineProperty(element, "value", {
get: function() { get: function() {
return value != null ? value : return value
this.firstChild ? this.firstChild.nodeValue : ""
}, },
set: function(v) {value = v}, set: valueSetter,
enumerable: true, enumerable: true,
}) })
// we currently emulate the non-ie behavior, but emulating ie may be more useful (throw when an invalid type is set)
var typeSetter = spy(function(v) {
this.setAttribute("type", v)
})
Object.defineProperty(element, "type", {
get: function() {
if (!this.hasAttribute("type")) return "text"
var type = this.getAttribute("type")
return (/^(?:radio|button|checkbox|color|date|datetime|datetime-local|email|file|hidden|month|number|password|range|research|search|submit|tel|text|url|week|image)$/)
.test(type)
? type
: "text"
},
set: typeSetter,
enumerable: true,
})
registerSpies(element, {
valueSetter: valueSetter,
typeSetter: typeSetter
})
}
if (element.nodeName === "TEXTAREA") {
var wasNeverSet = true
var value = ""
var valueSetter = spy(function(v) {
wasNeverSet = false
/*eslint-disable no-implicit-coercion*/
value = v === null ? "" : "" + v
/*eslint-enable no-implicit-coercion*/
})
Object.defineProperty(element, "value", {
get: function() {
return wasNeverSet && this.firstChild ? this.firstChild.nodeValue : value
},
set: valueSetter,
enumerable: true,
})
registerSpies(element, {
valueSetter: valueSetter
})
} }
/* eslint-disable radix */ /* eslint-disable radix */
if (element.nodeName === "CANVAS") { if (element.nodeName === "CANVAS") {
Object.defineProperty(element, "width", { Object.defineProperty(element, "width", {
get: function() {return this.attributes["width"] ? Math.floor(parseInt(this.attributes["width"].nodeValue) || 0) : 300}, get: function() {return this.attributes["width"] ? Math.floor(parseInt(this.attributes["width"].value) || 0) : 300},
set: function(value) {this.setAttribute("width", Math.floor(Number(value) || 0).toString())}, set: function(value) {this.setAttribute("width", Math.floor(Number(value) || 0).toString())},
}) })
Object.defineProperty(element, "height", { Object.defineProperty(element, "height", {
get: function() {return this.attributes["height"] ? Math.floor(parseInt(this.attributes["height"].nodeValue) || 0) : 300}, get: function() {return this.attributes["height"] ? Math.floor(parseInt(this.attributes["height"].value) || 0) : 300},
set: function(value) {this.setAttribute("height", Math.floor(Number(value) || 0).toString())}, set: function(value) {this.setAttribute("height", Math.floor(Number(value) || 0).toString())},
}) })
} }
@ -296,7 +501,7 @@ module.exports = function() {
} }
function getOptionValue(element) { function getOptionValue(element) {
return element.attributes["value"] != null ? return element.attributes["value"] != null ?
element.attributes["value"].nodeValue : element.attributes["value"].value :
element.firstChild != null ? element.firstChild.nodeValue : "" element.firstChild != null ? element.firstChild.nodeValue : ""
} }
if (element.nodeName === "SELECT") { if (element.nodeName === "SELECT") {
@ -317,14 +522,14 @@ module.exports = function() {
}, },
enumerable: true, enumerable: true,
}) })
Object.defineProperty(element, "value", { var valueSetter = spy(function(value) {
get: function() { if (value === null) {
if (this.selectedIndex > -1) return getOptionValue(getOptions(this)[this.selectedIndex]) selectedIndex = -1
return "" } else {
},
set: function(value) {
var options = getOptions(this) var options = getOptions(this)
var stringValue = String(value) /*eslint-disable no-implicit-coercion*/
var stringValue = "" + value
/*eslint-enable no-implicit-coercion*/
for (var i = 0; i < options.length; i++) { for (var i = 0; i < options.length; i++) {
if (getOptionValue(options[i]) === stringValue) { if (getOptionValue(options[i]) === stringValue) {
// selectedValue = stringValue // selectedValue = stringValue
@ -334,19 +539,37 @@ module.exports = function() {
} }
// selectedValue = stringValue // selectedValue = stringValue
selectedIndex = -1 selectedIndex = -1
}
})
Object.defineProperty(element, "value", {
get: function() {
if (this.selectedIndex > -1) return getOptionValue(getOptions(this)[this.selectedIndex])
return ""
}, },
set: valueSetter,
enumerable: true, enumerable: true,
}) })
registerSpies(element, {
valueSetter: valueSetter
})
} }
if (element.nodeName === "OPTION") { if (element.nodeName === "OPTION") {
var valueSetter = spy(function(value) {
/*eslint-disable no-implicit-coercion*/
this.setAttribute("value", "" + value)
/*eslint-enable no-implicit-coercion*/
})
Object.defineProperty(element, "value", { Object.defineProperty(element, "value", {
get: function() {return getOptionValue(this)}, get: function() {return getOptionValue(this)},
set: function(value) { set: valueSetter,
this.setAttribute("value", value)
},
enumerable: true, enumerable: true,
}) })
registerSpies(element, {
valueSetter: valueSetter
})
Object.defineProperty(element, "selected", { Object.defineProperty(element, "selected", {
// TODO? handle `selected` without a parent (works in browsers)
get: function() { get: function() {
var options = getOptions(this.parentNode) var options = getOptions(this.parentNode)
var index = options.indexOf(this) var index = options.indexOf(this)
@ -372,13 +595,19 @@ module.exports = function() {
return element return element
}, },
createTextNode: function(text) { createTextNode: function(text) {
var nodeValue = String(text) /*eslint-disable no-implicit-coercion*/
var nodeValue = "" + text
/*eslint-enable no-implicit-coercion*/
return { return {
nodeType: 3, nodeType: 3,
nodeName: "#text", nodeName: "#text",
parentNode: null, parentNode: null,
get nodeValue() {return nodeValue}, get nodeValue() {return nodeValue},
set nodeValue(value) {nodeValue = String(value)}, set nodeValue(value) {
/*eslint-disable no-implicit-coercion*/
nodeValue = "" + value
/*eslint-enable no-implicit-coercion*/
},
} }
}, },
createDocumentFragment: function() { createDocumentFragment: function() {
@ -397,7 +626,8 @@ module.exports = function() {
}, },
createEvent: function() { createEvent: function() {
return { return {
initEvent: function(type) {this.type = type}, eventPhase: 0,
initEvent: function(type) {this.type = type}
} }
}, },
get activeElement() {return activeElement}, get activeElement() {return activeElement},
@ -409,5 +639,7 @@ module.exports = function() {
$window.document.documentElement.appendChild($window.document.body) $window.document.documentElement.appendChild($window.document.body)
activeElement = $window.document.body activeElement = $window.document.body
if (options.spy) $window.__getSpies = getSpies
return $window return $window
} }

View file

@ -7,21 +7,20 @@
<script src="../../module/module.js"></script> <script src="../../module/module.js"></script>
<script src="../../ospec/ospec.js"></script> <script src="../../ospec/ospec.js"></script>
<script src="../../querystring/parse.js"></script> <script src="../../querystring/parse.js"></script>
<script src="../../test-utils/callAsync.js"></script> <script src="../../test-utils/callAsync.js"></script>
<script src="../../test-utils/parseURL.js"></script> <script src="../../test-utils/parseURL.js"></script>
<script src="../../test-utils/pushStateMock.js"></script> <script src="../../test-utils/pushStateMock.js"></script>
<script src="../../test-utils/xhrMock.js"></script> <script src="../../test-utils/xhrMock.js"></script>
<script src="../../test-utils/domMock.js"></script> <script src="../../test-utils/domMock.js"></script>
<script src="../../test-utils/browserMock.js"></script> <script src="../../test-utils/browserMock.js"></script>
<script src="../../test-utils/component.js"></script> <script src="../../test-utils/components.js"></script>
<script src="test-callAsync.js"></script> <script src="test-callAsync.js"></script>
<script src="test-parseURL.js"></script> <script src="test-parseURL.js"></script>
<script src="test-pushStateMock.js"></script> <script src="test-pushStateMock.js"></script>
<script src="test-xhrMock.js"></script> <script src="test-xhrMock.js"></script>
<script src="test-domMock.js"></script> <script src="test-domMock.js"></script>
<script src="test-browserMock.js"></script> <script src="test-browserMock.js"></script>
<script src="test-component.js"></script> <script src="test-components.js"></script>
<script>require("../../ospec/ospec").run()</script> <script>require("../../ospec/ospec").run()</script>
</body> </body>

Some files were not shown because too many files have changed in this diff Show more