diff --git a/.eslintignore b/.eslintignore index a3726b93..61d2a0b7 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,10 +1,7 @@ -coverage .vscode -examples -docs -node_modules -tests -test-utils -ospec -mithril.js -mithril.min.js +/coverage +/docs/lib +/examples +/mithril.js +/mithril.min.js +/node_modules diff --git a/.eslintrc.js b/.eslintrc.js index 25278201..c14d0119 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -60,7 +60,14 @@ module.exports = { "id-blacklist": "error", "id-length": "off", "id-match": "error", - "indent": "off", + "indent": [ + "warn", + "tab", + { + "outerIIFEBody": 0, + "SwitchCase": 1 + } + ], "init-declarations": "off", "jsx-quotes": "error", "key-spacing": "off", @@ -188,7 +195,7 @@ module.exports = { "quotes": [ "error", "double", - "avoid-escape" + {"avoidEscape": true} ], "radix": [ "error", @@ -209,7 +216,7 @@ module.exports = { "space-infix-ops": "off", "space-unary-ops": "error", "spaced-comment": "off", - "strict": "off", + "strict": ["error", "global"], "template-curly-spacing": "error", "valid-jsdoc": "off", "vars-on-top": "off", @@ -217,5 +224,6 @@ module.exports = { "wrap-regex": "error", "yield-star-spacing": "error", "yoda": "off" - } -}; \ No newline at end of file + }, + "root": true +}; diff --git a/.gitattributes b/.gitattributes index 21256661..6de5c647 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ -* text=auto \ No newline at end of file +* text=auto +/mithril.js binary +/mithril.min.js binary diff --git a/.gitignore b/.gitignore index 8af32a76..285af458 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ jsconfig.json npm-debug.log .vscode .DS_Store +.eslintcache diff --git a/.travis.yml b/.travis.yml index 4d118c54..494a4fef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,48 +1,97 @@ sudo: false +# Only care about running tests against latest node language: node_js node_js: - node +# Keep node_modules around, it speeds up builds & they don't change often cache: directories: - node_modules -# Custom install step so the travis scripts don't need to be in package.json +# Custom install step so the travis-only stuff doesn't need to be in package.json install: - - npm install - - npm install @alrra/travis-scripts@^3.0.1 +- npm install +- npm install @alrra/travis-scripts@^3.0.1 gh-pages@^0.12.0 -# Lint (but don't fail build) before running tests -before_script: npm run lint || true +# Bundle before running tests so the bundle is always up-to-date +before_script: npm run build --silent -# Run more than just npm test -script: npm run build && npm test +# Run tests, lint, and then check for perf regressions +script: +- npm test --silent +- npm run perf --silent -# After a successful build create bundles & commit back to the repo +# After a successful build commit changes back to repo after_success: - | - - # Only want to commit things on commits to $BRANCH - if [ "$TRAVIS_EVENT_TYPE" == "pull_request" ] || [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then - echo "Artifacts only built on $BRANCH" - exit 0 - fi - # Set up SSH environment - $(npm bin)/set-up-ssh --key "$encrypted_8b86e0359d64_key" \ - --iv "$encrypted_8b86e0359d64_iv" \ - --path-encrypted-key "./.deploy.enc" - - # Build & commit changes - $(npm bin)/commit-changes --commit-message "Bundled output for commit $TRAVIS_COMMIT [skip ci]" \ - --branch "$BRANCH" + $(npm bin)/set-up-ssh \ + --key "$encrypted_8b86e0359d64_key" \ + --iv "$encrypted_8b86e0359d64_iv" \ + --path-encrypted-key "./.deploy.enc" + # Commit bundle changes generated in before_script step + # --commands is a weird no-op but required for commit-changes to run + # --branch arg is to ensure this only runs against the `next` branch + $(npm bin)/commit-changes \ + --commands "echo committing" \ + --commit-message "Bundled output for commit $TRAVIS_COMMIT [skip ci]" \ + --branch "next" + + # Only want to commit docs when building pushes on master & + # this doesn't have the built-in branch protection like commit-changes + if [ "$TRAVIS_EVENT_TYPE" == "push" ] && \ + [ "$TRAVIS_BRANCH" == "master" ] && \ + [ "$TRAVIS_REPO_SLUG" == "MithrilJS/mithril.js" ] + then + # Generate docs + npm run gendocs + + # Set up git env + git config --global user.email "$GH_USER_EMAIL" + git config --global user.name "$GH_USER_NAME" + + # Commit docs to gh-pages branch + # Using --add to ensure that archived versions aren't lost + # Using --repo to force it to go over SSH so the saved keys are used (tschaub/gh-pages#160) + $(npm bin)/gh-pages \ + --dist ./dist \ + --add \ + --repo "git@github.com:MithrilJS/mithril.js.git" \ + --message "Generated docs for commit $TRAVIS_COMMIT [skip ci]" + else + echo "Not submitting documentation updates" + fi + +# Environment configuration env: global: - # Restrict the branch this will activate on - - BRANCH=rewrite - # Set up GH_USER_EMAIL & GH_USER_NAME env variables used by travis-scripts package - secure: Xvqvm3+PvJu/rs3jl/NNn0RWLkkLkIoPHiL0GCfVRaywgjCYVN02g54NVvIDaOfybqPmu9E6PJFVs92vhF34NMFQHf4EWskynusIGV271R2BV0i+OJBfLMuLgiwm6zRn7/Zw4JvWIUGEwcnlz0qxbqdHsS0SOR3fIkFzePickW0= - secure: Rf/ldEO9d4vItJhe6EmqWpFAyCARzoCb422nHnjr1hYJknnwIXpgyZ1C/7On/9o7rWPPf+8WcHC/rgjK2rthKCldzdG5I60LfWSNzap9lk3Aa4TpSCoDBuEp7JVvDr5tc3rKnBXVT71hOay7RSx1StWzXiJs9mjaeVMJzYzRT78= + +# Deploy to npm and github pages on tagged commits that successfully build +deploy: + - provider: releases + api_key: + secure: PauFuz+pn7oRpHn2JTl4k3+iWjOofyBYBvavPQVNdXgKws9mGj0i2n5k2oIDU09VD7NeyEkwP6tdLCUFNaR8uwTJH/TBXMZE95oxUEaliFreA0nOiI3WkG4NCW0GwUoIIn1yL14y6+9oEBinWUia8DIn9kZNS11DNDgQpIPnoQQ= + file: + - "mithril.js" + - "mithril.min.js" + skip_cleanup: true + on: + tags: true + repo: MithrilJS/mithril.js + branch: master + + - provider: npm + skip_cleanup: true + email: npm@patcavit.com + api_key: + secure: ADElvD1oxn9GfEG7dDOggX96b36A/cGEybovAc0221CCKzv5kWCavMrtxneiJYI6N/n24abSlbM90vMfU84FEzH0Ev28dGVokRP4ad6VRkISszKlYVEP8Lds4QxfKh78jZlUxmxM0B3vmQ1kYJbTBqp3ICtaJ5ptEQHWhrLtxnc= + on: + tags: true + repo: MithrilJS/mithril.js + branch: master diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..2aae0f1e --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md index bfe22f41..08636be2 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,267 @@ -# Mithril.js - A framework for building brilliant applications +# Introduction -[Installation](docs/installation.md) | [API](docs/api.md) | [Examples](docs/examples.md) | [Changelog/Migration Guide](docs/change-log.md) +- [What is Mithril?](#what-is-mithril) +- [Getting started](#getting-started) +- [Hello world](#hello-world) +- [DOM elements](#dom-elements) +- [Components](#components) +- [Routing](#routing) +- [XHR](#xhr) -Note: This branch is the upcoming version 1.0. It's a rewrite from the ground up and it's not backwards compatible with [Mithril 0.2.x](http://mithril.js.org). You can find preliminary [documentation here](docs) and [migration guide here](docs/change-log.md) +--- -This rewrite aims to fix longstanding API design issues, significantly improve performance, and clean up the codebase. +### What is Mithril? -## Early Preview +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. -You can install this via NPM using this command: +
+
+
Download size
+ Mithril (8kb) +
+ Vue + Vue-Router + Vuex + fetch (40kb) +
+ React + React-Router + Redux + fetch (64kb) +
+ Angular (135kb) +
+
+
+
Performance
+ Mithril (6.4ms) +
+ Vue (9.8ms) +
+ React (12.1ms) +
+ Angular (11.5ms) +
+
+
-``` -npm install mithril@rewrite +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 + + + + ``` -Examples run out of the box. Just open the HTML files. +--- -## Status +### Hello world -The code is fairly stable and I'm using it in production, but there may be bugs still lurking. +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) -Some examples of usage can be found in the [examples](examples) folder. [ThreadItJS](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/threaditjs/index.html) has the largest API surface coverage. +```javascript +var root = document.body -Partial documentation can be found in the [`/docs`](docs) directory +m.render(root, "Hello world") +``` -## Performance +Now, let's change the text to something else. Add this line of code under the previous one: -Mithril's virtual DOM engine is around 500 lines of well organized code and it implements a modern search space reduction diff algorithm and a DOM recycling mechanism, which translate to top-of-class performance. See the [dbmon implementation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html) (for comparison, here are dbmon implementations for [React v15.3.2](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/react/index.html), [Angular v2.0.0-beta.17](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/angular/index.html) and [Vue 2](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/vue/index.html). All implementations are naive (i.e. apples-to-apples, no optimizations) +```javascript +m.render(root, "My first app") +``` -## Robustness +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. -There are over 4000 assertions in the test suite, and tests cover even difficult-to-test things like `location.href`, `element.innerHTML` and `XMLHttpRequest` usage. +--- -## Modularity +### DOM elements -Despite the huge improvements in performance and modularity, the new codebase is smaller than v0.2.x, currently clocking at 7.60 KB min+gzip +Let's wrap our text in an `

` tag. -In addition, Mithril is now completely modular: you can import only the modules that you need and easily integrate 3rd party modules if you wish to use a different library for routing, ajax, and even rendering +```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 `

`: + +```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 `` 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 +
+

My first app

+ +
+``` + +--- + +### 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 +
+

My first app

+ +
+``` + +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. diff --git a/api/mount.js b/api/mount.js index 0cebfcf6..2178505a 100644 --- a/api/mount.js +++ b/api/mount.js @@ -10,7 +10,7 @@ module.exports = function(redrawService) { return } - if (component.view == null) throw new Error("m.mount(element, component) expects a component, not a vnode") + if (component.view == null && typeof component !== "function") throw new Error("m.mount(element, component) expects a component, not a vnode") var run = function() { redrawService.render(root, Vnode(component)) diff --git a/api/redraw.js b/api/redraw.js index 3f98b061..a05b6c88 100644 --- a/api/redraw.js +++ b/api/redraw.js @@ -26,9 +26,10 @@ function throttle(callback) { module.exports = function($window) { var renderService = coreRenderer($window) renderService.setEventCallback(function(e) { - if (e.redraw !== false) redraw() + if (e.redraw === false) e.redraw = undefined + else redraw() }) - + var callbacks = [] function subscribe(key, callback) { unsubscribe(key) @@ -38,10 +39,10 @@ module.exports = function($window) { var index = callbacks.indexOf(key) if (index > -1) callbacks.splice(index, 2) } - function redraw() { - for (var i = 1; i < callbacks.length; i += 2) { - callbacks[i]() - } - } + function redraw() { + for (var i = 1; i < callbacks.length; i += 2) { + callbacks[i]() + } + } return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render} } diff --git a/api/router.js b/api/router.js index cf406737..93f2e074 100644 --- a/api/router.js +++ b/api/router.js @@ -14,17 +14,19 @@ module.exports = function($window, redrawService) { var run = function() { if (render != null) redrawService.render(root, render(Vnode(component, attrs.key, attrs))) } - var bail = function() { - routeService.setPath(defaultRoute, null, {replace: true}) + var bail = function(path) { + if (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true}) + else throw new Error("Could not resolve default route " + defaultRoute) } routeService.defineRoutes(routes, function(payload, params, path) { var update = lastUpdate = function(routeResolver, comp) { if (update !== lastUpdate) return - component = comp != null && typeof comp.view === "function" ? comp : "div", attrs = params, currentPath = path, lastUpdate = null + component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div" + attrs = params, currentPath = path, lastUpdate = null render = (routeResolver.render || identity).bind(routeResolver) run() } - if (payload.view) update({}, payload) + if (payload.view || typeof payload === "function") update({}, payload) else { if (payload.onmatch) { Promise.resolve(payload.onmatch(params, path)).then(function(resolved) { @@ -37,7 +39,10 @@ module.exports = function($window, redrawService) { redrawService.subscribe(root, run) } route.set = function(path, data, options) { - if (lastUpdate != null) options = {replace: true} + if (lastUpdate != null) { + options = options || {} + options.replace = true + } lastUpdate = null routeService.setPath(path, data, options) } @@ -54,6 +59,10 @@ module.exports = function($window, redrawService) { route.set(href, undefined, undefined) } } + route.param = function(key) { + if(typeof attrs !== "undefined" && typeof key !== "undefined") return attrs[key] + return attrs + } return route } diff --git a/api/tests/index.html b/api/tests/index.html index fd2557d5..37d313f4 100644 --- a/api/tests/index.html +++ b/api/tests/index.html @@ -13,6 +13,7 @@ + diff --git a/api/tests/test-mount.js b/api/tests/test-mount.js index 210a0627..53a35640 100644 --- a/api/tests/test-mount.js +++ b/api/tests/test-mount.js @@ -1,10 +1,10 @@ "use strict" var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var m = require("../../render/hyperscript") -var coreRenderer = require("../../render/render") var apiRedraw = require("../../api/redraw") var apiMounter = require("../../api/mount") @@ -19,220 +19,236 @@ o.spec("mount", function() { redrawService = apiRedraw($window) mount = apiMounter(redrawService) - render = coreRenderer($window).render + render = redrawService.render }) - o("throws on invalid `root` DOM node", function() { + o("throws on invalid component", function() { var threw = false try { - mount(null, {view: function() {}}) + mount(root, {}) } catch (e) { threw = true } o(threw).equals(true) }) - o("renders into `root`", function() { - mount(root, { - view : function() { - return m("div") - } - }) + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create - o(root.firstChild.nodeName).equals("DIV") - }) + o("throws on invalid `root` DOM node", function() { + var threw = false + try { + mount(null, createComponent({view: function() {}})) + } catch (e) { + threw = true + } + o(threw).equals(true) + }) - o("mounting null unmounts", function() { - mount(root, { - view : function() { - return m("div") - } - }) - - mount(root, null) - - o(root.childNodes.length).equals(0) - }) - - o("redraws on events", function(done) { - var onupdate = o.spy() - var oninit = o.spy() - var onclick = o.spy() - var e = $window.document.createEvent("MouseEvents") - - e.initEvent("click", true, true) - - mount(root, { - view : function() { - return m("div", { - oninit : oninit, - onupdate : onupdate, - onclick : onclick, - }) - } - }) - - root.firstChild.dispatchEvent(e) - - o(oninit.callCount).equals(1) - o(onupdate.callCount).equals(0) - - o(onclick.callCount).equals(1) - o(onclick.this).equals(root.firstChild) - o(onclick.args[0].type).equals("click") - o(onclick.args[0].target).equals(root.firstChild) - - // Wrapped to give time for the rate-limited redraw to fire - setTimeout(function() { - o(onupdate.callCount).equals(1) - - done() - }, FRAME_BUDGET) - }) - - o("redraws several mount points on events", function(done, timeout) { - timeout(60) - - var onupdate0 = o.spy() - var oninit0 = o.spy() - var onclick0 = o.spy() - var onupdate1 = o.spy() - var oninit1 = o.spy() - var onclick1 = o.spy() - - var e = $window.document.createEvent("MouseEvents") - - e.initEvent("click", true, true) - - render(root, [ - m("#child0"), - m("#child1") - ]) - - mount(root.childNodes[0], { - view : function() { - return m("div", { - oninit : oninit0, - onupdate : onupdate0, - onclick : onclick0, - }) - } - }) - - o(oninit0.callCount).equals(1) - o(onupdate0.callCount).equals(0) - - mount(root.childNodes[1], { - view : function() { - return m("div", { - oninit : oninit1, - onupdate : onupdate1, - onclick : onclick1, - }) - } - }) - - o(oninit1.callCount).equals(1) - o(onupdate1.callCount).equals(0) - - root.childNodes[0].firstChild.dispatchEvent(e) - o(onclick0.callCount).equals(1) - o(onclick0.this).equals(root.childNodes[0].firstChild) - - setTimeout(function() { - o(onupdate0.callCount).equals(1) - o(onupdate1.callCount).equals(1) - - root.childNodes[1].firstChild.dispatchEvent(e) - o(onclick1.callCount).equals(1) - o(onclick1.this).equals(root.childNodes[1].firstChild) - - setTimeout(function() { - o(onupdate0.callCount).equals(2) - o(onupdate1.callCount).equals(2) - - done() - }, FRAME_BUDGET) - }, FRAME_BUDGET) - - }) - - o("event handlers can skip redraw", function(done) { - var onupdate = o.spy() - var oninit = o.spy() - var e = $window.document.createEvent("MouseEvents") - - e.initEvent("click", true, true) - - mount(root, { - view: function() { - return m("div", { - oninit: oninit, - onupdate: onupdate, - onclick: function(e) { - e.redraw = false + o("renders into `root`", function() { + mount(root, createComponent({ + view : function() { + return m("div") } - }) - } + })) + + o(root.firstChild.nodeName).equals("DIV") + }) + + o("mounting null unmounts", function() { + mount(root, createComponent({ + view : function() { + return m("div") + } + })) + + mount(root, null) + + o(root.childNodes.length).equals(0) + }) + + o("redraws on events", function(done) { + var onupdate = o.spy() + var oninit = o.spy() + var onclick = o.spy() + var e = $window.document.createEvent("MouseEvents") + + e.initEvent("click", true, true) + + mount(root, createComponent({ + view : function() { + return m("div", { + oninit : oninit, + onupdate : onupdate, + onclick : onclick, + }) + } + })) + + root.firstChild.dispatchEvent(e) + + o(oninit.callCount).equals(1) + o(onupdate.callCount).equals(0) + + o(onclick.callCount).equals(1) + o(onclick.this).equals(root.firstChild) + o(onclick.args[0].type).equals("click") + o(onclick.args[0].target).equals(root.firstChild) + + // Wrapped to give time for the rate-limited redraw to fire + setTimeout(function() { + o(onupdate.callCount).equals(1) + + done() + }, FRAME_BUDGET) + }) + + o("redraws several mount points on events", function(done, timeout) { + timeout(60) + + var onupdate0 = o.spy() + var oninit0 = o.spy() + var onclick0 = o.spy() + var onupdate1 = o.spy() + var oninit1 = o.spy() + var onclick1 = o.spy() + + var e = $window.document.createEvent("MouseEvents") + + e.initEvent("click", true, true) + + render(root, [ + m("#child0"), + m("#child1") + ]) + + mount(root.childNodes[0], createComponent({ + view : function() { + return m("div", { + oninit : oninit0, + onupdate : onupdate0, + onclick : onclick0, + }) + } + })) + + o(oninit0.callCount).equals(1) + o(onupdate0.callCount).equals(0) + + mount(root.childNodes[1], createComponent({ + view : function() { + return m("div", { + oninit : oninit1, + onupdate : onupdate1, + onclick : onclick1, + }) + } + })) + + o(oninit1.callCount).equals(1) + o(onupdate1.callCount).equals(0) + + root.childNodes[0].firstChild.dispatchEvent(e) + o(onclick0.callCount).equals(1) + o(onclick0.this).equals(root.childNodes[0].firstChild) + + setTimeout(function() { + o(onupdate0.callCount).equals(1) + o(onupdate1.callCount).equals(1) + + root.childNodes[1].firstChild.dispatchEvent(e) + o(onclick1.callCount).equals(1) + o(onclick1.this).equals(root.childNodes[1].firstChild) + + setTimeout(function() { + o(onupdate0.callCount).equals(2) + o(onupdate1.callCount).equals(2) + + done() + }, FRAME_BUDGET) + }, FRAME_BUDGET) + + }) + + o("event handlers can skip redraw", function(done) { + var onupdate = o.spy() + var oninit = o.spy() + var e = $window.document.createEvent("MouseEvents") + + e.initEvent("click", true, true) + + mount(root, createComponent({ + view: function() { + return m("div", { + oninit: oninit, + onupdate: onupdate, + onclick: function(e) { + e.redraw = false + } + }) + } + })) + + root.firstChild.dispatchEvent(e) + + o(oninit.callCount).equals(1) + + // Wrapped to ensure no redraw fired + setTimeout(function() { + o(onupdate.callCount).equals(0) + + done() + }, FRAME_BUDGET) + }) + + o("redraws when the render function is run", function(done) { + var onupdate = o.spy() + var oninit = o.spy() + + mount(root, createComponent({ + view : function() { + return m("div", { + oninit: oninit, + onupdate: onupdate + }) + } + })) + + o(oninit.callCount).equals(1) + o(onupdate.callCount).equals(0) + + redrawService.redraw() + + // Wrapped to give time for the rate-limited redraw to fire + setTimeout(function() { + o(onupdate.callCount).equals(1) + + done() + }, FRAME_BUDGET) + }) + + o("throttles", function(done, timeout) { + timeout(200) + + var i = 0 + mount(root, createComponent({view: function() {i++}})) + var before = i + + redrawService.redraw() + redrawService.redraw() + redrawService.redraw() + redrawService.redraw() + + var after = i + + setTimeout(function(){ + o(before).equals(1) // mounts synchronously + o(after).equals(1) // throttles rest + o(i).equals(2) + done() + },40) + }) }) - - root.firstChild.dispatchEvent(e) - - o(oninit.callCount).equals(1) - - // Wrapped to ensure no redraw fired - setTimeout(function() { - o(onupdate.callCount).equals(0) - - done() - }, FRAME_BUDGET) - }) - - o("redraws when the render function is run", function(done) { - var onupdate = o.spy() - var oninit = o.spy() - - mount(root, { - view : function() { - return m("div", { - oninit: oninit, - onupdate: onupdate - }) - } - }) - - o(oninit.callCount).equals(1) - o(onupdate.callCount).equals(0) - - redrawService.redraw() - - // Wrapped to give time for the rate-limited redraw to fire - setTimeout(function() { - o(onupdate.callCount).equals(1) - - done() - }, FRAME_BUDGET) - }) - - o("throttles", function(done, timeout) { - timeout(200) - - var i = 0 - mount(root, {view: function() {i++}}) - var before = i - - redrawService.redraw() - redrawService.redraw() - redrawService.redraw() - redrawService.redraw() - - var after = i - - setTimeout(function(){ - o(before).equals(1) // mounts synchronously - o(after).equals(1) // throttles rest - o(i).equals(2) - done() - },40) }) }) diff --git a/api/tests/test-router.js b/api/tests/test-router.js index 6a281237..f0defd22 100644 --- a/api/tests/test-router.js +++ b/api/tests/test-router.js @@ -6,7 +6,6 @@ var browserMock = require("../../test-utils/browserMock") var m = require("../../render/hyperscript") var callAsync = require("../../test-utils/callAsync") -var coreRenderer = require("../../render/render") var apiRedraw = require("../../api/redraw") var apiRouter = require("../../api/router") var Promise = require("../../promise/promise") @@ -31,7 +30,7 @@ o.spec("route", function() { o("throws on invalid `root` DOM node", function() { var threw = false try { - route(null, '/', {'/':{view: function() {}}}) + route(null, "/", {"/":{view: function() {}}}) } catch (e) { threw = true } @@ -51,7 +50,7 @@ o.spec("route", function() { o(root.firstChild.nodeName).equals("DIV") }) - o("routed mount points can redraw synchronously (#1275)", function() { + o("routed mount points can redraw synchronously (POJO component)", function() { var view = o.spy() $window.location.href = prefix + "/" @@ -65,6 +64,39 @@ o.spec("route", function() { }) + o("routed mount points can redraw synchronously (constructible component)", function() { + var view = o.spy() + + var Cmp = function(){} + Cmp.prototype.view = view + + $window.location.href = prefix + "/" + route(root, "/", {"/":Cmp}) + + o(view.callCount).equals(1) + + redrawService.redraw() + + o(view.callCount).equals(2) + + }) + + o("routed mount points can redraw synchronously (closure component)", function() { + var view = o.spy() + + function Cmp() {return {view: view}} + + $window.location.href = prefix + "/" + route(root, "/", {"/":Cmp}) + + o(view.callCount).equals(1) + + redrawService.redraw() + + o(view.callCount).equals(2) + + }) + o("default route doesn't break back button", function(done) { $window.location.href = "http://old.com" $window.location.href = "http://new.com" @@ -173,7 +205,6 @@ o.spec("route", function() { o("event handlers can skip redraw", function(done) { var onupdate = o.spy() var oninit = o.spy() - var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) @@ -193,9 +224,11 @@ o.spec("route", function() { } }) + o(oninit.callCount).equals(1) + root.firstChild.dispatchEvent(e) - o(oninit.callCount).equals(1) + o(e.redraw).notEquals(false) // Wrapped to ensure no redraw fired callAsync(function() { @@ -321,11 +354,6 @@ o.spec("route", function() { o("accepts RouteResolver with onmatch that returns Promise", function(done) { var matchCount = 0 var renderCount = 0 - var Component = { - view: function() { - return m("span") - } - } var resolver = { onmatch: function(args, requestedPath) { @@ -362,11 +390,6 @@ o.spec("route", function() { o("accepts RouteResolver with onmatch that returns Promise", function(done) { var matchCount = 0 var renderCount = 0 - var Component = { - view: function() { - return m("span") - } - } var resolver = { onmatch: function(args, requestedPath) { @@ -404,14 +427,9 @@ o.spec("route", function() { var matchCount = 0 var renderCount = 0 var spy = o.spy() - var Component = { - view: function() { - return m("span") - } - } var resolver = { - onmatch: function(args, requestedPath) { + onmatch: function() { matchCount++ return Promise.reject(new Error("error")) }, @@ -466,7 +484,7 @@ o.spec("route", function() { }) }) - o("changing `vnode.key` in `render` resets the component", function(done, timeout){ + o("changing `vnode.key` in `render` resets the component", function(done){ var oninit = o.spy() var Component = { oninit: oninit, @@ -512,25 +530,19 @@ o.spec("route", function() { }) o(root.firstChild.nodeName).equals("DIV") + o(renderCount).equals(1) }) o("RouteResolver `render` does not have component semantics", function(done) { - var renderCount = 0 - var A = { - view: function() { - return m("div") - } - } - $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { - render: function(vnode) { + render: function() { return m("div") }, }, "/b" : { - render: function(vnode) { + render: function() { return m("div") }, }, @@ -599,7 +611,7 @@ o.spec("route", function() { onmatch: function() { matchCount++ }, - render: function(vnode) { + render: function() { renderCount++ return {tag: Component} }, @@ -655,7 +667,7 @@ o.spec("route", function() { route(root, "/a", { "/a" : { onmatch: function() { - route.set("/b") + route.set("/b", {}, {state: {a: 5}}) }, render: render }, @@ -674,6 +686,7 @@ o.spec("route", function() { o(view.callCount).equals(1) o(root.childNodes.length).equals(1) o(root.firstChild.nodeName).equals("DIV") + o($window.history.state).deepEquals({a: 5}) done() }) @@ -693,7 +706,7 @@ o.spec("route", function() { render: render }, "/b" : { - render: function(vnode){ + render: function(){ redirected = true } } @@ -805,7 +818,7 @@ o.spec("route", function() { }) callAsync(function() { - route.set('/b') + route.set("/b") callAsync(function() { callAsync(function() { callAsync(function() { @@ -832,7 +845,7 @@ o.spec("route", function() { render: render }, "/b" : { - onmatch: function(vnode){ + onmatch: function(){ redirected = true return {view: function() {}} } @@ -862,7 +875,7 @@ o.spec("route", function() { render: render }, "/b" : { - render: function(vnode){ + render: function(){ redirected = true } } @@ -891,7 +904,7 @@ o.spec("route", function() { render: render }, "/b" : { - view: function(vnode){ + view: function(){ redirected = true } } @@ -999,7 +1012,7 @@ o.spec("route", function() { var render = o.spy(function() {return m("div")}) $window.location.href = prefix + "/" - route(root, '/', { + route(root, "/", { "/": { onmatch: onmatch, render: render @@ -1048,23 +1061,23 @@ o.spec("route", function() { o("routing with RouteResolver works more than once", function(done) { $window.location.href = prefix + "/a" - route(root, '/a', { - '/a': { + route(root, "/a", { + "/a": { render: function() { return m("a", "a") } }, - '/b': { + "/b": { render: function() { return m("b", "b") } } }) - route.set('/b') + route.set("/b") callAsync(function() { - route.set('/a') + route.set("/a") callAsync(function() { o(root.firstChild.nodeName).equals("A") @@ -1089,7 +1102,7 @@ o.spec("route", function() { }) }) }, - render: function(vnode) { + render: function() { rendered = true resolved = "a" } @@ -1147,7 +1160,7 @@ o.spec("route", function() { route.set("/b") }) }, - render: function(vnode) { + render: function() { rendered = true resolved = "a" } @@ -1177,7 +1190,7 @@ o.spec("route", function() { var i = 0 $window.location.href = prefix + "/" route(root, "/", { - "/": {view: function(v) {i++}} + "/": {view: function() {i++}} }) var before = i @@ -1194,6 +1207,30 @@ o.spec("route", function() { done() }, FRAME_BUDGET * 2) }) + + o("m.route.param is available outside of route handlers", function(done) { + $window.location.href = prefix + "/" + + route(root, "/1", { + "/:id" : { + view : function() { + o(route.param("id")).equals("1") + + return m("div") + } + } + }) + + o(route.param("id")).equals(undefined); + o(route.param()).deepEquals(undefined); + + callAsync(function() { + o(route.param("id")).equals("1") + o(route.param()).deepEquals({id:"1"}) + + done() + }) + }) }) }) }) diff --git a/browser.js b/browser.js index fed323f1..0debb4ea 100644 --- a/browser.js +++ b/browser.js @@ -1,3 +1,5 @@ +"use strict" + var m = require("./index") if (typeof module !== "undefined") module["exports"] = m else window.m = m diff --git a/bundler/bin/bundle b/bundler/bin/bundle index e0c4279a..81c65c90 100644 --- a/bundler/bin/bundle +++ b/bundler/bin/bundle @@ -1,3 +1,4 @@ #!/usr/bin/env node +"use strict" require("../cli") diff --git a/bundler/bundle.js b/bundler/bundle.js index 34148951..54971214 100644 --- a/bundler/bundle.js +++ b/bundler/bundle.js @@ -114,7 +114,7 @@ function run(input, output) { .replace(/(\r|\n)+/g, "\n").replace(/(\r|\n)$/, "") // remove multiline breaks .replace(versionTag, isFile(packageFile) ? parse(packageFile).version : versionTag) // set version - code = "new function() {\n" + code + "\n}" + code = ";(function() {\n" + code + "\n}());" if (!isFile(output) || code !== read(output)) { //try {new Function(code); console.log("build completed at " + new Date())} catch (e) {} diff --git a/bundler/tests/test-bundler.js b/bundler/tests/test-bundler.js index 3055bf7c..15e7f932 100644 --- a/bundler/tests/test-bundler.js +++ b/bundler/tests/test-bundler.js @@ -1,3 +1,5 @@ +"use strict" + var o = require("../../ospec/ospec") var bundle = require("../bundle") @@ -5,10 +7,10 @@ var fs = require("fs") var ns = "bundler/tests/" function read(filepath) { - try {return fs.readFileSync(ns + filepath, "utf8")} catch (e) {} + try {return fs.readFileSync(ns + filepath, "utf8")} catch (e) {/* ignore */} } function write(filepath, data) { - try {var exists = fs.statSync(ns + filepath).isFile()} catch (e) {} + try {var exists = fs.statSync(ns + filepath).isFile()} catch (e) {/* ignore */} if (exists) throw new Error("Don't call `write('" + filepath + "')`. Cannot overwrite file") fs.writeFileSync(ns + filepath, data, "utf8") } @@ -18,255 +20,255 @@ function remove(filepath) { o.spec("bundler", function() { o("relative imports works", function() { - write("a.js", `var b = require("./b")`) - write("b.js", `module.exports = 1`) + write("a.js", 'var b = require("./b")') + write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b = 1\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with semicolons", function() { - write("a.js", `var b = require("./b");`) - write("b.js", `module.exports = 1;`) + write("a.js", 'var b = require("./b");') + write("b.js", "module.exports = 1;") bundle(ns + "a.js", ns + "out.js") - o(read("out.js")).equals(`new function() {\nvar b = 1;\n}`) - + o(read("out.js")).equals(";(function() {\nvar b = 1;\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with let", function() { - write("a.js", `let b = require("./b")`) - write("b.js", `module.exports = 1`) + write("a.js", 'let b = require("./b")') + write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - o(read("out.js")).equals(`new function() {\nlet b = 1\n}`) - + o(read("out.js")).equals(";(function() {\nlet b = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with const", function() { write("a.js", 'const b = require("./b")') - write("b.js", `module.exports = 1`) + write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - o(read("out.js")).equals(`new function() {\nconst b = 1\n}`) - + o(read("out.js")).equals(";(function() {\nconst b = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with assignment", function() { - write("a.js", `var a = {}\na.b = require("./b")`) - write("b.js", `module.exports = 1`) + write("a.js", 'var a = {}\na.b = require("./b")') + write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar a = {}\na.b = 1\n}`) - + + o(read("out.js")).equals(";(function() {\nvar a = {}\na.b = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with reassignment", function() { - write("a.js", `var b = {}\nb = require("./b")`) - write("b.js", `module.exports = 1`) + write("a.js", 'var b = {}\nb = require("./b")') + write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b = {}\nb = 1\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b = {}\nb = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict", function() { - write("a.js", `"use strict"\nvar b = require("./b")`) - write("b.js", `"use strict"\nmodule.exports = 1`) + write("a.js", '"use strict"\nvar b = require("./b")') + write("b.js", '"use strict"\nmodule.exports = 1') bundle(ns + "a.js", ns + "out.js") - o(read("out.js")).equals(`new function() {\n"use strict"\nvar b = 1\n}`) - + o(read("out.js")).equals(';(function() {\n"use strict"\nvar b = 1\n}());') + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict using single quotes", function() { - write("a.js", `'use strict'\nvar b = require("./b")`) - write("b.js", `'use strict'\nmodule.exports = 1`) + write("a.js", "'use strict'\nvar b = require(\"./b\")") + write("b.js", "'use strict'\nmodule.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\n'use strict'\nvar b = 1\n}`) - + + o(read("out.js")).equals(";(function() {\n'use strict'\nvar b = 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict using mixed quotes", function() { - write("a.js", `"use strict"\nvar b = require("./b")`) - write("b.js", `'use strict'\nmodule.exports = 1`) + write("a.js", '"use strict"\nvar b = require("./b")') + write("b.js", "'use strict'\nmodule.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\n"use strict"\nvar b = 1\n}`) - + + o(read("out.js")).equals(';(function() {\n"use strict"\nvar b = 1\n}());') + remove("a.js") remove("b.js") remove("out.js") }) o("works w/ window", function() { - write("a.js", `window.a = 1\nvar b = require("./b")`) - write("b.js", `module.exports = function() {return a}`) + write("a.js", 'window.a = 1\nvar b = require("./b")') + write("b.js", "module.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nwindow.a = 1\nvar b = function() {return a}\n}`) - + + o(read("out.js")).equals(";(function() {\nwindow.a = 1\nvar b = function() {return a}\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works without assignment", function() { - write("a.js", `require("./b")`) - write("b.js", `1 + 1`) + write("a.js", 'require("./b")') + write("b.js", "1 + 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\n1 + 1\n}`) - + + o(read("out.js")).equals(";(function() {\n1 + 1\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently", function() { - write("a.js", `var b = require("./b").toString()`) - write("b.js", `module.exports = []`) + write("a.js", 'var b = require("./b").toString()') + write("b.js", "module.exports = []") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = []\nvar b = _0.toString()\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0.toString()\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently w/ multiline", function() { - write("a.js", `var b = require("./b")\n\t.toString()`) - write("b.js", `module.exports = []`) + write("a.js", 'var b = require("./b")\n\t.toString()') + write("b.js", "module.exports = []") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = []\nvar b = _0\n\t.toString()\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0\n\t.toString()\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if used w/ curry", function() { - write("a.js", `var b = require("./b")()`) - write("b.js", `module.exports = function() {}`) + write("a.js", 'var b = require("./b")()') + write("b.js", "module.exports = function() {}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = function() {}\nvar b = _0()\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = function() {}\nvar b = _0()\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if used w/ curry w/ multiline", function() { - write("a.js", `var b = require("./b")\n()`) - write("b.js", `module.exports = function() {}`) + write("a.js", 'var b = require("./b")\n()') + write("b.js", "module.exports = function() {}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = function() {}\nvar b = _0\n()\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = function() {}\nvar b = _0\n()\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently in one place and not in another", function() { - write("a.js", `var b = require("./b").toString()\nvar c = require("./c")`) - write("b.js", `module.exports = []`) - write("c.js", `var b = require("./b")\nmodule.exports = function() {return b}`) + write("a.js", 'var b = require("./b").toString()\nvar c = require("./c")') + write("b.js", "module.exports = []") + write("c.js", 'var b = require("./b")\nmodule.exports = function() {return b}') bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = []\nvar b = _0.toString()\nvar b0 = _0\nvar c = function() {return b0}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0.toString()\nvar b0 = _0\nvar c = function() {return b0}\n}());") + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if used in sequence", function() { - write("a.js", `var b = require("./b"), c = require("./c")`) - write("b.js", `module.exports = 1`) - write("c.js", `var x\nmodule.exports = 2`) + write("a.js", 'var b = require("./b"), c = require("./c")') + write("b.js", "module.exports = 1") + write("c.js", "var x\nmodule.exports = 2") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b = 1\nvar x\nvar c = 2\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b = 1\nvar x\nvar c = 2\n}());") + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if assigned to property", function() { - write("a.js", `var x = {}\nx.b = require("./b")\nx.c = require("./c")`) - write("b.js", `var bb = 1\nmodule.exports = bb`) - write("c.js", `var cc = 2\nmodule.exports = cc`) + write("a.js", 'var x = {}\nx.b = require("./b")\nx.c = require("./c")') + write("b.js", "var bb = 1\nmodule.exports = bb") + write("c.js", "var cc = 2\nmodule.exports = cc") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar x = {}\nvar bb = 1\nx.b = bb\nvar cc = 2\nx.c = cc\n}`) - + + o(read("out.js")).equals(";(function() {\nvar x = {}\nvar bb = 1\nx.b = bb\nvar cc = 2\nx.c = cc\n}());") + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if assigned to property using bracket notation", function() { - write("a.js", `var x = {}\nx["b"] = require("./b")\nx["c"] = require("./c")`) - write("b.js", `var bb = 1\nmodule.exports = bb`) - write("c.js", `var cc = 2\nmodule.exports = cc`) + write("a.js", 'var x = {}\nx["b"] = require("./b")\nx["c"] = require("./c")') + write("b.js", "var bb = 1\nmodule.exports = bb") + write("c.js", "var cc = 2\nmodule.exports = cc") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar x = {}\nvar bb = 1\nx["b"] = bb\nvar cc = 2\nx["c"] = cc\n}`) - + + o(read("out.js")).equals(';(function() {\nvar x = {}\nvar bb = 1\nx["b"] = bb\nvar cc = 2\nx["c"] = cc\n}());') + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if collision", function() { - write("a.js", `var b = require("./b")`) - write("b.js", `var b = 1\nmodule.exports = 2`) + write("a.js", 'var b = require("./b")') + write("b.js", "var b = 1\nmodule.exports = 2") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b0 = 1\nvar b = 2\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b0 = 1\nvar b = 2\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("works if multiple aliases", function() { - write("a.js", `var b = require("./b")\n`) - write("b.js", `var b = require("./c")\nb.x = 1\nmodule.exports = b`) - write("c.js", `var b = {}\nmodule.exports = b`) + write("a.js", 'var b = require("./b")\n') + write("b.js", 'var b = require("./c")\nb.x = 1\nmodule.exports = b') + write("c.js", "var b = {}\nmodule.exports = b") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b = {}\nb.x = 1\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b = {}\nb.x = 1\n}());") + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if multiple collision", function() { - write("a.js", `var b = require("./b")\nvar c = require("./c")\nvar d = require("./d")`) - write("b.js", `var a = 1\nmodule.exports = a`) - write("c.js", `var a = 2\nmodule.exports = a`) - write("d.js", `var a = 3\nmodule.exports = a`) + write("a.js", 'var b = require("./b")\nvar c = require("./c")\nvar d = require("./d")') + write("b.js", "var a = 1\nmodule.exports = a") + write("c.js", "var a = 2\nmodule.exports = a") + write("d.js", "var a = 3\nmodule.exports = a") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar a = 1\nvar b = a\nvar a0 = 2\nvar c = a0\nvar a1 = 3\nvar d = a1\n}`) - + + o(read("out.js")).equals(";(function() {\nvar a = 1\nvar b = a\nvar a0 = 2\nvar c = a0\nvar a1 = 3\nvar d = a1\n}());") + remove("a.js") remove("b.js") remove("c.js") @@ -274,38 +276,38 @@ o.spec("bundler", function() { remove("out.js") }) o("works if included multiple times", function() { - write("a.js", `module.exports = 123`) - write("b.js", `var a = require("./a").toString()\nmodule.exports = a`) - write("c.js", `var a = require("./a").toString()\nvar b = require("./b")`) + write("a.js", "module.exports = 123") + write("b.js", 'var a = require("./a").toString()\nmodule.exports = a') + write("c.js", 'var a = require("./a").toString()\nvar b = require("./b")') bundle(ns + "c.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = 123\nvar a = _0.toString()\nvar a0 = _0.toString()\nvar b = a0\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = 123\nvar a = _0.toString()\nvar a0 = _0.toString()\nvar b = a0\n}());") + remove("a.js") remove("b.js") remove("c.js") }) o("works if included multiple times reverse", function() { - write("a.js", `module.exports = 123`) - write("b.js", `var a = require("./a").toString()\nmodule.exports = a`) - write("c.js", `var b = require("./b")\nvar a = require("./a").toString()`) + write("a.js", "module.exports = 123") + write("b.js", 'var a = require("./a").toString()\nmodule.exports = a') + write("c.js", 'var b = require("./b")\nvar a = require("./a").toString()') bundle(ns + "c.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar _0 = 123\nvar a0 = _0.toString()\nvar b = a0\nvar a = _0.toString()\n}`) - + + o(read("out.js")).equals(";(function() {\nvar _0 = 123\nvar a0 = _0.toString()\nvar b = a0\nvar a = _0.toString()\n}());") + remove("a.js") remove("b.js") remove("c.js") }) o("reuses binding if possible", function() { - write("a.js", `var b = require("./b")\nvar c = require("./c")`) - write("b.js", `var d = require("./d")\nmodule.exports = function() {return d + 1}`) - write("c.js", `var d = require("./d")\nmodule.exports = function() {return d + 2}`) - write("d.js", `module.exports = 1`) + write("a.js", 'var b = require("./b")\nvar c = require("./c")') + write("b.js", 'var d = require("./d")\nmodule.exports = function() {return d + 1}') + write("c.js", 'var d = require("./d")\nmodule.exports = function() {return d + 2}') + write("d.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar d = 1\nvar b = function() {return d + 1}\nvar c = function() {return d + 2}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar d = 1\nvar b = function() {return d + 1}\nvar c = function() {return d + 2}\n}());") + remove("a.js") remove("b.js") remove("c.js") @@ -313,71 +315,71 @@ o.spec("bundler", function() { remove("out.js") }) o("disambiguates conflicts if imported collides with itself", function() { - write("a.js", `var b = require("./b")`) - write("b.js", `var b = 1\nmodule.exports = function() {return b}`) + write("a.js", 'var b = require("./b")') + write("b.js", "var b = 1\nmodule.exports = function() {return b}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b0 = 1\nvar b = function() {return b0}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b0 = 1\nvar b = function() {return b0}\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with something else", function() { - write("a.js", `var a = 1\nvar b = require("./b")`) - write("b.js", `var a = 2\nmodule.exports = function() {return a}`) + write("a.js", 'var a = 1\nvar b = require("./b")') + write("b.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar a = 1\nvar a0 = 2\nvar b = function() {return a0}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar a = 1\nvar a0 = 2\nvar b = function() {return a0}\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with function declaration", function() { - write("a.js", `function a() {}\nvar b = require("./b")`) - write("b.js", `var a = 2\nmodule.exports = function() {return a}`) + write("a.js", 'function a() {}\nvar b = require("./b")') + write("b.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nfunction a() {}\nvar a0 = 2\nvar b = function() {return a0}\n}`) - + + o(read("out.js")).equals(";(function() {\nfunction a() {}\nvar a0 = 2\nvar b = function() {return a0}\n}());") + remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with another module's private", function() { - write("a.js", `var b = require("./b")\nvar c = require("./c")`) - write("b.js", `var a = 1\nmodule.exports = function() {return a}`) - write("c.js", `var a = 2\nmodule.exports = function() {return a}`) + write("a.js", 'var b = require("./b")\nvar c = require("./c")') + write("b.js", "var a = 1\nmodule.exports = function() {return a}") + write("c.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar a = 1\nvar b = function() {return a}\nvar a0 = 2\nvar c = function() {return a0}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar a = 1\nvar b = function() {return a}\nvar a0 = 2\nvar c = function() {return a0}\n}());") + remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("does not mess up strings", function() { - write("a.js", `var b = require("./b")`) - write("b.js", `var b = "b b b \\\" b"\nmodule.exports = function() {return b}`) + write("a.js", 'var b = require("./b")') + write("b.js", 'var b = "b b b \\" b"\nmodule.exports = function() {return b}') bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b0 = "b b b \\\" b"\nvar b = function() {return b0}\n}`) - + + o(read("out.js")).equals(';(function() {\nvar b0 = "b b b \\\" b"\nvar b = function() {return b0}\n}());') + remove("a.js") remove("b.js") remove("out.js") }) o("does not mess up properties", function() { - write("a.js", `var b = require("./b")`) - write("b.js", `var b = {b: 1}\nmodule.exports = function() {return b.b}`) + write("a.js", 'var b = require("./b")') + write("b.js", "var b = {b: 1}\nmodule.exports = function() {return b.b}") bundle(ns + "a.js", ns + "out.js") - - o(read("out.js")).equals(`new function() {\nvar b0 = {b: 1}\nvar b = function() {return b0.b}\n}`) - + + o(read("out.js")).equals(";(function() {\nvar b0 = {b: 1}\nvar b = function() {return b0.b}\n}());") + remove("a.js") remove("b.js") remove("out.js") }) -}) \ No newline at end of file +}) diff --git a/docs/CNAME b/docs/CNAME new file mode 100644 index 00000000..5c153480 --- /dev/null +++ b/docs/CNAME @@ -0,0 +1 @@ +mithril.js.org diff --git a/docs/animation.md b/docs/animation.md new file mode 100644 index 00000000..de9d2bea --- /dev/null +++ b/docs/animation.md @@ -0,0 +1,105 @@ +# Animations + +- [Technology choices](#technology-choices) +- [Animation on element creation](#animation-on-element-creation) +- [Animation on element removal](#animation-on-element-removal) +- [Performance](#performance) + +--- + +### Technology choices + +Animations are often used to make applications come alive. Nowadays, browsers have good support for CSS animations, and there are [various](https://greensock.com/gsap) [libraries](http://velocityjs.org/) that provide fast Javascript-based animations. There's also an upcoming [Web API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API) and a [polyfill](https://github.com/web-animations/web-animations-js) if you like living on the bleeding edge. + +Mithril does not provide any animation APIs per se, since these other options are more than sufficient to achieve rich, complex animations. Mithril does, however, offer hooks to make life easier in some specific cases where it's traditionally difficult to make animations work. + +--- + +### Animation on element creation + +Animating an element via CSS when the element created couldn't be simpler. Just add an animation to a CSS class normally: + +```css +.fancy {animation:fade-in 0.5s;} +@keyframes fade-in { + from {opacity:0;} + to {opacity:1;} +} +``` + +```javascript +var FancyComponent = { + view: function() { + return m(".fancy", "Hello world") + } +} + +m.mount(document.body, FancyComponent) +``` + +--- + +### Animation on element removal + +The problem with animating before removing an element is that we must wait until the animation is complete before we can actually remove the element. Fortunately, Mithril offers a [`onbeforeremove`](lifecycle-methods.md#onbeforeremove) hook that allows us to defer the removal of an element. + +Let's create an `exit` animation that fades `opacity` from 1 to 0. + +```css +.exit {animation:fade-out 0.5s;} +@keyframes fade-out { + from {opacity:1;} + to {opacity:0;} +} +``` + +Now let's create a contrived component that shows and hides the `FancyComponent` we created in the previous section: + +```javascript +var on = true + +var Toggler = { + view: function() { + return [ + m("button", {onclick: function() {on = !on}}, "Toggle"), + on ? m(FancyComponent) : null, + ] + } +} +``` + +Next, let's modify `FancyComponent` so that it fades out when removed: + +```javascript +var FancyComponent = { + onbeforeremove: function(vnode) { + vnode.dom.classList.add("exit") + return new Promise(function(resolve) { + setTimeout(resolve, 500) + }) + }, + view: function() { + return m(".fancy", "Hello world") + } +} +``` + +`vnode.dom` points to the root DOM element of the component (`
`). We use the classList API here to add an `exit` class to `
`. + +Then we return a [Promise](promise.md) that resolves after half a second. When we return a promise from `onbeforeremove`, Mithril waits until the promise is resolved and only then it removes the element. In this case, it waits half a second, giving the exit animation the exact time it needs to complete. + +We can verify that both the enter and exit animations work by mounting the `Toggler` component: + +```javascript +m.mount(document.body, Toggler) +``` + +Note that the `onbeforeremove` hook only fires on the element that loses its `parentNode` when an element gets detached from the DOM. This behavior is by design and exists to prevent a potential jarring user experience where every conceivable exit animation on the page would run on a route change. If your exit animation is not running, make sure to attach the `onbeforeremove` handler as high up the tree as it makes sense to ensure that your animation code is called. + +--- + +### Performance + +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). diff --git a/docs/autoredraw.md b/docs/autoredraw.md index 97a4575d..eb1f093f 100644 --- a/docs/autoredraw.md +++ b/docs/autoredraw.md @@ -87,9 +87,9 @@ m.route(document.body, "/", { --- -### When Mithril does not redraws +### When Mithril does not redraw -Mithril does not redraw after `setTimeout`, `setInterval`, `requestAnimationFrame` and 3rd party library event handlers (e.g. Socket.io callbacks). In those cases, you must manually call [`m.redraw()`](redraw.md). +Mithril does not redraw after `setTimeout`, `setInterval`, `requestAnimationFrame`, raw `Promise` resolutions and 3rd party library event handlers (e.g. Socket.io callbacks). In those cases, you must manually call [`m.redraw()`](redraw.md). Mithril also does not redraw after lifecycle methods. Parts of the UI may be redrawn after an `oninit` handler, but other parts of the UI may already have been redrawn when a given `oninit` handler fires. Handlers like `oncreate` and `onupdate` fire after the UI has been redrawn. diff --git a/docs/change-log.md b/docs/change-log.md index c97d7d12..eedac49b 100644 --- a/docs/change-log.md +++ b/docs/change-log.md @@ -1,6 +1,48 @@ # Change log +- [v1.1.1](#v111) +- [v1.1.0](#v110) +- [v1.0.1](#v101) - [Migrating from v0.2.x](#migrating-from-v02x) +- [Older docs](http://mithril.js.org/archive/v0.2.5/index.html) + +--- + +### v1.1.1 + +#### Bug fixes + +- 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/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)) + +### v1.1.0 + +#### News + +- support for ES6 class components +- support for closure components +- improvements in build and release automation + +#### Bug fixes + +- fix IE11 input[type] error - [#1610](https://github.com/MithrilJS/mithril.js/issues/1610) +- apply [#1609](https://github.com/MithrilJS/mithril.js/issues/1609) to unkeyed children case +- 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/MithrilJS/mithril.js/issues/1593) + +--- + +### v1.0.1 + +#### News + +- performance improvements in IE [#1598](https://github.com/MithrilJS/mithril.js/pull/1598) + +#### Bug fixes + +- 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/MithrilJS/mithril.js/issues/1609) --- @@ -16,6 +58,8 @@ If you are migrating, consider using the [mithril-codemods](https://www.npmjs.co - [Changes in redraw behaviour](#changes-in-redraw-behaviour) - [No more redraw locks](#no-more-redraw-locks) - [Cancelling redraw from event handlers](#cancelling-redraw-from-event-handlers) + - [Synchronous redraw removed](#synchronous-redraw-removed) + - [`m.startComputation`/`m.endComputation` removed](#mstartcomputationmendcomputation-removed) - [Component `controller` function](#component-controller-function) - [Component arguments](#component-arguments) - [`view()` parameters](#view-parameters) @@ -25,21 +69,21 @@ If you are migrating, consider using the [mithril-codemods](https://www.npmjs.co - [`m.route` and anchor tags](#mroute-and-anchor-tags) - [Reading/writing the current route](#readingwriting-the-current-route) - [Accessing route params](#accessing-route-params) +- [Building/Parsing query strings](#buildingparsing-query-strings) - [Preventing unmounting](#preventing-unmounting) +- [Run code on component removal](#run-code-on-component-removal) - [`m.request`](#mrequest) - [`m.deferred` removed](#mdeferred-removed) - [`m.sync` removed](#msync-removed) - [`xlink` namespace required](#xlink-namespace-required) - [Nested arrays in views](#nested-arrays-in-views) - [`vnode` equality checks](#vnode-equality-checks) -- [`m.startComputation`/`m.endComputation` removed](#mstartcomputationmendcomputation-removed) -- [Synchronous redraw removed](#synchronous-redraw-removed) --- ## `m.prop` removed -In `v1.x`, `m.prop()` is now a more powerful stream micro-library, but it's no longer part of core. +In `v1.x`, `m.prop()` is now a more powerful stream micro-library, but it's no longer part of core. You can read about how to use the optional Streams module in [the documentation](stream.md). ### `v0.2.x` @@ -110,7 +154,8 @@ m("div", { onbeforeupdate : function(vnode, old) { /*...*/ }, // Called after the node is updated onupdate : function(vnode) { /*...*/ }, - // Called before the node is removed, return a Promise that resolves when ready for the node to be removed from the DOM + // Called before the node is removed, return a Promise that resolves when + // ready for the node to be removed from the DOM onbeforeremove : function(vnode) { /*...*/ }, // Called before the node is removed, but after onbeforeremove calls done() onremove : function(vnode) { /*...*/ } @@ -133,7 +178,7 @@ In v0.2.x, Mithril allowed 'redraw locks' which temporarily prevented blocked dr `m.mount()` and `m.route()` still automatically redraw after a DOM event handler runs. Cancelling these redraws from within your event handlers is now done by setting the `redraw` property on the passed-in event object to `false`. -### `v0.2.x` +#### `v0.2.x` ```javascript m("div", { @@ -143,7 +188,7 @@ m("div", { }) ``` -### `v1.x` +#### `v1.x` ```javascript m("div", { @@ -153,6 +198,26 @@ m("div", { }) ``` +### Synchronous redraw removed + +In v0.2.x it was possible to force mithril to redraw immediately by passing a truthy value to `m.redraw()`. This behavior complicated usage of `m.redraw()` and caused some hard-to-reason about issues and has been removed. + +#### `v0.2.x` + +```javascript +m.redraw(true) // redraws immediately & synchronously +``` + +#### `v1.x` + +```javascript +m.redraw() // schedules a redraw on the next requestAnimationFrame tick +``` + +### `m.startComputation`/`m.endComputation` removed + +They are considered anti-patterns and have a number of problematic edge cases, so they no longer exist in v1.x. + --- ## Component `controller` function @@ -400,13 +465,16 @@ m.route.set("/other/route") ## Accessing route params -In `v0.2.x` reading route params was all handled through the `m.route.param()` method. In `v1.x` any route params are passed as the `attrs` object on the vnode passed as the first argument to lifecycle methods/`view`. +In `v0.2.x` reading route params was entirely handled through `m.route.param()`. This API is still available in `v1.x`, and additionally any route params are passed as properties in the `attrs` object on the vnode. ### `v0.2.x` ```javascript m.route(document.body, "/booga", { "/:attr" : { + controller : function() { + m.route.param("attr") // "booga" + }, view : function() { m.route.param("attr") // "booga" } @@ -421,9 +489,11 @@ m.route(document.body, "/booga", { "/:attr" : { oninit : function(vnode) { vnode.attrs.attr // "booga" + m.route.param("attr") // "booga" }, view : function(vnode) { vnode.attrs.attr // "booga" + m.route.param("attr") // "booga" } } }) @@ -431,6 +501,28 @@ m.route(document.body, "/booga", { --- +## Building/Parsing query strings + +`v0.2.x` used methods hanging off of `m.route`, `m.route.buildQueryString()` and `m.route.parseQueryString()`. In `v1.x` these have been broken out and attached to the root `m`. + +### `v0.2.x` + +```javascript +var qs = m.route.buildQueryString({ a : 1 }); + +var obj = m.route.parseQueryString("a=1"); +``` + +### `v1.x` + +```javascript +var qs = m.buildQueryString({ a : 1 }); + +var obj = m.parseQueryString("a=1"); +``` + +--- + ## Preventing unmounting It is no longer possible to prevent unmounting via `onunload`'s `e.preventDefault()`. Instead you should explicitly call `m.route.set` when the expected conditions are met. @@ -462,6 +554,40 @@ var Component = { --- +## Run code on component removal + +Components no longer call `this.onunload` when they are being removed. They now use the standardized lifecycle hook `onremove`. + +### `v0.2.x` + +```javascript +var Component = { + controller: function() { + this.onunload = function(e) { + // ... + } + }, + view: function() { + // ... + } +} +``` + +### `v1.x` + +```javascript +var Component = { + onremove : function() { + // ... + } + view: function() { + // ... + } +} +``` + +--- + ## m.request Promises returned by [m.request](request.md) are no longer `m.prop` getter-setters. In addition, `initialValue`, `unwrapSuccess` and `unwrapError` are no longer supported options. @@ -499,7 +625,7 @@ setTimeout(function() { }, 1000) ``` -Additionally, if the `extract` option is passed to `m.request` the return value of the provided function will be used directly to resolve its promise, and the `deserialize` callback is ignored. +Additionally, if the `extract` option is passed to `m.request` the return value of the provided function will be used directly to resolve the request promise, and the `deserialize` callback is ignored. --- @@ -526,11 +652,13 @@ greetAsync() ### `v1.x` ```javascript -var greetAsync = new Promise(function(resolve){ - setTimeout(function() { - resolve("hello") - }, 1000) -}) +var greetAsync = function() { + return new Promise(function(resolve){ + setTimeout(function() { + resolve("hello") + }, 1000) + }) +} greetAsync() .then(function(value) {return value + " world"}) @@ -602,27 +730,3 @@ Arrays now represent [fragments](fragment.md), which are structurally significan ## `vnode` equality checks If a vnode is strictly equal to the vnode occupying its place in the last draw, v1.x will skip that part of the tree without checking for mutations or triggering any lifecycle methods in the subtree. The component documentation contains [more detail on this issue](components.md#avoid-creating-component-instances-outside-views). - ---- - -## `m.startComputation`/`m.endComputation` removed - -They are considered anti-patterns and have a number of problematic edge cases, so they no longer exist in v1.x. - ---- - -## Synchronous redraw removed - -In v0.2.x it was possible to force mithril to redraw immediately by passing a truthy value to `m.redraw()`. This behavior complicated usage of `m.redraw()` and caused some hard-to-reason about issues and has been removed. - -### `v0.2.x` - -```javascript -m.redraw(true) // redraws immediately & synchronously -``` - -### `v1.x` - -```javascript -m.redraw() // schedules a redraw on the next requestAnimationFrame tick -``` diff --git a/docs/code-of-conduct.md b/docs/code-of-conduct.md new file mode 100644 index 00000000..50ebe61d --- /dev/null +++ b/docs/code-of-conduct.md @@ -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 Code of Conduct). 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/ diff --git a/docs/components.md b/docs/components.md index 7e454519..4df9dfe4 100644 --- a/docs/components.md +++ b/docs/components.md @@ -2,8 +2,9 @@ - [Structure](#structure) - [Lifecycle methods](#lifecycle-methods) +- [Syntactic variants](#syntactic-variants) - [State](#state) -- [Avoid-anti-patterns](#avoid-anti-patterns) +- [Avoid anti-patterns](#avoid-anti-patterns) ### Structure @@ -100,6 +101,107 @@ To learn more about lifecycle methods, [see the lifecycle methods page](lifecycl --- +### Syntactic variants + +#### ES6 classes + +Components can also be written using ES6 class syntax: + +```javascript +class ES6ClassComponent { + constructor(vnode) { + // vnode.state is undefined at this point + this.kind = "ES6 class" + } + view() { + return m("div", `Hello from an ${this.kind}`) + } + oncreate() { + console.log(`A ${this.kind} component was created`) + } +} +``` + +Component classes must define a `view()` method, detected via `.prototype.view`, to get the tree to render. + +They can be consumed in the same way regular components can. + +```javascript +// EXAMPLE: via m.render +m.render(document.body, m(ES6ClassComponent)) + +// EXAMPLE: via m.mount +m.mount(document.body, ES6ClassComponent) + +// EXAMPLE: via m.route +m.route(document.body, "/", { + "/": ES6ClassComponent +}) + +// EXAMPLE: component composition +class AnotherES6ClassComponent { + view() { + return m("main", [ + m(ES6ClassComponent) + ]) + } +} +``` + +#### Closure components + +Functionally minded developers may prefer using the "closure component" syntax: + +```javascript +function closureComponent(vnode) { + // vnode.state is undefined at this point + var kind = "closure component" + + return { + view: function() { + return m("div", "Hello from a " + kind) + }, + oncreate: function() { + console.log("We've created a " + kind) + } + } +} +``` + +The returned object must hold a `view` function, used to get the tree to render. + +They can be consumed in the same way regular components can. + +```javascript +// EXAMPLE: via m.render +m.render(document.body, m(closureComponent)) + +// EXAMPLE: via m.mount +m.mount(document.body, closuresComponent) + +// EXAMPLE: via m.route +m.route(document.body, "/", { + "/": closureComponent +}) + +// EXAMPLE: component composition +function anotherClosureComponent() { + return { + view: function() { + return m("main", [ + m(closureComponent) + ]) + } + } +} +``` + +#### Mixing component kinds + +Components can be freely mixed. A Class component can have closure or POJO components as children, etc... + +--- + ### State Like all virtual DOM nodes, component vnodes can have state. Component state is useful for supporting object-oriented architectures, for encapsulation and for separation of concerns. @@ -108,7 +210,7 @@ The state of a component can be accessed three ways: as a blueprint at initializ #### At initialization -Any property attached to the component object is copied for every instance of the component. This allows simple state initialization. +For POJO components, the component object is the prototype of each component instance, so any property defined on the component object will be accessible as a property of `vnode.state`. This allows simple state initialization. In the example below, `data` is a property of the `ComponentWithInitialState` component's state object. @@ -126,6 +228,10 @@ m(ComponentWithInitialState) //
Initial content
``` +For class components, the state is an instance of the class, set right after the constructor is called. + +For closure components, the state is the object returned by the closure, set right after the closure returns. The state object is mostly redundant for closure components (since variables defined in the closure scope can be used instead). + #### Via vnode.state State can also be accessed via the `vnode.state` property, which is available to all lifecycle methods as well as the `view` method of a component. @@ -174,6 +280,89 @@ Be aware that when using ES5 functions, the value of `this` in nested anonymous Although Mithril is flexible, some code patterns are discouraged: +#### Avoid fat components + +Generally speaking, a "fat" component is a component that has custom instance methods. In other words, you should avoid attaching functions to `vnode.state` or `this`. It's exceedingly rare to have logic that logically fits in a component instance method and that can't be reused by other components. It's relatively common that said logic might be needed by a different component down the road. + +It's easier to refactor code if that logic is placed in the data layer than if it's tied to a component state. + +Consider this fat component: + +```javascript +// views/Login.js +// AVOID +var Login = { + username: "", + password: "", + setUsername: function(value) { + this.username = value + }, + setPassword: function(value) { + this.password = value + }, + canSubmit: function() { + return this.username !== "" && this.password !== "" + }, + login: function() {/*...*/}, + view: function() { + return m(".login", [ + m("input[type=text]", {oninput: m.withAttr("value", this.setUsername.bind(this)), value: this.username}), + m("input[type=password]", {oninput: m.withAttr("value", this.setPassword.bind(this)), value: this.password}), + m("button", {disabled: !this.canSubmit(), onclick: this.login}, "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). + +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: + +```javascript +// models/Auth.js +// PREFER +var Auth = { + username: "", + password: "", + setUsername: function(value) { + Auth.username = value + }, + setPassword: function(value) { + Auth.password = value + }, + canSubmit: function() { + return Auth.username !== "" && Auth.password !== "" + }, + login: function() {/*...*/}, +} + +module.exports = Auth +``` + +Then, we can clean up the component: + +```javascript +// views/Login.js +// PREFER +var Auth = require("../models/Auth") + +var Login = { + view: function() { + return m(".login", [ + 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("button", {disabled: !Auth.canSubmit(), onclick: Auth.login}, "Login"), + ]) + } +} +``` + +This way, the `Auth` module is now the source of truth for auth-related state, and a `Register` component can easily access this data, and even reuse methods like `canSubmit`, if needed. In addition, if validation code is required (for example, for the email field), you only need to modify `setEmail`, and that change will do email validation for any component that modifies an email field. + +As a bonus, notice that we no longer need to use `.bind` to keep a reference to the state for the component's event handlers. + #### Avoid restrictive interfaces Try to keep component interfaces generic - using `attrs` and `children` directly - unless the component requires special logic to operate on input. @@ -206,7 +395,7 @@ var FlexibleComponent = { #### Don't manipulate `children` -However, if a component is opinionated in how it applies attributes or children, you should switch to using custom attributes. +If a component is opinionated in how it applies attributes or children, you should switch to using custom attributes. Often it's desirable to define multiple sets of children, for example, if a component has a configurable title and body. diff --git a/docs/contributing.md b/docs/contributing.md index 5b4770d3..189d0b99 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -4,7 +4,7 @@ ## 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. @@ -20,12 +20,12 @@ Ideally, the best way to report bugs is to provide a small snippet of code where To send a pull request: -- fork the repo (button at the top right in Github) -- clone the forked repo to your computer (green button in Github) +- fork the repo (button at the top right in GitHub) +- clone the forked repo to your computer (green button in GitHub) - create a feature branch (run `git checkout -b the-feature-branch-name`) - make your changes - run the tests (run `npm t`) -- submit a pull request (go to the pull requests tab in Github, click the green button and select your feature branch) +- submit a pull request (go to the pull requests tab in GitHub, click the green button and select your feature branch) diff --git a/docs/credits.md b/docs/credits.md index 2a0df4d1..7fd2a048 100644 --- a/docs/credits.md +++ b/docs/credits.md @@ -4,7 +4,7 @@ Mithril was originally written by Leo Horie, but it is where it is today thanks Special thanks to: -- Pat Cavit, who exposed most of the public API for Mithril 1.0 and brought in test coverage +- Pat Cavit, who exposed most of the public API for Mithril 1.0, brought in test coverage and automated the publishing process - Isiah Meadows, who brought in linting, modernized the test suite and has been a strong voice in design discussions - Zoli Kahan, who replaced the original Promise implementation with one that actually worked properly - Alec Embke, who single-handedly wrote the JSON-P implementation @@ -17,10 +17,10 @@ Special thanks to: - Leon Sorokin, for writing a DOM instrumentation tool that helped improve performance in Mithril 1.0 - Jordan Walke, whose work on React was prior art to the implementation of keys in Mithril - Pierre-Yves Gérardy, who consistently makes high quality contributions +- Gyandeep Singh, who contributed significant IE performance improvements Other people who also deserve recognition: - Arthur Clemens - creator of [Polythene](https://github.com/ArthurClemens/Polythene) and the [HTML-to-Mithril converter](http://arthurclemens.github.io/mithril-template-converter/index.html) - Stephan Hoyer - creator of [mithril-node-render](https://github.com/StephanHoyer/mithril-node-render), [mithril-query](https://github.com/StephanHoyer/mithril-query) and [mithril-source-hint](https://github.com/StephanHoyer/mithril-source-hint) - the countless people who have reported and fixed bugs, participated in discussions, and helped promote Mithril - diff --git a/docs/css.md b/docs/css.md new file mode 100644 index 00000000..7664d1ca --- /dev/null +++ b/docs/css.md @@ -0,0 +1,94 @@ +# CSS + +- [Vanilla CSS](#vanilla-css) +- [Tachyons](#tachyons) +- [CSS-in-JS](#css-in-js) + +--- + +### Vanilla CSS + +For various reasons, CSS has a bad reputation and often developers reach for complex tools in an attempt to make styling more manageable. In this section, we'll take a step back and cover some tips on writing plain CSS: + +- **Avoid using the space operator** - The vast majority of CSS maintainability issues are due to CSS specificity issues. The space operator defines a descendant (e.g. `.a .b`) and at the same time, it increases the level of specificity for the CSS rules that apply to that selector, sometimes overriding styles unexpectedly. + + Instead, it's preferable to share a namespace prefix in all class names that belong to a logical group of elements: + + ```css + /* AVOID */ + .chat.container {/*...*/} + .chat .item {/*...*/} + .chat .avatar {/*...*/} + .chat .text {/*...*/} + + /* PREFER */ + .chat-container {/*...*/} + .chat-item {/*...*/} + .chat-avatar {/*...*/} + .chat-text {/*...*/} + ``` + +- **Use only single-class selectors** - This convention goes hand-in-hand with the previous one: avoiding high specificity selectors such as `#foo` or `div.bar` help decrease the likelyhood of specificity conflicts. + + ```css + /* AVOID */ + #home {} + input.highlighted {} + + /* PREFER */ + .home {} + .input-highlighted {} + ``` + +- **Develop naming conventions** - You can reduce naming collisions by defining keywords for certain types of UI elements. This is particularly effective when brand names are involved: + + ```css + /* AVOID */ + .twitter {} /* icon link in footer */ + .facebook {} /* icon link in footer */ + /* later... */ + .modal.twitter {} /* tweet modal */ + .modal.facebook {} /* share modal */ + + /* PREFER */ + .link-twitter {} + .link-facebook {} + /* later... */ + .modal-twitter {} + .modal-facebook {} + ``` + +--- + +### Tachyons + +[Tachyons](https://github.com/tachyons-css/tachyons) is a CSS framework, but the concept behind it can easily be used without the library itself. + +The basic idea is that every class name must declare one and only one CSS rule. For example, `bw1` stands for `border-width:1px;`. To create a complex style, one simply combines class names representing each of the required CSS rules. For example, `.black.bg-dark-blue.br2` styles an element with blue background, black text and a 4px border-radius. + +Since each class is small and atomic, it's essentially impossible to run into CSS conflicts. + +As it turns out, the Tachyons convention fits extremely well with Mithril and JSX: + +```jsx +var Hero = ".black.bg-dark-blue.br2.pa3" + +m.mount(document.body, Hello) +// equivalent to `m(".black.bg-dark.br2.pa3", "Hello")` +``` + +--- + +### CSS in JS + +In plain CSS, all selectors live in the global scope and are prone to name collisions and specificity conflicts. CSS-in-JS aims to solve the issue of scoping in CSS, i.e. it groups related styles into non-global modules that are invisible to each other. CSS-in-JS is suitable for extremely large dev teams working on a single codebase, but it's not a good choice for most teams. + +Nowadays there are [a lot of CSS-in-JS libraries with various degrees of robustness](https://github.com/MicheleBertoli/css-in-js). + +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. `` vs `` (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). + +Another common issue is lack of support for less basic CSS features such as `@keyframes` and `@font-face`. + +If you are adamant about using a CSS-in-JS library, consider using [J2C](https://github.com/j2css/j2c), which works without configuration and implements `@keyframes` and `@font-face`. diff --git a/docs/es6.md b/docs/es6.md index 2f629223..0192a6ca 100644 --- a/docs/es6.md +++ b/docs/es6.md @@ -5,7 +5,7 @@ --- -Mithril is written in ES5, and is fully compatible with ES6 as well. +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. @@ -70,10 +70,12 @@ Create a `.babelrc` file: Next, create a file called `webpack.config.js` ```javascript +const path = require('path') + module.exports = { entry: './src/index.js', output: { - path: './bin', + path: path.resolve(__dirname, './bin'), filename: 'app.js', }, module: { diff --git a/docs/examples.md b/docs/examples.md index 140ad3f6..749900cc 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -2,10 +2,10 @@ Here are some examples of Mithril in action -- [Animation](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/animation/mosaic.html) -- [DBMonster](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/dbmonster/mithril/index.html) -- [Markdown Editor](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/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) -- [ThreadItJS](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/threaditjs/index.html) -- [TodoMVC](http://cdn.rawgit.com/lhorie/mithril.js/rewrite/examples/todomvc/index.html) +- [Animation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/animation/mosaic.html) +- [DBMonster](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html) +- [Markdown Editor](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/editor/index.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/MithrilJS/mithril.js/master/examples/threaditjs/index.html) +- [TodoMVC](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/todomvc/index.html) diff --git a/docs/favicon.ico b/docs/favicon.ico new file mode 100644 index 00000000..61807fae Binary files /dev/null and b/docs/favicon.ico differ diff --git a/docs/favicon.png b/docs/favicon.png new file mode 100644 index 00000000..50712630 Binary files /dev/null and b/docs/favicon.png differ diff --git a/docs/fragment.md b/docs/fragment.md index 018dc4ab..d3bddc7a 100644 --- a/docs/fragment.md +++ b/docs/fragment.md @@ -35,11 +35,11 @@ Generates a fragment [vnode](vnodes.md) `vnode = m.fragment(attrs, children)` -Argument | Type | Required | Description ------------ | -------------------- | -------- | --- -`attrs` | `Object` | Yes | A map of attributes -`children` | `Array` | Yes | A list of vnodes -**returns** | `Vnode` | | A fragment [vnode](vnodes.md) +Argument | Type | Required | Description +----------- | --------------------------------------------------- | -------- | --- +`attrs` | `Object` | Yes | A map of attributes +`children` | `Array` | Yes | A list of vnodes +**returns** | `Vnode` | | A fragment [vnode](vnodes.md) [How to read signatures](signatures.md) diff --git a/docs/framework-comparison.md b/docs/framework-comparison.md index 4beb034a..0969b2c9 100644 --- a/docs/framework-comparison.md +++ b/docs/framework-comparison.md @@ -12,23 +12,25 @@ If you're reading this page, you probably have used other frameworks to build ap ## Why not [insert favorite framework here]? -The reality is that most modern frameworks are fast, well-suited to build complex applications, and highly maintainable if you know how to use them effectively. There are examples of highly complex applications in the wild using just about every popular framework: Udemy uses Angular, AirBnB uses React, Gitlab uses Vue, Guild Wars 2 uses Mithril (yes, inside the game!). Clearly, these are all production-quality frameworks. +The reality is that most modern frameworks are fast, well-suited to build complex applications, and maintainable if you know how to use them effectively. There are examples of highly complex applications in the wild using just about every popular framework: Udemy uses Angular, AirBnB uses React, Gitlab uses Vue, Guild Wars 2 uses Mithril (yes, inside the game!). Clearly, these are all production-quality frameworks. As a rule of thumb, if your team is already heavily invested in another framework/library/stack, it makes more sense to stick with it, unless your team agrees that there's a very strong reason to justify a costly rewrite. -If you're starting something new, do consider giving Mithril a try, if nothing else, to see how much value Mithril adopters have been getting out of 8kb (gzipped) of code. +However, if you're starting something new, do consider giving Mithril a try, if nothing else, to see how much value Mithril adopters have been getting out of 8kb (gzipped) of code. Mithril is used by many well-known companies (e.g. Vimeo, Nike, Fitbit), and it powers large open-sourced platforms too (e.g. Lichess, Flarum). --- ## Why use Mithril? -In one sentence: because **Mithril is pragmatic**. If you don't believe me, take 10 minutes to go over the [guide](introduction.md) to see how much it accomplishes, compared with official guides for other frameworks. +In one sentence: because **Mithril is pragmatic**. This [10 minute guide](index.md) is a good example: that's how long it takes to learn components, XHR and routing - and that's just about the right amount of knowledge needed to build useful applications. -Mithril is all about getting stuff done. It comes out of the box with a compact set of tools that you'll likely need for building Single Page Applications, and no distractions. The Mithril API is small and focused, and it's designed to leverage previous knowledge - e.g. view language is Javascript, HTML attributes have no syntax caveats, Promises are Promises, hyperscript selectors mirror CSS and is JSX-compatible, `m.request` option names mirror [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) - all of this so you can get up to speed fast. +Mithril is all about getting meaningful work done efficiently. Doing file uploads? [The docs show you how](request.md#file-uploads). Authentication? [Documented too](route.md#authentication). Exit animations? [You got it](animation.md). No extra libraries, no magic. --- -## React +## Comparisons + +### React React is a view library maintained by Facebook. @@ -38,11 +40,11 @@ React and Mithril share a lot of similarities. If you already learned React, you - They both organize views via components - They both use Javascript as a flow control mechanism within views -The most obvious difference between React and Mithril is in their scope. React is a view library, so a typical React-based application relies on third-party libraries for routing, XHR and state management. Using a library oriented approach allows developers to customize their stack to precisely match their needs. The not-so-nice way of saying that is that React-based architectures can vary wildly from project to project. +The most obvious difference between React and Mithril is in their scope. React is a view library, so a typical React-based application relies on third-party libraries for routing, XHR and state management. Using a library oriented approach allows developers to customize their stack to precisely match their needs. The not-so-nice way of saying that is that React-based architectures can vary wildly from project to project, and that those projects are that much more likely to cross the 1MB size line. Mithril has built-in modules for common necessities such as routing and XHR, and the [guide](simple-application.md) demonstrates idiomatic usage. This approach is preferable for teams that value consistency and ease of onboarding. -### Performance +#### Performance Both React and Mithril care strongly about rendering performance, but go about it in different ways. In the past React had two DOM rendering implementations (one using the DOM API, and one using `innerHTML`). Its upcoming fiber architecture introduces scheduling and prioritization of units of work. React also has a sophisticated build system that disables various checks and error messages for production deployments, and various browser-specific optimizations. In addition, there are also several performance-oriented libraries that leverage React's `shouldComponentUpdate` hook and immutable data structure libraries' fast object equality checking properties to reduce virtual DOM reconciliation times. Generally speaking, React's approach to performance is to engineer relatively complex solutions. @@ -50,21 +52,21 @@ Mithril follows the less-is-more school of thought. It has a substantially small Here's a comparison of library load times, i.e. the time it takes to parse and run the Javascript code for each framework, by adding a `console.time()` call on the first line and a `console.timeEnd()` call on the last of a script that is composed solely of framework code. For your reading convenience, here are best-of-20 results with logging code manually added to bundled scripts, running from the filesystem, in Chrome on a modest 2010 PC desktop: -React v15.4.1 | Mithril 1.0 -------------- | ------- -55.8 ms | 4.5 ms +React | Mithril +------- | ------- +55.8 ms | 4.5 ms Library load times matter in applications that don't stay open for long periods of time (for example, anything in mobile) and cannot be improved via caching or other optimization techniques. -Since this is a micro-benchmark, you are encourage to replicate these tests yourself since hardware can heavily affect the numbers. Note that bundler frameworks like Webpack can move dependencies out before the timer calls to emulate static module resolution, so you should either copy the code from the compiled CDN files or open the output file from the bundler library, and manually add the high resolution timer calls `console.time` and `console.timeEnd` to the bundled script. Avoid using `new Date` and `performance.now`, as those mechanisms are not as statistically accurate. +Since this is a micro-benchmark, you are encouraged to replicate these tests yourself since hardware can heavily affect the numbers. Note that bundler frameworks like Webpack can move dependencies out before the timer calls to emulate static module resolution, so you should either copy the code from the compiled CDN files or open the output file from the bundler library, and manually add the high resolution timer calls `console.time` and `console.timeEnd` to the bundled script. Avoid using `new Date` and `performance.now`, as those mechanisms are not as statistically accurate. For your reading convenience, here's a version of that benchmark adapted to use CDNs on the web: the [benchmark for React is here](https://jsfiddle.net/0ovkv64u/), and the [benchmark for Mithril is here](https://jsfiddle.net/o7hxooqL/). Note that we're benchmarking all of Mithril rather than benchmarking only the rendering module (which would be equivalent in scope to React). Also note that this CDN-driven setup incurs some overheads due to fetching resources from disk cache (~2ms per resource). Due to those reasons, the numbers here are not entirely accurate, but they should be sufficient to observe that Mithril's initialization speed is noticeably better than React. Here's a slightly more meaningful benchmark: measuring the scripting time for creating 10,000 divs (and 10,000 text nodes). Again, here's the benchmark code for [React](https://jsfiddle.net/bfoeay4f/) and [Mithril](https://jsfiddle.net/fft0ht7n/). Their best results are shown below: -React v15.4.1 | Mithril 1.0 -------------- | ------- -99.7 ms | 42.8 ms +React | Mithril +------- | ------- +99.7 ms | 42.8 ms What these numbers show is that not only does Mithril initializes significantly faster, it can process upwards of 20,000 virtual DOM nodes before React is ready to use. @@ -72,37 +74,49 @@ 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. -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 v15.4.1 | Mithril 1.0 -------------- | ------- -12.1 ms | 6.4 ms +React | Mithril +------- | ------- +12.1 ms | 6.4 ms ##### Development performance Another thing to keep in mind is that because React adds extra checks and helpful error messages in development mode, it is slower in development than the production version used for the benchmarks above. To illustrate, [here's the 10,000 node benchmark from above using the development version of React](https://jsfiddle.net/r1jfckrd/). -### Complexity +##### Drop-in replacements + +There are [several](https://preactjs.com/) [projects](https://github.com/Lucifier129/react-lite) [that](https://infernojs.org/) [claim](https://github.com/alibaba/rax) API parity with React (some via compatibility layer libraries), but they are not fully compatible (e.g. PropType support is usually stubbed out, synthetic events are sometimes not supported, and some APIs have different semantics). Note that these libraries typically also include features of their own that are not part of the official React API, which may become problematic down the road if one decides to switch back to React Fiber. + +Claims about small download size (compared to React) are accurate, but most of these libraries are slightly larger than Mithril's renderer module. Preact is the only exception. + +Be wary of aggressive performance claims, as benchmarks used by some of these projects are known to be out-of-date and flawed (in the sense that they can be - and are - exploited). Boris Kaul (author of some of the benchmarks) has [written in detail about how benchmarks are gamed](https://medium.com/@localvoid/how-to-win-in-web-framework-benchmarks-8bc31af76ce7). Another thing to keep in mind is that some benchmarks aggressively use advanced optimization features and thus demonstrate *potential* performance, i.e. performance that is possible given some caveats, but realistically unlikely unless you actively spend the time to go over your entire codebase identifying optimization candidates and evaluating the regression risks brought by the optimization caveats. + +In the spirit of demonstrating *typical* performance characteristics, the benchmarks presented in this comparison page are implemented in an apples-to-apples, naive, idiomatic way (i.e. the way you would normally write 99% of your code) and do not employ tricks or advanced optimizations to make one or other framework look artificially better. You are encouraged to contribute a PR if you feel any DbMonster implementation here could be written more idiomatically. + +#### Complexity Both React and Mithril have relatively small API surfaces compared to other frameworks, which help ease learning curve. However, whereas idiomatic Mithril can be written without loss of readability using plain ES5 and no other dependencies, idiomatic React relies heavily on complex tooling (e.g. Babel, JSX plugin, etc), and this level of complexity frequently extends to popular parts of its ecosystem, be it in the form of syntax extensions (e.g. non-standard object spread syntax in Redux), architectures (e.g. ones using immutable data libraries), or bells and whistles (e.g. hot module reloading). -### Learning curve +While complex toolchains are also possible with Mithril and other frameworks alike, it's *strongly* recommended that you follow the [KISS](https://en.wikipedia.org/wiki/KISS_principle) and [YAGNI](https://en.wikipedia.org/wiki/You_aren't_gonna_need_it) principles when using Mithril. + +#### Learning curve Both React and Mithril have relatively small learning curves. React's learning curve mostly involves understanding components and their lifecycle. The learning curve for Mithril components is nearly identical. There are obviously more APIs to learn in Mithril, since Mithril also includes routing and XHR, but the learning curve would be fairly similar to learning React, React Router and a XHR library like superagent or axios. Idiomatic React requires working knowledge of JSX and its caveats, and therefore there's also a small learning curve related to Babel. -### Documentation +#### Documentation -React documentation is clear and well written, and includes a good API reference, tutorials for getting started, as well as pages covering various advanced concepts. +React documentation is clear and well written, and includes a good API reference, tutorials for getting started, as well as pages covering various advanced concepts. Unfortunately, since React is limited to being only a view library, its documentation does not explore how to use React idiomatically in the context of a real-life application. As a result, there are many popular state management libraries and thus architectures using React can differ drastically from company to company (or even between projects). -Mithril documentation also includes [introductory](introduction.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. +Mithril documentation also includes [introductory](index.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. -Unfortunately, since React is limited to being only a view library, its documentation does not explore how to use React in the context of a real-life application. As a result, there are many popular state management libraries and as a result, architectures using React can differ drastically from company to company (or even between projects). +Mithril documentation also demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. --- -## Angular +### Angular Angular is a web application framework maintained by Google. @@ -113,7 +127,7 @@ Angular and Mithril are fairly different, but they share a few similarities: The most obvious difference between Angular and Mithril is in their complexity. This can be seen most easily in how views are implemented. Mithril views are plain Javascript, and flow control is done with Javascript built-in mechanisms such as ternary operators or `Array.prototype.map`. Angular, on the other hand, implements a directive system to extend HTML views so that it's possible to evaluate Javascript-like expressions within HTML attributes and interpolations. Angular actually ships with a parser and a compiler written in Javascript to achieve that. If that doesn't seem complex enough, there's actually two compilation modes (a default mode that generates Javascript functions dynamically for performance, and [a slower mode](https://docs.angularjs.org/api/ng/directive/ngCsp) for dealing with Content Security Policy restrictions). -### Performance +#### Performance Angular has made a lot of progress in terms of performance over the years. Angular 1 used a mechanism known as dirty checking which tended to get slow due to the need to constantly diff large `$scope` structures. Angular 2 uses a template change detection mechanism that is much more performant. However, even despite Angular's improvements, Mithril is often faster than Angular, due to the ease of auditing that Mithril's small codebase size affords. @@ -125,33 +139,36 @@ Also, remember that frameworks like Angular and Mithril are designed for non-tri ##### 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 ------- | ------- 11.5 ms | 6.4 ms -### Complexity +#### Complexity Angular is superior to Mithril in the amount of tools it offers (in the form of various directives and services), but it is also far more complex. Compare [Angular's API surface](https://angular.io/docs/ts/latest/api/) with [Mithril's](api.md). You can make your own judgment on which API is more self-descriptive and more relevant to your needs. Angular 2 has a lot more concepts to understand: on the language level, Typescript is the recommended language, and on top of that there's also Angular-specific template syntax such as bindings, pipes, "safe navigator operator". You also need to learn about architectural concepts such as modules, components, services, directives, etc, and where it's appropriate to use what. -### Learning curve +#### Learning curve If we compare apples to apples, Angular 2 and Mithril have similar learning curves: in both, components are a central aspect of architecture, and both have reasonable routing and XHR tools. With that being said, Angular has a lot more concepts to learn than Mithril. It offers Angular-specific APIs for many things that often can be trivially implemented (e.g. pluralization is essentially a switch statement, "required" validation is simply an equality check, etc). Angular templates also have several layers of abstractions to emulate what Javascript does natively in Mithril - Angular's `ng-if`/`ngIf` is a *directive*, which uses a custom *parser* and *compiler* to evaluate an expression string and emulate lexical scoping... and so on. Mithril tends to be a lot more transparent, and therefore easier to reason about. -### Documentation +#### Documentation Angular 2 documentation provides an extensive introductory tutorial, and another tutorial that implements an application. It also has various guides for advanced concepts, a cheatsheet and a style guide. Unfortunately, at the moment, the API reference leaves much to be desired. Several APIs are either undocumented or provide no context for what the API might be used for. -Mithril documentation includes [introductory](introduction.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. +Mithril documentation includes [introductory](index.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. + +Mithril documentation also demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. + --- -## Vue +### Vue Vue is a view library similar to Angular. @@ -160,11 +177,11 @@ Vue and Mithril have a lot of differences but they also share some similarities: - They both use virtual DOM and lifecycle methods - Both organize views via components -Vue also provides tools for routing and state management as separate modules. Vue looks very similar to Angular and provides a similar directive system, HTML-based templates and logic flow directives. It differs from Angular in that it implements a monkeypatching reactive system that overwrites native methods in a component's data (whereas Angular 1 uses dirty checking and digest/apply cycles to achieve similar results). Similar to Angular 2, Vue compiles HTML templates into functions, but the compiled functions look more like Mithril or React views, rather than Angular's compiled rendering functions. +Vue 2 uses a fork of Snabbdom as its virtual DOM system. In addition, Vue also provides tools for routing and state management as separate modules. Vue looks very similar to Angular and provides a similar directive system, HTML-based templates and logic flow directives. It differs from Angular in that it implements a monkeypatching reactive system that overwrites native methods in a component's data tree (whereas Angular 1 uses dirty checking and digest/apply cycles to achieve similar results). Similar to Angular 2, Vue compiles HTML templates into functions, but the compiled functions look more like Mithril or React views, rather than Angular's compiled rendering functions. -Vue is significantly smaller than Angular when comparing apples to apples, but not as small as Mithril (Vue core is around 23kb gzipped, whereas the equivalent rendering module in Mithril is around 4kb gzipped). Both have similar performance characteristics, but benchmarks often suggest Mithril is slightly faster. +Vue is significantly smaller than Angular when comparing apples to apples, but not as small as Mithril (Vue core is around 23kb gzipped, whereas the equivalent rendering module in Mithril is around 4kb gzipped). Both have similar performance characteristics, but benchmarks usually suggest Mithril is slightly faster. -### Performance +#### Performance Here's a comparison of library load times, i.e. the time it takes to parse and run the Javascript code for each framework, by adding a `console.time()` call on the first line and a `console.timeEnd()` call on the last of a script that is composed solely of framework code. For your reading convenience, here are best-of-20 results with logging code manually added to bundled scripts, running from the filesystem, in Chrome on a modest 2010 PC desktop: @@ -176,24 +193,24 @@ Library load times matter in applications that don't stay open for long periods ##### 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/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 ------ | ------- 9.8 ms | 6.4 ms -### Complexity +#### Complexity -Vue is heavily inspired by Angular and has many things that Angular does (e.g. directives, filters, `v-cloak`), but also has things inspired by React (e.g. components). As of Vue 2.0, it's also possible to write templates using hyperscript/JSX syntax (in addition to single-file components and the various webpack-based language transpilation plugins). Vue provides both bi-directional data binding and an optional Redux-like state management library, and unlike Angular, it provides no style guide. The many-ways-of-doing-one-thing approach can cause architectural fragmentation in long-lived projects. +Vue is heavily inspired by Angular and has many things that Angular does (e.g. directives, filters, bi-directional bindings, `v-cloak`), but also has things inspired by React (e.g. components). As of Vue 2.0, it's also possible to write templates using hyperscript/JSX syntax (in addition to single-file components and the various webpack-based language transpilation plugins). Vue provides both bi-directional data binding and an optional Redux-like state management library, but unlike Angular, it provides no style guide. The many-ways-of-doing-one-thing approach can cause architectural fragmentation in long-lived projects. -Mithril has far less concepts and typically organizes applications in terms of components and a data layer. There are no different ways of defining components, and thus there's no need to install different sets of tools to make different flavors work. +Mithril has far less concepts and typically organizes applications in terms of components and a data layer. All component creation styles in Mithril output the same vnode structure using native Javascript features only. The direct consequence of leaning on the language is less tooling and a simpler project setup. -### Documentation +#### Documentation Both Vue and Mithril have good documentation. Both include a good API reference with examples, tutorials for getting started, as well as pages covering various advanced concepts. -However, due to Vue's many-ways-to-do-one-thing approach, some things are not adequately documented. For example, there's no documentation on hyperscript syntax or usage. +However, due to Vue's many-ways-to-do-one-thing approach, some things may not be adequately documented. For example, there's no documentation on hyperscript syntax or usage. -Mithril documentation typically errs on the side of being overly thorough if a topic involves things outside of the scope of Mithril. For example, when a topic involves a 3rd party library, Mithril documentation walks through the installation process for the 3rd party library. +Mithril documentation typically errs on the side of being overly thorough if a topic involves things outside of the scope of Mithril. For example, when a topic involves a 3rd party library, Mithril documentation walks through the installation process for the 3rd party library. Mithril documentation also often demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. -Mithril's tutorials also cover a lot more ground than Vue's: the [Vue tutorial](https://vuejs.org/v2/guide/#Getting-Started) finishes with a static list of foodstuff. [Mithril's 10 minute guide](introduction.md) covers the majority of its API and goes over key aspects of real-life applications, such as fetching data from a server and routing (and there's a [longer, more thorough tutorial](simple-application.md) if that's not enough). +Mithril's tutorials also cover a lot more ground than Vue's: the [Vue tutorial](https://vuejs.org/v2/guide/#Getting-Started) finishes with a static list of foodstuff. [Mithril's 10 minute guide](index.md) covers the majority of its API and goes over key aspects of real-life applications, such as fetching data from a server and routing (and there's a [longer, more thorough tutorial](simple-application.md) if that's not enough). diff --git a/docs/generate.js b/docs/generate.js index a9d0f759..ef3ce424 100644 --- a/docs/generate.js +++ b/docs/generate.js @@ -1,15 +1,19 @@ +"use strict" + var fs = require("fs") var path = require("path") var marked = require("marked") var layout = fs.readFileSync("./docs/layout.html", "utf-8") var version = JSON.parse(fs.readFileSync("./package.json", "utf-8")).version -try {fs.mkdirSync("docs/archive/")} catch (e) {} -try {fs.mkdirSync("docs/archive/" + version)} catch (e) {} -try {fs.mkdirSync("docs/archive/" + version + "/lib")} catch (e) {} -try {fs.mkdirSync("docs/archive/" + version + "/lib/prism")} catch (e) {} +try {fs.mkdirSync("./dist")} catch (e) {/* ignore */} +try {fs.mkdirSync("./dist/archive")} catch (e) {/* ignore */} +try {fs.mkdirSync("./dist/archive/v" + version)} catch (e) {/* ignore */} -var guides = fs.readFileSync("docs/guides.md", "utf-8") -var methods = fs.readFileSync("docs/methods.md", "utf-8") +var guides = fs.readFileSync("docs/nav-guides.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") @@ -19,16 +23,16 @@ function generate(pathname) { generate(pathname + "/" + filename) }) } - else if (!pathname.match(/tutorials|archive/)) { + else if (!pathname.match(/tutorials|archive|nav-/)) { if (pathname.match(/\.md$/)) { var outputFilename = pathname.replace(/\.md$/, ".html") var markdown = fs.readFileSync(pathname, "utf-8") + var anchors = {} var fixed = markdown - .replace(/(`[^`]+?)<(.*`)/gim, "$1<$2") // fix generic syntax .replace(/`((?:\S| -> |, )+)(\|)(\S+)`/gim, function(match, a, b, c) { // fix pipes in code tags return "" + (a + b + c).replace(/\|/g, "|") + "" }) - .replace(/(^# .+?(?:\r?\n){2,}?)(?:(-(?:.|\r|\n)+?)((?:\r?\n){2,})|)/m, function(match, title, nav, space) { // inject menu + .replace(/(^# .+?(?:\r?\n){2,}?)(?:(-(?:.|\r|\n)+?)((?:\r?\n){2,})|)/m, function(match, title, nav) { // inject menu var file = path.basename(pathname) var link = new RegExp("([ \t]*)(- )(\\[.+?\\]\\(" + file + "\\))") var replace = function(match, space, li, link) { @@ -40,17 +44,31 @@ function generate(pathname) { .replace(/(\]\([^\)]+)(\.md)/gim, function(match, path, extension) { return path + (path.match(/http/) ? extension : ".html") }) // fix links + var markedHtml = marked(fixed) + .replace(/(\W)Array<([^/<]+?)>/gim, "$1Array<$2>") // Fix type signatures containing Array<...> + var title = fixed.match(/^#([^\n\r]+)/i) || [] var html = layout - .replace(/\[version\]/, version) // update version - .replace(/\[body\]/, marked(fixed)) - .replace(/
([^<]+?)<\/h5>/gim, function(match, id, text) { // fix anchors - return "
" + text + "
" + .replace(/Mithril\.js<\/title>/, "<title>" + title[1] + " - Mithril.js") + .replace(/\[version\]/g, version) // update version + .replace(/\[body\]/, markedHtml) + .replace(/(.+?)<\/h.>/gim, function(match, n, id, text) { // fix anchors + var anchor = text.toLowerCase().replace(/<(\/?)code>/g, "").replace(/.+?<\/a>/g, "").replace(/\.|\[|\]|"|\/|\(|\)/g, "").replace(/\s/g, "-"); + + if(anchor in anchors) { + anchor += ++anchors[anchor] + } else { + anchors[anchor] = 0; + } + + return `${text}`; }) - fs.writeFileSync("docs/archive/" + version + "/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") + fs.writeFileSync("./dist/archive/v" + version + "/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") + fs.writeFileSync("./dist/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") } - else { - fs.writeFileSync("docs/archive/" + version + "/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, "utf-8"), "utf-8") + else if (!pathname.match(/lint|generate/)) { + var encoding = (/\.(ico|png)$/i).test(path.extname(pathname)) ? "binary" : "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) } } } - diff --git a/docs/hyperscript.md b/docs/hyperscript.md index 6108f2d5..8ebe297b 100644 --- a/docs/hyperscript.md +++ b/docs/hyperscript.md @@ -170,7 +170,7 @@ Mithril supports both strings and objects as valid `style` values. In other word ```javascript m("div", {style: "background:red;"}) m("div", {style: {background: "red"}}) -m("div[style=background:red") +m("div[style=background:red]") ``` Using a string as a `style` would overwrite all inline styles in the element if it is redrawn, and not only CSS rules whose values have changed. @@ -181,7 +181,7 @@ Mithril does not attempt to add units to number values. ### Events -Mithril supports event handler binding for all DOM events, including events whose specs do not define an `on` property, such as `touchstart` +Mithril supports event handler binding for all DOM events, including events whose specs do not define an `on${event}` property, such as `touchstart` ```javascript function doSomething(e) { diff --git a/docs/introduction.md b/docs/index.md similarity index 53% rename from docs/introduction.md rename to docs/index.md index 671541e5..22bb9021 100644 --- a/docs/introduction.md +++ b/docs/index.md @@ -12,36 +12,71 @@ ### What is Mithril? -Mithril is a client-side Javascript framework for building Single Page Applications. +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. +
+
+
Download size
+ Mithril (8kb) +
+ Vue + Vue-Router + Vuex + fetch (40kb) +
+ React + React-Router + Redux + fetch (64kb) +
+ Angular (135kb) +
+
+
+
Performance
+ Mithril (6.4ms) +
+ Vue (9.8ms) +
+ React (12.1ms) +
+ Angular (11.5ms) +
+
+
+ +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](framework-comparison.md) page. ---- +Mithril supports browsers all the way back to IE9, no polyfills required. -Note: This introduction assumes you have basic level of Javacript knowledge. If you don't, there are many great resources to learn. [Speaking Javascript](http://speakingjs.com/es5/index.html) is a good e-book for absolute beginners. If you're already familiar with other programming languages, the [Eloquent Javascript](http://eloquentjavascript.net/) e-book might be more suitable for you. [Codecademy](https://www.codecademy.com/learn/javascript) is another good resource that emphasizes learning via interactivity. +--- ### 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. +An easy 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 - - - + + // your code goes here! + + ``` +To make things simpler you can fork this pen which already has the latest version of mithril loaded. + +

See the Pen Mithril Scaffold by Pat Cavit (@tivac) on CodePen.

+ + +Mithril is also loaded onto this page already, so you can start poking at the `m` object in the developer console right away if you'd like! + --- ### Hello world -Let's start as small as well 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) +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 @@ -57,6 +92,11 @@ 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. +#### Live Example + +

See the Pen Mithril Hello World by Pat Cavit (@tivac) on CodePen.

+ + --- ### DOM elements @@ -67,7 +107,7 @@ Let's wrap our text in an `

` tag. m.render(root, m("h1", "My first app")) ``` -The `m()` function can be used to describe any HTML structure you want. So if you to add a class to the `

`: +The `m()` function can be used to describe any HTML structure you want. So if you need to add a class to the `

`: ```javascript m("h1", {class: "title"}, "My first app") @@ -91,9 +131,14 @@ m("main", [ ]) ``` +#### Live Example + +

See the Pen Simple Mithril Example by Pat Cavit (@tivac) on CodePen.

+ + Note: If you prefer `` syntax, [it's possible to use it via a Babel plugin](jsx.md). -```markup +```jsx // HTML syntax via Babel's JSX plugin

My first app

@@ -142,7 +187,8 @@ var Hello = { view: function() { return m("main", [ m("h1", {class: "title"}, "My first app"), - m("button", {onclick: function() {count++}}, count + " clicks"), // changed this line + // changed the next line + m("button", {onclick: function() {count++}}, count + " clicks"), ]) } } @@ -156,6 +202,11 @@ You can now update the label of the button by clicking the button. Since we used 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. +#### Live Example + +

See the Pen Mithril Component Example by Pat Cavit (@tivac) on CodePen.

+ + --- ### Routing @@ -189,6 +240,11 @@ The `"/splash"` right after `root` means that's the default route, i.e. if the h 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. +#### Live Example + +

See the Pen Mithril Routing Example by Pat Cavit (@tivac) on CodePen.

+ + --- ### XHR @@ -197,16 +253,16 @@ 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 `useCredentials` means to enable cookies (a requirement for the REM API to work) +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: "http://rem-rest-api.herokuapp.com/api/tutorial/1", + url: "//rem-rest-api.herokuapp.com/api/tutorial/1", data: {count: count + 1}, - useCredentials: true, + withCredentials: true, }) .then(function(data) { count = parseInt(data.count) @@ -231,6 +287,11 @@ var Hello = { Clicking the button should now update the count. +#### Live Example + +

See the Pen Mithril XHR Example by Pat Cavit (@tivac) on CodePen.

+ + --- 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. diff --git a/docs/installation.md b/docs/installation.md index ddc85853..c4604ad5 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -8,7 +8,7 @@ If you're new to Javascript or just want a very simple setup to get your feet wet, you can get Mithril from a [CDN](https://en.wikipedia.org/wiki/Content_delivery_network): ```markup - + ``` --- @@ -19,7 +19,7 @@ If you're new to Javascript or just want a very simple setup to get your feet we ```bash # 1) install -npm install mithril@rewrite --save +npm install mithril --save npm install webpack --save @@ -55,7 +55,7 @@ npm init --yes Then, to install Mithril, run: ```bash -npm install mithril@rewrite --save +npm install mithril --save ``` This will create a folder called `node_modules`, and a `mithril` folder inside of it. It will also add an entry under `dependencies` in the `package.json` file @@ -178,7 +178,7 @@ Live reload is a feature where code changes automatically trigger the page to re ```bash # 1) install -npm install mithril@rewrite --save +npm install mithril --save npm install budo -g # 2) add this line into the scripts section in package.json @@ -219,7 +219,7 @@ If you don't have the ability to run a bundler script due to company security po Hello world - + diff --git a/docs/jsonp.md b/docs/jsonp.md index 1e2300f7..0a5997fd 100644 --- a/docs/jsonp.md +++ b/docs/jsonp.md @@ -36,6 +36,7 @@ Argument | Type | Required | Descript `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.callbackName` | `String` | No | The name of the function that will be called as the callback. Defaults to a randomized string (e.g. `_mithril_6888197422121285_0({a: 1})` `options.callbackKey` | `String` | No | The name of the querystring parameter name that specifies the callback name. Defaults to `callback` (e.g. `/someapi?callback=_mithril_6888197422121285_0`) +`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 `type` method [How to read signatures](signatures.md) diff --git a/docs/jsx.md b/docs/jsx.md index b439c867..0b8cd7f9 100644 --- a/docs/jsx.md +++ b/docs/jsx.md @@ -10,7 +10,7 @@ ### Description -JSX is a syntax extension that enables you to write HTML tags interspersed with Javascript. +JSX is a syntax extension that enables you to write HTML tags interspersed with Javascript. It's not part of any Javascript standards and it's not required for building applications, but it may be more pleasing to use depending on your team's preferences. ```jsx var MyComponent = { @@ -39,14 +39,14 @@ When using JSX, it's possible to interpolate Javascript expressions within JSX t var greeting = "Hello" var url = "http://google.com" var link = {greeting + "!"} -// yields Hello +// yields Hello! ``` Components can be used by using a convention of uppercasing the first letter of the component name: ```jsx -m.mount(document.body, ) -// equivalent to m.mount(document.body, m(MyComponent)) +m.render(document.body, ) +// equivalent to m.render(document.body, m(MyComponent)) ``` --- @@ -112,10 +112,12 @@ Create a `.babelrc` file: Next, create a file called `webpack.config.js` ```javascript +const path = require('path') + module.exports = { entry: './src/index.js', output: { - path: './bin', + path: path.resolve(__dirname, './bin'), filename: 'app.js', }, module: { @@ -186,8 +188,8 @@ 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: -1 - it does not require repeating the tag name in closing tags (e.g. `m("div")` vs `
`) -2 - static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `
` +- it does not require repeating the tag name in closing tags (e.g. `m("div")` vs `
`) +- static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `
` In addition, since hyperscript is plain Javascript, it's often more natural to indent than JSX: diff --git a/docs/keys.md b/docs/keys.md index 9fd87814..0ad0b0c5 100644 --- a/docs/keys.md +++ b/docs/keys.md @@ -3,7 +3,6 @@ - [What are keys](#what-are-keys) - [How to use](#how-to-use) - [Debugging key related issues](#debugging-key-related-issues) -- [Avoid anti-patterns](#avoid-anti-patterns) --- @@ -97,19 +96,21 @@ users.map(function(u) { #### Avoid hiding keys in component root elements -If you refactor the code and put the button inside a component, the key must be moved out of the component and placed back where the component took the place of the button. +If you refactor the code and make a user component, the key must be moved out of the component and put on the component itself, since it is now the immediate child of the array. ```javascript // AVOID -var Button = { +var User = { view: function(vnode) { - return m("button", {key: vnode.attrs.id}, u.name) + return m("div", { key: vnode.attrs.user.id }, [ + m(Button, vnode.attrs.user.name) + ]) } } + +// PREFER users.map(function(u) { - return m("div", [ - m(Button, {id: u.id}, u.name) // key should be here, not in component - ]) + return m(User, { key: u.id, user: u }) // key should be here, not in component }) ``` @@ -150,3 +151,56 @@ var things = [ ] ``` +#### Avoid mixing keyed and non-keyed vnodes in the same array + +An array of vnodes must have only keyed vnodes or non-keyed vnodes, but not both. If you need to mix them, create a nested array. + +```javascript +// AVOID +m("div", [ + m("div", "a"), + m("div", {key: 1}, "b"), +]) + +// PREFER +m("div", [ + m("div", {key: 0}, "a"), + m("div", {key: 1}, "b"), +]) + + +// PREFER +m("div", [ + m("div", "a"), + [ + m("div", {key: 1}, "b"), + ] +]) +``` + +#### 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: + +```javascript +// Data model +var users = [ + {id: 1, name: "John", key: 'a'}, + {id: 2, name: "Mary", key: 'b'}, +] + +// Later on... +users[0].key = 'c' + +// AVOID +users.map(function(user){ + // The component for John will be destroyed and recreated + return m(UserComponent, user) +}) + +// PREFER +users.map(function(user){ + // Key is specifically extracted: data model is given its own property + return m(UserComponent, {key: user.id, model: user}) +}) +``` diff --git a/docs/layout.html b/docs/layout.html index b6e1c504..110a890b 100644 --- a/docs/layout.html +++ b/docs/layout.html @@ -2,19 +2,21 @@ Mithril.js - - + + +
-

Mithril [version]

+ ≡ +

Mithril [version]

@@ -25,6 +27,16 @@ License: MIT. © Leo Horie.
- + + + + - diff --git a/docs/lib/prism/prism.css b/docs/lib/prism/prism.css deleted file mode 100644 index 0c252867..00000000 --- a/docs/lib/prism/prism.css +++ /dev/null @@ -1,6 +0,0 @@ -.token.comment,.token.prolog,.token.doctype,.token.cdata {color:#888;} -.token.property,.token.tag,.token.boolean,.token.number,.token.constant,.token.symbol {color:#905;} -.token.selector,.token.attr-name,.token.string,.token.builtin {color:#690;} -.token.atrule,.token.attr-value,.token.punctuation,.token.keyword {color:#1e5799;} -.token.regex,.token.important {color:#e90;} - diff --git a/docs/lib/prism/prism.js b/docs/lib/prism/prism.js deleted file mode 100644 index b7f84870..00000000 --- a/docs/lib/prism/prism.js +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Prism: Lightweight, robust, elegant syntax highlighting - * MIT license http://www.opensource.org/licenses/mit-license.php/ - * @author Lea Verou http://lea.verou.me - */(function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.util.clone(e[i]));return r;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var r=t.util.clone(t.languages[e]);for(var i in n)r[i]=n[i];return r},insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);t.util.type(e)==="Object"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent;if(!f)return;f=f.replace(/&/g,"&").replace(/e.length)break e;if(p instanceof i)continue;a.lastIndex=0;var d=a.exec(p);if(d){l&&(c=d[1].length);var v=d.index-1+c,d=d[0].slice(c),m=d.length,g=v+m,y=p.slice(0,v+1),b=p.slice(g+1),w=[h,1];y&&w.push(y);var E=new i(u,f?t.tokenize(d,f):d);w.push(E);b&&w.push(b);Array.prototype.splice.apply(s,w)}}}return s},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e,r,i){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]")return e.map(function(t){return n.stringify(t,r,e)}).join("");var s={type:e.type,content:n.stringify(e.content,r,i),tag:"span",classes:["token",e.type],attributes:{},language:r,parent:i};s.type=="comment"&&(s.attributes.spellcheck="true");t.hooks.run("wrap",s);var o="";for(var u in s.attributes)o+=u+'="'+(s.attributes[u]||"")+'"';return"<"+s.tag+' class="'+s.classes.join(" ")+'" '+o+">"+s.content+""};if(!self.document){self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}})();; -Prism.languages.markup={comment:/<!--[\w\W]*?-->/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|\w+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&/,"&"))});; -Prism.languages.clike={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/ig,inside:{punctuation:/\(/}}, number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g}; -; -Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|get|set|new|with|typeof|try|throw|catch|finally|null|break|continue)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}});Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<|<)script[\w\W]*?(>|>)[\w\W]*?(<|<)\/script(>|>)/ig,inside:{tag:{pattern:/(<|<)script[\w\W]*?(>|>)|(<|<)\/script(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});; diff --git a/docs/lifecycle-methods.md b/docs/lifecycle-methods.md index af78738f..cac48a82 100644 --- a/docs/lifecycle-methods.md +++ b/docs/lifecycle-methods.md @@ -65,7 +65,7 @@ var ComponentWithState = { this.data = vnode.attrs.data }, view: function() { - return m("div", this.data) + return m("div", this.data) // displays data from initialization time } } @@ -154,7 +154,7 @@ var Fader = { ### onremove -The `onremove(vnode)` hook is called before a DOM element is removed from the document. If a `onbeforeremove` hook is also defined, the `onremove` hook runs after the `done` callback is called. +The `onremove(vnode)` hook is called before a DOM element is removed from the document. If a `onbeforeremove` hook is also defined, the `onremove` hook runs after the promise returned from `onbeforeremove` is completed. This hook is called on any element that is removed from the document, regardless of whether it was directly detached from its parent or whether it is a child of another element that was detached. @@ -194,64 +194,6 @@ This hook is useful to reduce lag in updates in cases where there is a overly la Although Mithril is flexible, some code patterns are discouraged: -#### Do not redraw synchronously from lifecycle hooks - -The [`m.render`](render.md) method modifies DOM state, and therefore it's [non-reentrant](https://en.wikipedia.org/wiki/Reentrancy_(computing)). All lifecyle methods are called by `m.render()`, and therefore you cannot call `m.render`, `m.mount`, `m.route` or `m.redraw` from a lifecycle method. Redrawing synchronously from a lifecycle method will result in **undefined behavior**. - -Typically, redrawing from an `oninit` or `onbeforeupdate` hook is meaningless since the element in question renders shortly after them anyways. If redrawing is required from any other hooks, you should consider moving code up the execution path; for example, refactor it so that the application code runs on an event handler, before its natural redraw occurs. - -```javascript -// AVOID -var greeting = "" - -var BrokenComponent = { - onupdate: function() { - this.greeting = greeting() - m.redraw() - }, - view: function() { - return m("div[title=Hello]", {onclick: m.withAttr("title", function(v) {greeting = v})}, this.greeting) - } -} - -// PREFER -var greeting = "" - -var WorkingComponent = { - view: function() { - return m("div[title=Hello]", {onclick: m.withAttr("title", function(v) {greeting = v})}, greeting) - } -} -``` - -On rare occasions, there may not be a way to refactor a redraw out of a lifecycle method due to dependencies on layout values (e.g. scrollbar position, an element's updated offsetHeight, etc). In those cases, you should redraw asynchronously, by wrapping the redraw call in a `requestAnimationFrame`, `setTimeout` or similar function. - -```javascript -// AVOID -var BrokenComponent = { - onupdate: function(vnode) { - var oldWidth = this.width - this.width = vnode.dom.offsetWidth - if (oldWidth !== this.width) m.redraw() - }, - view: function() { - return m("div", {onclick: function() {console.log("calculating width")}}, "Width is: " + this.width) - } -} - -// PREFER -var WorkingComponent = { - onupdate: function(vnode) { - var oldWidth = this.width - this.width = vnode.dom.offsetWidth - if (oldWidth !== this.width) requestAnimationFrame(m.redraw) - }, - view: function() { - return m("div", {onclick: function() {console.log("calculating width")}}, "Width is: " + this.width) - } -} -``` - #### Avoid premature optimizations You should only use `onbeforeupdate` to skip diffing as a last resort. Avoid using it unless you have a noticeable performance issue. diff --git a/docs/lint.js b/docs/lint.js index 65f6c1a5..2fb39e3b 100644 --- a/docs/lint.js +++ b/docs/lint.js @@ -1,4 +1,5 @@ #!/usr/bin/env node +"use strict" var fs = require("fs") var path = require("path") @@ -37,7 +38,7 @@ function ensureCodeIsSyntaticallyValid(file, data) { function ensureCodeIsRunnable(file, data) { var codeBlocks = data.match(/```javascript(.|\n|\r)*?```/gim) || [] var code = codeBlocks.map(function(block) {return block.slice(13, -3)}).join(";") - + //stubs var silentConsole = {log: function() {}} var fetch = function() { @@ -54,7 +55,7 @@ function ensureCodeIsRunnable(file, data) { if (dep.indexOf("mithril/ospec/ospec") === 0) return global.o if (dep.indexOf("mithril/stream") === 0) return global.stream if (dep === "mithril") return global.m - + if (dep === "../model/User") return { list: [], current: {}, @@ -74,7 +75,6 @@ function ensureCodeIsRunnable(file, data) { }) } catch (e) {console.log(file + " - javascript code cannot run\n\n" + e.stack + "\n\n" + code + "\n\n---\n\n")} - } function ensureCommentStyle(file, data) { @@ -86,10 +86,10 @@ function ensureCommentStyle(file, data) { } function ensureLinkIsValid(file, data) { - var links = data.match(/\]\(([^\)]+)\)/gim) + var links = data.match(/\]\(([^\)]+?)\)/gim) || [] links.forEach(function(match) { var link = match.slice(2, -1) - var path = link.match(/[\w-]+\.md/) + var path = (link.match(/[\w-#]+\.md/) || [])[0] if (link.match(/http/)) { var u = url.parse(link) http.request({method: "HEAD", host: u.host, path: u.pathname, port: 80}).on("error", function() { @@ -101,46 +101,46 @@ function ensureLinkIsValid(file, data) { } function initMocks() { - global.window = require("../test-utils/browserMock")() + global.window = require("../test-utils/browserMock")() // eslint-disable-line global-require global.document = window.document - global.m = require("../index") - global.o = require("../ospec/ospec") - global.stream = require("../stream") + global.m = require("../index") // eslint-disable-line global-require + global.o = require("../ospec/ospec") // eslint-disable-line global-require + global.stream = require("../stream") // eslint-disable-line global-require global.alert = function() {} //routes consumed by request.md global.window.$defineRoutes({ - "GET /api/v1/users": function(request) { + "GET /api/v1/users": function() { return {status: 200, responseText: JSON.stringify([{name: ""}])} }, - "GET /api/v1/users/search": function(request) { + "GET /api/v1/users/search": function() { return {status: 200, responseText: JSON.stringify([{id: 1, name: ""}])} }, - "GET /api/v1/users/1/projects": function(request) { + "GET /api/v1/users/1/projects": function() { return {status: 200, responseText: JSON.stringify([{id: 1, name: ""}])} }, - "GET /api/v1/todos": function(request) { + "GET /api/v1/todos": function() { return {status: 200, responseText: JSON.stringify([])} }, "PUT /api/v1/users/1": function(request) { return {status: 200, responseText: request.query.callback ? request.query.callback + "([])" : "[]"} }, - "POST /api/v1/upload": function(request) { + "POST /api/v1/upload": function() { return {status: 200, responseText: JSON.stringify([])} }, - "GET /files/icon.svg": function(request) { + "GET /files/icon.svg": function() { return {status: 200, responseText: ""} }, - "GET /files/data.csv": function(request) { + "GET /files/data.csv": function() { return {status: 200, responseText: "a,b,c"} }, - "GET /api/v1/users/123": function(request) { + "GET /api/v1/users/123": function() { return {status: 200, responseText: JSON.stringify({id: 123})} }, - "GET /api/v1/users/foo:bar": function(request) { + "GET /api/v1/users/foo:bar": function() { return {status: 200, responseText: JSON.stringify({id: 123})} }, - "GET /files/image.svg": function(request) { + "GET /files/image.svg": function() { return {status: 200, responseText: ""} }, }) diff --git a/docs/logo.svg b/docs/logo.svg new file mode 100644 index 00000000..ebac4eb3 --- /dev/null +++ b/docs/logo.svg @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/mount.md b/docs/mount.md index f8a28e95..9e0957a6 100644 --- a/docs/mount.md +++ b/docs/mount.md @@ -27,6 +27,10 @@ var Counter = { m.mount(document.body, Counter) ``` +To pass arguments when mounting a component use: +```javascript +m.mount(element, {view: function () {return m(Component, attrs)}}) +``` --- ### Signature @@ -69,7 +73,7 @@ In contrast, traversing a javascript data structure has a much more predictable ### 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. Note that calls to `m.prop()` do not trigger auto-redraws. +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. `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. diff --git a/docs/guides.md b/docs/nav-guides.md similarity index 72% rename from docs/guides.md rename to docs/nav-guides.md index 424d7f72..872ce86b 100644 --- a/docs/guides.md +++ b/docs/nav-guides.md @@ -1,9 +1,12 @@ - Tutorials - [Installation](installation.md) - - [Introduction](introduction.md) + - [Introduction](index.md) - [Tutorial](simple-application.md) +- Resources - [JSX](jsx.md) - [ES6](es6.md) + - [CSS](css.md) + - [Animation](animation.md) - [Testing](testing.md) - [Examples](examples.md) - Key concepts @@ -13,9 +16,10 @@ - [Keys](keys.md) - [Autoredraw system](autoredraw.md) - 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) - [Credits](credits.md) + - [Code of Conduct](code-of-conduct.md) - Misc - [Framework comparison](framework-comparison.md) - [Change log/Migration](change-log.md) diff --git a/docs/methods.md b/docs/nav-methods.md similarity index 86% rename from docs/methods.md rename to docs/nav-methods.md index 06809b50..06ae1f42 100644 --- a/docs/methods.md +++ b/docs/nav-methods.md @@ -16,4 +16,4 @@ - Optional - [Stream](stream.md) - Tooling - - [Ospec](https://github.com/lhorie/mithril.js/blob/rewrite/ospec) + - [Ospec](https://github.com/MithrilJS/mithril.js/blob/master/ospec) diff --git a/docs/redraw.md b/docs/redraw.md index be215e18..85b397dc 100644 --- a/docs/redraw.md +++ b/docs/redraw.md @@ -14,7 +14,7 @@ You DON'T need to call it if data is modified within the execution context of an 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 improves 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. +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. --- diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 00000000..37bec28d --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,114 @@ +# 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 + +### Prepare the release + +1. Ensure your local branch is up to date + +```bash +$ git co next +$ git pull --rebase mithriljs next +``` + +2. Determine patch level of the change +3. Update information in `docs/change-log.md` to match reality of the new version being prepared for release +4. Commit changes to `next` + +``` +$ git add . +$ git commit -m "Preparing for release" + +# 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 co master +$ git pull --rebase mithriljs master +``` + +6. merge `next` on top of it + +```bash +$ git merge next +``` + +7. Clean & update npm dependencies and ensure the tests are passing. + +```bash +$ npm prune +$ npm i +$ npm test +``` + +### Publish the release + +8. `npm run release `, see the docs for [`npm version`](https://docs.npmjs.com/cli/version) +9. The changes will be automatically pushed to your fork +10. Push the changes to `MithrilJS/mithril.js` + +```bash +$ git push mithriljs master +``` + +11. Travis will push the new release to npm & create a GitHub release + +### Merge `master` back into `next` + +This helps to ensure that the `version` field of `package.json` doesn't get out of date. + +12. Switch to `next` and make sure it's up to date + +```bash +$ git co next +$ git pull --rebase mithriljs next +``` + +13. Merge `master` back onto `next` + +```bash +$ git merge master +``` + +14. Push the changes to your fork & `MithrilJS/mithril.js` + +```bash +$ git push +$ git push mithriljs next +``` + +### Update the GitHub release + +15. The GitHub Release will require a manual description & title to be added. I suggest coming up with a fun title & then copying the `docs/change-log.md` entry for the build. + +## Updating mithril.js.org + +Fixes to documentation can land whenever, updates to the site are published via Travis. + +```bash +# These steps assume that MithrilJS/mithril.js is a git remote named "mithriljs" + +# Ensure your next branch is up to date +$ git co next +$ git pull mithriljs next + +# Splat the docs folder from next onto master +$ git co master +$ git co next -- ./docs + +# Manually ensure that no new feature docs were added + +$ git push mithriljs +``` + +After the Travis build completes the updated docs should appear on https://mithril.js.org in a few minutes. diff --git a/docs/request.md b/docs/request.md index 3671f957..3277c378 100644 --- a/docs/request.md +++ b/docs/request.md @@ -53,8 +53,8 @@ Argument | Type | Required | Descr `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.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 response. Defaults to a small wrapper around `JSON.parse` that returns `null` for empty responses. -`options.extract` | `string = Function(xhr, options)` | No | A hook to specify how the XMLHttpRequest response should be read. Useful for reading response headers and cookies. Defaults to a function that returns `xhr.responseText`. If defined, the `xhr` parameter is the XMLHttpRequest instance used for the request, and `options` is the object that was passed to the `m.request` call. If a custom `extract` callback is set, `options.deserialize` is ignored and the string returned from the extract callback will not be parsed as JSON. +`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.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`. **returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods @@ -77,7 +77,7 @@ 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). @@ -287,7 +287,7 @@ function upload(e) { var data = new FormData() for (var i = 0; i < files.length; i++) { - data.append("file" + i, file) + data.append("file" + i, files[i]) } m.request({ diff --git a/docs/route.md b/docs/route.md index d8566215..6f5c571b 100644 --- a/docs/route.md +++ b/docs/route.md @@ -7,6 +7,7 @@ - [m.route.get](#mrouteget) - [m.route.prefix](#mrouteprefix) - [m.route.link](#mroutelink) + - [m.route.param](#mrouteparam) - [RouteResolver](#routeresolver) - [routeResolver.onmatch](#routeresolveronmatch) - [routeResolver.render](#routeresolverrender) @@ -100,16 +101,47 @@ Argument | Type | Required | Description ##### m.route.link -`eventHandler = m.route.link(vnode)` +This function can be used as the `oncreate` (and `onupdate`) hook in a `m("a")` vnode: + +```JS +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`. + +If the `href` attribute is not static, the `onupdate` hook must also be set: + +```JS +m("a", {href: someVariable, oncreate: m.route.link, onupdate: m.route.link})` +``` + +`m.route.link(vnode)` Argument | Type | Required | Description ----------------- | ----------- | -------- | --- -`vnode` | `Vnode` | Yes | This method is meant to be used in conjunction with an `` [vnode](vnodes.md)'s [`oncreate` hook](lifecycle-methods.md) -**returns** | Function(e) | | Returns an event handler that calls `m.route.set` with the link's `href` as the `path` +`vnode` | `Vnode` | Yes | This method is meant to be used as or in conjunction with an `` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md) +**returns** | | | Returns `undefined` + +##### m.route.param + +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"`) +- router querystrings (e.g. if the path is `/users?page=1`, the route parameter has a key `page` and value `"1"`) +- `history.state` (e.g. if history.state is `{foo: "bar"}`, the route parameter has key `foo` and value `"bar"`) + +`value = m.route.param(key)` + +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`) +**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 -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}` @@ -123,11 +155,11 @@ For more information on `onmatch`, see the [advanced component resolution](#adva `routeResolver.onmatch(args, requestedPath)` -Argument | Type | Description ---------------- | ------------------------------ | --- -`args` | `Object` | The [routing parameters](#routing-parameters) -`requestedPath` | `String` | The router path requested by the last routing action, including interpolated routing parameter values, but without the prefix. When `onmatch` is called, the resolution for this path is not complete and `m.route.get()` still returns the previous path. -**returns** | `Component|Promise` | Returns a component or a promise that resolves to a component +Argument | Type | Description +--------------- | ---------------------------------------- | --- +`args` | `Object` | The [routing parameters](#routing-parameters) +`requestedPath` | `String` | The router path requested by the last routing action, including interpolated routing parameter values, but without the prefix. When `onmatch` is called, the resolution for this path is not complete and `m.route.get()` still returns the previous path. +**returns** | `Component|Promise|undefined` | Returns a component or a promise that resolves to a component If `onmatch` returns a component or a promise that resolves to a component, this component is used as the `vnode.tag` for the first argument in the RouteResolver's `render` method. Otherwise, `vnode.tag` is set to `"div"`. Similarly, if the `onmatch` method is omitted, `vnode.tag` is also `"div"`. @@ -139,11 +171,11 @@ The `render` method is called on every redraw for a matching route. It is simila `vnode = routeResolve.render(vnode)` -Argument | Type | Description -------------------- | --------------- | ----------- -`vnode` | `Object` | A [vnode](vnodes.md) whose attributes object contains routing parameters. If onmatch does not return a component or a promise that resolves to a component, the vnode's `tag` field defaults to `"div"` -`vnode.attrs` | `Object` | A map of URL parameter values -**returns** | `Vnode` | Returns a vnode +Argument | Type | Description +------------------- | -------------------- | ----------- +`vnode` | `Object` | A [vnode](vnodes.md) whose attributes object contains routing parameters. If onmatch does not return a component or a promise that resolves to a component, the vnode's `tag` field defaults to `"div"` +`vnode.attrs` | `Object` | A map of URL parameter values +**returns** | `Array|Vnode` | The [vnodes](vnodes.md) to be rendered --- @@ -257,8 +289,6 @@ In the example above, we defined a route `/edit/:id`. This creates a dynamic rou It's possible to have multiple arguments in a route, for example `/edit/:projectID/:userID` would yield the properties `projectID` and `userID` on the component's vnode attributes object. -In addition to routing parameters, the `attrs` object also includes a `path` property that contains the current route path, and a `route` property that contains the matched routed. - #### Key parameter When a user navigates from a parameterized route to the same route with a different parameter (e.g. going from `/page/1` to `/page/2` given a route `/page/:id`, the component would not be recreated from scratch since both routes resolve to the same component, and thus result in a virtual dom in-place diff. This has the side-effect of triggering the `onupdate` hook, rather than `oninit`/`oncreate`. However, it's relatively common for a developer to want to synchronize the recreation of the component to the route change event. @@ -291,6 +321,20 @@ m.route(document.body, "/edit/pictures/image.jpg", { }) ``` +#### Handling 404s + +For isomorphic / universal javascript app, an url param and a variadic route combined is very usefull 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 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. @@ -385,7 +429,7 @@ var Layout = { } ``` -In the example above, the layout merely consists of a `
` that contains the children passed to the component, but in a real life scenario it could be as complex as neeeded. +In the example above, the layout merely consists of a `
` that contains the children passed to the component, but in a real life scenario it could be as complex as needed. One way to wrap the layout is to define an anonymous component in the routes map: @@ -464,7 +508,7 @@ In example 2, since `Layout` is the top-level component in both routes, the DOM #### 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 initializated. The example below shows how to implement a login wall that prevents users from seeing the `/secret` page unless they login. ```javascript var isLoggedIn = false @@ -486,9 +530,7 @@ m.route(document.body, "/secret", { "/secret": { onmatch: function() { if (!isLoggedIn) m.route.set("/login") - }, - render: function() { - return m(Home) + else return Home } }, "/login": Login @@ -497,7 +539,50 @@ m.route(document.body, "/secret", { When the application loads, `onmatch` is called and since `isLoggedIn` is false, the application redirects to `/login`. Once the user pressed the login button, `isLoggedIn` would be set to true, and the application would redirect to `/secret`. The `onmatch` hook would run once again, and since `isLoggedIn` is true this time, the application would render the `Home` component. -For the sake of simplicity, in the example above, the user's logged in status is kept in a global variable, and that flag is merely toggled when the user clicks the login button. In a real life application, a user would obviously have to supply proper login credentials, and clicking the login button would trigger a request to a server to authenticate the user. +For the sake of simplicity, in the example above, the user's logged in status is kept in a global variable, and that flag is merely toggled when the user clicks the login button. In a real life application, a user would obviously have to supply proper login credentials, and clicking the login button would trigger a request to a server to authenticate the user: + +```javascript +var Auth = { + username: "", + password: "", + + setUsername: function(value) { + Auth.username = value + }, + setPassword: function(value) { + Auth.password = value + }, + login: function() { + m.request({ + url: "/api/v1/auth", + data: {username: Auth.username, password: Auth.password} + }).then(function(data) { + localStorage.setItem("auth-token": data.token) + m.route.set("/secret") + }) + } +} + +var Login = { + view: function() { + return m("form", [ + 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("button[type=button]", {onclick: Auth.login, "Login") + ]) + } +} + +m.route(document.body, "/secret", { + "/secret": { + onmatch: function() { + if (!localStorage.getItem("auth-token")) m.route.set("/login") + else return Home + } + }, + "/login": Login +}) +``` --- diff --git a/docs/simple-application.md b/docs/simple-application.md index f23ff82b..d1763fba 100644 --- a/docs/simple-application.md +++ b/docs/simple-application.md @@ -13,14 +13,14 @@ First let's create an entry point for the application. Create a file `index.html My Application - + ``` The `` line indicates this is an HTML 5 document. The first `charset` meta tag indicates the encoding of the document and the `viewport` meta tag dictates how mobile browsers should scale the page. The `title` tag contains the text to be displayed on the browser tab for this application, and the `script` tag indicates what is the path to the Javascript file that controls the application. -We could create the entire application in a single Javascript file, but doing so would make it difficult to navigate the codebase later on. Instead, let's split the code into *modules*, and assemble these modules into a *bundle* `app.js`. +We could create the entire application in a single Javascript file, but doing so would make it difficult to navigate the codebase later on. Instead, let's split the code into *modules*, and assemble these modules into a *bundle* `bin/app.js`. There are many ways to setup a bundler tool, but most are distributed via NPM. In fact, most modern Javascript libraries and tools are distributed that way, including Mithril. NPM stands for Node.js Package Manager. To download NPM, [install Node.js](https://nodejs.org/en/); NPM is installed automatically with it. Once you have Node.js and NPM installed, open the command line and run this command: @@ -61,7 +61,7 @@ module.exports = User Next we create a function that will trigger an XHR call. Let's call it `loadList` ```javascript -// models/User.js +// src/models/User.js var m = require("mithril") var User = { @@ -74,10 +74,10 @@ var User = { module.exports = User ``` -Then we can add an `m.request` call to make an XHR request. For this tutorial, we'll make XHR calls to the [REM](http://rem-rest-api.herokuapp.com/) API, a mock REST API designed for rapid prototyping. This API returns a list of users from the `GET http://rem-rest-api.herokuapp.com/api/users` endpoint. Let's use `m.request` to make an XHR request and populate our data with the response of that endpoint. +Then we can add an `m.request` call to make an XHR request. For this tutorial, we'll make XHR calls to the [REM](http://rem-rest-api.herokuapp.com/) API, a mock REST API designed for rapid prototyping. This API returns a list of users from the `GET https://rem-rest-api.herokuapp.com/api/users` endpoint. Let's use `m.request` to make an XHR request and populate our data with the response of that endpoint. ```javascript -// models/User.js +// src/models/User.js var m = require("mithril") var User = { @@ -85,7 +85,7 @@ var User = { loadList: function() { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users", + url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { @@ -99,7 +99,7 @@ module.exports = User The `method` option is an [HTTP method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods). To retrieve data from the server without causing side-effects on the server, we need to use the `GET` method. The `url` is the address for the API endpoint. The `withCredentials: true` line indicates that we're using cookies (which is a requirement for the REM API). -The `m.request` call returns a Promise that resolves to the data from the endpoint. By default, Mithril assumes a HTTP response body are in JSON format and automatically parses it into a Javascript object or array. The `.then` callback runs when the XHR request completes. In this case, the callback assigns the `reesult.data` array to `User.list`. +The `m.request` call returns a Promise that resolves to the data from the endpoint. By default, Mithril assumes a HTTP response body are in JSON format and automatically parses it into a Javascript object or array. The `.then` callback runs when the XHR request completes. In this case, the callback assigns the `result.data` array to `User.list`. Notice we also have a `return` statement in `loadList`. This is a general good practice when working with Promises, which allows us to register more callbacks to run after the completion of the XHR request. @@ -112,15 +112,17 @@ Now, let's create a view module so that we can display data from our User model Create a file called `src/views/UserList.js`. First, let's include Mithril and our model, since we'll need to use both: ```javascript +// src/views/UserList.js var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") ``` Next, let's create a Mithril component. A component is simply an object that has a `view` method: ```javascript +// src/views/UserList.js var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") module.exports = { view: function() { @@ -135,7 +137,7 @@ Let's use Mithril hyperscript to create a list of items. Hyperscript is the most ```javascript var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") module.exports = { view: function() { @@ -149,16 +151,15 @@ The `".user-list"` string is a CSS selector, and as you would expect, `.user-lis Now, let's reference the list of users from the model we created earlier (`User.list`) to dynamically loop through data: ```javascript +// src/views/UserList.js var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") module.exports = { view: function() { - return m(".user-list", [ - User.list.map(function(user) { - return m(".user-list-item", user.firstName + " " + user.lastName) - }) - ]) + return m(".user-list", User.list.map(function(user) { + return m(".user-list-item", user.firstName + " " + user.lastName) + })) } } ``` @@ -168,38 +169,38 @@ Since `User.list` is a Javascript array, and since hyperscript views are just Ja The problem, of course, is that we never called the `User.loadList` function. Therefore, `User.list` is still an empty array, and thus this view would render a blank page. Since we want `User.loadList` to be called when we render this component, we can take advantage of component [lifecycle methods](lifecycle-methods.md): ```javascript +// src/views/UserList.js var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") module.exports = { oninit: User.loadList, view: function() { - return m(".user-list", [ - User.list.map(function(user) { - return m(".user-list-item", user.firstName + " " + user.lastName) - }) - ]) + return m(".user-list", User.list.map(function(user) { + return m(".user-list-item", user.firstName + " " + user.lastName) + })) } } ``` Notice that we added an `oninit` method to the component, which references `User.loadList`. This means that when the component initializes, User.loadList will be called, triggering an XHR request. When the server returns a response, `User.list` gets populated. -Also notice we **didn't** do `oninit: User.loadList()` (with parentheses at the end). The difference is that `oninit: User.loadList()` calls the function once and immediately, but `oninit: User.loadList` only calls that function when the component renders. This is an important difference and a common newbie mistake: calling the function immediately means that the XHR request will fire even if the component never renders. Also, if the component is ever recreated (through navigating back and forth through the application), the function won't be called again as expected. +Also notice we **didn't** do `oninit: User.loadList()` (with parentheses at the end). The difference is that `oninit: User.loadList()` calls the function once and immediately, but `oninit: User.loadList` only calls that function when the component renders. This is an important difference and a common pitfall for developers new to javascript: calling the function immediately means that the XHR request will fire as soon as the source code is evaluated, even if the component never renders. Also, if the component is ever recreated (through navigating back and forth through the application), the function won't be called again as expected. --- -Let's render the view from the entry point file `index.js` we created earlier: +Let's render the view from the entry point file `src/index.js` we created earlier: ```javascript +// src/index.js var m = require("mithril") -var UserList = require("./view/UserList") +var UserList = require("./views/UserList") m.mount(document.body, UserList) ``` -The `m.mount` call renders the specified component (`UserList`) into a DOM element (`document.body`), erasing any DOM that were there previously. Opening the HTML file in a browser should now display a list of person names. +The `m.mount` call renders the specified component (`UserList`) into a DOM element (`document.body`), erasing any DOM that was there previously. Opening the HTML file in a browser should now display a list of person names. --- @@ -207,9 +208,9 @@ Right now, the list looks rather plain because we have not defined any styles. There are many similar conventions and libraries that help organize application styles nowadays. Some, like [Bootstrap](http://getbootstrap.com/) dictate a specific set of HTML structures and semantically meaningful class names, which has the upside of providing low cognitive dissonance, but the downside of making customization more difficult. Others, like [Tachyons](http://tachyons.io/) provide a large number of self-describing, atomic class names at the cost of making the class names themselves non-semantic. "CSS-in-JS" is another type of CSS system that is growing in popularity, which basically consists of scoping CSS via transpilation tooling. CSS-in-JS libraries achieve maintainability by reducing the size of the problem space, but come at the cost of having high complexity. -Regardless of what CSS convention/library you choose, a good rule of thumb is to avoid the cascading aspect of CSS. To keep this tutorial simple, we'll just use plain CSS with overly explicit class names, so that the styles themselves provide the atomicity of Tachyons, and class name collisions are made unlikely through the verbosity of the class names. Plain CSS can be sufficient for low-complexity projects (e.g. 3 to 6 man-months of initial implementation time and few project phases) +Regardless of what CSS convention/library you choose, a good rule of thumb is to avoid the cascading aspect of CSS. To keep this tutorial simple, we'll just use plain CSS with overly explicit class names, so that the styles themselves provide the atomicity of Tachyons, and class name collisions are made unlikely through the verbosity of the class names. Plain CSS can be sufficient for low-complexity projects (e.g. 3 to 6 man-months of initial implementation time and few project phases). -To add styles, let's first create a file called `styles.css` and include it in the `index.html` file +To add styles, let's first create a file called `styles.css` and include it in the `index.html` file: ```markup @@ -221,7 +222,7 @@ To add styles, let's first create a file called `styles.css` and include it in t - + ``` @@ -249,9 +250,10 @@ Routing means binding a screen to a unique URL, to create the ability to go from We can add routing by changing the `m.mount` call to a `m.route` call: ```javascript +// src/index.js var m = require("mithril") -var UserList = require("./view/UserList") +var UserList = require("./views/UserList") m.route(document.body, "/list", { "/list": UserList @@ -278,14 +280,14 @@ module.exports = { } ``` -Then we can `require` this new module from `index.js` +Then we can `require` this new module from `src/index.js` ```javascript -// index.js +// src/index.js var m = require("mithril") -var UserList = require("./view/UserList") -var UserForm = require("./view/UserForm") +var UserList = require("./views/UserList") +var UserForm = require("./views/UserForm") m.route(document.body, "/list", { "/list": UserList @@ -295,11 +297,11 @@ m.route(document.body, "/list", { And finally, we can create a route that references it: ```javascript -// index.js +// src/index.js var m = require("mithril") -var UserList = require("./view/UserList") -var UserForm = require("./view/UserForm") +var UserList = require("./views/UserList") +var UserForm = require("./views/UserForm") m.route(document.body, "/list", { "/list": UserList, @@ -322,7 +324,7 @@ module.exports = { m("input.input[type=text][placeholder=First name]"), m("label.label", "Last name"), m("input.input[placeholder=Last name]"), - m("button.button[type=submit]", "Save"), + m("button.button[type=button]", "Save"), ]) } } @@ -344,7 +346,7 @@ body,.input,.button {font:normal 16px Verdana;margin:0;} .button:hover {background:#e8e8e8;} ``` -Right now, this component does nothing to respond to user events. Let's add some code to our `User` model in `src/model/User.js`. This is how the code is right now: +Right now, this component does nothing to respond to user events. Let's add some code to our `User` model in `src/models/User.js`. This is how the code is right now: ```javascript // src/models/User.js @@ -355,7 +357,7 @@ var User = { loadList: function() { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users", + url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { @@ -378,7 +380,7 @@ var User = { loadList: function() { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users", + url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { @@ -390,8 +392,7 @@ var User = { load: function(id) { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users/:id", - data: {id: id}, + url: "https://rem-rest-api.herokuapp.com/api/users/" + id, withCredentials: true, }) .then(function(result) { @@ -408,7 +409,7 @@ Notice we added a `User.current` property, and a `User.load(id)` method which po ```javascript // src/views/UserForm.js var m = require("mithril") -var User = require("./model/User") +var User = require("../models/User") module.exports = { oninit: function(vnode) {User.load(vnode.attrs.id)}, @@ -418,7 +419,7 @@ module.exports = { m("input.input[type=text][placeholder=First name]", {value: User.current.firstName}), m("label.label", "Last name"), m("input.input[placeholder=Last name]", {value: User.current.lastName}), - m("button.button[type=submit]", "Save"), + m("button.button[type=button]", "Save"), ]) } } @@ -429,18 +430,16 @@ Similar to the `UserList` component, `oninit` calls `User.load()`. Remember we h Now, let's modify the `UserList` view so that we can navigate from there to a `UserForm`: ```javascript -// src/views/UserForm.js +// src/views/UserList.js var m = require("mithril") -var User = require("../model/User") +var User = require("../models/User") module.exports = { oninit: User.loadList, view: function() { - return m(".user-list", [ - User.list.map(function(user) { - return m("a.user-list-item", {href: "/edit/" + user.id, oncreate: m.route.link}, user.firstName + " " + user.lastName) - }) - ]) + return m(".user-list", User.list.map(function(user) { + return m("a.user-list-item", {href: "/edit/" + user.id, oncreate: m.route.link}, user.firstName + " " + user.lastName) + })) } } ``` @@ -456,12 +455,17 @@ The form itself still doesn't save when you press "Save". Let's make this form w ```javascript // src/views/UserForm.js var m = require("mithril") -var User = require("./model/User") +var User = require("../models/User") module.exports = { oninit: function(vnode) {User.load(vnode.attrs.id)}, view: function() { - return m("form", [ + return m("form", { + onsubmit: function(e) { + e.preventDefault() + User.save() + } + }, [ m("label.label", "First name"), m("input.input[type=text][placeholder=First name]", { oninput: m.withAttr("value", function(value) {User.current.firstName = value}), @@ -472,7 +476,7 @@ module.exports = { oninput: m.withAttr("value", function(value) {User.current.lastName = value}), value: User.current.lastName }), - m("button.button[type=submit]", {onclick: User.save}, "Save"), + m("button.button[type=submit]", "Save"), ]) } } @@ -491,7 +495,7 @@ var User = { loadList: function() { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users", + url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { @@ -503,8 +507,7 @@ var User = { load: function(id) { return m.request({ method: "GET", - url: "http://rem-rest-api.herokuapp.com/api/users/:id", - data: {id: id}, + url: "https://rem-rest-api.herokuapp.com/api/users/" + id, withCredentials: true, }) .then(function(result) { @@ -515,7 +518,7 @@ var User = { save: function() { return m.request({ method: "PUT", - url: "http://rem-rest-api.herokuapp.com/api/users/:id", + url: "https://rem-rest-api.herokuapp.com/api/users/" + User.current.id, data: User.current, withCredentials: true, }) @@ -536,7 +539,9 @@ 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`: ```javascript -var Layout = { +var m = require("mithril") + +module.exports = { view: function(vnode) { return m("main.layout", [ m("nav.menu", [ @@ -571,14 +576,15 @@ body,.input,.button {font:normal 16px Verdana;margin:0;} .button:hover {background:#e8e8e8;} ``` -Let's change the router in `index.js` to add our layout into the mix: +Let's change the router in `src/index.js` to add our layout into the mix: ```javascript -// index.js +// src/index.js var m = require("mithril") -var UserList = require("./view/UserList") -var UserForm = require("./view/UserForm") +var UserList = require("./views/UserList") +var UserForm = require("./views/UserForm") +var Layout = require("./views/Layout") m.route(document.body, "/list", { "/list": { @@ -598,7 +604,7 @@ We replaced each component with a [RouteResolver](route.md#routeresolver) (basic The interesting thing to pay attention to is how components can be used instead of a selector string in a `m()` call. Here, in the `/list` route, we have `m(Layout, m(UserList))`. This means there's a root vnode that represents an instance of `Layout`, which has a `UserList` vnode as its only child. -In the `/edit/:id` route, there's also a `vnode` argument that carries the route parameters into the `UserForm` component. So if the URL is `/edit/1`, then `vnode.attrs` in this case is `{id: 1}`, and this `m(UserForm, vnode.attrs)` is equivalent to `m(UserForm, {id: 1})`. The equivalent JSX code would be ``. +In the `/edit/:id` route, there's also a `vnode` argument that carries the route parameters into the `UserForm` component. So if the URL is `/edit/1`, then `vnode.attrs` in this case is `{id: 1}`, and this `m(UserForm, vnode.attrs)` is equivalent to `m(UserForm, {id: 1})`. The equivalent JSX code would be ``. Refresh the page in the browser and now you'll see the global navigation on every page in the app. @@ -608,5 +614,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. -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). diff --git a/docs/stream.md b/docs/stream.md index fe233f18..dc720ef4 100644 --- a/docs/stream.md +++ b/docs/stream.md @@ -5,6 +5,8 @@ - [Static members](#static-members) - [Stream.combine](#streamcombine) - [Stream.merge](#streammerge) + - [Stream.scan](#streamscan) + - [Stream.scanMerge](#streamscanmerge) - [Stream.HALT](#streamhalt) - [Stream["fantasy-land/of"]](#streamfantasy-landof) - [Instance members](#static-members) @@ -40,6 +42,14 @@ Streams are NOT bundled with Mithril's core distribution. To include the Streams var Stream = require("mithril/stream") ``` +You can also download the module directly if your environment does not support a bundling toolchain: + +```markup + +``` + +When loaded directly with a ` + + + + + + + + + + + + + + + + diff --git a/performance/test-perf.js b/performance/test-perf.js new file mode 100644 index 00000000..2ba9b622 --- /dev/null +++ b/performance/test-perf.js @@ -0,0 +1,336 @@ +/* global Benchmark */ +"use strict" + +/* Based off of preact's perf tests, so including their MIT license */ +/* +The MIT License (MIT) + +Copyright (c) 2017 Jason Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +var browserMock = require("../test-utils/browserMock") + +// Do this silly dance so browser testing works +var B = typeof Benchmark === "undefined" ? require("benchmark") : Benchmark + +var m, scratch; + +// set up browser env on before running tests +var doc = typeof document !== "undefined" ? document : null + +if(!doc) { + var mock = browserMock() + if (typeof global !== "undefined") { global.window = mock } + + doc = mock.document +} + +// Have to include mithril AFTER browser polyfill is set up +m = require("../mithril") // eslint-disable-line global-require + +scratch = doc.createElement("div"); + +(doc.body || doc.documentElement).appendChild(scratch) + +// Initialize benchmark suite +var suite = new B.Suite("mithril perf") + +suite.on("start", function() { + this.start = Date.now(); +}) + +suite.on("cycle", function(e) { + console.log(e.target.toString()) + + scratch.innerHTML = "" +}) + +suite.on("complete", function() { + console.log("Completed perf tests in " + (Date.now() - this.start) + "ms") +}) + +suite.on("error", console.error.bind(console)) + +suite.add({ + name : "rerender without changes", + onStart : function() { + this.vdom = 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" + ) + ) + ) + ) + ) + }, + fn : function() { + m.render(scratch, this.vdom) + } +}) + +suite.add({ + name : "construct large VDOM tree", + + onStart : function() { + var fields = [] + + for(var i=100; i--;) { + fields.push((i * 999).toString(36)) + } + + this.fields = fields; + }, + + fn : function () { + 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"}), + m("fieldset", + this.fields.map(function (field) { + return m("label", + field, + ":", + m("input", {placeholder: field}) + ) + }) + ), + m("button-bar", + m("button", + {style: "width:10px; height:10px; border:1px solid #FFF;"}, + "Normal CSS" + ), + m("button", + {style: "top:0 ; right: 20"}, + "Poor CSS" + ), + m("button", + {style: "invalid-prop:1;padding:1px;font:12px/1.1 arial,sans-serif;", icon: true}, + "Poorer CSS" + ), + m("button", + {style: {margin: 0, padding: "10px", overflow: "visible"}}, + "Object CSS" + ) + ) + ) + ) + ) + } +}) + +suite.add({ + name : "mutate styles/properties", + + onStart : function () { + var counter = 0 + var keyLooper = function (n) { return function (c) { return c % n ? (c + "px") : c } } + var get = function (obj, i) { return obj[i%obj.length] } + var classes = ["foo", "foo bar", "", "baz-bat", null, "fooga"] + var styles = [] + var multivalue = ["0 1px", "0 0 1px 0", "0", "1px", "20px 10px", "7em 5px", "1px 0 5em 2px"] + var stylekeys = [ + ["left", keyLooper(3)], + ["top", keyLooper(2)], + ["margin", function (c) { return get(multivalue, c).replace("1px", c+"px") }], + ["padding", function (c) { return get(multivalue, c) }], + ["position", function (c) { return c%5 ? c%2 ? "absolute" : "relative" : null }], + ["display", function (c) { return c%10 ? c%2 ? "block" : "inline" : "none" }], + ["color", function (c) { return ("rgba(" + (c%255) + ", " + (255 - c%255) + ", " + (50+c%150) + ", " + (c%50/50) + ")") }], + ["border", function (c) { return c%5 ? ((c%10) + "px " + (c%2?"solid":"dotted") + " " + (stylekeys[6][1](c))) : "" }] + ] + var i, j, style, conf + + for (i=0; i<1000; i++) { + style = {} + for (j=0; j 0) attrs.className = classes.join(" ") + return selectorCache[selector] = {tag: tag, attrs: attrs} +} + +function execSelector(state, attrs, children) { + var hasAttrs = false, childList, text + var className = attrs.className || attrs.class + + for (var key in state.attrs) { + if (hasOwn.call(state.attrs, key)) { + attrs[key] = state.attrs[key] + } + } + + if (className !== undefined) { + if (attrs.class !== undefined) { + attrs.class = undefined + attrs.className = className + } + + if (state.attrs.className != null) { + attrs.className = state.attrs.className + " " + className + } + } + + for (var key in attrs) { + if (hasOwn.call(attrs, key) && key !== "key") { + hasAttrs = true + break + } + } + + if (Array.isArray(children) && children.length === 1 && children[0] != null && children[0].tag === "#") { + text = children[0].children + } else { + childList = children + } + + return Vnode(state.tag, attrs.key, hasAttrs ? attrs : undefined, childList, text) +} + function hyperscript(selector) { - if (selector == null || typeof selector !== "string" && selector.view == null) { + // Because sloppy mode sucks + var attrs = arguments[1], start = 2, children + + if (selector == null || typeof selector !== "string" && typeof selector !== "function" && typeof selector.view !== "function") { throw Error("The selector must be either a string or a component."); } - if (typeof selector === "string" && selectorCache[selector] === undefined) { - var match, tag, classes = [], attributes = {} - while (match = selectorParser.exec(selector)) { - var type = match[1], value = match[2] - if (type === "" && value !== "") tag = value - else if (type === "#") attributes.id = value - else if (type === ".") classes.push(value) - else if (match[3][0] === "[") { - var attrValue = match[6] - if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\") - if (match[4] === "class") classes.push(attrValue) - else attributes[match[4]] = attrValue || true - } - } - if (classes.length > 0) attributes.className = classes.join(" ") - selectorCache[selector] = function(attrs, children) { - var hasAttrs = false, childList, text - var className = attrs.className || attrs.class - for (var key in attributes) attrs[key] = attributes[key] - if (className !== undefined) { - if (attrs.class !== undefined) { - attrs.class = undefined - attrs.className = className - } - if (attributes.className !== undefined) attrs.className = attributes.className + " " + className - } - for (var key in attrs) { - if (key !== "key") { - hasAttrs = true - break - } - } - if (Array.isArray(children) && children.length == 1 && children[0] != null && children[0].tag === "#") text = children[0].children - else childList = children + if (typeof selector === "string") { + var cached = selectorCache[selector] || compileSelector(selector) + } - return Vnode(tag || "div", attrs.key, hasAttrs ? attrs : undefined, childList, text, undefined) - } + if (attrs == null) { + attrs = {} + } else if (typeof attrs !== "object" || attrs.tag != null || Array.isArray(attrs)) { + attrs = {} + start = 1 } - var attrs, children, childrenIndex - if (arguments[1] == null || typeof arguments[1] === "object" && arguments[1].tag === undefined && !Array.isArray(arguments[1])) { - attrs = arguments[1] - childrenIndex = 2 - } - else childrenIndex = 1 - if (arguments.length === childrenIndex + 1) { - children = Array.isArray(arguments[childrenIndex]) ? arguments[childrenIndex] : [arguments[childrenIndex]] - } - else { + + if (arguments.length === start + 1) { + children = arguments[start] + if (!Array.isArray(children)) children = [children] + } else { children = [] - for (var i = childrenIndex; i < arguments.length; i++) children.push(arguments[i]) + while (start < arguments.length) children.push(arguments[start++]) } - if (typeof selector === "string") return selectorCache[selector](attrs || {}, Vnode.normalizeChildren(children)) + var normalized = Vnode.normalizeChildren(children) - return Vnode(selector, attrs && attrs.key, attrs || {}, Vnode.normalizeChildren(children), undefined, undefined) + if (typeof selector === "string") { + return execSelector(cached, attrs, normalized) + } else { + return Vnode(selector, attrs.key, attrs, normalized) + } } module.exports = hyperscript diff --git a/render/render.js b/render/render.js index 4e993f59..e24a76eb 100644 --- a/render/render.js +++ b/render/render.js @@ -6,38 +6,50 @@ module.exports = function($window) { var $doc = $window.document var $emptyFragment = $doc.createDocumentFragment() + var nameSpace = { + svg: "http://www.w3.org/2000/svg", + math: "http://www.w3.org/1998/Math/MathML" + } + var onevent function setEventCallback(callback) {return onevent = callback} + function getNameSpace(vnode) { + return vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag] + } + //create function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) { for (var i = start; i < end; i++) { var vnode = vnodes[i] if (vnode != null) { - insertNode(parent, createNode(vnode, hooks, ns), nextSibling) + createNode(parent, vnode, hooks, ns, nextSibling) } } } - function createNode(vnode, hooks, ns) { + function createNode(parent, vnode, hooks, ns, nextSibling) { var tag = vnode.tag - if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks) if (typeof tag === "string") { + vnode.state = {} + if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks) switch (tag) { - case "#": return createText(vnode) - case "<": return createHTML(vnode) - case "[": return createFragment(vnode, hooks, ns) - default: return createElement(vnode, hooks, ns) + case "#": return createText(parent, vnode, nextSibling) + case "<": return createHTML(parent, vnode, nextSibling) + case "[": return createFragment(parent, vnode, hooks, ns, nextSibling) + default: return createElement(parent, vnode, hooks, ns, nextSibling) } } - else return createComponent(vnode, hooks, ns) + else return createComponent(parent, vnode, hooks, ns, nextSibling) } - function createText(vnode) { - return vnode.dom = $doc.createTextNode(vnode.children) + function createText(parent, vnode, nextSibling) { + vnode.dom = $doc.createTextNode(vnode.children) + insertNode(parent, vnode.dom, nextSibling) + return vnode.dom } - function createHTML(vnode) { + function createHTML(parent, vnode, nextSibling) { var match = vnode.children.match(/^\s*?<(\w+)/im) || [] - var parent = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"}[match[1]] || "div" - var temp = $doc.createElement(parent) + var parent1 = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"}[match[1]] || "div" + var temp = $doc.createElement(parent1) temp.innerHTML = vnode.children vnode.dom = temp.firstChild @@ -47,9 +59,10 @@ module.exports = function($window) { while (child = temp.firstChild) { fragment.appendChild(child) } + insertNode(parent, fragment, nextSibling) return fragment } - function createFragment(vnode, hooks, ns) { + function createFragment(parent, vnode, hooks, ns, nextSibling) { var fragment = $doc.createDocumentFragment() if (vnode.children != null) { var children = vnode.children @@ -57,18 +70,16 @@ module.exports = function($window) { } vnode.dom = fragment.firstChild vnode.domSize = fragment.childNodes.length + insertNode(parent, fragment, nextSibling) return fragment } - function createElement(vnode, hooks, ns) { + function createElement(parent, vnode, hooks, ns, nextSibling) { 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 is = attrs && attrs.is + ns = getNameSpace(vnode) || ns + var element = ns ? is ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) : is ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag) @@ -78,6 +89,8 @@ module.exports = function($window) { setAttrs(vnode, attrs, ns) } + insertNode(parent, element, nextSibling) + if (vnode.attrs != null && vnode.attrs.contenteditable != null) { setContentEditable(vnode) } @@ -94,19 +107,34 @@ module.exports = function($window) { } return element } - function createComponent(vnode, hooks, ns) { - vnode.state = Object.create(vnode.tag) - var view = vnode.tag.view - if (view.reentrantLock != null) return $emptyFragment - view.reentrantLock = true - initLifecycle(vnode.tag, vnode, hooks) - vnode.instance = Vnode.normalize(view.call(vnode.state, vnode)) - view.reentrantLock = null + function initComponent(vnode, hooks) { + var sentinel + if (typeof vnode.tag.view === "function") { + vnode.state = Object.create(vnode.tag) + sentinel = vnode.state.view + if (sentinel.$$reentrantLock$$ != null) return $emptyFragment + sentinel.$$reentrantLock$$ = true + } else { + vnode.state = void 0 + sentinel = vnode.tag + if (sentinel.$$reentrantLock$$ != null) return $emptyFragment + 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.state + if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks) + initLifecycle(vnode._state, vnode, hooks) + vnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode)) + if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument") + sentinel.$$reentrantLock$$ = null + } + function createComponent(parent, vnode, hooks, ns, nextSibling) { + initComponent(vnode, hooks) if (vnode.instance != null) { - if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as arguments") - var element = createNode(vnode.instance, hooks, ns) + var element = createNode(parent, vnode.instance, hooks, ns, nextSibling) vnode.dom = vnode.instance.dom vnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0 + insertNode(parent, element, nextSibling) return element } else { @@ -116,9 +144,9 @@ module.exports = function($window) { } //update - function updateNodes(parent, old, vnodes, hooks, nextSibling, ns) { + function updateNodes(parent, old, vnodes, recycling, hooks, nextSibling, ns) { if (old === vnodes || old == null && vnodes == null) return - else if (old == null) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, undefined) + else if (old == null) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns) else if (vnodes == null) removeNodes(old, 0, old.length, vnodes) else { if (old.length === vnodes.length) { @@ -132,15 +160,18 @@ module.exports = function($window) { if (isUnkeyed) { for (var i = 0; i < old.length; i++) { if (old[i] === vnodes[i]) continue - else if (old[i] == null && vnodes[i] != null) insertNode(parent, createNode(vnodes[i], hooks, ns), getNextSibling(old, i + 1, nextSibling)) + else if (old[i] == null && vnodes[i] != null) createNode(parent, vnodes[i], hooks, ns, getNextSibling(old, i + 1, nextSibling)) else if (vnodes[i] == null) removeNodes(old, i, i + 1, vnodes) - else updateNode(parent, old[i], vnodes[i], hooks, getNextSibling(old, i + 1, nextSibling), false, ns) + else updateNode(parent, old[i], vnodes[i], hooks, getNextSibling(old, i + 1, nextSibling), recycling, ns) } return } } - var recycling = isRecyclable(old, vnodes) - if (recycling) old = old.concat(old.pool) + recycling = recycling || isRecyclable(old, vnodes) + if (recycling) { + var pool = old.pool + old = old.concat(old.pool) + } var oldStart = 0, start = 0, oldEnd = old.length - 1, end = vnodes.length - 1, map while (oldEnd >= oldStart && end >= start) { @@ -149,8 +180,9 @@ module.exports = function($window) { else if (o == null) oldStart++ else if (v == null) start++ else if (o.key === v.key) { + var shouldRecycle = (pool != null && oldStart >= old.length - pool.length) || ((pool == null) && recycling) oldStart++, start++ - updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), recycling, ns) + updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), shouldRecycle, ns) if (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling) } else { @@ -159,7 +191,8 @@ module.exports = function($window) { else if (o == null) oldEnd-- else if (v == null) start++ else if (o.key === v.key) { - updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns) + var shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling) + updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns) if (recycling || start < end) insertNode(parent, toFragment(o), getNextSibling(old, oldStart, nextSibling)) oldEnd--, start++ } @@ -172,7 +205,8 @@ module.exports = function($window) { else if (o == null) oldEnd-- else if (v == null) end-- else if (o.key === v.key) { - updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns) + var shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling) + updateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns) if (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling) if (o.dom != null) nextSibling = o.dom oldEnd--, end-- @@ -183,14 +217,14 @@ module.exports = function($window) { var oldIndex = map[v.key] if (oldIndex != null) { var movable = old[oldIndex] + var shouldRecycle = (pool != null && oldIndex >= old.length - pool.length) || ((pool == null) && recycling) updateNode(parent, movable, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns) insertNode(parent, toFragment(movable), nextSibling) old[oldIndex].skip = true if (movable.dom != null) nextSibling = movable.dom } else { - var dom = createNode(v, hooks, undefined) - insertNode(parent, dom, nextSibling) + var dom = createNode(parent, v, hooks, ns, nextSibling) nextSibling = dom } } @@ -206,24 +240,29 @@ module.exports = function($window) { var oldTag = old.tag, tag = vnode.tag if (oldTag === tag) { vnode.state = old.state + vnode._state = old._state vnode.events = old.events - if (shouldUpdate(vnode, old)) return - if (vnode.attrs != null) { - updateLifecycle(vnode.attrs, vnode, hooks, recycling) - } + if (!recycling && shouldNotUpdate(vnode, old)) return if (typeof oldTag === "string") { + if (vnode.attrs != null) { + if (recycling) { + vnode.state = {} + initLifecycle(vnode.attrs, vnode, hooks) + } + else updateLifecycle(vnode.attrs, vnode, hooks) + } switch (oldTag) { case "#": updateText(old, vnode); break case "<": updateHTML(parent, old, vnode, nextSibling); break - case "[": updateFragment(parent, old, vnode, hooks, nextSibling, ns); break - default: updateElement(old, vnode, hooks, ns) + case "[": updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns); break + default: updateElement(old, vnode, recycling, hooks, ns) } } else updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) } else { removeNode(old, null) - insertNode(parent, createNode(vnode, hooks, ns), nextSibling) + createNode(parent, vnode, hooks, ns, nextSibling) } } function updateText(old, vnode) { @@ -235,12 +274,12 @@ module.exports = function($window) { function updateHTML(parent, old, vnode, nextSibling) { if (old.children !== vnode.children) { toFragment(old) - insertNode(parent, createHTML(vnode), nextSibling) + createHTML(parent, vnode, nextSibling) } else vnode.dom = old.dom, vnode.domSize = old.domSize } - function updateFragment(parent, old, vnode, hooks, nextSibling, ns) { - updateNodes(parent, old.children, vnode.children, hooks, nextSibling, ns) + function updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns) { + updateNodes(parent, old.children, vnode.children, recycling, hooks, nextSibling, ns) var domSize = 0, children = vnode.children vnode.dom = null if (children != null) { @@ -254,12 +293,10 @@ module.exports = function($window) { if (domSize !== 1) vnode.domSize = domSize } } - function updateElement(old, vnode, hooks, ns) { + function updateElement(old, vnode, recycling, hooks, ns) { var element = vnode.dom = old.dom - switch (vnode.tag) { - case "svg": ns = "http://www.w3.org/2000/svg"; break - case "math": ns = "http://www.w3.org/1998/Math/MathML"; break - } + ns = getNameSpace(vnode) || ns + if (vnode.tag === "textarea") { if (vnode.attrs == null) vnode.attrs = {} if (vnode.text != null) { @@ -277,14 +314,20 @@ module.exports = function($window) { else { 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)] - updateNodes(element, old.children, vnode.children, hooks, null, ns) + updateNodes(element, old.children, vnode.children, recycling, hooks, null, ns) } } function updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) { - vnode.instance = Vnode.normalize(vnode.tag.view.call(vnode.state, vnode)) - updateLifecycle(vnode.tag, vnode, hooks, recycling) + if (recycling) { + initComponent(vnode, hooks) + } else { + vnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode)) + 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 (old.instance == null) insertNode(parent, createNode(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) vnode.dom = vnode.instance.dom vnode.domSize = vnode.instance.domSize @@ -367,15 +410,15 @@ module.exports = function($window) { } function removeNode(vnode, context) { var expected = 1, called = 0 - if (vnode.attrs && vnode.attrs.onbeforeremove) { + if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") { var result = vnode.attrs.onbeforeremove.call(vnode.state, vnode) if (result != null && typeof result.then === "function") { expected++ result.then(continuation, continuation) } } - if (typeof vnode.tag !== "string" && vnode.tag.onbeforeremove) { - var result = vnode.tag.onbeforeremove.call(vnode.state, vnode) + if (typeof vnode.tag !== "string" && typeof vnode._state.onbeforeremove === "function") { + var result = vnode._state.onbeforeremove.call(vnode.state, vnode) if (result != null && typeof result.then === "function") { expected++ result.then(continuation, continuation) @@ -407,8 +450,8 @@ module.exports = function($window) { if (parent != null) parent.removeChild(node) } function onremove(vnode) { - if (vnode.attrs && vnode.attrs.onremove) vnode.attrs.onremove.call(vnode.state, vnode) - if (typeof vnode.tag !== "string" && vnode.tag.onremove) vnode.tag.onremove.call(vnode.state, vnode) + if (vnode.attrs && typeof vnode.attrs.onremove === "function") vnode.attrs.onremove.call(vnode.state, vnode) + if (typeof vnode.tag !== "string" && typeof vnode._state.onremove === "function") vnode._state.onremove.call(vnode.state, vnode) if (vnode.instance != null) onremove(vnode.instance) else { var children = vnode.children @@ -437,12 +480,26 @@ module.exports = function($window) { else if (key[0] === "o" && key[1] === "n" && typeof value === "function") updateEvent(vnode, key, value) else if (key === "style") updateStyle(element, old, value) 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 (vnode.tag === "input" && key === "value" && vnode.dom.value === value && vnode.dom === $doc.activeElement) return - //setting select[value] to same value while having select open blinks select dropdown in Chrome - if (vnode.tag === "select" && key === "value" && vnode.dom.value === value && vnode.dom === $doc.activeElement) return - //setting option[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 (key === "value") { + var normalized = "" + value // eslint-disable-line no-implicit-coercion + //setting input[value] to same value by typing on focused element moves cursor to end in Chrome + if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === normalized && vnode.dom === $doc.activeElement) return + //setting select[value] to same value while having select open blinks select dropdown in Chrome + 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 (vnode.tag === "input" && key === "type") { + element.setAttribute(key, value) + return + } element[key] = value } else { @@ -536,14 +593,13 @@ module.exports = function($window) { if (typeof source.oninit === "function") source.oninit.call(vnode.state, vnode) if (typeof source.oncreate === "function") hooks.push(source.oncreate.bind(vnode.state, vnode)) } - function updateLifecycle(source, vnode, hooks, recycling) { - if (recycling) initLifecycle(source, vnode, hooks) - else if (typeof source.onupdate === "function") hooks.push(source.onupdate.bind(vnode.state, vnode)) + function updateLifecycle(source, vnode, hooks) { + if (typeof source.onupdate === "function") hooks.push(source.onupdate.bind(vnode.state, vnode)) } - function shouldUpdate(vnode, old) { + function shouldNotUpdate(vnode, old) { var forceVnodeUpdate, forceComponentUpdate if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") forceVnodeUpdate = vnode.attrs.onbeforeupdate.call(vnode.state, vnode, old) - if (typeof vnode.tag !== "string" && typeof vnode.tag.onbeforeupdate === "function") forceComponentUpdate = vnode.tag.onbeforeupdate.call(vnode.state, vnode, old) + if (typeof vnode.tag !== "string" && typeof vnode._state.onbeforeupdate === "function") forceComponentUpdate = vnode._state.onbeforeupdate.call(vnode.state, vnode, old) if (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) { vnode.dom = old.dom vnode.domSize = old.domSize @@ -557,12 +613,13 @@ 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.") var hooks = [] var active = $doc.activeElement + var namespace = dom.namespaceURI // First time rendering into a node clears it out if (dom.vnodes == null) dom.textContent = "" if (!Array.isArray(vnodes)) vnodes = [vnodes] - updateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), hooks, null, undefined) + updateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), false, hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? undefined : namespace) dom.vnodes = vnodes for (var i = 0; i < hooks.length; i++) hooks[i]() if ($doc.activeElement !== active) active.focus() diff --git a/render/tests/index.html b/render/tests/index.html index 480b8b7c..eda51921 100644 --- a/render/tests/index.html +++ b/render/tests/index.html @@ -8,6 +8,7 @@ + diff --git a/render/tests/test-attributes.js b/render/tests/test-attributes.js index 2d08007b..fcc7f150 100644 --- a/render/tests/test-attributes.js +++ b/render/tests/test-attributes.js @@ -11,20 +11,60 @@ o.spec("attributes", function() { root = $window.document.body 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("when vnode is customElement, custom setAttribute called", function(){ - var normal = [ - { tag: "input", attrs: { value: 'hello' } }, - { tag: "input", attrs: { value: 'hello' } }, - { tag: "input", attrs: { value: 'hello' } } + var normal = [ + {tag: "input", attrs: {value: "hello"}}, + {tag: "input", attrs: {value: "hello"}}, + {tag: "input", attrs: {value: "hello"}} ] - + var custom = [ - { tag: "custom-element", attrs: { custom: 'x' } }, - { tag: "input", attrs: { is: 'something-special', custom: 'x' } }, - { tag: "custom-element", attrs: { is: 'something-special', custom: 'x' } } + {tag: "custom-element", attrs: {custom: "x"}}, + {tag: "input", attrs: {is: "something-special", custom: "x"}}, + {tag: "custom-element", attrs: {is: "something-special", custom: "x"}} ] var view = normal.concat(custom) @@ -43,8 +83,8 @@ o.spec("attributes", function() { } render(root, view) - - o(spy.callCount).equals( custom.length ) + + o(spy.callCount).equals(custom.length) }) }) @@ -54,7 +94,7 @@ o.spec("attributes", function() { 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() { var a = {tag: "input", attrs: {readonly: false}} @@ -96,6 +136,196 @@ o.spec("attributes", function() { 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("when link href is true, attribute is present", function() { var a = {tag: "a", attrs: {href: true}} @@ -118,7 +348,7 @@ o.spec("attributes", function() { 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) }) }) @@ -128,12 +358,223 @@ o.spec("attributes", function() { 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 the empty string", 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("") + o(a.dom.getAttribute("value")).equals("") + + render(root, [b]); + + o(b.dom.value).equals("test") + o(b.dom.getAttribute("value")).equals("test") + + render(root, [c]); + + o(c.dom.value).equals("") + o(c.dom.getAttribute("value")).equals("") + }) + 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: ""}} + ]} + } + 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("including text nodes", function() { - var div = {tag: "div", attrs: {contenteditable: true}, text: ''} + var div = {tag: "div", attrs: {contenteditable: true}, text: ""} var succeeded = false try { @@ -141,7 +582,7 @@ o.spec("attributes", function() { succeeded = true } - catch(e){} + catch(e){/* ignore */} o(succeeded).equals(false) }) @@ -154,7 +595,7 @@ o.spec("attributes", function() { succeeded = true } - catch(e){} + catch(e){/* ignore */} o(succeeded).equals(false) }) @@ -167,7 +608,7 @@ o.spec("attributes", function() { succeeded = true } - catch(e){} + catch(e){/* ignore */} o(succeeded).equals(true) }) @@ -180,7 +621,7 @@ o.spec("attributes", function() { succeeded = true } - catch(e){} + catch(e){/* ignore */} o(succeeded).equals(true) }) diff --git a/render/tests/test-component.js b/render/tests/test-component.js index 4bb0a3b6..c391ddd2 100644 --- a/render/tests/test-component.js +++ b/render/tests/test-component.js @@ -1,6 +1,7 @@ "use strict" var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var vdom = require("../../render/render") @@ -9,689 +10,1022 @@ o.spec("component", function() { o.beforeEach(function() { $window = domMock() root = $window.document.createElement("div") + render = vdom($window).render }) - o.spec("basics", function() { - o("works", function() { - var component = { - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - var node = {tag: component} + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create - render(root, [node]) + o.spec("basics", function() { + o("works", function() { + var component = createComponent({ + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + var node = {tag: component} - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("receives arguments", function() { - var component = { - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs, text: vnode.text} - } - } - var node = {tag: component, attrs: {id: "a"}, text: "b"} + render(root, [node]) - render(root, [node]) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("receives arguments", function() { + var component = createComponent({ + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs, text: vnode.text} + } + }) + var node = {tag: component, attrs: {id: "a"}, text: "b"} - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("updates", function() { - var component = { - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs, text: vnode.text} - } - } - render(root, [{tag: component, attrs: {id: "a"}, text: "b"}]) - render(root, [{tag: component, attrs: {id: "c"}, text: "d"}]) + render(root, [node]) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("c") - o(root.firstChild.firstChild.nodeValue).equals("d") - }) - o("updates root from null", function() { - var visible = false - var component = { - view: function(vnode) { - return visible ? {tag: "div"} : null - } - } - render(root, [{tag: component}]) - visible = true - render(root, [{tag: component}]) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("updates", function() { + var component = createComponent({ + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs, text: vnode.text} + } + }) + render(root, [{tag: component, attrs: {id: "a"}, text: "b"}]) + render(root, [{tag: component, attrs: {id: "c"}, text: "d"}]) - o(root.firstChild.nodeName).equals("DIV") - }) - o("updates root from primitive", function() { - var visible = false - var component = { - view: function(vnode) { - return visible ? {tag: "div"} : false - } - } - render(root, [{tag: component}]) - visible = true - render(root, [{tag: component}]) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("c") + o(root.firstChild.firstChild.nodeValue).equals("d") + }) + o("updates root from null", function() { + var visible = false + var component = createComponent({ + view: function() { + return visible ? {tag: "div"} : null + } + }) + render(root, [{tag: component}]) + visible = true + render(root, [{tag: component}]) - o(root.firstChild.nodeName).equals("DIV") - }) - o("updates root to null", function() { - var visible = true - var component = { - view: function(vnode) { - return visible ? {tag: "div"} : null - } - } - render(root, [{tag: component}]) - visible = false - render(root, [{tag: component}]) + o(root.firstChild.nodeName).equals("DIV") + }) + o("updates root from primitive", function() { + var visible = false + var component = createComponent({ + view: function() { + return visible ? {tag: "div"} : false + } + }) + render(root, [{tag: component}]) + visible = true + render(root, [{tag: component}]) - o(root.childNodes.length).equals(0) - }) - o("updates root to primitive", function() { - var visible = true - var component = { - view: function(vnode) { - return visible ? {tag: "div"} : false - } - } - render(root, [{tag: component}]) - visible = false - render(root, [{tag: component}]) + o(root.firstChild.nodeName).equals("DIV") + }) + o("updates root to null", function() { + var visible = true + var component = createComponent({ + view: function() { + return visible ? {tag: "div"} : null + } + }) + render(root, [{tag: component}]) + visible = false + render(root, [{tag: component}]) - o(root.firstChild.nodeValue).equals("") - }) - o("updates root from null to null", function() { - var component = { - view: function(vnode) { - return null - } - } - render(root, [{tag: component}]) - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(0) - }) - o("removes", function() { - var component = { - view: function(vnode) { - return {tag: "div"} - } - } - var div = {tag: "div", key: 2} - render(root, [{tag: component, key: 1}, div]) - render(root, [{tag: "div", key: 2}]) - - o(root.childNodes.length).equals(1) - o(root.firstChild).equals(div.dom) - }) - o("svg works when creating across component boundary", function() { - var component = { - view: function(vnode) { - return {tag: "g"} - } - } - render(root, [{tag: "svg", children: [{tag: component}]}]) - - o(root.firstChild.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") - }) - o("svg works when updating across component boundary", function() { - var component = { - view: function(vnode) { - return {tag: "g"} - } - } - render(root, [{tag: "svg", children: [{tag: component}]}]) - render(root, [{tag: "svg", children: [{tag: component}]}]) - - o(root.firstChild.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") - }) - }) - o.spec("return value", function() { - o("can return fragments", function() { - var component = { - view: function(vnode) { - return [ - {tag: "label"}, - {tag: "input"}, - ] - } - } - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(2) - o(root.childNodes[0].nodeName).equals("LABEL") - o(root.childNodes[1].nodeName).equals("INPUT") - }) - o("can return string", function() { - var component = { - view: function(vnode) { - return "a" - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("a") - }) - o("can return falsy string", function() { - var component = { - view: function(vnode) { - return "" - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("") - }) - o("can return number", function() { - var component = { - view: function(vnode) { - return 1 - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("1") - }) - o("can return falsy number", function() { - var component = { - view: function(vnode) { - return 0 - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("0") - }) - o("can return boolean", function() { - var component = { - view: function(vnode) { - return true - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("true") - }) - o("can return falsy boolean", function() { - var component = { - view: function(vnode) { - return false - } - } - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("") - }) - o("can return null", function() { - var component = { - view: function(vnode) { - return null - } - } - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(0) - }) - o("can return undefined", function() { - var component = { - view: function(vnode) { - return undefined - } - } - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(0) - }) - o("throws a custom error if it returns itself", function() { - // A view that returns its vnode would otherwise trigger an infinite loop - var component = { - view: function(vnode) { - return vnode - } - } - try { - render(root, [{tag: component}]) - } - catch (e) { - o(e instanceof Error).equals(true) - // Call stack exception is a RangeError - o(e instanceof RangeError).equals(false) - } - }) - o("can update when returning fragments", function() { - var component = { - view: function(vnode) { - return [ - {tag: "label"}, - {tag: "input"}, - ] - } - } - render(root, [{tag: component}]) - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(2) - o(root.childNodes[0].nodeName).equals("LABEL") - o(root.childNodes[1].nodeName).equals("INPUT") - }) - o("can update when returning primitive", function() { - var component = { - view: function(vnode) { - return "a" - } - } - render(root, [{tag: component}]) - render(root, [{tag: component}]) - - o(root.firstChild.nodeType).equals(3) - o(root.firstChild.nodeValue).equals("a") - }) - o("can update when returning null", function() { - var component = { - view: function(vnode) { - return null - } - } - render(root, [{tag: component}]) - render(root, [{tag: component}]) - - o(root.childNodes.length).equals(0) - }) - o("can remove when returning fragments", function() { - var component = { - view: function(vnode) { - return [ - {tag: "label"}, - {tag: "input"}, - ] - } - } - var div = {tag: "div", key: 2} - render(root, [{tag: component, key: 1}, div]) - - render(root, [{tag: "div", key: 2}]) - - o(root.childNodes.length).equals(1) - o(root.firstChild).equals(div.dom) - }) - o("can remove when returning primitive", function() { - var component = { - view: function(vnode) { - return "a" - } - } - var div = {tag: "div", key: 2} - render(root, [{tag: component, key: 1}, div]) - - render(root, [{tag: "div", key: 2}]) - - o(root.childNodes.length).equals(1) - o(root.firstChild).equals(div.dom) - }) - }) - o.spec("lifecycle", function() { - o("calls oninit", function() { - var called = 0 - var component = { - oninit: function(vnode) { - called++ - - o(vnode.tag).equals(component) - o(vnode.dom).equals(undefined) o(root.childNodes.length).equals(0) - }, - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - var node = {tag: component} + }) + o("updates root to primitive", function() { + var visible = true + var component = createComponent({ + view: function() { + return visible ? {tag: "div"} : false + } + }) + render(root, [{tag: component}]) + visible = false + render(root, [{tag: component}]) - render(root, [node]) + o(root.firstChild.nodeValue).equals("") + }) + o("updates root from null to null", function() { + var component = createComponent({ + view: function() { + return null + } + }) + render(root, [{tag: component}]) + render(root, [{tag: component}]) - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("calls oninit when returning fragment", function() { - var called = 0 - var component = { - oninit: function(vnode) { - called++ - - o(vnode.tag).equals(component) - o(vnode.dom).equals(undefined) o(root.childNodes.length).equals(0) - }, - view: function() { - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - } - } - var node = {tag: component} + }) + o("removes", function() { + var component = createComponent({ + view: function() { + return {tag: "div"} + } + }) + var div = {tag: "div", key: 2} + render(root, [{tag: component, key: 1}, div]) + render(root, [{tag: "div", key: 2}]) - render(root, [node]) + o(root.childNodes.length).equals(1) + o(root.firstChild).equals(div.dom) + }) + o("svg works when creating across component boundary", function() { + var component = createComponent({ + view: function() { + return {tag: "g"} + } + }) + render(root, [{tag: "svg", children: [{tag: component}]}]) - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("calls oninit before view", function() { - var viewCalled = false + o(root.firstChild.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") + }) + o("svg works when updating across component boundary", function() { + var component = createComponent({ + view: function() { + return {tag: "g"} + } + }) + render(root, [{tag: "svg", children: [{tag: component}]}]) + render(root, [{tag: "svg", children: [{tag: component}]}]) - render(root, { - tag: { - view: function() { - viewCalled = true - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - }, - oninit: function(vnode) { - o(viewCalled).equals(false) - }, - } + o(root.firstChild.firstChild.namespaceURI).equals("http://www.w3.org/2000/svg") + }) + }) + o.spec("return value", function() { + o("can return fragments", function() { + var component = createComponent({ + view: function() { + return [ + {tag: "label"}, + {tag: "input"}, + ] + } + }) + render(root, [{tag: component}]) + + o(root.childNodes.length).equals(2) + o(root.childNodes[0].nodeName).equals("LABEL") + o(root.childNodes[1].nodeName).equals("INPUT") + }) + o("can return string", function() { + var component = createComponent({ + view: function() { + return "a" + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("a") + }) + o("can return falsy string", function() { + var component = createComponent({ + view: function() { + return "" + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("") + }) + o("can return number", function() { + var component = createComponent({ + view: function() { + return 1 + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("1") + }) + o("can return falsy number", function() { + var component = createComponent({ + view: function() { + return 0 + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("0") + }) + o("can return boolean", function() { + var component = createComponent({ + view: function() { + return true + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("true") + }) + o("can return falsy boolean", function() { + var component = createComponent({ + view: function() { + return false + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("") + }) + o("can return null", function() { + var component = createComponent({ + view: function() { + return null + } + }) + render(root, [{tag: component}]) + + o(root.childNodes.length).equals(0) + }) + o("can return undefined", function() { + var component = createComponent({ + view: function() { + return undefined + } + }) + render(root, [{tag: component}]) + + o(root.childNodes.length).equals(0) + }) + o("throws a custom error if it returns itself when created", function() { + // A view that returns its vnode would otherwise trigger an infinite loop + var threw = false + var component = createComponent({ + view: function(vnode) { + return vnode + } + }) + try { + render(root, [{tag: component}]) + } + catch (e) { + threw = true + o(e instanceof Error).equals(true) + // Call stack exception is a RangeError + o(e instanceof RangeError).equals(false) + } + o(threw).equals(true) + }) + o("throws a custom error if it returns itself when updated", function() { + // A view that returns its vnode would otherwise trigger an infinite loop + var threw = false + var init = true + var oninit = o.spy() + var component = createComponent({ + oninit: oninit, + view: function(vnode) { + if (init) return init = false + else return vnode + } + }) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("") + + try { + render(root, [{tag: component}]) + } + catch (e) { + threw = true + o(e instanceof Error).equals(true) + // Call stack exception is a RangeError + o(e instanceof RangeError).equals(false) + } + o(threw).equals(true) + o(oninit.callCount).equals(1) + }) + o("can update when returning fragments", function() { + var component = createComponent({ + view: function() { + return [ + {tag: "label"}, + {tag: "input"}, + ] + } + }) + render(root, [{tag: component}]) + render(root, [{tag: component}]) + + o(root.childNodes.length).equals(2) + o(root.childNodes[0].nodeName).equals("LABEL") + o(root.childNodes[1].nodeName).equals("INPUT") + }) + o("can update when returning primitive", function() { + var component = createComponent({ + view: function() { + return "a" + } + }) + render(root, [{tag: component}]) + render(root, [{tag: component}]) + + o(root.firstChild.nodeType).equals(3) + o(root.firstChild.nodeValue).equals("a") + }) + o("can update when returning null", function() { + var component = createComponent({ + view: function() { + return null + } + }) + render(root, [{tag: component}]) + render(root, [{tag: component}]) + + o(root.childNodes.length).equals(0) + }) + o("can remove when returning fragments", function() { + var component = createComponent({ + view: function() { + return [ + {tag: "label"}, + {tag: "input"}, + ] + } + }) + var div = {tag: "div", key: 2} + render(root, [{tag: component, key: 1}, div]) + + render(root, [{tag: "div", key: 2}]) + + o(root.childNodes.length).equals(1) + o(root.firstChild).equals(div.dom) + }) + o("can remove when returning primitive", function() { + var component = createComponent({ + view: function() { + return "a" + } + }) + var div = {tag: "div", key: 2} + render(root, [{tag: component, key: 1}, div]) + + render(root, [{tag: "div", key: 2}]) + + o(root.childNodes.length).equals(1) + o(root.firstChild).equals(div.dom) + }) + }) + o.spec("lifecycle", function() { + o("calls oninit", function() { + var called = 0 + var component = createComponent({ + oninit: function(vnode) { + called++ + + o(vnode.tag).equals(component) + o(vnode.dom).equals(undefined) + o(root.childNodes.length).equals(0) + }, + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + var node = {tag: component} + + render(root, [node]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("calls oninit when returning fragment", function() { + var called = 0 + var component = createComponent({ + oninit: function(vnode) { + called++ + + o(vnode.tag).equals(component) + o(vnode.dom).equals(undefined) + o(root.childNodes.length).equals(0) + }, + view: function() { + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + } + }) + var node = {tag: component} + + render(root, [node]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("calls oninit before view", function() { + var viewCalled = false + + render(root, createComponent({ + tag: { + view: function() { + viewCalled = true + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + }, + oninit: function() { + o(viewCalled).equals(false) + }, + } + })) + }) + o("does not calls oninit on redraw", function() { + var init = o.spy() + var component = createComponent({ + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + }, + oninit: init, + }) + + function view() { + return {tag: component} + } + + render(root, view()) + render(root, view()) + + o(init.callCount).equals(1) + }) + o("calls oncreate", function() { + var called = 0 + var component = createComponent({ + oncreate: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + var node = {tag: component} + + render(root, [node]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("does not calls oncreate on redraw", function() { + var create = o.spy() + var component = createComponent({ + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + }, + oncreate: create, + }) + + function view() { + return {tag: component} + } + + render(root, view()) + render(root, view()) + + o(create.callCount).equals(1) + }) + o("calls oncreate when returning fragment", function() { + var called = 0 + var component = createComponent({ + oncreate: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + } + }) + var node = {tag: component} + + render(root, [node]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("calls onupdate", function() { + var called = 0 + var component = createComponent({ + onupdate: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, [{tag: component}]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("calls onupdate when returning fragment", function() { + var called = 0 + var component = createComponent({ + onupdate: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, [{tag: component}]) + + o(called).equals(1) + o(root.firstChild.nodeName).equals("DIV") + o(root.firstChild.attributes["id"].value).equals("a") + o(root.firstChild.firstChild.nodeValue).equals("b") + }) + o("calls onremove", function() { + var called = 0 + var component = createComponent({ + onremove: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, []) + + o(called).equals(1) + o(root.childNodes.length).equals(0) + }) + o("calls onremove when returning fragment", function() { + var called = 0 + var component = createComponent({ + onremove: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, []) + + o(called).equals(1) + o(root.childNodes.length).equals(0) + }) + o("calls onbeforeremove", function() { + var called = 0 + var component = createComponent({ + onbeforeremove: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return {tag: "div", attrs: {id: "a"}, text: "b"} + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, []) + + o(called).equals(1) + o(root.childNodes.length).equals(0) + }) + o("calls onbeforeremove when returning fragment", function() { + var called = 0 + var component = createComponent({ + onbeforeremove: function(vnode) { + called++ + + o(vnode.dom).notEquals(undefined) + o(vnode.dom).equals(root.firstChild) + o(root.childNodes.length).equals(1) + }, + view: function() { + return [{tag: "div", attrs: {id: "a"}, text: "b"}] + } + }) + + render(root, [{tag: component}]) + + o(called).equals(0) + + render(root, []) + + o(called).equals(1) + o(root.childNodes.length).equals(0) + }) + o("does not recycle when there's an onupdate", function() { + var component = createComponent({ + onupdate: function() {}, + view: function() { + return {tag: "div"} + } + }) + var vnode = {tag: component, key: 1} + var updated = {tag: component, key: 1} + + render(root, [vnode]) + render(root, []) + render(root, [updated]) + + o(vnode.dom).notEquals(updated.dom) + }) + o("lifecycle timing megatest (for a single component)", function() { + var methods = { + view: o.spy(function() { + 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() { + o(attrs[hook].callCount).equals(methods[hook].callCount + 1) + }) + methods[hook] = o.spy(function() { + o(attrs[hook].callCount).equals(methods[hook].callCount) + }) + }) + + 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("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(){ + var methods = { + view: o.spy(function(vnode) { + o(this).equals(vnode.state) + return "" + }) + } + var attrs = {} + var hooks = [ + "oninit", "oncreate", "onbeforeupdate", + "onupdate", "onbeforeremove", "onremove" + ] + hooks.forEach(function(hook) { + attrs[hook] = o.spy(function(vnode){ + o(this).equals(vnode.state)(hook) + }) + methods[hook] = o.spy(function(vnode){ + o(this).equals(vnode.state) + }) + }) + + var component = createComponent(methods) + + render(root, [{tag: component, attrs: attrs}]) + render(root, [{tag: component, attrs: attrs}]) + render(root, []) + + hooks.forEach(function(hook) { + o(attrs[hook].this).equals(methods.view.this)(hook) + o(methods[hook].this).equals(methods.view.this)(hook) + }) + + o(methods.view.args.length).equals(1) + o(methods.oninit.args.length).equals(1) + o(methods.oncreate.args.length).equals(1) + o(methods.onbeforeupdate.args.length).equals(2) + o(methods.onupdate.args.length).equals(1) + o(methods.onbeforeremove.args.length).equals(1) + o(methods.onremove.args.length).equals(1) + + hooks.forEach(function(hook) { + o(methods[hook].args.length).equals(attrs[hook].args.length)(hook) + }) + }) + o("recycled components get a fresh state", function() { + var step = 0 + var firstState + var view = o.spy(function(vnode) { + if (step === 0) { + firstState = vnode.state + } else { + o(vnode.state).notEquals(firstState) + } + return {tag: "div"} + }) + var component = createComponent({view: view}) + + render(root, [{tag: "div", children: [{tag: component, key: 1}]}]) + var child = root.firstChild.firstChild + render(root, []) + step = 1 + render(root, [{tag: "div", children: [{tag: component, key: 1}]}]) + + o(child).equals(root.firstChild.firstChild) + o(view.callCount).equals(2) + }) + }) + o.spec("state", function() { + o("initializes state", function() { + var data = {a: 1} + var component = createComponent(createComponent({ + data: data, + oninit: init, + view: function() { + return "" + } + })) + + render(root, [{tag: component}]) + + function init(vnode) { + o(vnode.state.data).equals(data) + } + }) + o("state proxies to the component object/prototype", function() { + var body = {a: 1} + var data = [body] + var component = createComponent(createComponent({ + data: data, + oninit: init, + view: function() { + return "" + } + })) + + render(root, [{tag: component}]) + + function init(vnode) { + o(vnode.state.data).equals(data) + o(vnode.state.data[0]).equals(body) + } + }) }) }) - o("does not calls oninit on redraw", function() { - var init = o.spy() - var component = { - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - }, - oninit: init, - } - - function view() { - return {tag: component} - } - - render(root, view()) - render(root, view()) - - o(init.callCount).equals(1) - }) - o("calls oncreate", function() { - var called = 0 - var component = { - oncreate: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - var node = {tag: component} - - render(root, [node]) - - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("does not calls oncreate on redraw", function() { - var create = o.spy() - var component = { - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - }, - oncreate: create, - } - - function view() { - return {tag: component} - } - - render(root, view()) - render(root, view()) - - o(create.callCount).equals(1) - }) - o("calls oncreate when returning fragment", function() { - var called = 0 - var component = { - oncreate: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - } - } - var node = {tag: component} - - render(root, [node]) - - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("calls onupdate", function() { - var called = 0 - var component = { - onupdate: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, [{tag: component}]) - - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("calls onupdate when returning fragment", function() { - var called = 0 - var component = { - onupdate: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, [{tag: component}]) - - o(called).equals(1) - o(root.firstChild.nodeName).equals("DIV") - o(root.firstChild.attributes["id"].nodeValue).equals("a") - o(root.firstChild.firstChild.nodeValue).equals("b") - }) - o("calls onremove", function() { - var called = 0 - var component = { - onremove: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, []) - - o(called).equals(1) - o(root.childNodes.length).equals(0) - }) - o("calls onremove when returning fragment", function() { - var called = 0 - var component = { - onremove: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, []) - - o(called).equals(1) - o(root.childNodes.length).equals(0) - }) - o("calls onbeforeremove", function() { - var called = 0 - var component = { - onbeforeremove: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return {tag: "div", attrs: {id: "a"}, text: "b"} - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, []) - - o(called).equals(1) - o(root.childNodes.length).equals(0) - }) - o("calls onbeforeremove when returning fragment", function() { - var called = 0 - var component = { - onbeforeremove: function(vnode) { - called++ - - o(vnode.dom).notEquals(undefined) - o(vnode.dom).equals(root.firstChild) - o(root.childNodes.length).equals(1) - }, - view: function() { - return [{tag: "div", attrs: {id: "a"}, text: "b"}] - } - } - - render(root, [{tag: component}]) - - o(called).equals(0) - - render(root, []) - - o(called).equals(1) - o(root.childNodes.length).equals(0) - }) - o("does not recycle when there's an onupdate", function() { - var component = { - onupdate: function() {}, - view: function() { - return {tag: "div"} - } - } - var update = o.spy() - var vnode = {tag: component, key: 1} - var updated = {tag: component, key: 1} - - render(root, [vnode]) - render(root, []) - render(root, [updated]) - - o(vnode.dom).notEquals(updated.dom) - }) }) - o.spec("state", function() { - o("copies state", function() { - var called = 0 - var data = {a: 1} - var component = { - data: data, - oninit: init, - view: function() { - return "" + o.spec("Tests specific to certain component kinds", function() { + o.spec("state", function() { + o("POJO", function() { + var data = {} + var component = { + data: data, + oninit: init, + view: function() { + return "" + } } - } - render(root, [{tag: component}]) + render(root, [{tag: component}]) - function init(vnode) { - o(vnode.state.data).deepEquals(data) - o(vnode.state.data).equals(data) + function init(vnode) { + o(vnode.state.data).equals(data) - //inherits state via prototype - component.x = 1 - o(vnode.state.x).equals(1) - } - }) - o("state copy is shallow", function() { - var called = 0 - var body = {a: 1} - var data = [body] - var component = { - data: data, - oninit: init, - view: function() { - return "" + //inherits state via prototype + component.x = 1 + o(vnode.state.x).equals(1) } - } + }) + o("Constructible", function() { + var oninit = o.spy() + var component = o.spy(function(vnode){ + o(vnode.state).equals(undefined) + o(oninit.callCount).equals(0) + }) + var view = o.spy(function(){ + o(this instanceof component).equals(true) + return "" + }) + component.prototype.view = view + component.prototype.oninit = oninit - render(root, [{tag: component}]) + render(root, [{tag: component, attrs: {oninit: oninit}}]) + render(root, [{tag: component, attrs: {oninit: oninit}}]) + render(root, []) - function init(vnode) { - o(vnode.state.data).equals(data) - o(vnode.state.data[0]).equals(body) - } + o(component.callCount).equals(1) + o(oninit.callCount).equals(2) + o(view.callCount).equals(2) + }) + o("Closure", function() { + var state + var oninit = o.spy() + var view = o.spy(function() { + o(this).equals(state) + return "" + }) + var component = o.spy(function(vnode) { + o(vnode.state).equals(undefined) + o(oninit.callCount).equals(0) + return state = { + view: view + } + }) + + render(root, [{tag: component, attrs: {oninit: oninit}}]) + render(root, [{tag: component, attrs: {oninit: oninit}}]) + render(root, []) + + o(component.callCount).equals(1) + o(oninit.callCount).equals(1) + o(view.callCount).equals(2) + }) }) }) }) diff --git a/render/tests/test-createElement.js b/render/tests/test-createElement.js index 31599cfd..6e3dcdd7 100644 --- a/render/tests/test-createElement.js +++ b/render/tests/test-createElement.js @@ -1,3 +1,4 @@ +/* eslint-disable no-script-url */ "use strict" var o = require("../../ospec/ospec") @@ -23,8 +24,8 @@ o.spec("createElement", function() { render(root, [vnode]) o(vnode.dom.nodeName).equals("DIV") - o(vnode.dom.attributes["id"].nodeValue).equals("a") - o(vnode.dom.attributes["title"].nodeValue).equals("b") + o(vnode.dom.attributes["id"].value).equals("a") + o(vnode.dom.attributes["title"].value).equals("b") }) o("creates style", function() { var vnode = {tag: "div", attrs: {style: {backgroundColor: "red"}}} @@ -47,28 +48,34 @@ o.spec("createElement", function() { render(root, [vnode]) o(vnode.dom.nodeName).equals("DIV") - o(vnode.dom.attributes["id"].nodeValue).equals("a") - o(vnode.dom.attributes["title"].nodeValue).equals("b") + o(vnode.dom.attributes["id"].value).equals("a") + o(vnode.dom.attributes["title"].value).equals("b") o(vnode.dom.childNodes.length).equals(2) o(vnode.dom.childNodes[0].nodeName).equals("A") o(vnode.dom.childNodes[1].nodeName).equals("B") }) 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]) o(vnode.dom.nodeName).equals("svg") o(vnode.dom.namespaceURI).equals("http://www.w3.org/2000/svg") o(vnode.dom.firstChild.nodeName).equals("a") 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["href"].value).equals("javascript:;") o(vnode.dom.firstChild.attributes["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() { var vnode = {tag: "svg", ns: "http://www.w3.org/2000/svg", attrs: {viewBox: "0 0 100 100"}} 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("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"}]} diff --git a/render/tests/test-event.js b/render/tests/test-event.js index 31d2d012..1f7eec2a 100644 --- a/render/tests/test-event.js +++ b/render/tests/test-event.js @@ -69,7 +69,7 @@ o.spec("event", function() { 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"].nodeValue).equals("b") + o(div.dom.attributes["id"].value).equals("b") }) o("handles ontransitionend", function() { diff --git a/render/tests/test-hyperscript.js b/render/tests/test-hyperscript.js index 32e767d8..498a9dbf 100644 --- a/render/tests/test-hyperscript.js +++ b/render/tests/test-hyperscript.js @@ -1,3 +1,5 @@ +"use strict" + var o = require("../../ospec/ospec") var m = require("../../render/hyperscript") @@ -14,6 +16,95 @@ o.spec("hyperscript", function() { o(vnode.tag).equals("a") }) + o("v1.0.1 bug-for-bug regression suite", function(){ + o(m("a", { + class: null + }).attrs).deepEquals({ + class: undefined, + className: null + }) + o(m("a", { + class: undefined + }).attrs).deepEquals({ + class: undefined, + }) + o(m("a", { + class: false + }).attrs).deepEquals({ + class: undefined, + className: false + }) + o(m("a", { + class: true + }).attrs).deepEquals({ + class: undefined, + className: true + }) + o(m("a.x", { + class: null + }).attrs).deepEquals({ + class: undefined, + className: "x null" + }) + o(m("a.x", { + class: undefined + }).attrs).deepEquals({ + class: undefined, + className: "x" + }) + o(m("a.x", { + class: false + }).attrs).deepEquals({ + class: undefined, + className: "x false" + }) + o(m("a.x", { + class: true + }).attrs).deepEquals({ + class: undefined, + className: "x true" + }) + o(m("a", { + className: null + }).attrs).deepEquals({ + className: null + }) + o(m("a", { + className: undefined + }).attrs).deepEquals({ + className: undefined + }) + o(m("a", { + className: false + }).attrs).deepEquals({ + className: false + }) + o(m("a", { + className: true + }).attrs).deepEquals({ + className: true + }) + o(m("a.x", { + className: null + }).attrs).deepEquals({ + className: "x" + }) + o(m("a.x", { + className: undefined + }).attrs).deepEquals({ + className: "x" + }) + o(m("a.x", { + className: false + }).attrs).deepEquals({ + className: "x" + }) + o(m("a.x", { + className: true + }).attrs).deepEquals({ + className: "x true" + }) + }) o("handles class in selector", function() { var vnode = m(".a") @@ -127,6 +218,18 @@ o.spec("hyperscript", function() { o(vnode.tag).equals("div") 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("handles string attr", function() { @@ -271,6 +374,11 @@ o.spec("hyperscript", function() { o(vnode.children[0]).equals(null) o(vnode.children[1]).equals(undefined) }) + o("handles falsy number single child without attrs", function() { + var vnode = m("div", 0) + + o(vnode.text).equals(0) + }) }) o.spec("permutations", function() { o("handles null attr and children", function() { @@ -424,7 +532,7 @@ o.spec("hyperscript", function() { }) }) o.spec("components", function() { - o("works", function() { + o("works with POJOs", function() { var component = { view: function() { return m("div") @@ -432,6 +540,19 @@ o.spec("hyperscript", function() { } var vnode = m(component, {id: "a"}, "b") + o(vnode.tag).equals(component) + o(vnode.attrs.id).equals("a") + o(vnode.children.length).equals(1) + o(vnode.children[0].tag).equals("#") + o(vnode.children[0].children).equals("b") + }) + o("works with functions", function() { + var component = o.spy() + + var vnode = m(component, {id: "a"}, "b") + + o(component.callCount).equals(0) + o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) diff --git a/render/tests/test-input.js b/render/tests/test-input.js index 73eecf1e..d61bad54 100644 --- a/render/tests/test-input.js +++ b/render/tests/test-input.js @@ -80,6 +80,57 @@ o.spec("form inputs", function() { 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() { var select = {tag: "select", attrs: {value: "a"}} diff --git a/render/tests/test-onbeforeremove.js b/render/tests/test-onbeforeremove.js index c9af4894..0e83d4a0 100644 --- a/render/tests/test-onbeforeremove.js +++ b/render/tests/test-onbeforeremove.js @@ -2,6 +2,7 @@ var o = require("../../ospec/ospec") var callAsync = require("../../test-utils/callAsync") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var vdom = require("../../render/render") var Promise = require("../../promise/promise") @@ -16,7 +17,6 @@ o.spec("onbeforeremove", function() { o("does not call onbeforeremove when creating", function() { var create = o.spy() - var update = o.spy() var vnode = {tag: "div", attrs: {onbeforeremove: create}} render(root, [vnode]) @@ -141,7 +141,7 @@ o.spec("onbeforeremove", function() { o(vnode.dom.attributes["onbeforeremove"]).equals(undefined) }) o("does not recycle when there's an onbeforeremove", function() { - var remove = function(vnode) {} + var remove = function() {} var vnode = {tag: "div", key: 1, attrs: {onbeforeremove: remove}} var updated = {tag: "div", key: 1, attrs: {onbeforeremove: remove}} @@ -152,7 +152,7 @@ o.spec("onbeforeremove", function() { o(vnode.dom).notEquals(updated.dom) }) o("does not leave elements out of order during removal", function(done) { - var remove = function(vnode) {return Promise.resolve()} + var remove = function() {return Promise.resolve()} var vnodes = [{tag: "div", key: 1, attrs: {onbeforeremove: remove}, text: "1"}, {tag: "div", key: 2, attrs: {onbeforeremove: remove}, text: "2"}] var updated = {tag: "div", key: 2, attrs: {onbeforeremove: remove}, text: "2"} @@ -169,39 +169,43 @@ o.spec("onbeforeremove", function() { done() }) }) - o("finalizes the remove phase asynchronously when promise is returned synchronously from both attrs- and tag.onbeforeremove", function(done) { - var onremove = o.spy() - var onbeforeremove = function(){return Promise.resolve()} - var component = { - onbeforeremove: onbeforeremove, - onremove: onremove, - view: function() {}, - } - render(root, [{tag: component, attrs: {onbeforeremove: onbeforeremove, onremove: onremove}}]) - render(root, []) - callAsync(function() { - o(onremove.callCount).equals(2) // once for `tag`, once for `attrs` - done() - }) - }) - o("awaits promise resolution before removing the node", function(done) { - var view = o.spy() - var onremove = o.spy() - var onbeforeremove = function(){return new Promise(function(resolve){callAsync(resolve)})} - var component = { - onbeforeremove: onbeforeremove, - onremove: onremove, - view: view, - } - render(root, [{tag: component}]) - render(root, []) + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create + o("finalizes the remove phase asynchronously when promise is returned synchronously from both attrs- and tag.onbeforeremove", function(done) { + var onremove = o.spy() + var onbeforeremove = function(){return Promise.resolve()} + var component = createComponent({ + onbeforeremove: onbeforeremove, + onremove: onremove, + view: function() {}, + }) + render(root, [{tag: component, attrs: {onbeforeremove: onbeforeremove, onremove: onremove}}]) + render(root, []) + callAsync(function() { + o(onremove.callCount).equals(2) // once for `tag`, once for `attrs` + done() + }) + }) + o("awaits promise resolution before removing the node", function(done) { + var view = o.spy() + var onremove = o.spy() + var onbeforeremove = function(){return new Promise(function(resolve){callAsync(resolve)})} + var component = createComponent({ + onbeforeremove: onbeforeremove, + onremove: onremove, + view: view, + }) + render(root, [{tag: component}]) + render(root, []) - callAsync(function(){ - o(onremove.callCount).equals(0) - - callAsync(function() { - o(onremove.callCount).equals(1) - done() + o(onremove.callCount).equals(0) + callAsync(function(){ + callAsync(function() { + o(onremove.callCount).equals(1) + done() + }) + }) }) }) }) diff --git a/render/tests/test-onbeforeupdate.js b/render/tests/test-onbeforeupdate.js index 8b326b8c..d8b2f2d6 100644 --- a/render/tests/test-onbeforeupdate.js +++ b/render/tests/test-onbeforeupdate.js @@ -1,6 +1,7 @@ "use strict" var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var vdom = require("../../render/render") @@ -20,7 +21,7 @@ o.spec("onbeforeupdate", function() { render(root, [vnode]) 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() { @@ -56,86 +57,6 @@ o.spec("onbeforeupdate", function() { o(root.firstChild.nodeValue).equals("a") }) - o("prevents update in component", function() { - var component = { - onbeforeupdate: function() {return false}, - view: function(vnode) { - return {tag: "div", children: vnode.children} - }, - } - var vnode = {tag: component, children: [{tag: "#", children: "a"}]} - var updated = {tag: component, children: [{tag: "#", children: "b"}]} - - render(root, [vnode]) - render(root, [updated]) - - o(root.firstChild.firstChild.nodeValue).equals("a") - }) - - o("prevents update if returning false in component and false in vnode", function() { - var component = { - onbeforeupdate: function() {return false}, - view: function(vnode) { - return {tag: "div", attrs: {id: vnode.attrs.id}} - }, - } - var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return false}}} - var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return false}}} - - render(root, [vnode]) - render(root, [updated]) - - o(root.firstChild.attributes["id"].nodeValue).equals("a") - }) - - o("does not prevent update if returning true in component and true in vnode", function() { - var component = { - onbeforeupdate: function() {return true}, - view: function(vnode) { - return {tag: "div", attrs: {id: vnode.attrs.id}} - }, - } - var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return true}}} - var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return true}}} - - render(root, [vnode]) - render(root, [updated]) - - o(root.firstChild.attributes["id"].nodeValue).equals("b") - }) - - o("does not prevent update if returning false in component but true in vnode", function() { - var component = { - onbeforeupdate: function() {return false}, - view: function(vnode) { - return {tag: "div", attrs: {id: vnode.attrs.id}} - }, - } - var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return true}}} - var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return true}}} - - render(root, [vnode]) - render(root, [updated]) - - o(root.firstChild.attributes["id"].nodeValue).equals("b") - }) - - o("does not prevent update if returning true in component but false in vnode", function() { - var component = { - onbeforeupdate: function() {return true}, - view: function(vnode) { - return {tag: "div", attrs: {id: vnode.attrs.id}} - }, - } - var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return false}}} - var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return false}}} - - render(root, [vnode]) - render(root, [updated]) - - o(root.firstChild.attributes["id"].nodeValue).equals("b") - }) - o("does not prevent update if returning true", function() { var onbeforeupdate = function() {return true} var vnode = {tag: "div", attrs: {id: "a", onbeforeupdate: onbeforeupdate}} @@ -144,23 +65,7 @@ o.spec("onbeforeupdate", function() { render(root, [vnode]) render(root, [updated]) - o(root.firstChild.attributes["id"].nodeValue).equals("b") - }) - - o("does not prevent update if returning true from component", function() { - var component = { - onbeforeupdate: function() {return true}, - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs} - }, - } - var vnode = {tag: component, attrs: {id: "a"}} - var updated = {tag: component, attrs: {id: "b"}} - - render(root, [vnode]) - 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() { @@ -181,66 +86,16 @@ o.spec("onbeforeupdate", function() { } o(count).equals(1) - o(root.firstChild.attributes["id"].nodeValue).equals("b") - }) - - o("accepts arguments for comparison in component", function() { - var component = { - onbeforeupdate: onbeforeupdate, - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs} - }, - } - var count = 0 - var vnode = {tag: component, attrs: {id: "a"}} - var updated = {tag: component, attrs: {id: "b"}} - - render(root, [vnode]) - render(root, [updated]) - - function onbeforeupdate(vnode, old) { - count++ - - o(old.attrs.id).equals("a") - o(vnode.attrs.id).equals("b") - - return old.attrs.id !== vnode.attrs.id - } - - 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() { var count = 0 var vnode = {tag: "div", attrs: {id: "a", onbeforeupdate: onbeforeupdate}} - var updated = {tag: "div", attrs: {id: "b", onbeforeupdate: onbeforeupdate}} render(root, [vnode]) - function onbeforeupdate(vnode, old) { - count++ - return true - } - - o(count).equals(0) - }) - - o("is not called on component creation", function() { - var component = { - onbeforeupdate: onbeforeupdate, - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs} - }, - } - - var count = 0 - var vnode = {tag: "div", attrs: {id: "a"}} - var updated = {tag: "div", attrs: {id: "b"}} - - render(root, [vnode]) - - function onbeforeupdate(vnode, old) { + function onbeforeupdate() { count++ return true } @@ -256,7 +111,7 @@ o.spec("onbeforeupdate", function() { render(root, [vnode]) render(root, [updated]) - function onbeforeupdate(vnode, old) { + function onbeforeupdate() { count++ return true } @@ -264,26 +119,191 @@ o.spec("onbeforeupdate", function() { o(count).equals(1) }) - o("is called only once on component update", function() { - var component = { - onbeforeupdate: onbeforeupdate, - view: function(vnode) { - return {tag: "div", attrs: vnode.attrs} - }, - } + o("doesn't fire on recycled nodes", function() { + var onbeforeupdate = o.spy() + var vnodes = [{tag: "div", key: 1}] + var temp = [] + var updated = [{tag: "div", key: 1, attrs: {onbeforeupdate: onbeforeupdate}}] - var count = 0 - var vnode = {tag: component, attrs: {id: "a"}} - var updated = {tag: component, attrs: {id: "b"}} + render(root, vnodes) + render(root, temp) + render(root, updated) - render(root, [vnode]) - render(root, [updated]) + o(vnodes[0].dom).equals(updated[0].dom) + o(updated[0].dom.nodeName).equals("DIV") + o(onbeforeupdate.callCount).equals(0) + }) - function onbeforeupdate(vnode, old) { - count++ - return true - } + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create - o(count).equals(1) + o("prevents update in component", function() { + var component = createComponent({ + onbeforeupdate: function() {return false}, + view: function(vnode) { + return {tag: "div", children: vnode.children} + }, + }) + var vnode = {tag: component, children: [{tag: "#", children: "a"}]} + var updated = {tag: component, children: [{tag: "#", children: "b"}]} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.firstChild.nodeValue).equals("a") + }) + + o("prevents update if returning false in component and false in vnode", function() { + var component = createComponent({ + onbeforeupdate: function() {return false}, + view: function(vnode) { + return {tag: "div", attrs: {id: vnode.attrs.id}} + }, + }) + var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return false}}} + var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return false}}} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.attributes["id"].value).equals("a") + }) + + o("does not prevent update if returning true in component and true in vnode", function() { + var component = createComponent({ + onbeforeupdate: function() {return true}, + view: function(vnode) { + return {tag: "div", attrs: {id: vnode.attrs.id}} + }, + }) + var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return true}}} + var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return true}}} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.attributes["id"].value).equals("b") + }) + + o("does not prevent update if returning false in component but true in vnode", function() { + var component = createComponent({ + onbeforeupdate: function() {return false}, + view: function(vnode) { + return {tag: "div", attrs: {id: vnode.attrs.id}} + }, + }) + var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return true}}} + var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return true}}} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.attributes["id"].value).equals("b") + }) + + o("does not prevent update if returning true in component but false in vnode", function() { + var component = createComponent({ + onbeforeupdate: function() {return true}, + view: function(vnode) { + return {tag: "div", attrs: {id: vnode.attrs.id}} + }, + }) + var vnode = {tag: component, attrs: {id: "a", onbeforeupdate: function() {return false}}} + var updated = {tag: component, attrs: {id: "b", onbeforeupdate: function() {return false}}} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.attributes["id"].value).equals("b") + }) + + o("does not prevent update if returning true from component", function() { + var component = createComponent({ + onbeforeupdate: function() {return true}, + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs} + }, + }) + var vnode = {tag: component, attrs: {id: "a"}} + var updated = {tag: component, attrs: {id: "b"}} + + render(root, [vnode]) + render(root, [updated]) + + o(root.firstChild.attributes["id"].value).equals("b") + }) + + o("accepts arguments for comparison in component", function() { + var component = createComponent({ + onbeforeupdate: onbeforeupdate, + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs} + }, + }) + var count = 0 + var vnode = {tag: component, attrs: {id: "a"}} + var updated = {tag: component, attrs: {id: "b"}} + + render(root, [vnode]) + render(root, [updated]) + + function onbeforeupdate(vnode, old) { + count++ + + o(old.attrs.id).equals("a") + o(vnode.attrs.id).equals("b") + + return old.attrs.id !== vnode.attrs.id + } + + o(count).equals(1) + o(root.firstChild.attributes["id"].value).equals("b") + }) + + o("is not called on component creation", function() { + createComponent({ + onbeforeupdate: onbeforeupdate, + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs} + }, + }) + + var count = 0 + var vnode = {tag: "div", attrs: {id: "a"}} + + render(root, [vnode]) + + function onbeforeupdate() { + count++ + return true + } + + o(count).equals(0) + }) + + o("is called only once on component update", function() { + var component = createComponent({ + onbeforeupdate: onbeforeupdate, + view: function(vnode) { + return {tag: "div", attrs: vnode.attrs} + }, + }) + + var count = 0 + var vnode = {tag: component, attrs: {id: "a"}} + var updated = {tag: component, attrs: {id: "b"}} + + render(root, [vnode]) + render(root, [updated]) + + function onbeforeupdate() { + count++ + return true + } + + o(count).equals(1) + }) + }) }) }) diff --git a/render/tests/test-oncreate.js b/render/tests/test-oncreate.js index d6f275c2..eb1daa5e 100644 --- a/render/tests/test-oncreate.js +++ b/render/tests/test-oncreate.js @@ -128,7 +128,6 @@ o.spec("oncreate", function() { }) o("does not call oncreate when removing", function() { var create = o.spy() - var update = o.spy() var vnode = {tag: "div", attrs: {oncreate: create}, state: {}} render(root, [vnode]) diff --git a/render/tests/test-oninit.js b/render/tests/test-oninit.js index 1f0e7701..4d94cae4 100644 --- a/render/tests/test-oninit.js +++ b/render/tests/test-oninit.js @@ -128,7 +128,6 @@ o.spec("oninit", function() { }) o("does not call oninit when removing", function() { var create = o.spy() - var update = o.spy() var vnode = {tag: "div", attrs: {oninit: create}, state: {}} render(root, [vnode]) @@ -187,7 +186,7 @@ o.spec("oninit", function() { called = true o(vnode.dom).equals(undefined) - o(root.childNodes.length).equals(0) + o(root.childNodes.length).equals(1) } o(called).equals(true) }) diff --git a/render/tests/test-onremove.js b/render/tests/test-onremove.js index d3f423fc..a7f88a6b 100644 --- a/render/tests/test-onremove.js +++ b/render/tests/test-onremove.js @@ -1,6 +1,7 @@ "use strict" var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var vdom = require("../../render/render") var m = require("../../render/hyperscript") @@ -80,39 +81,6 @@ o.spec("onremove", function() { o(remove.this).equals(vnode.state) o(remove.args[0]).equals(vnode) }) - o("calls onremove on nested component", function() { - var spy = o.spy() - var comp = { - view: function() {return m(outer)} - } - var outer = { - view: function() {return m(inner)} - } - var inner = { - onremove: spy, - view: function() {return m("div")} - } - render(root, {tag: comp}) - render(root, null) - - o(spy.callCount).equals(1) - }) - o("calls onremove on nested component child", function() { - var spy = o.spy() - var comp = { - view: function() {return m(outer)} - } - var outer = { - view: function() {return m(inner, m("a", {onremove: spy}))} - } - var inner = { - view: function(vnode) {return m("div", vnode.children)} - } - render(root, {tag: comp}) - render(root, null) - - o(spy.callCount).equals(1) - }) o("does not set onremove as an event handler", function() { var remove = o.spy() var vnode = {tag: "div", attrs: {onremove: remove}, children: []} @@ -145,4 +113,43 @@ o.spec("onremove", function() { o(vnode.dom).notEquals(updated.dom) }) -}) + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create + + o("calls onremove on nested component", function() { + var spy = o.spy() + var comp = createComponent({ + view: function() {return m(outer)} + }) + var outer = createComponent({ + view: function() {return m(inner)} + }) + var inner = createComponent({ + onremove: spy, + view: function() {return m("div")} + }) + render(root, {tag: comp}) + render(root, null) + + o(spy.callCount).equals(1) + }) + o("calls onremove on nested component child", function() { + var spy = o.spy() + var comp = createComponent({ + view: function() {return m(outer)} + }) + var outer = createComponent({ + view: function() {return m(inner, m("a", {onremove: spy}))} + }) + var inner = createComponent({ + view: function(vnode) {return m("div", vnode.children)} + }) + render(root, {tag: comp}) + render(root, null) + + o(spy.callCount).equals(1) + }) + }) + }) +}) \ No newline at end of file diff --git a/render/tests/test-onupdate.js b/render/tests/test-onupdate.js index 448a44f0..4b74d288 100644 --- a/render/tests/test-onupdate.js +++ b/render/tests/test-onupdate.js @@ -59,7 +59,6 @@ o.spec("onupdate", function() { }) o("does not call old onupdate when removing the onupdate property in new vnode", function() { var create = o.spy() - var update = o.spy() var vnode = {tag: "a", attrs: {onupdate: create}} var updated = {tag: "a"} @@ -171,9 +170,9 @@ o.spec("onupdate", function() { function update(vnode) { called = true - o(vnode.dom.parentNode.attributes["id"].nodeValue).equals("11") - o(vnode.dom.attributes["id"].nodeValue).equals("22") - o(vnode.dom.childNodes[0].attributes["id"].nodeValue).equals("33") + o(vnode.dom.parentNode.attributes["id"].value).equals("11") + o(vnode.dom.attributes["id"].value).equals("22") + o(vnode.dom.childNodes[0].attributes["id"].value).equals("33") } o(called).equals(true) }) diff --git a/render/tests/test-render.js b/render/tests/test-render.js index daa094fd..292433a0 100644 --- a/render/tests/test-render.js +++ b/render/tests/test-render.js @@ -21,7 +21,7 @@ o.spec("render", function() { o(root.childNodes.length).equals(0) }) - + o("throws on invalid root node", function() { var threw = false try { @@ -31,8 +31,8 @@ o.spec("render", function() { } o(threw).equals(true) }) - - o("does not enter infinite loop when oninit triggers render and view throws", function(done) { + + o("does not enter infinite loop when oninit triggers render and view throws with an object literal component", function(done) { var A = { oninit: init, view: function() {throw new Error("error")} @@ -44,15 +44,259 @@ o.spec("render", function() { setTimeout(function() { var threwInner = false try {run()} catch (e) {threwInner = true} - + o(threwInner).equals(false) done() }, 0) } - + var threwOuter = false try {run()} catch (e) {threwOuter = true} - + o(threwOuter).equals(true) }) + o("does not try to re-initialize a constructibe component whose view has thrown", function() { + var oninit = o.spy() + var onbeforeupdate = o.spy() + function A(){} + A.prototype.view = function() {throw new Error("error")} + A.prototype.oninit = oninit + A.prototype.onbeforeupdate = onbeforeupdate + var throwCount = 0 + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + }) + o("does not try to re-initialize a constructible component whose oninit has thrown", function() { + var oninit = o.spy(function(){throw new Error("error")}) + var onbeforeupdate = o.spy() + function A(){} + A.prototype.view = function(){} + A.prototype.oninit = oninit + A.prototype.onbeforeupdate = onbeforeupdate + var throwCount = 0 + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + }) + o("does not try to re-initialize a constructible component whose constructor has thrown", function() { + var oninit = o.spy() + var onbeforeupdate = o.spy() + function A(){throw new Error("error")} + A.prototype.view = function() {} + A.prototype.oninit = oninit + A.prototype.onbeforeupdate = onbeforeupdate + var throwCount = 0 + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(0) + o(onbeforeupdate.callCount).equals(0) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(0) + o(onbeforeupdate.callCount).equals(0) + }) + o("does not try to re-initialize a closure component whose view has thrown", function() { + var oninit = o.spy() + var onbeforeupdate = o.spy() + function A() { + return { + view: function() {throw new Error("error")}, + oninit: oninit, + onbeforeupdate: onbeforeupdate + } + } + var throwCount = 0 + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + }) + o("does not try to re-initialize a closure component whose oninit has thrown", function() { + var oninit = o.spy(function() {throw new Error("error")}) + var onbeforeupdate = o.spy() + function A() { + return { + view: function() {}, + oninit: oninit, + onbeforeupdate: onbeforeupdate + } + } + var throwCount = 0 + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + o(oninit.callCount).equals(1) + o(onbeforeupdate.callCount).equals(0) + }) + o("does not try to re-initialize a closure component whose closure has thrown", function() { + function A() { + throw new Error("error") + } + var throwCount = 0 + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + + try {render(root, {tag: A})} catch (e) {throwCount++} + + o(throwCount).equals(1) + }) + o("lifecycle methods work in keyed children of recycled keyed", function() { + var createA = o.spy() + var updateA = o.spy() + var removeA = o.spy() + var createB = o.spy() + var updateB = o.spy() + var removeB = o.spy() + var a = function() { + return {tag: "div", key: 1, children: [ + {tag: "div", key: 11, attrs: {oncreate: createA, onupdate: updateA, onremove: removeA}}, + {tag: "div", key: 12} + ]} + } + var b = function() { + return {tag: "div", key: 2, children: [ + {tag: "div", key: 21, attrs: {oncreate: createB, onupdate: updateB, onremove: removeB}}, + {tag: "div", key: 22} + ]} + } + render(root, a()) + render(root, b()) + render(root, a()) + + o(createA.callCount).equals(2) + o(updateA.callCount).equals(0) + o(removeA.callCount).equals(1) + o(createB.callCount).equals(1) + o(updateB.callCount).equals(0) + o(removeB.callCount).equals(1) + }) + o("lifecycle methods work in unkeyed children of recycled keyed", function() { + var createA = o.spy() + var updateA = o.spy() + var removeA = o.spy() + var createB = o.spy() + var updateB = o.spy() + var removeB = o.spy() + var a = function() { + return {tag: "div", key: 1, children: [ + {tag: "div", attrs: {oncreate: createA, onupdate: updateA, onremove: removeA}}, + ]} + } + var b = function() { + return {tag: "div", key: 2, children: [ + {tag: "div", attrs: {oncreate: createB, onupdate: updateB, onremove: removeB}}, + ]} + } + render(root, a()) + render(root, b()) + render(root, a()) + + o(createA.callCount).equals(2) + o(updateA.callCount).equals(0) + o(removeA.callCount).equals(1) + o(createB.callCount).equals(1) + o(updateB.callCount).equals(0) + o(removeB.callCount).equals(1) + }) + o("update lifecycle methods work on children of recycled keyed", function() { + var createA = o.spy() + var updateA = o.spy() + var removeA = o.spy() + var createB = o.spy() + var updateB = o.spy() + var removeB = o.spy() + + var a = function() { + return {tag: "div", key: 1, children: [ + {tag: "div", attrs: {oncreate: createA, onupdate: updateA, onremove: removeA}}, + ]} + } + var b = function() { + return {tag: "div", key: 2, children: [ + {tag: "div", attrs: {oncreate: createB, onupdate: updateB, onremove: removeB}}, + ]} + } + render(root, a()) + render(root, a()) + o(createA.callCount).equals(1) + o(updateA.callCount).equals(1) + o(removeA.callCount).equals(0) + + render(root, b()) + o(createA.callCount).equals(1) + o(updateA.callCount).equals(1) + o(removeA.callCount).equals(1) + + render(root, a()) + render(root, a()) + + o(createA.callCount).equals(2) + o(updateA.callCount).equals(2) + 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") + }) }) diff --git a/render/tests/test-updateElement.js b/render/tests/test-updateElement.js index 2211efd1..313fe1a9 100644 --- a/render/tests/test-updateElement.js +++ b/render/tests/test-updateElement.js @@ -21,7 +21,7 @@ o.spec("updateElement", function() { o(updated.dom).equals(vnode.dom) 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() { 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(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() { var vnode = {tag: "a"} @@ -43,7 +43,7 @@ o.spec("updateElement", function() { o(updated.dom).equals(vnode.dom) 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() { var vnode = {tag: "a", attrs: {id: "b", title: "d"}} @@ -209,14 +209,14 @@ o.spec("updateElement", function() { render(root, [vnode]) render(root, [updated]) - o(updated.dom.attributes["class"].nodeValue).equals("b") + o(updated.dom.attributes["class"].value).equals("b") }) o("updates svg child", function() { var vnode = {tag: "svg", children: [{ - tag: 'circle' + tag: "circle" }]} var updated = {tag: "svg", children: [{ - tag: 'line' + tag: "line" }]} render(root, [vnode]) @@ -235,7 +235,7 @@ o.spec("updateElement", function() { render(root, [vnode]) var c = vnode.dom - + o(root.childNodes.length).equals(1) o(a).equals(c) }) @@ -254,7 +254,7 @@ o.spec("updateElement", function() { render(root, [e, b, f]) var y = root.childNodes[1] - + o(root.childNodes.length).equals(3) o(x).equals(y) }) diff --git a/render/tests/test-updateNodes.js b/render/tests/test-updateNodes.js index b0e8c337..fa5231ea 100644 --- a/render/tests/test-updateNodes.js +++ b/render/tests/test-updateNodes.js @@ -1,6 +1,7 @@ "use strict" var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var vdom = require("../../render/render") @@ -726,7 +727,7 @@ o.spec("updateNodes", function() { }) o("change type, position and length", function() { var vnodes = {tag: "div", children: [ - undefined, + undefined, {tag: "#", children: "a"} ]} var updated = {tag: "div", children: [ @@ -737,7 +738,7 @@ o.spec("updateNodes", function() { render(root, vnodes) render(root, updated) - + o(root.firstChild.childNodes.length).equals(1) }) o("removes then recreates then reverses children", function() { @@ -838,38 +839,6 @@ o.spec("updateNodes", function() { o(root.childNodes[0].nodeName).equals("A") o(root.childNodes[1].nodeName).equals("B") }) - o("fragment child toggles from null when followed by null component then tag", function() { - var component = {view: function() {return null}} - var vnodes = [{tag: "[", children: [{tag: "a"}, {tag: component}, {tag: "b"}]}] - var temp = [{tag: "[", children: [null, {tag: component}, {tag: "b"}]}] - var updated = [{tag: "[", children: [{tag: "a"}, {tag: component}, {tag: "b"}]}] - - render(root, vnodes) - render(root, temp) - render(root, updated) - - o(root.childNodes.length).equals(2) - o(root.childNodes[0].nodeName).equals("A") - o(root.childNodes[1].nodeName).equals("B") - }) - o("fragment child toggles from null in component when followed by null component then tag", function() { - var flag = true - var a = {view: function() {return flag ? {tag: "a"} : null}} - var b = {view: function() {return null}} - var vnodes = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] - var temp = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] - var updated = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] - - render(root, vnodes) - flag = false - render(root, temp) - flag = true - render(root, updated) - - o(root.childNodes.length).equals(2) - o(root.childNodes[0].nodeName).equals("A") - o(root.childNodes[1].nodeName).equals("S") - }) o("cached, non-keyed nodes skip diff", function () { var onupdate = o.spy(); var cached = {tag:"a", attrs:{onupdate: onupdate}} @@ -895,13 +864,13 @@ o.spec("updateNodes", function() { var vnodes = [{tag: "div"}, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] var temp = [null, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] var updated = [{tag: "div"}, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] - + render(root, vnodes) var before = vnodes[1].dom render(root, temp) render(root, updated) var after = updated[1].dom - + o(before).equals(after) o(create.callCount).equals(1) o(update.callCount).equals(2) @@ -914,26 +883,63 @@ o.spec("updateNodes", function() { var vnodes = [{tag: "b"}, {tag: "div"}, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] var temp = [{tag: "b"}, null, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] var updated = [{tag: "b"}, {tag: "div"}, {tag: "a", attrs: {oncreate: create, onupdate: update, onremove: remove}}] - + render(root, vnodes) var before = vnodes[2].dom render(root, temp) render(root, updated) var after = updated[2].dom - + o(before).equals(after) o(create.callCount).equals(1) o(update.callCount).equals(2) o(remove.callCount).equals(0) }) - o("component is recreated if key changes to undefined", function () { + o("node is recreated if key changes to undefined", function () { var vnode = {tag: "b", key: 1} var updated = {tag: "b"} - + render(root, vnode) - var dom = vnode.dom render(root, updated) - + o(vnode.dom).notEquals(updated.dom) }) + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create + + o("fragment child toggles from null when followed by null component then tag", function() { + var component = createComponent({view: function() {return null}}) + var vnodes = [{tag: "[", children: [{tag: "a"}, {tag: component}, {tag: "b"}]}] + var temp = [{tag: "[", children: [null, {tag: component}, {tag: "b"}]}] + var updated = [{tag: "[", children: [{tag: "a"}, {tag: component}, {tag: "b"}]}] + + render(root, vnodes) + render(root, temp) + render(root, updated) + + o(root.childNodes.length).equals(2) + o(root.childNodes[0].nodeName).equals("A") + o(root.childNodes[1].nodeName).equals("B") + }) + o("fragment child toggles from null in component when followed by null component then tag", function() { + var flag = true + var a = createComponent({view: function() {return flag ? {tag: "a"} : null}}) + var b = createComponent({view: function() {return null}}) + var vnodes = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] + var temp = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] + var updated = [{tag: "[", children: [{tag: a}, {tag: b}, {tag: "s"}]}] + + render(root, vnodes) + flag = false + render(root, temp) + flag = true + render(root, updated) + + o(root.childNodes.length).equals(2) + o(root.childNodes[0].nodeName).equals("A") + o(root.childNodes[1].nodeName).equals("S") + }) + }) + }) }) diff --git a/render/vnode.js b/render/vnode.js index 56df8c81..ce137703 100644 --- a/render/vnode.js +++ b/render/vnode.js @@ -1,5 +1,7 @@ +"use strict" + function Vnode(tag, key, attrs, children, text, dom) { - return {tag: tag, key: key, attrs: attrs, children: children, text: text, dom: dom, domSize: undefined, state: {}, events: undefined, instance: undefined, skip: false} + 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} } Vnode.normalize = function(node) { if (Array.isArray(node)) return Vnode("[", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined) diff --git a/request.js b/request.js index 7e86421a..cb3bfbbe 100644 --- a/request.js +++ b/request.js @@ -1,2 +1,4 @@ +"use strict" + var PromisePolyfill = require("./promise/promise") module.exports = require("./request/request")(window, PromisePolyfill) diff --git a/request/request.js b/request/request.js index 123ae1e7..76e218c9 100644 --- a/request/request.js +++ b/request/request.js @@ -2,11 +2,14 @@ var buildQueryString = require("../querystring/build") +var FILE_PROTOCOL_REGEX = new RegExp("^file://", "i") + module.exports = function($window, Promise) { var callbackCount = 0 var oncompletion function setCompletionCallback(callback) {oncompletion = callback} + function finalizer() { var count = 0 function complete() {if (--count === 0 && typeof oncompletion === "function") oncompletion()} @@ -42,7 +45,7 @@ module.exports = function($window, Promise) { if (args.method == null) args.method = "GET" args.method = args.method.toUpperCase() - var useBody = typeof args.useBody === "boolean" ? args.useBody : args.method !== "GET" && args.method !== "TRACE" + var useBody = (args.method === "GET" || args.method === "TRACE") ? false : (typeof args.useBody === "boolean" ? args.useBody : true) if (typeof args.serialize !== "function") args.serialize = typeof FormData !== "undefined" && args.data instanceof FormData ? function(value) {return value} : JSON.stringify if (typeof args.deserialize !== "function") args.deserialize = deserialize @@ -52,7 +55,16 @@ module.exports = function($window, Promise) { if (useBody) args.data = args.serialize(args.data) else args.url = assemble(args.url, args.data) - var xhr = new $window.XMLHttpRequest() + var xhr = new $window.XMLHttpRequest(), + aborted = false, + _abort = xhr.abort + + + xhr.abort = function abort() { + aborted = true + _abort.call(xhr) + } + 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) { @@ -70,10 +82,13 @@ module.exports = function($window, Promise) { if (typeof args.config === "function") xhr = args.config(xhr, args) || xhr xhr.onreadystatechange = function() { + // Don't throw errors on xhr.abort(). + if(aborted) return + if (xhr.readyState === 4) { try { 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) { + if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) { resolve(cast(args.type, response)) } else { @@ -128,7 +143,6 @@ module.exports = function($window, Promise) { var key = tokens[i].slice(1) if (data[key] != null) { url = url.replace(tokens[i], data[key]) - delete data[key] } } return url diff --git a/request/tests/test-jsonp.js b/request/tests/test-jsonp.js index 7042274c..076ab26e 100644 --- a/request/tests/test-jsonp.js +++ b/request/tests/test-jsonp.js @@ -7,7 +7,7 @@ var Promise = require("../../promise/promise") var parseQueryString = require("../../querystring/parse") o.spec("jsonp", function() { - var mock, jsonp, spy, complete + var mock, jsonp, complete o.beforeEach(function() { mock = xhrMock() var requestService = Request(mock, Promise) @@ -28,7 +28,6 @@ o.spec("jsonp", function() { }).then(done) }) o("first argument can be a string aliasing url property", function(done){ - var s = new Date mock.$defineRoutes({ "GET /item": function(request) { var queryData = parseQueryString(request.query) @@ -104,8 +103,8 @@ o.spec("jsonp", function() { return {status: 200, responseText: queryData["callback"] + "([])"} } }) - var promise = jsonp("/item", {background: true}).then(function() {}) - + jsonp("/item", {background: true}).then(function() {}) + setTimeout(function() { o(complete.callCount).equals(0) done() diff --git a/request/tests/test-request.js b/request/tests/test-request.js index a9fce1dd..7f965498 100644 --- a/request/tests/test-request.js +++ b/request/tests/test-request.js @@ -18,7 +18,6 @@ o.spec("xhr", function() { o.spec("success", function() { o("works via GET", function(done) { - var s = new Date mock.$defineRoutes({ "GET /item": function() { return {status: 200, responseText: JSON.stringify({a: 1})} @@ -31,7 +30,6 @@ o.spec("xhr", function() { }) }) o("implicit GET method", function(done){ - var s = new Date mock.$defineRoutes({ "GET /item": function() { return {status: 200, responseText: JSON.stringify({a: 1})} @@ -44,7 +42,6 @@ o.spec("xhr", function() { }) }) o("first argument can be a string aliasing url property", function(done){ - var s = new Date mock.$defineRoutes({ "GET /item": function() { return {status: 200, responseText: JSON.stringify({a: 1})} @@ -123,7 +120,7 @@ o.spec("xhr", function() { } }) xhr({method: "GET", url: "/item/:x", data: {x: "y"}}).then(function(data) { - o(data).deepEquals({a: "/item/y", b: {}}) + o(data).deepEquals({a: "/item/y", b: "?x=y"}) }).then(done) }) o("works w/ parameterized url via POST", function(done) { @@ -133,7 +130,17 @@ o.spec("xhr", function() { } }) xhr({method: "POST", url: "/item/:x", data: {x: "y"}}).then(function(data) { - o(data).deepEquals({a: "/item/y", b: {}}) + o(data).deepEquals({a: "/item/y", b: {x: "y"}}) + }).then(done) + }) + o("works w/ array", function(done) { + mock.$defineRoutes({ + "POST /items": function(request) { + return {status: 200, responseText: JSON.stringify({a: request.url, b: JSON.parse(request.body)})} + } + }) + xhr({method: "POST", url: "/items", data: [{x: "y"}]}).then(function(data) { + o(data).deepEquals({a: "/items", b: [{x: "y"}]}) }).then(done) }) o("ignores unresolved parameter via GET", function(done) { @@ -162,7 +169,7 @@ o.spec("xhr", function() { } mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: JSON.stringify([{id: 1}, {id: 2}, {id: 3}])} } }) @@ -176,7 +183,7 @@ o.spec("xhr", function() { } mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: JSON.stringify({id: 1})} } }) @@ -218,12 +225,12 @@ o.spec("xhr", function() { } mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: JSON.stringify({test: 123})} } }) xhr({method: "GET", url: "/item", deserialize: deserialize}).then(function(data) { - o(data).equals("{\"test\":123}") + o(data).equals('{"test":123}') }).then(done) }) o("deserialize parameter works in POST", function(done) { @@ -232,40 +239,40 @@ o.spec("xhr", function() { } mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: JSON.stringify({test: 123})} } }) xhr({method: "POST", url: "/item", deserialize: deserialize}).then(function(data) { - o(data).equals("{\"test\":123}") + o(data).equals('{"test":123}') }).then(done) }) o("extract parameter works in GET", function(done) { - var extract = function(data) { + var extract = function() { return JSON.stringify({test: 123}) } mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: ""} } }) xhr({method: "GET", url: "/item", extract: extract}).then(function(data) { - o(data).equals("{\"test\":123}") + o(data).equals('{"test":123}') }).then(done) }) o("extract parameter works in POST", function(done) { - var extract = function(data) { + var extract = function() { return JSON.stringify({test: 123}) } mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: ""} } }) xhr({method: "POST", url: "/item", extract: extract}).then(function(data) { - o(data).equals("{\"test\":123}") + o(data).equals('{"test":123}') }).then(done) }) o("ignores deserialize if extract is defined", function(done) { @@ -275,7 +282,7 @@ o.spec("xhr", function() { var deserialize = o.spy() mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: ""} } }) @@ -287,7 +294,7 @@ o.spec("xhr", function() { }) o("config parameter works", function(done) { mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: ""} } }) @@ -301,7 +308,7 @@ o.spec("xhr", function() { }) o("requests don't block each other", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: "[]"} } }) @@ -318,7 +325,7 @@ o.spec("xhr", function() { }) o("requests trigger finally once with a chained then", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: "[]"} } }) @@ -332,11 +339,11 @@ o.spec("xhr", function() { }) o("requests does not trigger finally when background: true", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 200, responseText: "[]"} } }) - var promise = xhr("/item", {background: true}).then(function() {}) + xhr("/item", {background: true}).then(function() {}) setTimeout(function() { o(complete.callCount).equals(0) @@ -345,7 +352,7 @@ o.spec("xhr", function() { }) o("headers are set when header arg passed", function(done) { mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: ""} } }) @@ -357,7 +364,7 @@ o.spec("xhr", function() { }) o("headers are with higher precedence than default headers", function(done) { mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: ""} } }) @@ -369,7 +376,7 @@ o.spec("xhr", function() { }) o("json headers are set to the correct default value", function(done) { mock.$defineRoutes({ - "POST /item": function(request) { + "POST /item": function() { return {status: 200, responseText: ""} } }) @@ -380,11 +387,71 @@ o.spec("xhr", function() { o(xhr.getRequestHeader("Accept")).equals("application/json, text/*") } }) + o("doesn't fail on abort", function(done) { + mock.$defineRoutes({ + "GET /item": function() { + return {status: 200, responseText: JSON.stringify({a: 1})} + } + }) + + var failed = false + var resolved = false + function handleAbort(xhr) { + var onreadystatechange = xhr.onreadystatechange // probably not set yet + var testonreadystatechange = function() { + onreadystatechange.call(xhr) + setTimeout(function() { // allow promises to (not) resolve first + o(failed).equals(false) + o(resolved).equals(false) + done() + }, 0) + } + Object.defineProperty(xhr, "onreadystatechange", { + set: function(val) { onreadystatechange = val }, + get: function() { return testonreadystatechange } + }) + xhr.abort() + } + xhr({method: "GET", url: "/item", config: handleAbort}).catch(function() { + failed = true + }) + .then(function() { + resolved = true + }) + }) + o("doesn't fail on file:// status 0", function(done) { + mock.$defineRoutes({ + "GET /item": function() { + return {status: 0, responseText: JSON.stringify({a: 1})} + } + }) + var failed = false + xhr({method: "GET", url: "file:///item"}).catch(function() { + failed = true + }).then(function(data) { + o(failed).equals(false) + o(data).deepEquals({a: 1}) + }).then(function() { + done() + }) + }) + /*o("data maintains after interpolate", function() { + mock.$defineRoutes({ + "PUT /items/:x": function() { + return {status: 200, responseText: ""} + } + }) + var data = {x: 1, y: 2} + var dataCopy = Object.assign({}, data); + xhr({method: "PUT", url: "/items/:x", data}) + + o(data).deepEquals(dataCopy) + })*/ }) o.spec("failure", function() { o("rejects on server error", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 500, responseText: JSON.stringify({error: "error"})} } }) @@ -395,7 +462,7 @@ o.spec("xhr", function() { }) o("extends Error with JSON response", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 500, responseText: JSON.stringify({message: "error", stack: "error on line 1"})} } }) @@ -407,7 +474,7 @@ o.spec("xhr", function() { }) o("rejects on non-JSON server error", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 500, responseText: "error"} } }) @@ -417,7 +484,7 @@ o.spec("xhr", function() { }) o("triggers all branched catches upon rejection", function(done) { mock.$defineRoutes({ - "GET /item": function(request) { + "GET /item": function() { return {status: 500, responseText: "error"} } }) @@ -441,5 +508,15 @@ o.spec("xhr", function() { }) }) }) + o("rejects on cors-like error", function(done) { + mock.$defineRoutes({ + "GET /item": function() { + return {status: 0} + } + }) + xhr({method: "GET", url: "/item"}).catch(function(e) { + o(e instanceof Error).equals(true) + }).then(done) + }) }) }) diff --git a/route.js b/route.js index b8c8a15a..4e829527 100644 --- a/route.js +++ b/route.js @@ -1,3 +1,5 @@ +"use strict" + var redrawService = require("./redraw") -module.exports = require("./api/router")(window, redrawService) \ No newline at end of file +module.exports = require("./api/router")(window, redrawService) diff --git a/router/router.js b/router/router.js index 51961e99..106f6863 100644 --- a/router/router.js +++ b/router/router.js @@ -80,7 +80,7 @@ module.exports = function($window) { var path = router.getPath() var params = {} var pathname = parsePath(path, params, params) - + var state = $window.history.state if (state != null) { for (var k in state) params[k] = state[k] @@ -103,11 +103,11 @@ module.exports = function($window) { reject(path, params) } - + if (supportsPushState) $window.onpopstate = debounceAsync(resolveRoute) else if (router.prefix.charAt(0) === "#") $window.onhashchange = resolveRoute resolveRoute() } - + return router } diff --git a/router/tests/test-getPath.js b/router/tests/test-getPath.js index 6c5dc2b2..9b2603fa 100644 --- a/router/tests/test-getPath.js +++ b/router/tests/test-getPath.js @@ -6,7 +6,7 @@ var Router = require("../../router/router") o.spec("Router.getPath", function() { 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() { var $window, router, onRouteChange, onFail diff --git a/stream.js b/stream.js index 06dcd5d4..89e5baab 100644 --- a/stream.js +++ b/stream.js @@ -1 +1,3 @@ -module.exports = require("./stream/stream") \ No newline at end of file +"use strict" + +module.exports = require("./stream/stream") diff --git a/stream/package.json b/stream/package.json new file mode 100644 index 00000000..4eb14a07 --- /dev/null +++ b/stream/package.json @@ -0,0 +1,13 @@ +{ + "name": "mithril-stream", + "version": "1.0.0", + "description": "Streaming data, mithril-style", + "main": "stream.js", + "directories": { + "test": "tests" + }, + "keywords": [ "stream", "reactive", "data" ], + "author": "Leo Horie ", + "license": "MIT", + "repository": "MithrilJS/mithril.js" +} diff --git a/stream/scan.js b/stream/scan.js deleted file mode 100644 index 84b6e0a2..00000000 --- a/stream/scan.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict" - -var combine = require("./stream").combine - -module.exports = function (reducer, seed, stream) { - var newStream = combine(function (s) { - return seed = reducer(seed, s._state.value) - }, [stream]) - - if (newStream._state.state === 0) newStream(seed) - - return newStream -} diff --git a/stream/scanMerge.js b/stream/scanMerge.js deleted file mode 100644 index 088440fa..00000000 --- a/stream/scanMerge.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict" - -var combine = require("./stream").combine - -module.exports = function(tuples, seed) { - var streams = tuples.map(function(tuple) { - var stream = tuple[0] - if (stream._state.state === 0) stream(undefined) - return stream - }) - - var newStream = combine(function() { - var changed = arguments[arguments.length - 1] - - streams.forEach(function(stream, idx) { - if (changed.indexOf(stream) > -1) { - seed = tuples[idx][1](seed, stream._state.value) - } - }) - - return seed - }, streams) - - return newStream -} diff --git a/stream/stream.js b/stream/stream.js index 4a51f9e2..18c7e608 100644 --- a/stream/stream.js +++ b/stream/stream.js @@ -1,5 +1,7 @@ "use strict" +;(function() { + var guid = 0, HALT = {} function createStream() { function stream() { @@ -14,7 +16,7 @@ function createStream() { } function initStream(stream) { stream.constructor = createStream - stream._state = {id: guid++, value: undefined, state: 0, derive: undefined, recover: undefined, deps: {}, parents: [], endStream: undefined} + stream._state = {id: guid++, value: undefined, state: 0, derive: undefined, recover: undefined, deps: {}, parents: [], endStream: undefined, unregister: undefined} stream.map = stream["fantasy-land/map"] = map, stream["fantasy-land/ap"] = ap, stream["fantasy-land/of"] = createStream stream.valueOf = valueOf, stream.toJSON = toJSON, stream.toString = valueOf @@ -23,7 +25,10 @@ function initStream(stream) { if (!stream._state.endStream) { var endStream = createStream() endStream.map(function(value) { - if (value === true) unregisterStream(stream), unregisterStream(endStream) + if (value === true) { + unregisterStream(stream) + endStream._state.unregister = function(){unregisterStream(endStream)} + } return value }) stream._state.endStream = endStream @@ -35,6 +40,7 @@ function initStream(stream) { function updateStream(stream, value) { updateState(stream, value) for (var id in stream._state.deps) updateDependency(stream._state.deps[id], false) + if (stream._state.unregister != null) stream._state.unregister() finalize(stream) } function updateState(stream, value) { @@ -56,7 +62,7 @@ function finalize(stream) { } function combine(fn, streams) { - if (!streams.every(valid)) throw new Error("Ensure that each item passed to m.prop.combine/m.prop.merge is a stream") + if (!streams.every(valid)) throw new Error("Ensure that each item passed to stream.combine/stream.merge is a stream") return initDependency(createStream(), streams, function() { return fn.apply(this, streams.concat([streams.filter(changed)])) }) @@ -107,10 +113,48 @@ function merge(streams) { return streams.map(function(s) {return s()}) }, streams) } + +function scan(reducer, seed, stream) { + var newStream = combine(function (s) { + return seed = reducer(seed, s._state.value) + }, [stream]) + + if (newStream._state.state === 0) newStream(seed) + + return newStream +} + +function scanMerge(tuples, seed) { + var streams = tuples.map(function(tuple) { + var stream = tuple[0] + if (stream._state.state === 0) stream(undefined) + return stream + }) + + var newStream = combine(function() { + var changed = arguments[arguments.length - 1] + + streams.forEach(function(stream, idx) { + if (changed.indexOf(stream) > -1) { + seed = tuples[idx][1](seed, stream._state.value) + } + }) + + return seed + }, streams) + + return newStream +} + createStream["fantasy-land/of"] = createStream createStream.merge = merge createStream.combine = combine +createStream.scan = scan +createStream.scanMerge = scanMerge createStream.HALT = HALT if (typeof module !== "undefined") module["exports"] = createStream -else window.stream = createStream +else if (typeof window.m === "function" && !("stream" in window.m)) window.m.stream = createStream +else window.m = {stream : createStream} + +}()); diff --git a/stream/tests/test-scan.js b/stream/tests/test-scan.js index 72ef0277..db5d885f 100644 --- a/stream/tests/test-scan.js +++ b/stream/tests/test-scan.js @@ -2,12 +2,11 @@ var o = require("../../ospec/ospec") var stream = require("../stream") -var scan = require("../scan") o.spec("scan", function() { o("defaults to seed", function() { var parent = stream() - var child = scan(function(out, p) { + var child = stream.scan(function(out, p) { return out - p }, 123, parent) o(child()).equals(123) @@ -15,14 +14,14 @@ o.spec("scan", function() { o("accumulates values as expected", function() { var parent = stream() - var child = scan(function(arr, p) { + var child = stream.scan(function(arr, p) { return arr.concat(p) }, [], parent) parent(7) parent("11") parent(undefined) - parent({ a: 1 }) + parent({a: 1}) var result = child() // deepEquals fails on arrays? @@ -32,4 +31,3 @@ o.spec("scan", function() { o(result[3]).deepEquals({a: 1}) }) }) - diff --git a/stream/tests/test-scanMerge.js b/stream/tests/test-scanMerge.js index 1e396176..cbf1e7f1 100644 --- a/stream/tests/test-scanMerge.js +++ b/stream/tests/test-scanMerge.js @@ -2,14 +2,13 @@ var o = require("../../ospec/ospec") var stream = require("../stream") -var scanMerge = require("../scanMerge") o.spec("scanMerge", function() { o("defaults to seed", function() { var parent1 = stream() var parent2 = stream() - var child = scanMerge([ + var child = stream.scanMerge([ [parent1, function(out, p1) { return out + p1 }], @@ -25,7 +24,7 @@ o.spec("scanMerge", function() { var parent1 = stream() var parent2 = stream() - var child = scanMerge([ + var child = stream.scanMerge([ [parent1, function(out, p1) { return out + p1 }], diff --git a/stream/tests/test-stream.js b/stream/tests/test-stream.js index 92e16620..09b01209 100644 --- a/stream/tests/test-stream.js +++ b/stream/tests/test-stream.js @@ -1,7 +1,6 @@ "use strict" var o = require("../../ospec/ospec") -var callAsync = require("../../test-utils/callAsync") var Stream = require("../stream") o.spec("stream", function() { @@ -105,7 +104,7 @@ o.spec("stream", function() { var streams = [] var a = Stream() var b = Stream() - var c = Stream.combine(function(a, b, changed) { + Stream.combine(function(a, b, changed) { streams = changed }, [a, b]) @@ -119,7 +118,7 @@ o.spec("stream", function() { var streams = [] var a = Stream(3) var b = Stream(5) - var c = Stream.combine(function(a, b, changed) { + Stream.combine(function(a, b, changed) { streams = changed }, [a, b]) @@ -130,7 +129,7 @@ o.spec("stream", function() { }) o("combine can return undefined", function() { var a = Stream(1) - var b = Stream.combine(function(a) { + var b = Stream.combine(function() { return undefined }, [a]) @@ -138,7 +137,7 @@ o.spec("stream", function() { }) o("combine can return stream", function() { var a = Stream(1) - var b = Stream.combine(function(a) { + var b = Stream.combine(function() { return Stream(2) }, [a]) @@ -146,7 +145,7 @@ o.spec("stream", function() { }) o("combine can return pending stream", function() { var a = Stream(1) - var b = Stream.combine(function(a) { + var b = Stream.combine(function() { return Stream() }, [a]) @@ -155,22 +154,22 @@ o.spec("stream", function() { o("combine can halt", function() { var count = 0 var a = Stream(1) - var b = Stream.combine(function(a) { + var b = Stream.combine(function() { return Stream.HALT - }, [a]) - ["fantasy-land/map"](function() { + }, [a])["fantasy-land/map"](function() { count++ return 1 }) o(b()).equals(undefined) + o(count).equals(0) }) o("combine will throw with a helpful error if given non-stream values", function () { var spy = o.spy() var a = Stream(1) var thrown = null; try { - var b = Stream.combine(spy, [a, '']) + Stream.combine(spy, [a, ""]) } catch (e) { thrown = e } @@ -210,8 +209,9 @@ o.spec("stream", function() { var a = Stream() var b = Stream() - var all = Stream.merge([a.map(id), b.map(id)]).map(function(data) { + Stream.merge([a.map(id), b.map(id)]).map(function(data) { value = data[0] + data[1] + return undefined }) a(1) @@ -263,6 +263,18 @@ o.spec("stream", function() { o(doubled()).equals(4) }) + o("end stream can be mapped to", function() { + var stream = Stream() + var spy = o.spy() + + stream.end.map(spy) + + o(spy.callCount).equals(0) + + stream.end(true) + + o(spy.callCount).equals(1) + }) }) o.spec("valueOf", function() { o("works", function() { @@ -344,7 +356,7 @@ o.spec("stream", function() { }) o("works with pending stream", function() { var stream = Stream(undefined) - var mapped = stream["fantasy-land/map"](function(value) {return Stream()}) + var mapped = stream["fantasy-land/map"](function() {return Stream()}) o(mapped()()).equals(undefined) }) diff --git a/test-utils/components.js b/test-utils/components.js new file mode 100644 index 00000000..109af9bb --- /dev/null +++ b/test-utils/components.js @@ -0,0 +1,29 @@ +"use strict" + +module.exports = [ + { + kind: "POJO", + create: function(methods) { + var res = {view: function() {return {tag:"div"}}} + Object.keys(methods || {}).forEach(function(m){res[m] = methods[m]}) + return res + } + }, { + kind: "constructible", + create: function(methods) { + function res(){} + res.prototype.view = function() {return {tag:"div"}} + Object.keys(methods || {}).forEach(function(m){res.prototype[m] = methods[m]}) + return res + } + }, { + kind: "closure", + create: function(methods) { + return function() { + var res = {view: function() {return {tag:"div"}}} + Object.keys(methods || {}).forEach(function(m){res[m] = methods[m]}) + return res + } + } + } +] diff --git a/test-utils/domMock.js b/test-utils/domMock.js index 5da93b98..060ba4f7 100644 --- a/test-utils/domMock.js +++ b/test-utils/domMock.js @@ -1,6 +1,39 @@ "use strict" -module.exports = function() { +/* +Known limitations: + +- `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) { return type === "transitionstart" || type === "transitionend" || type === "animationstart" || type === "animationend" } @@ -62,14 +95,26 @@ module.exports = function() { } function getAttribute(name) { if (this.attributes[name] == null) return null - return this.attributes[name].nodeValue + return this.attributes[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] = { 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}, - set nodeValue(value) {nodeValue = String(value)}, + set nodeValue(value) { + this.value = value + } } } function setAttributeNS(ns, name, value) { @@ -79,6 +124,9 @@ module.exports = function() { function removeAttribute(name) { delete this.attributes[name] } + function hasAttribute(name) { + return name in this.attributes + } var declListTokenizer = /;|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'/g /** * This will split a semicolon-separated CSS declaration list into an array of @@ -96,7 +144,7 @@ module.exports = function() { declList = declList.replace( /("(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*')|\/\*[\s\S]*?\*\//g, function(m, str){ - return str || '' + return str || "" } ) /*eslint-disable no-cond-assign*/ @@ -115,7 +163,7 @@ module.exports = function() { var activeElement var $window = { document: { - createElement: function(tag, is) { + createElement: function(tag) { var cssText = "" var style = {} Object.defineProperty(style, "cssText", { @@ -150,6 +198,7 @@ module.exports = function() { appendChild: appendChild, removeChild: removeChild, insertBefore: insertBefore, + hasAttribute: hasAttribute, getAttribute: getAttribute, setAttribute: setAttribute, setAttributeNS: setAttributeNS, @@ -204,25 +253,25 @@ module.exports = function() { throw new Error("setting element.style is not portable") }, get className() { - return this.attributes["class"] ? this.attributes["class"].nodeValue : "" + return this.attributes["class"] ? this.attributes["class"].value : "" }, set className(value) { if (this.namespaceURI === "http://www.w3.org/2000/svg") throw new Error("Cannot set property className of SVGElement") else this.setAttribute("class", value) }, focus: function() {activeElement = this}, - addEventListener: function(type, callback, useCapture) { + addEventListener: function(type, callback) { if (events[type] == null) events[type] = [callback] else events[type].push(callback) }, - removeEventListener: function(type, callback, useCapture) { + removeEventListener: function(type, callback) { if (events[type] != null) { var index = events[type].indexOf(callback) if (index > -1) events[type].splice(index, 1) } }, dispatchEvent: function(e) { - if (this.nodeName === "INPUT" && this.attributes["type"] != null && this.attributes["type"].nodeValue === "checkbox" && e.type === "click") { + if (this.nodeName === "INPUT" && this.attributes["type"] != null && this.attributes["type"].value === "checkbox" && e.type === "click") { this.checked = !this.checked } @@ -241,7 +290,6 @@ module.exports = function() { } if (element.nodeName === "A") { - var href Object.defineProperty(element, "href", { get: function() {return this.attributes["href"] === undefined ? "" : "[FIXME implement]"}, set: function(value) {this.setAttribute("href", value)}, @@ -257,32 +305,79 @@ module.exports = function() { enumerable: true, }) - element.value = "" - } - - if (element.nodeName === "TEXTAREA") { - var value + var value = "" + var valueSetter = spy(function(v) { + /*eslint-disable no-implicit-coercion*/ + value = v === null ? "" : "" + v + /*eslint-enable no-implicit-coercion*/ + }) Object.defineProperty(element, "value", { get: function() { - return value != null ? value : - this.firstChild ? this.firstChild.nodeValue : "" + return value }, - set: function(v) {value = v}, + set: valueSetter, 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 */ + if (element.nodeName === "CANVAS") { 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())}, }) 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())}, }) } + /* eslint-enable radix */ + function getOptions(element) { var options = [] for (var i = 0; i < element.childNodes.length; i++) { @@ -293,56 +388,75 @@ module.exports = function() { } function getOptionValue(element) { return element.attributes["value"] != null ? - element.attributes["value"].nodeValue : + element.attributes["value"].value : element.firstChild != null ? element.firstChild.nodeValue : "" } if (element.nodeName === "SELECT") { - var selectedValue, selectedIndex = 0 + // var selectedValue + var selectedIndex = 0 Object.defineProperty(element, "selectedIndex", { get: function() {return getOptions(this).length > 0 ? selectedIndex : -1}, set: function(value) { var options = getOptions(this) if (value >= 0 && value < options.length) { - selectedValue = getOptionValue(options[selectedIndex]) + // selectedValue = getOptionValue(options[selectedIndex]) selectedIndex = value } else { - selectedValue = "" + // selectedValue = "" selectedIndex = -1 } }, enumerable: true, }) + var valueSetter = spy(function(value) { + if (value === null) { + selectedIndex = -1 + } else { + var options = getOptions(this) + /*eslint-disable no-implicit-coercion*/ + var stringValue = "" + value + /*eslint-enable no-implicit-coercion*/ + for (var i = 0; i < options.length; i++) { + if (getOptionValue(options[i]) === stringValue) { + // selectedValue = stringValue + selectedIndex = i + return + } + } + // selectedValue = stringValue + selectedIndex = -1 + } + }) Object.defineProperty(element, "value", { get: function() { if (this.selectedIndex > -1) return getOptionValue(getOptions(this)[this.selectedIndex]) return "" }, - set: function(value) { - var options = getOptions(this) - var stringValue = String(value) - for (var i = 0; i < options.length; i++) { - if (getOptionValue(options[i]) === stringValue) { - selectedValue = stringValue - selectedIndex = i - return - } - } - selectedValue = stringValue - selectedIndex = -1 - }, + set: valueSetter, enumerable: true, }) + registerSpies(element, { + valueSetter: valueSetter + }) } if (element.nodeName === "OPTION") { + var valueSetter = spy(function(value) { + /*eslint-disable no-implicit-coercion*/ + this.setAttribute("value", value === null ? "" : "" + value) + /*eslint-enable no-implicit-coercion*/ + }) Object.defineProperty(element, "value", { get: function() {return getOptionValue(this)}, - set: function(value) { - this.setAttribute("value", value) - }, + set: valueSetter, enumerable: true, }) + registerSpies(element, { + valueSetter: valueSetter + }) + Object.defineProperty(element, "selected", { + // TODO? handle `selected` without a parent (works in browsers) get: function() { var options = getOptions(this.parentNode) var index = options.indexOf(this) @@ -368,13 +482,19 @@ module.exports = function() { return element }, createTextNode: function(text) { - var nodeValue = String(text) + /*eslint-disable no-implicit-coercion*/ + var nodeValue = "" + text + /*eslint-enable no-implicit-coercion*/ return { nodeType: 3, nodeName: "#text", parentNode: null, 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() { @@ -405,5 +525,7 @@ module.exports = function() { $window.document.documentElement.appendChild($window.document.body) activeElement = $window.document.body + if (options.spy) $window.__getSpies = getSpies + return $window } diff --git a/test-utils/parseURL.js b/test-utils/parseURL.js index f5e76e8d..e60cc531 100644 --- a/test-utils/parseURL.js +++ b/test-utils/parseURL.js @@ -3,7 +3,7 @@ module.exports = function parseURL(url, root) { var data = {} var protocolIndex = url.indexOf("://") - var pathnameIndex = protocolIndex > - 1 ? url.indexOf("/", protocolIndex + 3) : url.indexOf("/") + var pathnameIndex = protocolIndex > -1 ? url.indexOf("/", protocolIndex + 3) : url.indexOf("/") var searchIndex = url.indexOf("?") var hashIndex = url.indexOf("#") if ((pathnameIndex > searchIndex && searchIndex > -1) || (pathnameIndex > hashIndex && hashIndex > -1)) pathnameIndex = -1 diff --git a/test-utils/pushStateMock.js b/test-utils/pushStateMock.js index 91e7a136..f2273a2d 100644 --- a/test-utils/pushStateMock.js +++ b/test-utils/pushStateMock.js @@ -1,10 +1,22 @@ "use strict" var parseURL = require("../test-utils/parseURL") +var callAsync = require("../test-utils/callAsync") + +function debouncedAsync(f) { + var ref + return function() { + if (ref != null) return + ref = callAsync(function(){ + ref = null + f() + }) + } +} module.exports = function(options) { if (options == null) options = {} - + var $window = options.window || {} var protocol = options.protocol || "http:" var hostname = options.hostname || "localhost" @@ -29,18 +41,21 @@ module.exports = function(options) { if (data.search != null && data.search !== search) search = data.search, isNew = true if (data.hash != null && data.hash !== hash) { hash = data.hash - if (!isNew) hashchange() + if (!isNew) { + hashchange() + } } return isNew } - + function prefix(prefix, value) { if (value === "") return "" return (value.charAt(0) !== prefix ? prefix : "") + value } - function hashchange() { + function _hashchange() { if (typeof $window.onhashchange === "function") $window.onhashchange({type: "hashchange"}) } + var hashchange = debouncedAsync(_hashchange) function popstate() { if (typeof $window.onpopstate === "function") $window.onpopstate({type: "popstate", state: $window.history.state}) } diff --git a/test-utils/tests/index.html b/test-utils/tests/index.html index e24fa2f8..51b04d73 100644 --- a/test-utils/tests/index.html +++ b/test-utils/tests/index.html @@ -14,12 +14,14 @@ + + diff --git a/test-utils/tests/test-browserMock.js b/test-utils/tests/test-browserMock.js index d47c58ce..861f1ef0 100644 --- a/test-utils/tests/test-browserMock.js +++ b/test-utils/tests/test-browserMock.js @@ -17,7 +17,7 @@ o.spec("browserMock", function() { }) o("$window.onhashchange can be reached from the pushStateMock functions", function(done) { $window.onhashchange = o.spy() - $window.location.hash = '#a' + $window.location.hash = "#a" callAsync(function(){ o($window.onhashchange.callCount).equals(1) @@ -33,7 +33,7 @@ o.spec("browserMock", function() { }) o("$window.onunload can be reached from the pushStateMock functions", function() { $window.onunload = o.spy() - $window.location.href = '/a' + $window.location.href = "/a" o($window.onunload.callCount).equals(1) }) diff --git a/test-utils/tests/test-components.js b/test-utils/tests/test-components.js new file mode 100644 index 00000000..e0ede703 --- /dev/null +++ b/test-utils/tests/test-components.js @@ -0,0 +1,54 @@ +"use strict" + +var o = require("../../ospec/ospec") +var components = require("../../test-utils/components") + +o.spec("test-utils/components", function() { + var test = o.spy(function(component) { + return function() { + o("works", function() { + o(typeof component.kind).equals("string") + + var methods = {oninit: function(){}, view: function(){}} + + var cmp1, cmp2 + + if (component.kind === "POJO") { + cmp1 = component.create() + cmp2 = component.create(methods) + } else if (component.kind === "constructible") { + cmp1 = new (component.create()) + cmp2 = new (component.create(methods)) + } else if (component.kind === "closure") { + cmp1 = component.create()() + cmp2 = component.create(methods)() + } else { + throw new Error("unexpected component kind") + } + + o(cmp1 != null).equals(true) + o(typeof cmp1.view).equals("function") + + var vnode = cmp1.view() + + o(vnode != null).equals(true) + o(vnode).deepEquals({tag: "div"}) + + if (component.kind !== "constructible") { + o(cmp2).deepEquals(methods) + } else { + // deepEquals doesn't search the prototype, do it manually + o(cmp2 != null).equals(true) + o(cmp2.view).equals(methods.view) + o(cmp2.oninit).equals(methods.oninit) + } + }) + } + }) + o.after(function(){ + o(test.callCount).equals(3) + }) + components.forEach(function(component) { + o.spec(component.kind, test(component)) + }) +}) diff --git a/test-utils/tests/test-domMock.js b/test-utils/tests/test-domMock.js index edd896d5..a5829458 100644 --- a/test-utils/tests/test-domMock.js +++ b/test-utils/tests/test-domMock.js @@ -77,6 +77,27 @@ o.spec("domMock", function() { o(node.nodeValue).equals("true") }) + if (typeof Symbol === "function") { + o("doesn't work with symbols", function(){ + var threw = false + try { + $document.createTextNode(Symbol("nono")) + } catch(e) { + threw = true + } + o(threw).equals(true) + }) + o("symbols can't be used as nodeValue", function(){ + var threw = false + try { + var node = $document.createTextNode("a") + node.nodeValue = Symbol("nono") + } catch(e) { + threw = true + } + o(threw).equals(true) + }) + } }) o.spec("createDocumentFragment", function() { @@ -321,12 +342,13 @@ o.spec("domMock", function() { o(div.getAttribute("id")).equals("aaa") }) }) - + o.spec("setAttribute", function() { o("works", function() { var div = $document.createElement("div") div.setAttribute("id", "aaa") + o(div.attributes["id"].value).equals("aaa") o(div.attributes["id"].nodeValue).equals("aaa") o(div.attributes["id"].namespaceURI).equals(null) }) @@ -334,32 +356,51 @@ o.spec("domMock", function() { var div = $document.createElement("div") div.setAttribute("id", 123) - o(div.attributes["id"].nodeValue).equals("123") + o(div.attributes["id"].value).equals("123") }) o("works w/ null", function() { var div = $document.createElement("div") div.setAttribute("id", null) - o(div.attributes["id"].nodeValue).equals("null") + o(div.attributes["id"].value).equals("null") }) o("works w/ undefined", function() { var div = $document.createElement("div") div.setAttribute("id", undefined) - o(div.attributes["id"].nodeValue).equals("undefined") + o(div.attributes["id"].value).equals("undefined") }) o("works w/ object", function() { var div = $document.createElement("div") div.setAttribute("id", {}) - o(div.attributes["id"].nodeValue).equals("[object Object]") + o(div.attributes["id"].value).equals("[object Object]") }) o("setting via attributes map stringifies", function() { var div = $document.createElement("div") div.setAttribute("id", "a") - div.attributes["id"].nodeValue = 123 + div.attributes["id"].value = 123 - o(div.attributes["id"].nodeValue).equals("123") + o(div.attributes["id"].value).equals("123") + + div.attributes["id"].nodeValue = 456 + + o(div.attributes["id"].value).equals("456") + }) + }) + o.spec("hasAttribute", function() { + o("works", function() { + var div = $document.createElement("div") + + o(div.hasAttribute("id")).equals(false) + + div.setAttribute("id", "aaa") + + o(div.hasAttribute("id")).equals(true) + + div.removeAttribute("id") + + o(div.hasAttribute("id")).equals(false) }) }) @@ -368,14 +409,14 @@ o.spec("domMock", function() { var div = $document.createElement("div") div.setAttributeNS("http://www.w3.org/1999/xlink", "href", "aaa") - o(div.attributes["href"].nodeValue).equals("aaa") + o(div.attributes["href"].value).equals("aaa") o(div.attributes["href"].namespaceURI).equals("http://www.w3.org/1999/xlink") }) o("works w/ number", function() { var div = $document.createElement("div") div.setAttributeNS("http://www.w3.org/1999/xlink", "href", 123) - o(div.attributes["href"].nodeValue).equals("123") + o(div.attributes["href"].value).equals("123") o(div.attributes["href"].namespaceURI).equals("http://www.w3.org/1999/xlink") }) }) @@ -393,7 +434,6 @@ o.spec("domMock", function() { o.spec("textContent", function() { o("works", function() { var div = $document.createElement("div") - var a = $document.createElement("a") div.textContent = "aaa" o(div.childNodes.length).equals(1) @@ -402,7 +442,6 @@ o.spec("domMock", function() { }) o("works with empty string", function() { var div = $document.createElement("div") - var a = $document.createElement("a") div.textContent = "" o(div.childNodes.length).equals(0) @@ -418,18 +457,18 @@ o.spec("domMock", function() { o(div.childNodes[0].nodeName).equals("BR") o(div.childNodes[1].nodeType).equals(1) o(div.childNodes[1].nodeName).equals("A") - o(div.childNodes[1].attributes["class"].nodeValue).equals("aaa") - o(div.childNodes[1].attributes["id"].nodeValue).equals("xyz") + o(div.childNodes[1].attributes["class"].value).equals("aaa") + o(div.childNodes[1].attributes["id"].value).equals("xyz") o(div.childNodes[1].childNodes[0].nodeType).equals(3) o(div.childNodes[1].childNodes[0].nodeValue).equals("123") o(div.childNodes[1].childNodes[1].nodeType).equals(1) o(div.childNodes[1].childNodes[1].nodeName).equals("B") - o(div.childNodes[1].childNodes[1].attributes["class"].nodeValue).equals("bbb") + o(div.childNodes[1].childNodes[1].attributes["class"].value).equals("bbb") o(div.childNodes[1].childNodes[2].nodeType).equals(3) o(div.childNodes[1].childNodes[2].nodeValue).equals("234") o(div.childNodes[1].childNodes[3].nodeType).equals(1) o(div.childNodes[1].childNodes[3].nodeName).equals("BR") - o(div.childNodes[1].childNodes[3].attributes["class"].nodeValue).equals("ccc") + o(div.childNodes[1].childNodes[3].attributes["class"].value).equals("ccc") o(div.childNodes[1].childNodes[4].nodeType).equals(3) o(div.childNodes[1].childNodes[4].nodeValue).equals("345") }) @@ -514,8 +553,8 @@ o.spec("domMock", function() { var div = $document.createElement("div") div.style.cssText = "background: url(';'); font-family: \";\"" - o(div.style.background).equals("url(';')") - o(div.style.fontFamily).equals("\";\"") + o(div.style.background).equals("url(';')") + o(div.style.fontFamily).equals('";"') o(div.style.cssText).equals("background: url(';'); font-family: \";\";") }) o("comments in style.cssText are stripped", function(){ @@ -534,9 +573,10 @@ o.spec("domMock", function() { }) o("setting style throws", function () { + var div = $document.createElement("div") var err = false try { - div.style = '' + div.style = "" } catch (e) { err = e } @@ -629,14 +669,14 @@ o.spec("domMock", function() { a.setAttribute("href", "") o(a.href).notEquals("") - o(a.attributes["href"].nodeValue).equals("") + o(a.attributes["href"].value).equals("") }) o("is path if property is set", function() { var a = $document.createElement("a") a.href = "" o(a.href).notEquals("") - o(a.attributes["href"].nodeValue).equals("") + o(a.attributes["href"].value).equals("") }) }) o.spec("input[checked]", function() { @@ -657,7 +697,7 @@ o.spec("domMock", function() { input.setAttribute("checked", "") o(input.checked).equals(true) - o(input.attributes["checked"].nodeValue).equals("") + o(input.attributes["checked"].value).equals("") input.removeAttribute("checked") @@ -700,20 +740,95 @@ o.spec("domMock", function() { o("value" in input).equals(true) o("value" in a).equals(false) }) + o("converts null to ''", function() { + var input = $document.createElement("input") + input.value = "x" + + o(input.value).equals("x") + + input.value = null + + o(input.value).equals("") + }) + o("converts values to strings", function() { + var input = $document.createElement("input") + input.value = 5 + + o(input.value).equals("5") + + input.value = 0 + + o(input.value).equals("0") + + input.value = undefined + + o(input.value).equals("undefined") + }) + if (typeof Symbol === "function") o("throws when set to a symbol", function() { + var threw = false + var input = $document.createElement("input") + try { + input.value = Symbol("") + } catch (e) { + o(e instanceof TypeError).equals(true) + threw = true + } + + o(input.value).equals("") + o(threw).equals(true) + }) + }) + o.spec("input[type]", function(){ + o("only exists in input elements", function() { + var input = $document.createElement("input") + var a = $document.createElement("a") + + o("type" in input).equals(true) + o("type" in a).equals(false) + }) + o("is 'text' by default", function() { + var input = $document.createElement("input") + + o(input.type).equals("text") + }) + "radio|button|checkbox|color|date|datetime|datetime-local|email|file|hidden|month|number|password|range|research|search|submit|tel|text|url|week|image" + .split("|").forEach(function(type) { + o("can be set to " + type, function(){ + var input = $document.createElement("input") + input.type = type + + o(input.getAttribute("type")).equals(type) + o(input.type).equals(type) + }) + o("bad values set the attribute, but the getter corrects to 'text', " + type, function(){ + var input = $document.createElement("input") + input.type = "badbad" + type + + o(input.getAttribute("type")).equals("badbad" + type) + o(input.type).equals("text") + }) + }) }) o.spec("textarea[value]", function() { - o("reads from child if no value", function() { - var input = $document.createElement("textarea") - input.appendChild($document.createTextNode("aaa")) + o("reads from child if no value was ever set", function() { + var textarea = $document.createElement("textarea") + textarea.appendChild($document.createTextNode("aaa")) - o(input.value).equals("aaa") + o(textarea.value).equals("aaa") }) o("ignores child if value set", function() { - var input = $document.createElement("textarea") - input.value = "aaa" - input.setAttribute("value", "bbb") + var textarea = $document.createElement("textarea") + textarea.value = null + textarea.appendChild($document.createTextNode("aaa")) - o(input.value).equals("aaa") + o(textarea.value).equals("") + }) + o("textarea[value] doesn't reflect `attributes.value`", function() { + var textarea = $document.createElement("textarea") + textarea.value = "aaa" + textarea.setAttribute("value", "bbb") + + o(textarea.value).equals("aaa") }) }) o.spec("select[value] and select[selectedIndex]", function() { @@ -774,10 +889,76 @@ o.spec("domMock", function() { option2.setAttribute("value", "b") select.appendChild(option2) + var option3 = $document.createElement("option") + option3.setAttribute("value", "") + select.appendChild(option3) + + var option4 = $document.createElement("option") + option4.setAttribute("value", "null") + select.appendChild(option4) + select.value = "b" o(select.value).equals("b") o(select.selectedIndex).equals(1) + + select.value = "" + + o(select.value).equals("") + o(select.selectedIndex).equals(2) + + select.value = "null" + + o(select.value).equals("null") + o(select.selectedIndex).equals(3) + + select.value = null + + o(select.value).equals("") + o(select.selectedIndex).equals(-1) + }) + o("setting valid value works with type conversion", function() { + var select = $document.createElement("select") + + var option1 = $document.createElement("option") + option1.setAttribute("value", "0") + select.appendChild(option1) + + var option2 = $document.createElement("option") + option2.setAttribute("value", "undefined") + select.appendChild(option2) + + var option3 = $document.createElement("option") + option3.setAttribute("value", "") + select.appendChild(option3) + + select.value = 0 + + o(select.value).equals("0") + o(select.selectedIndex).equals(0) + + select.value = undefined + + o(select.value).equals("undefined") + o(select.selectedIndex).equals(1) + + if (typeof Symbol === "function") { + var threw = false + try { + select.value = Symbol("x") + } catch (e) { + threw = true + } + o(threw).equals(true) + o(select.value).equals("undefined") + o(select.selectedIndex).equals(1) + } + }) + o("option.value = null is converted to the empty string", function() { + var option = $document.createElement("option") + option.value = null + + o(option.value).equals("") }) o("setting valid value works with optgroup", function() { var select = $document.createElement("select") @@ -919,57 +1100,57 @@ o.spec("domMock", function() { o.spec("canvas width and height", function() { o("setting property works", function() { var canvas = $document.createElement("canvas") - + canvas.width = 100 - o(canvas.attributes["width"].nodeValue).equals("100") + o(canvas.attributes["width"].value).equals("100") o(canvas.width).equals(100) - + canvas.height = 100 - o(canvas.attributes["height"].nodeValue).equals("100") + o(canvas.attributes["height"].value).equals("100") o(canvas.height).equals(100) }) o("setting string casts to number", function() { var canvas = $document.createElement("canvas") - + canvas.width = "100" - o(canvas.attributes["width"].nodeValue).equals("100") + o(canvas.attributes["width"].value).equals("100") o(canvas.width).equals(100) - + canvas.height = "100" - o(canvas.attributes["height"].nodeValue).equals("100") + o(canvas.attributes["height"].value).equals("100") o(canvas.height).equals(100) }) o("setting float casts to int", function() { var canvas = $document.createElement("canvas") - + canvas.width = 1.2 - o(canvas.attributes["width"].nodeValue).equals("1") + o(canvas.attributes["width"].value).equals("1") o(canvas.width).equals(1) - + canvas.height = 1.2 - o(canvas.attributes["height"].nodeValue).equals("1") + o(canvas.attributes["height"].value).equals("1") o(canvas.height).equals(1) }) o("setting percentage fails", function() { var canvas = $document.createElement("canvas") - + canvas.width = "100%" - o(canvas.attributes["width"].nodeValue).equals("0") + o(canvas.attributes["width"].value).equals("0") o(canvas.width).equals(0) - + canvas.height = "100%" - o(canvas.attributes["height"].nodeValue).equals("0") + o(canvas.attributes["height"].value).equals("0") o(canvas.height).equals(0) }) o("setting attribute works", function() { var canvas = $document.createElement("canvas") - + canvas.setAttribute("width", "100%") - o(canvas.attributes["width"].nodeValue).equals("100%") + o(canvas.attributes["width"].value).equals("100%") o(canvas.width).equals(100) - + canvas.setAttribute("height", "100%") - o(canvas.attributes["height"].nodeValue).equals("100%") + o(canvas.attributes["height"].value).equals("100%") o(canvas.height).equals(100) }) }) @@ -980,7 +1161,7 @@ o.spec("domMock", function() { el.className = "a" o(el.className).equals("a") - o(el.attributes["class"].nodeValue).equals("a") + o(el.attributes["class"].value).equals("a") }) o("setter throws in svg", function(done) { var el = $document.createElementNS("http://www.w3.org/2000/svg", "svg") @@ -992,4 +1173,85 @@ o.spec("domMock", function() { } }) }) + o.spec("spies", function() { + var $window + o.beforeEach(function() { + $window = domMock({spy: o.spy}) + }) + o("basics", function() { + o(typeof $window.__getSpies).equals("function") + o("__getSpies" in domMock()).equals(false) + }) + o("input elements have spies on value and type setters", function() { + var input = $window.document.createElement("input") + + var spies = $window.__getSpies(input) + + o(typeof spies).equals("object") + o(spies).notEquals(null) + o(typeof spies.valueSetter).equals("function") + o(typeof spies.typeSetter).equals("function") + o(spies.valueSetter.callCount).equals(0) + o(spies.typeSetter.callCount).equals(0) + + input.value = "aaa" + input.type = "radio" + + o(spies.valueSetter.callCount).equals(1) + o(spies.valueSetter.this).equals(input) + o(spies.valueSetter.args[0]).equals("aaa") + + o(spies.typeSetter.callCount).equals(1) + o(spies.typeSetter.this).equals(input) + o(spies.typeSetter.args[0]).equals("radio") + }) + o("select elements have spies on value setters", function() { + var select = $window.document.createElement("select") + + var spies = $window.__getSpies(select) + + o(typeof spies).equals("object") + o(spies).notEquals(null) + o(typeof spies.valueSetter).equals("function") + o(spies.valueSetter.callCount).equals(0) + + select.value = "aaa" + + o(spies.valueSetter.callCount).equals(1) + o(spies.valueSetter.this).equals(select) + o(spies.valueSetter.args[0]).equals("aaa") + }) + o("option elements have spies on value setters", function() { + var option = $window.document.createElement("option") + + var spies = $window.__getSpies(option) + + o(typeof spies).equals("object") + o(spies).notEquals(null) + o(typeof spies.valueSetter).equals("function") + o(spies.valueSetter.callCount).equals(0) + + option.value = "aaa" + + o(spies.valueSetter.callCount).equals(1) + o(spies.valueSetter.this).equals(option) + o(spies.valueSetter.args[0]).equals("aaa") + }) + o("textarea elements have spies on value setters", function() { + var textarea = $window.document.createElement("textarea") + + var spies = $window.__getSpies(textarea) + + o(typeof spies).equals("object") + o(spies).notEquals(null) + o(typeof spies.valueSetter).equals("function") + o(spies.valueSetter.callCount).equals(0) + + textarea.value = "aaa" + + o(spies.valueSetter.callCount).equals(1) + o(spies.valueSetter.this).equals(textarea) + o(spies.valueSetter.args[0]).equals("aaa") + }) + }) }) diff --git a/test-utils/tests/test-pushStateMock.js b/test-utils/tests/test-pushStateMock.js index 3cb51716..b07ee1b4 100644 --- a/test-utils/tests/test-pushStateMock.js +++ b/test-utils/tests/test-pushStateMock.js @@ -2,7 +2,7 @@ var o = require("../../ospec/ospec") var pushStateMock = require("../../test-utils/pushStateMock") - +var callAsync = require("../../test-utils/callAsync") o.spec("pushStateMock", function() { var $window @@ -168,13 +168,13 @@ o.spec("pushStateMock", function() { }) o.spec("set protocol", function() { o("setting protocol throws", function(done) { - var old = $window.location.href try { $window.location.protocol = "https://" } catch (e) { - done() + return done() } + throw new Error("Expected an error") }) }) o.spec("set port", function() { @@ -413,17 +413,17 @@ o.spec("pushStateMock", function() { }) o("replaceState does not break forward history", function() { $window.onpopstate = o.spy() - + $window.history.pushState(null, null, "b") $window.history.back() o($window.onpopstate.callCount).equals(1) o($window.location.href).equals("http://localhost/") - + $window.history.replaceState(null, null, "a") - + o($window.location.href).equals("http://localhost/a") - + $window.history.forward() o($window.onpopstate.callCount).equals(2) @@ -431,46 +431,46 @@ o.spec("pushStateMock", function() { }) o("pushstate retains state", function() { $window.onpopstate = o.spy() - + $window.history.pushState({a: 1}, null, "#a") $window.history.pushState({b: 2}, null, "#b") - + o($window.onpopstate.callCount).equals(0) $window.history.back() - + o($window.onpopstate.callCount).equals(1) o($window.onpopstate.args[0].type).equals("popstate") o($window.onpopstate.args[0].state).deepEquals({a: 1}) $window.history.back() - + o($window.onpopstate.callCount).equals(2) o($window.onpopstate.args[0].type).equals("popstate") o($window.onpopstate.args[0].state).equals(null) $window.history.forward() - + o($window.onpopstate.callCount).equals(3) o($window.onpopstate.args[0].type).equals("popstate") o($window.onpopstate.args[0].state).deepEquals({a: 1}) $window.history.forward() - + o($window.onpopstate.callCount).equals(4) o($window.onpopstate.args[0].type).equals("popstate") o($window.onpopstate.args[0].state).deepEquals({b: 2}) }) o("replacestate replaces state", function() { $window.onpopstate = o.spy(pop) - + $window.history.replaceState({a: 1}, null, "a") - + o($window.history.state).deepEquals({a: 1}) - + $window.history.pushState(null, null, "a") $window.history.back() - + function pop(e) { o(e.state).deepEquals({a: 1}) o($window.history.state).deepEquals({a: 1}) @@ -478,93 +478,160 @@ o.spec("pushStateMock", function() { }) }) o.spec("onhashchance", function() { - o("onhashchange triggers on location.href change", function() { + o("onhashchange triggers on location.href change", function(done) { $window.onhashchange = o.spy() $window.location.href = "http://localhost/#a" - o($window.onhashchange.callCount).equals(1) - o($window.onhashchange.args[0].type).equals("hashchange") + callAsync(function(){ + o($window.onhashchange.callCount).equals(1) + o($window.onhashchange.args[0].type).equals("hashchange") + done() + }) }) - o("onhashchange triggers on relative location.href change", function() { + o("onhashchange triggers on relative location.href change", function(done) { $window.onhashchange = o.spy() $window.location.href = "#a" - o($window.onhashchange.callCount).equals(1) + callAsync(function(){ + o($window.onhashchange.callCount).equals(1) + done() + }) }) - o("onhashchange triggers on location.hash change", function() { + o("onhashchange triggers on location.hash change", function(done) { $window.onhashchange = o.spy() $window.location.hash = "#a" - o($window.onhashchange.callCount).equals(1) + callAsync(function(){ + o($window.onhashchange.callCount).equals(1) + done() + }) }) - o("onhashchange does not trigger on page change", function() { + o("onhashchange does not trigger on page change", function(done) { $window.onhashchange = o.spy() $window.location.href = "http://localhost/a" - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) }) - o("onhashchange does not trigger on page change with different hash", function() { + o("onhashchange does not trigger on page change with different hash", function(done) { $window.location.href = "http://localhost/#a" - $window.onhashchange = o.spy() - $window.location.href = "http://localhost/a#b" + callAsync(function(){ + $window.onhashchange = o.spy() + $window.location.href = "http://localhost/a#b" - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) - o("onhashchange does not trigger on page change with same hash", function() { + o("onhashchange does not trigger on page change with same hash", function(done) { $window.location.href = "http://localhost/#b" - $window.onhashchange = o.spy() - $window.location.href = "http://localhost/a#b" + callAsync(function(){ + $window.onhashchange = o.spy() + $window.location.href = "http://localhost/a#b" - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) - o("onhashchange triggers on history.back()", function() { + o("onhashchange triggers on history.back()", function(done) { $window.location.href = "#a" - $window.onhashchange = o.spy() - $window.history.back() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() - o($window.onhashchange.callCount).equals(1) + callAsync(function(){ + o($window.onhashchange.callCount).equals(1) + done() + }) + }) }) - o("onhashchange triggers on history.forward()", function() { + o("onhashchange triggers on history.forward()", function(done) { $window.location.href = "#a" - $window.onhashchange = o.spy() - $window.history.back() - $window.history.forward() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() + callAsync(function(){ + $window.history.forward() - o($window.onhashchange.callCount).equals(2) + callAsync(function(){ + o($window.onhashchange.callCount).equals(2) + done() + }) + }) + }) }) - o("onhashchange does not trigger on history.back() that causes page change with different hash", function() { + o("onhashchange triggers once when the hash changes twice in a single tick", function(done) { + $window.location.href = "#a" + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() + $window.history.forward() + + callAsync(function(){ + o($window.onhashchange.callCount).equals(1) + done() + }) + }) + }) + o("onhashchange does not trigger on history.back() that causes page change with different hash", function(done) { $window.location.href = "#a" $window.location.href = "a#b" - $window.onhashchange = o.spy() - $window.history.back() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) - o("onhashchange does not trigger on history.back() that causes page change with same hash", function() { + o("onhashchange does not trigger on history.back() that causes page change with same hash", function(done) { $window.location.href = "#a" $window.location.href = "a#a" - $window.onhashchange = o.spy() - $window.history.back() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) - o("onhashchange does not trigger on history.forward() that causes page change with different hash", function() { + o("onhashchange does not trigger on history.forward() that causes page change with different hash", function(done) { $window.location.href = "#a" $window.location.href = "a#b" - $window.onhashchange = o.spy() - $window.history.back() - $window.history.forward() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() + $window.history.forward() - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) - o("onhashchange does not trigger on history.forward() that causes page change with same hash", function() { + o("onhashchange does not trigger on history.forward() that causes page change with same hash", function(done) { $window.location.href = "#a" $window.location.href = "a#b" - $window.onhashchange = o.spy() - $window.history.back() - $window.history.forward() + callAsync(function(){ + $window.onhashchange = o.spy() + $window.history.back() + $window.history.forward() - o($window.onhashchange.callCount).equals(0) + callAsync(function(){ + o($window.onhashchange.callCount).equals(0) + done() + }) + }) }) }) o.spec("onunload", function() { diff --git a/test-utils/tests/test-xhrMock.js b/test-utils/tests/test-xhrMock.js index cef2d9ca..8bdfcf21 100644 --- a/test-utils/tests/test-xhrMock.js +++ b/test-utils/tests/test-xhrMock.js @@ -5,13 +5,13 @@ var xhrMock = require("../../test-utils/xhrMock") var parseQueryString = require("../../querystring/parse") o.spec("xhrMock", function() { - var $window, ajax + var $window o.beforeEach(function() { $window = xhrMock() }) o.spec("xhr", function() { - o("works", function(done, timeout) { + o("works", function(done) { $window.$defineRoutes({ "GET /item": function(request) { o(request.url).equals("/item") @@ -29,7 +29,7 @@ o.spec("xhrMock", function() { } xhr.send() }) - o("works w/ search", function(done, timeout) { + o("works w/ search", function(done) { $window.$defineRoutes({ "GET /item": function(request) { o(request.query).equals("?a=b") @@ -45,7 +45,7 @@ o.spec("xhrMock", function() { } xhr.send() }) - o("works w/ body", function(done, timeout) { + o("works w/ body", function(done) { $window.$defineRoutes({ "POST /item": function(request) { o(request.body).equals("a=b") @@ -61,7 +61,7 @@ o.spec("xhrMock", function() { } xhr.send("a=b") }) - o("handles routing error", function(done, timeout) { + o("handles routing error", function(done) { var xhr = new $window.XMLHttpRequest() xhr.open("GET", "/nonexistent") xhr.onreadystatechange = function() { @@ -113,7 +113,7 @@ o.spec("xhrMock", function() { done() } }) - o("works with other querystring params", function(done, timeout) { + o("works with other querystring params", function(done) { $window.$defineRoutes({ "GET /test": function(request) { var queryData = parseQueryString(request.query) diff --git a/test-utils/xhrMock.js b/test-utils/xhrMock.js index 37d48e92..d3bbf5b8 100644 --- a/test-utils/xhrMock.js +++ b/test-utils/xhrMock.js @@ -6,7 +6,7 @@ var parseQueryString = require("../querystring/parse") module.exports = function() { var routes = {} - var callback = "callback" + // var callback = "callback" var serverErrorHandler = function(url) { return {status: 500, responseText: "server error, most likely the URL was not defined " + url} } @@ -15,6 +15,7 @@ module.exports = function() { XMLHttpRequest: function XMLHttpRequest() { var args = {} var headers = {} + var aborted = false this.setRequestHeader = function(header, value) { headers[header] = value } @@ -32,18 +33,24 @@ module.exports = function() { } this.send = function(body) { var self = this - var handler = routes[args.method + " " + args.pathname] || serverErrorHandler.bind(null, args.pathname) - var data = handler({url: args.pathname, query: args.search || {}, body: body || null}) + if(!aborted) { + var handler = routes[args.method + " " + args.pathname] || serverErrorHandler.bind(null, args.pathname) + var data = handler({url: args.pathname, query: args.search || {}, body: body || null}) + self.status = data.status + self.responseText = data.responseText + } else { + self.status = 0 + } self.readyState = 4 - self.status = data.status - self.responseText = data.responseText if (args.async === true) { - var s = new Date callAsync(function() { if (typeof self.onreadystatechange === "function") self.onreadystatechange() }) } } + this.abort = function() { + aborted = true + } }, document: { createElement: function(tag) { @@ -56,7 +63,7 @@ module.exports = function() { var urlData = parseURL(element.src, {protocol: "http:", hostname: "localhost", port: "", pathname: "/"}) var handler = routes["GET " + urlData.pathname] || serverErrorHandler.bind(null, element.src) var data = handler({url: urlData.pathname, query: urlData.search, body: null}) - var query = parseQueryString(urlData.search) + parseQueryString(urlData.search) callAsync(function() { if (data.status === 200) { new Function("$window", "with ($window) return " + data.responseText).call($window, $window) @@ -75,8 +82,8 @@ module.exports = function() { $defineRoutes: function(rules) { routes = rules }, - $defineJSONPCallbackKey: function(key) { - callback = key + $defineJSONPCallbackKey: function(/* key */) { + // callback = key }, } return $window diff --git a/tests/test-api.js b/tests/test-api.js index 0a5824f9..3240141c 100644 --- a/tests/test-api.js +++ b/tests/test-api.js @@ -2,6 +2,7 @@ var o = require("../ospec/ospec") var browserMock = require("../test-utils/browserMock") +var components = require("../test-utils/components") o.spec("api", function() { var m @@ -9,13 +10,13 @@ o.spec("api", function() { o.beforeEach(function() { var mock = browserMock() if (typeof global !== "undefined") global.window = mock - m = require("../mithril") + m = require("../mithril") // eslint-disable-line global-require }) - + o.spec("m", function() { o("works", function() { var vnode = m("div") - + o(vnode.tag).equals("div") }) }) @@ -29,7 +30,7 @@ o.spec("api", function() { o.spec("m.trust", function() { o("works", function() { var vnode = m.trust("
") - + o(vnode.tag).equals("<") o(vnode.children).equals("
") }) @@ -37,7 +38,7 @@ o.spec("api", function() { o.spec("m.fragment", function() { o("works", function() { var vnode = m.fragment({key: 123}, [m("div")]) - + o(vnode.tag).equals("[") o(vnode.key).equals(123) o(vnode.children.length).equals(1) @@ -48,115 +49,26 @@ o.spec("api", function() { o("works", function() { var spy = o.spy() var handler = m.withAttr("value", spy) - + handler({currentTarget: {value: 10}}) - + o(spy.args[0]).equals(10) }) }) o.spec("m.parseQueryString", function() { o("works", function() { var query = m.parseQueryString("?a=1&b=2") - + o(query).deepEquals({a: "1", b: "2"}) }) }) o.spec("m.buildQueryString", function() { o("works", function() { var query = m.buildQueryString({a: 1, b: 2}) - + o(query).equals("a=1&b=2") }) }) - o.spec("m.render", function() { - o("works", function() { - var root = window.document.createElement("div") - m.render(root, m("div")) - - o(root.childNodes.length).equals(1) - o(root.firstChild.nodeName).equals("DIV") - }) - }) - o.spec("m.mount", function() { - o("works", function() { - var root = window.document.createElement("div") - m.mount(root, {view: function() {return m("div")}}) - - o(root.childNodes.length).equals(1) - o(root.firstChild.nodeName).equals("DIV") - }) - }) - o.spec("m.route", function() { - o("works", function(done) { - var root = window.document.createElement("div") - m.route(root, "/a", { - "/a": {view: function() {return m("div")}} - }) - - setTimeout(function() { - o(root.childNodes.length).equals(1) - o(root.firstChild.nodeName).equals("DIV") - - done() - }, FRAME_BUDGET) - }) - o("m.route.prefix", function(done) { - var root = window.document.createElement("div") - m.route.prefix("#") - m.route(root, "/a", { - "/a": {view: function() {return m("div")}} - }) - - setTimeout(function() { - o(root.childNodes.length).equals(1) - o(root.firstChild.nodeName).equals("DIV") - - done() - }, FRAME_BUDGET) - }) - o("m.route.get", function(done) { - var root = window.document.createElement("div") - m.route(root, "/a", { - "/a": {view: function() {return m("div")}} - }) - - setTimeout(function() { - o(m.route.get()).equals("/a") - - done() - }, FRAME_BUDGET) - }) - o("m.route.set", function(done, timeout) { - timeout(100) - var root = window.document.createElement("div") - m.route(root, "/a", { - "/:id": {view: function() {return m("div")}} - }) - - setTimeout(function() { - m.route.set("/b") - setTimeout(function() { - o(m.route.get()).equals("/b") - - done() - }, FRAME_BUDGET) - }, FRAME_BUDGET) - }) - }) - o.spec("m.redraw", function() { - o("works", function(done) { - var count = 0 - var root = window.document.createElement("div") - m.mount(root, {view: function() {count++}}) - setTimeout(function() { - m.redraw() - - o(count).equals(2) - - done() - }, FRAME_BUDGET) - }) - }) o.spec("m.request", function() { o("works", function() { o(typeof m.request).equals("function") // TODO improve @@ -167,4 +79,99 @@ o.spec("api", function() { o(typeof m.jsonp).equals("function") // TODO improve }) }) -}) \ No newline at end of file + o.spec("m.render", function() { + o("works", function() { + var root = window.document.createElement("div") + m.render(root, m("div")) + + o(root.childNodes.length).equals(1) + o(root.firstChild.nodeName).equals("DIV") + }) + }) + components.forEach(function(cmp){ + o.spec(cmp.kind, function(){ + var createComponent = cmp.create + + o.spec("m.mount", function() { + o("works", function() { + var root = window.document.createElement("div") + m.mount(root, createComponent({view: function() {return m("div")}})) + + o(root.childNodes.length).equals(1) + o(root.firstChild.nodeName).equals("DIV") + }) + }) + o.spec("m.route", function() { + o("works", function(done) { + var root = window.document.createElement("div") + m.route(root, "/a", { + "/a": createComponent({view: function() {return m("div")}}) + }) + + setTimeout(function() { + o(root.childNodes.length).equals(1) + o(root.firstChild.nodeName).equals("DIV") + + done() + }, FRAME_BUDGET) + }) + o("m.route.prefix", function(done) { + var root = window.document.createElement("div") + m.route.prefix("#") + m.route(root, "/a", { + "/a": createComponent({view: function() {return m("div")}}) + }) + + setTimeout(function() { + o(root.childNodes.length).equals(1) + o(root.firstChild.nodeName).equals("DIV") + + done() + }, FRAME_BUDGET) + }) + o("m.route.get", function(done) { + var root = window.document.createElement("div") + m.route(root, "/a", { + "/a": createComponent({view: function() {return m("div")}}) + }) + + setTimeout(function() { + o(m.route.get()).equals("/a") + + done() + }, FRAME_BUDGET) + }) + o("m.route.set", function(done, timeout) { + timeout(100) + var root = window.document.createElement("div") + m.route(root, "/a", { + "/:id": createComponent({view: function() {return m("div")}}) + }) + + setTimeout(function() { + m.route.set("/b") + setTimeout(function() { + o(m.route.get()).equals("/b") + + done() + }, FRAME_BUDGET) + }, FRAME_BUDGET) + }) + }) + o.spec("m.redraw", function() { + o("works", function(done) { + var count = 0 + var root = window.document.createElement("div") + m.mount(root, createComponent({view: function() {count++}})) + setTimeout(function() { + m.redraw() + + o(count).equals(2) + + done() + }, FRAME_BUDGET) + }) + }) + }) + }) +}) diff --git a/util/withAttr.js b/util/withAttr.js index d0e06484..5df4332a 100644 --- a/util/withAttr.js +++ b/util/withAttr.js @@ -2,6 +2,6 @@ module.exports = function(attrName, callback, context) { return function(e) { - return callback.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName)) + callback.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName)) } }