From 9ae592ee4d186567925c866b663f5d995d374ee6 Mon Sep 17 00:00:00 2001 From: impinball Date: Thu, 9 Jul 2015 16:14:08 -0400 Subject: [PATCH] Do some local style modifications and profile. 1. Do some temporary style modifications to help make the code more readable for profiling (with help from ESLint). 2. Profile the code, and optimize accordingly. --- .eslintignore | 5 + .eslintrc | 27 + Gruntfile.js | 302 +- README.md | 2 + docs/layout/tools/template-converter.js | 164 +- mithril.js | 2626 +++++++++++------ package.json | 97 +- tests/e2e/.eslintrc | 23 + tests/e2e/tests.js | 403 +-- tests/mithril-tests.js | 3411 +++++++++++++---------- tests/mock.js | 50 +- tests/test.js | 11 +- 12 files changed, 4426 insertions(+), 2695 deletions(-) create mode 100644 .eslintignore create mode 100644 .eslintrc create mode 100644 tests/e2e/.eslintrc diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..29de9e28 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +node_modules +**/*.min.js +docs/layout/lib/**/*.js +tests/e2e/libs/** +mithril.closure-compiler-externs.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..a3c03520 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,27 @@ +{ + "env": { + "browser": true + }, + "rules": { + "no-cond-assign": [2, "except-parens"], + "no-shadow": 0, + "semi-spacing": 0, + "quotes": [2, "double", "avoid-escape"], + "curly": [2, "multi-line"], + "semi": [2, "never"], + "eqeqeq": [2, "allow-null"], + "no-throw-literal": 2, + "wrap-iife": 2, + "strict": [2, "function"], + "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "linebreak-style": [1, "windows"], + "one-var": [2, { + "initialized": "never" + }], + "new-cap": 0, + "no-use-before-define": [2, "nofunc"], + "max-len": [2, 80, 4], + "dot-notation": 2, + "indent": [2, "tab"] + } +} diff --git a/Gruntfile.js b/Gruntfile.js index ae789912..69afbcb0 100755 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,14 +1,15 @@ +/* eslint-env node */ module.exports = function(grunt) { - _ = require('lodash'); + "use strict" - var version = "0.2.0"; + var _ = require("lodash") + var version = "0.4.0" - var inputFolder = "./docs"; - var tempFolder = "./temp"; - var archiveFolder = "./archive"; - var outputFolder = "../mithril"; + var inputFolder = "./docs" + var tempFolder = "./temp" + var archiveFolder = "./archive" + var outputFolder = "../mithril" - var guideLayout = "guide"; var guide = [ "auto-redrawing", "benchmarks", @@ -24,8 +25,7 @@ module.exports = function(grunt) { "routing", "tools", "web-services" - ]; - var apiLayout = "api"; + ] var api = [ "change-log", "roadmap", @@ -45,55 +45,68 @@ module.exports = function(grunt) { "mithril.trust", "mithril.withAttr", "mithril.xhr" - ]; + ] - - - var md2htmlTasks = {}; + var md2htmlTasks = {} var makeTasks = function(layout, pages) { pages.map(function(name) { - var src = inputFolder + "/" + name + ".md"; - var title = (grunt.file.exists(src)) ? grunt.file.read(src).split(/\n/)[0].substring(3) + ' - ' : ''; + var src = inputFolder + "/" + name + ".md" + var title + if (grunt.file.exist(src)) { + title = grunt.file.read(src) + .split(/\n/)[0] + .substring(3) + " - " + } else { + title = "" + } md2htmlTasks[name] = { - options: {layout: inputFolder + "/layout/" + layout + ".html", templateData: { "topic": title }}, + options: { + layout: inputFolder + "/layout/" + layout + ".html", + templateData: { "topic": title } + }, files: [{src: [src], dest: tempFolder + "/" + name + ".html"}] } }) - }; - makeTasks("guide", guide); - makeTasks("api", api); + } + makeTasks("guide", guide) + makeTasks("api", api) - var sauceBrowsers =[ - { browserName: 'firefox', version: '19', platform: 'XP' }, + var sauceBrowsers = [ + { browserName: "firefox", version: "19", platform: "XP" }, { browserName: "internet explorer", platform: "XP", version: "6"}, { browserName: "safari", platform: "OS X 10.9", version: "7"}, { browserName: "iPad", platform: "OS X 10.9", version: "7.1"}, { browserName: "opera", platform: "Linux", version: "12"}, { browserName: "chrome", platform: "XP", version: "26"}, { browserName: "chrome", platform: "Windows 8", version: "26"} - ]; + ] var sauceOnTestComplete = function(result, callback) { - var request = require('request'); + var request = require("request") - var user = process.env.SAUCE_USERNAME; - var pass = process.env.SAUCE_ACCESS_KEY; + var user = process.env.SAUCE_USERNAME + var pass = process.env.SAUCE_ACCESS_KEY request.put({ - url: ['https://saucelabs.com/rest/v1', user, 'jobs', result.job_id].join('/'), + url: [ + "https://saucelabs.com/rest/v1", + user, + "jobs", + result.job_id + ].join("/"), auth: { user: user, pass: pass }, json: { passed: result.passed } - }, function (error, response, body) { + }, function (error, response) { if (error) { - callback(error); + callback(error) } else if (response.statusCode !== 200) { - callback(new Error('Unexpected response status: ' - + response.statusCode + "\n ")); + callback(new Error("Unexpected response status: " + + response.statusCode + "\n ")) } else { - callback(null, result.passed); + callback(null, result.passed) } - }); - }; + }) + } var sauceBaseOptions = { username: process.env.SAUCE_USERNAME, @@ -102,74 +115,164 @@ module.exports = function(grunt) { browsers: sauceBrowsers, sauceConfig: { "record-video": false, - "record-screenshots": false, + "record-screenshots": false }, build: process.env.TRAVIS_JOB_ID, onTestComplete: sauceOnTestComplete, - tunnelTimeout: 5, - }; + tunnelTimeout: 5 + } var sauceCustomOptions = { - testname: "Mithril Custom Tests "+ new Date().toJSON(), - urls: ["http://127.0.0.1:8000/tests/index.html"], - }; - _.assign(sauceCustomOptions, sauceBaseOptions); + testname: "Mithril Custom Tests " + new Date().toJSON(), + urls: ["http://127.0.0.1:8000/tests/index.html"] + } + _.assign(sauceCustomOptions, sauceBaseOptions) var sauceQunitOptions = { - testname: "qUnit Tests "+ new Date().toJSON(), - urls: ["http://127.0.0.1:8000/tests/e2e/test.html"], - }; - _.assign(sauceQunitOptions, sauceBaseOptions); + testname: "qUnit Tests " + new Date().toJSON(), + urls: ["http://127.0.0.1:8000/tests/e2e/test.html"] + } + _.assign(sauceQunitOptions, sauceBaseOptions) - var currentVersionArchiveFolder = archiveFolder + "/v" + version; + var currentVersionArchiveFolder = archiveFolder + "/v" + version grunt.initConfig({ md2html: md2htmlTasks, uglify: { - options: {banner: "/*\nMithril v" + version + "\nhttp://github.com/lhorie/mithril.js\n(c) Leo Horie\nLicense: MIT\n*/", sourceMap: true}, + options: { + banner: [[ + "/*", + "Mithril v" + version, + "http://github.com/lhorie/mithril.js", + "(c) Leo Horie", + "License: MIT", + "*/" + ].join("\n")], + sourceMap: true + }, mithril: {src: "mithril.js", dest: "mithril.min.js"} }, concat: { - test: {src: ["mithril.js", "./tests/test.js", "./tests/mock.js", "./tests/mithril-tests.js"], dest: currentVersionArchiveFolder + "/mithril-tests.js"} + test: { + src: [ + "mithril.js", + "./tests/test.js", + "./tests/mock.js", + "./tests/mithril-tests.js" + ], + dest: currentVersionArchiveFolder + "/mithril-tests.js" + } }, zip: { distribution: { cwd: currentVersionArchiveFolder + "/", - src: [currentVersionArchiveFolder + "/mithril.min.js", currentVersionArchiveFolder + "/mithril.min.js.map", currentVersionArchiveFolder + "/mithril.js"], + src: [ + currentVersionArchiveFolder + "/mithril.min.js", + currentVersionArchiveFolder + "/mithril.min.js.map", + currentVersionArchiveFolder + "/mithril.js" + ], dest: currentVersionArchiveFolder + "/mithril.min.zip" } }, replace: { - options: {force: true, patterns: [{match: /\.md/g, replacement: ".html"}, {match: /\$version/g, replacement: version}]}, - links: {expand: true, flatten: true, src: [tempFolder + "/**/*.html"], dest: currentVersionArchiveFolder + "/"}, - index: {src: inputFolder + "/layout/index.html", dest: currentVersionArchiveFolder + "/index.html"}, - commonjs: {expand: true, flatten: true, src: [inputFolder + "/layout/*.json"], dest: currentVersionArchiveFolder}, - cdnjs: {src: "deploy/cdnjs-package.json", dest: "../cdnjs/ajax/libs/mithril/package.json"} + options: { + force: true, + patterns: [ + {match: /\.md/g, replacement: ".html"}, + {match: /\$version/g, replacement: version} + ] + }, + links: { + expand: true, + flatten: true, + src: [tempFolder + "/**/*.html"], + dest: currentVersionArchiveFolder + "/" + }, + index: { + src: inputFolder + "/layout/index.html", + dest: currentVersionArchiveFolder + "/index.html" + }, + commonjs: { + expand: true, + flatten: true, + src: [inputFolder + "/layout/*.json"], + dest: currentVersionArchiveFolder + }, + cdnjs: { + src: "deploy/cdnjs-package.json", + dest: "../cdnjs/ajax/libs/mithril/package.json" + } }, copy: { - style: {src: inputFolder + "/layout/style.css", dest: currentVersionArchiveFolder + "/style.css"}, - pages: {src: inputFolder + "/layout/pages.json", dest: currentVersionArchiveFolder + "/pages.json"}, - lib: {expand: true, cwd: inputFolder + "/layout/lib/", src: "./**", dest: currentVersionArchiveFolder + "/lib/"}, - tools: {expand: true, cwd: inputFolder + "/layout/tools/", src: "./**", dest: currentVersionArchiveFolder + "/tools/"}, - comparisons: {expand: true, cwd: inputFolder + "/layout/comparisons/", src: "./**", dest: currentVersionArchiveFolder + "/comparisons/"}, - unminified: {src: "mithril.js", dest: currentVersionArchiveFolder + "/mithril.js"}, - minified: {src: "mithril.min.js", dest: currentVersionArchiveFolder + "/mithril.min.js"}, - readme: {src: "README.md", dest: currentVersionArchiveFolder + "/README.md"}, - map: {src: "mithril.min.js.map", dest: currentVersionArchiveFolder + "/mithril.min.js.map"}, - typescript: {src: "mithril.d.ts", dest: currentVersionArchiveFolder + "/mithril.d.ts"}, - publish: {expand: true, cwd: currentVersionArchiveFolder, src: "./**", dest: outputFolder}, - archive: {expand: true, cwd: currentVersionArchiveFolder, src: "./**", dest: outputFolder + "/archive/v" + version}, + style: { + src: inputFolder + "/layout/style.css", + dest: currentVersionArchiveFolder + "/style.css" + }, + pages: { + src: inputFolder + "/layout/pages.json", + dest: currentVersionArchiveFolder + "/pages.json" + }, + lib: { + expand: true, + cwd: inputFolder + "/layout/lib/", + src: "./**", + dest: currentVersionArchiveFolder + "/lib/" + }, + tools: { + expand: true, + cwd: inputFolder + "/layout/tools/", + src: "./**", + dest: currentVersionArchiveFolder + "/tools/" + }, + comparisons: { + expand: true, + cwd: inputFolder + "/layout/comparisons/", + src: "./**", + dest: currentVersionArchiveFolder + "/comparisons/" + }, + unminified: { + src: "mithril.js", + dest: currentVersionArchiveFolder + "/mithril.js" + }, + minified: { + src: "mithril.min.js", + dest: currentVersionArchiveFolder + "/mithril.min.js" + }, + readme: { + src: "README.md", + dest: currentVersionArchiveFolder + "/README.md" + }, + map: { + src: "mithril.min.js.map", + dest: currentVersionArchiveFolder + "/mithril.min.js.map" + }, + typescript: { + src: "mithril.d.ts", + dest: currentVersionArchiveFolder + "/mithril.d.ts" + }, + publish: { + expand: true, + cwd: currentVersionArchiveFolder, + src: "./**", + dest: outputFolder + }, + archive: { + expand: true, + cwd: currentVersionArchiveFolder, + src: "./**", + dest: outputFolder + "/archive/v" + version + } }, execute: { tests: {src: [currentVersionArchiveFolder + "/mithril-tests.js"]} }, qunit: { - all: ['tests/e2e/**/*.html'] + all: ["tests/e2e/**/*.html"] }, "saucelabs-custom": { - all:{ + all: { options: sauceCustomOptions } }, "saucelabs-qunit": { - all:{ + all: { options: sauceQunitOptions } }, @@ -179,7 +282,7 @@ module.exports = function(grunt) { server: { options: { port: 8888, - base: '.' + base: "." } } }, @@ -191,34 +294,45 @@ module.exports = function(grunt) { default: { files: [{ expand: true, - src: ['mithril.js'], - cwd: '.', - dest: '.' + src: ["mithril.js"], + cwd: ".", + dest: "." }] } + }, + eslint: { + target: [ + "**/*.js", + "!node_modules/**", + "!**/*.min.js", + "!docs/layout/lib/**/*.js" + ] } - }); + }) - grunt.loadNpmTasks("grunt-contrib-clean"); - grunt.loadNpmTasks('grunt-contrib-concat'); - grunt.loadNpmTasks("grunt-contrib-copy"); - grunt.loadNpmTasks("grunt-contrib-uglify"); - grunt.loadNpmTasks('grunt-execute'); - grunt.loadNpmTasks("grunt-md2html"); - grunt.loadNpmTasks("grunt-replace"); - grunt.loadNpmTasks('grunt-zip'); - grunt.loadNpmTasks('grunt-contrib-qunit'); - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-saucelabs'); - grunt.loadNpmTasks('grunt-jsfmt'); + grunt.loadNpmTasks("grunt-contrib-clean") + grunt.loadNpmTasks("grunt-contrib-concat") + grunt.loadNpmTasks("grunt-contrib-copy") + grunt.loadNpmTasks("grunt-contrib-uglify") + grunt.loadNpmTasks("grunt-execute") + grunt.loadNpmTasks("grunt-md2html") + grunt.loadNpmTasks("grunt-replace") + grunt.loadNpmTasks("grunt-zip") + grunt.loadNpmTasks("grunt-contrib-qunit") + grunt.loadNpmTasks("grunt-contrib-connect") + grunt.loadNpmTasks("grunt-saucelabs") + grunt.loadNpmTasks("grunt-jsfmt") + grunt.loadNpmTasks("grunt-eslint") - grunt.registerTask("build", ["test", "uglify", "zip", "md2html", "replace", "copy", "clean"]); - grunt.registerTask("testall", ["test", "teste2e"]); - grunt.registerTask("test", ["concat", "execute"]); - grunt.registerTask('teste2e', ['connect', 'qunit']); - grunt.registerTask("default", ["build"]); + grunt.registerTask("build", [ + "test", "uglify", "zip", "md2html", "replace", "copy", "clean"]) + grunt.registerTask("testall", ["test", "teste2e"]) + grunt.registerTask("test", ["eslint", "concat", "execute"]) + grunt.registerTask("teste2e", ["connect", "qunit"]) + grunt.registerTask("default", ["build"]) - grunt.registerTask("sauce-qunit", ["connect", "saucelabs-qunit"]); - grunt.registerTask("sauce-custom", ["connect", "saucelabs-custom"]); - grunt.registerTask("sauce-all", ["connect", "saucelabs-qunit", "saucelabs-custom"]); -}; + grunt.registerTask("sauce-qunit", ["connect", "saucelabs-qunit"]) + grunt.registerTask("sauce-custom", ["connect", "saucelabs-custom"]) + grunt.registerTask("sauce-all", [ + "connect", "saucelabs-qunit", "saucelabs-custom"]) +} diff --git a/README.md b/README.md index 8f8cc956..ca56901a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +**Note: This is a WIP partial rewrite of Mithril.** + [![JS.ORG](https://img.shields.io/badge/js.org-mithril-ffb400.svg?style=flat-square)](http://js.org) [![Join the chat at https://gitter.im/lhorie/mithril.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/lhorie/mithril.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/lhorie/mithril.js.svg?branch=master)](https://travis-ci.org/lhorie/mithril.js) diff --git a/docs/layout/tools/template-converter.js b/docs/layout/tools/template-converter.js index b8cd01cf..79046db2 100644 --- a/docs/layout/tools/template-converter.js +++ b/docs/layout/tools/template-converter.js @@ -1,90 +1,128 @@ -var templateConverter = {}; +/* globals m */ + +var templateConverter = {} templateConverter.DOMFragment = function(markup) { - if (markup.indexOf(" -1) return [new DOMParser().parseFromString(markup, "text/html").childNodes[1]] - var container = document.createElement("div"); - container.insertAdjacentHTML("beforeend", markup); - return container.childNodes; + "use strict" + if (markup.indexOf(" -1) { + return [ + new DOMParser().parseFromString(markup, "text/html").childNodes[1] + ] + } + var container = document.createElement("div") + container.insertAdjacentHTML("beforeend", markup) + return container.childNodes } templateConverter.VirtualFragment = function recurse(domFragment) { - var virtualFragment = []; - for (var i = 0, el; el = domFragment[i]; i++) { - if (el.nodeType == 3) { - virtualFragment.push(el.nodeValue); - } - else if (el.nodeType == 1) { - var attrs = {}; - for (var j = 0, attr; attr = el.attributes[j]; j++) { - attrs[attr.name] = attr.value; + "use strict" + var virtualFragment = [] + for (var i = 0; i < domFragment.length; i++) { + var el = domFragment[i] + if (el.nodeType === 3) { + virtualFragment.push(el.nodeValue) + } else if (el.nodeType === 1) { + var attrs = {} + for (var j = 0; el.attributes.length; j++) { + var attr = el.attributes[j] + attrs[attr.name] = attr.value } - - virtualFragment.push({tag: el.nodeName.toLowerCase(), attrs: attrs, children: recurse(el.childNodes)}); + + virtualFragment.push({ + tag: el.nodeName.toLowerCase(), + attrs: attrs, + children: recurse(el.childNodes) + }) } } - return virtualFragment; + return virtualFragment } templateConverter.Template = function recurse() { - if (Object.prototype.toString.call(arguments[0]) == "[object String]") { - return new recurse(new templateConverter.VirtualFragment(new templateConverter.DOMFragment(arguments[0]))); + "use strict" + if (Object.prototype.toString.call(arguments[0]) === "[object String]") { + return new recurse(new templateConverter.VirtualFragment( + new templateConverter.DOMFragment(arguments[0]))) } - - var virtualFragment = arguments[0], level = arguments[1] - if (!level) level = 1; - - var tab = "\n" + new Array(level + 1).join("\t"); - var virtuals = []; - for (var i = 0, el; el = virtualFragment[i]; i++) { - if (typeof el == "string") { - if (el.match(/\t| {2,}/g) && el.trim().length == 0) virtuals.indented = true; - else virtuals.push('"' + el.replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n") + '"'); - } - else { - var virtual = ""; - if (el.tag != "div") virtual += el.tag; - if (el.attrs["class"]) { - virtual += "." + el.attrs["class"].replace(/\t+/g, " ").split(" ").join("."); - delete el.attrs["class"]; + + var virtualFragment = arguments[0] + var level = arguments[1] + if (!level) level = 1 + + var tab = "\n" + new Array(level + 1).join("\t") + var virtuals = [] + for (var i = 0; i < virtualFragment.length; i++) { + var el = virtualFragment[i] + if (typeof el === "string") { + if (el.match(/\t| {2,}/g) && el.trim().length === 0) { + virtuals.indented = true + } else { + virtuals.push('"' + el + .replace(/"/g, '\\"') + .replace(/\r/g, "\\r") + .replace(/\n/g, "\\n") + '"') + } + } else { + var virtual = "" + if (el.tag !== "div") virtual += el.tag + if (el.attrs.class) { + virtual += "." + el.attrs.class + .replace(/\t+/g, " ") + .split(" ") + .join(".") + delete el.attrs.class } var attrNames = Object.keys(el.attrs).sort() - for (var j = 0, attrName; attrName = attrNames[j]; j++) { - if (attrName != "style") virtual += "[" + attrName + "='" + el.attrs[attrName].replace(/'/g, "\\'") + "']"; + for (var j = 0; j < attrNames.length; j++) { + var attrName = attrNames[j] + if (attrName !== "style") { + virtual += "[" + attrName + "='" + + el.attrs[attrName].replace(/'/g, "\\'") + "']" + } } - if (virtual == "") virtual = "div" - virtual = '"' + virtual + '"'; - - var style = "" + if (virtual === "") virtual = "div" + virtual = '"' + virtual + '"' + if (el.attrs.style) { - virtual += ", {style: " + ("{\"" + el.attrs.style.replace(/:/g, "\": \"").replace(/;/g, "\", \"") + "}").replace(/, "}|"}/, "}") + "}" + virtual += ", {style: " + ("{\"" + el.attrs.style + .replace(/:/g, "\": \"") + .replace(/;/g, "\", \"") + "}") + .replace(/, "}|"}/, "}") + "}" } - + if (el.children.length > 0) { - virtual += ", " + recurse(el.children, level + 1); + virtual += ", " + recurse(el.children, level + 1) } - virtual = "m(" + virtual + ")"; - virtuals.push(virtual); + virtual = "m(" + virtual + ")" + virtuals.push(virtual) } } - if (!virtuals.indented) tab = ""; - - var isInline = virtuals.length == 1 && virtuals[0].charAt(0) == '"'; - var template = isInline ? virtuals.join(", ") : "[" + tab + virtuals.join("," + tab) + tab.slice(0, -1) + "]"; - return new String(template); + if (!virtuals.indented) tab = "" + + var isInline = virtuals.length === 1 && virtuals[0].charAt(0) === '"' + var template = isInline ? + virtuals.join(", ") : + "[" + tab + virtuals.join("," + tab) + tab.slice(0, -1) + "]" + return new String(template) // eslint-disable-line no-new-wrappers } templateConverter.controller = function() { - this.source = m.prop(""); - this.output = m.prop(""); - + "use strict" + this.source = m.prop("") + this.output = m.prop("") + this.convert = function() { - return this.output(new templateConverter.Template(this.source())); - }; - -}; + return this.output(new templateConverter.Template(this.source())) + } +} templateConverter.view = function(ctrl) { + "use strict" return m("div", [ - m("textarea", {autofocus: true, style: {width:"100%", height: "40%"}, onchange: m.withAttr("value", ctrl.source)}, ctrl.source()), + m("textarea", { + autofocus: true, + style: {width: "100%", height: "40%"}, + onchange: m.withAttr("value", ctrl.source) + }, ctrl.source()), m("button", {onclick: ctrl.convert.bind(ctrl)}, "Convert"), - m("textarea", {style: {width:"100%", height: "40%"}}, ctrl.output()) - ]); -}; \ No newline at end of file + m("textarea", {style: {width: "100%", height: "40%"}}, ctrl.output()) + ]) +} diff --git a/mithril.js b/mithril.js index c4ed06fc..06e10307 100644 --- a/mithril.js +++ b/mithril.js @@ -1,33 +1,63 @@ +/* eslint-disable wrap-iife, no-shadow-restricted-names */ var m = (function app(window, undefined) { +/* eslint-enable wrap-iife, no-shadow-restricted-names */ + "use strict" + + function noop() {} + + var type = {}.toString + function isFunction(object) { - return typeof object === "function"; + return typeof object === "function" } + function isObject(object) { - return type.call(object) === "[object Object]"; + return type.call(object) === "[object Object]" } + function isString(object) { - return type.call(object) === "[object String]"; + return type.call(object) === "[object String]" } + var isArray = Array.isArray || function (object) { - return type.call(object) === "[object Array]"; - }; - var type = {}.toString; - var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/; - var voidElements = /^(AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR)$/; - var noop = function () {}; + return type.call(object) === "[object Array]" + } + + var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g + var attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/ + /* eslint-disable max-len */ + var voidElements = /^(AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR)$/ + /* eslint-enable max-len */ // caching commonly used variables - var $document, $location, $requestAnimationFrame, $cancelAnimationFrame; + var $document, $location, $requestAnimationFrame, $cancelAnimationFrame + + var roots = [] + var components = [] + var controllers = [] + var lastRedrawId = null + var lastRedrawCallTime = 0 + var computePreRedrawHook = null + var computePostRedrawHook = null + var unloaders = [] + var FRAME_BUDGET = 16 // 60 frames per second = 1 call per 16 ms + var topComponent + + var redrawing = false + var forcing = false + var pendingRequests = 0 // self invoking function needed because of the way mocks work - function initialize(window){ - $document = window.document; - $location = window.location; - $cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout; - $requestAnimationFrame = window.requestAnimationFrame || window.setTimeout; + function initialize(window) { + $document = window.document + $location = window.location + $cancelAnimationFrame = window.cancelAnimationFrame || + window.clearTimeout + $requestAnimationFrame = window.requestAnimationFrame || + window.setTimeout } - initialize(window); + initialize(window) /** @@ -40,1163 +70,1977 @@ var m = (function app(window, undefined) { * * @param {Tag} The DOM node tag * @param {Object=[]} optional key-value pairs to be mapped to DOM attrs - * @param {...mNode=[]} Zero or more Mithril child nodes. Can be an array, or splat (optional) + * @param {...mNode=[]} Zero or more Mithril child nodes. Can be an array, + * or splat (optional) * */ function m(tag, pairs) { for (var args = [], i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - if (isObject(tag)) return parameterize(tag, args); - var hasAttrs = pairs != null && isObject(pairs) && !("tag" in pairs || "view" in pairs || "subtree" in pairs); - var attrs = hasAttrs ? pairs : {}; - var classAttrName = "class" in attrs ? "class" : "className"; - var cell = {tag: "div", attrs: {}}; - var match, classes = []; - if (!isString(tag)) throw new Error("selector in m(selector, attrs, children) should be a string"); - while (match = parser.exec(tag)) { - if (match[1] === "" && match[2]) cell.tag = match[2]; - else if (match[1] === "#") cell.attrs.id = match[2]; - else if (match[1] === ".") classes.push(match[2]); - else if (match[3][0] === "[") { - var pair = attrParser.exec(match[3]); - cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" :true); - } + args[i - 1] = arguments[i] } - var children = hasAttrs ? args.slice(1) : args; - if (children.length === 1 && isArray(children[0])) { - cell.children = children[0]; + if (isObject(tag)) return parameterize(tag, args) + + var hasAttrs = pairs != null && + isObject(pairs) && + !("tag" in pairs || "view" in pairs || "subtree" in pairs) + + var attrs = hasAttrs ? pairs : {} + var classAttrName = "class" in attrs ? "class" : "className" + var cell = {tag: "div", attrs: {}} + var classes = [] + + if (!isString(tag)) { + throw new Error( + "selector in m(selector, attrs, children) should be a string") } - else { - cell.children = children; + + var match = parser.exec(tag) + + while (match != null) { + if (match[1] === "" && match[2]) { + cell.tag = match[2] + } else if (match[1] === "#") { + cell.attrs.id = match[2] + } else if (match[1] === ".") { + classes.push(match[2]) + } else if (match[3][0] === "[") { + var pair = attrParser.exec(match[3]) + cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" : true) + } + + match = parser.exec(tag) + } + + var children = hasAttrs ? args.slice(1) : args + + if (children.length === 1 && isArray(children[0])) { + cell.children = children[0] + } else { + cell.children = children } for (var attrName in attrs) { if (attrs.hasOwnProperty(attrName)) { - if (attrName === classAttrName && attrs[attrName] != null && attrs[attrName] !== "") { - classes.push(attrs[attrName]); - cell.attrs[attrName] = ""; //create key in correct iteration order + if (attrName === classAttrName && + attrs[attrName] != null && + attrs[attrName] !== "") { + classes.push(attrs[attrName]) + // create key in correct iteration order + cell.attrs[attrName] = "" + } else { + cell.attrs[attrName] = attrs[attrName] } - else cell.attrs[attrName] = attrs[attrName]; } } - if (classes.length) cell.attrs[classAttrName] = classes.join(" "); + if (classes.length) cell.attrs[classAttrName] = classes.join(" ") - return cell; + return cell } + function forEach(list, f) { - for (var i = 0; i < list.length && !f(list[i], i++);) {} + for (var i = 0; i < list.length && !f(list[i], i++);) { + // do nothing + } } + function forKeys(list, f) { forEach(list, function (attrs, i) { - return (attrs = attrs && attrs.attrs) && attrs.key != null && f(attrs, i); - }); + attrs = attrs && attrs.attrs + return attrs && attrs.key != null && f(attrs, i) + }) } + // This function was causing deopts in Chrome. function dataToString(data) { - //data.toString() might throw or return null if data is the return value of Console.log in Firefox (behavior depends on version) + // data.toString() might throw or return null if data is the return + // value of Console.log in Firefox (behavior depends on version) try { - if (data == null || data.toString() == null) data = ""; + if (data == null || data.toString() == null) return "" } catch (e) { - data = ""; + return "" } - return data; + return data } + // This function was causing deopts in Chrome. function injectTextNode(parentElement, first, index, data) { try { - parentElement.insertBefore(first, parentElement.childNodes[index] || null); - first.nodeValue = data; + parentElement.insertBefore( + first, + parentElement.childNodes[index] || null) + first.nodeValue = data + } catch (e) { + // IE erroneously throws error when appending an empty text node + // after a null } - catch (e) {} //IE erroneously throws error when appending an empty text node after a null } - function build(parentElement, parentTag, parentCache, parentIndex, data, cached, shouldReattach, index, editable, namespace, configs) { - //`build` is a recursive function that manages creation/diffing/removal of DOM elements based on comparison between `data` and `cached` - //the diff algorithm can be summarized as this: - //1 - compare `data` and `cached` - //2 - if they are different, copy `data` to `cached` and update the DOM based on what the difference is - //3 - recursively apply this algorithm for every array and for the children of every virtual element - //the `cached` data structure is essentially the same as the previous redraw's `data` data structure, with a few additions: - //- `cached` always has a property called `nodes`, which is a list of DOM elements that correspond to the data represented by the respective virtual element - //- in order to support attaching `nodes` as a property of `cached`, `cached` is *always* a non-primitive object, i.e. if the data was a string, then cached is a String instance. If data was `null` or `undefined`, cached is `new String("")` - //- `cached also has a `configContext` property, which is the state storage object exposed by config(element, isInitialized, context) - //- when `cached` is an Object, it represents a virtual element; when it's an Array, it represents a list of elements; when it's a String, Number or Boolean, it represents a text node - - //`parentElement` is a DOM element used for W3C DOM API calls - //`parentTag` is only used for handling a corner case for textarea values - //`parentCache` is used to remove nodes in some multi-node cases - //`parentIndex` and `index` are used to figure out the offset of nodes. They're artifacts from before arrays started being flattened and are likely refactorable - //`data` and `cached` are, respectively, the new and old nodes being diffed - //`shouldReattach` is a flag indicating whether a parent node was recreated (if so, and if this node is reused, then this node must reattach itself to the new parent) - //`editable` is a flag that indicates whether an ancestor is contenteditable - //`namespace` indicates the closest HTML namespace as it cascades down from an ancestor - //`configs` is a list of config functions to run after the topmost `build` call finishes running - - //there's logic that relies on the assumption that null and undefined data are equivalent to empty strings - //- this prevents lifecycle surprises from procedural helpers that mix implicit and explicit return statements (e.g. function foo() {if (cond) return m("div")} - //- it simplifies diffing code - data = dataToString(data); - if (data.subtree === "retain") return cached; - var cachedType = type.call(cached), dataType = type.call(data); - if (cached == null || cachedType !== dataType) { - if (cached != null) { - if (parentCache && parentCache.nodes) { - var offset = index - parentIndex; - var end = offset + (isArray(data) ? data : cached.nodes).length; - clear(parentCache.nodes.slice(offset, end), parentCache.slice(offset, end)); - } - else if (cached.nodes) clear(cached.nodes, cached); + function flatten(list) { + // recursively flatten array + for (var i = 0; i < list.length; i++) { + if (isArray(list[i])) { + list = list.concat.apply([], list) + // check current index again and flatten until there are no + // more nested arrays at that index + i-- } - cached = new data.constructor; - if (cached.tag) cached = {}; //if constructor creates a virtual dom element, use a blank object as the base cached node instead of copying the virtual el (#277) - cached.nodes = []; } + return list + } + + function insertNode(parentElement, node, index) { + parentElement.insertBefore( + node, + parentElement.childNodes[index] || null) + } + + var DELETION = 1 + var INSERTION = 2 + var MOVE = 3 + + function handleKeysDiffer(data, existing, cached, parentElement) { + forKeys(data, function (attrs, i) { + var key = attrs.key + if (existing[key]) { + existing[key] = { + action: MOVE, + index: i, + from: existing[key].index, + element: cached.nodes[existing[key].index] || + $document.createElement("div") + } + } else { + existing[key] = {action: INSERTION, index: i} + } + }) + var actions = [] + for (var prop in existing) actions.push(existing[prop]) + var changes = actions.sort(sortChanges) + var newCached = new Array(cached.length) + newCached.nodes = cached.nodes.slice() + + forEach(changes, function (change) { + var index = change.index + if (change.action === DELETION) { + clear(cached[index].nodes, cached[index]) + newCached.splice(index, 1) + } + if (change.action === INSERTION) { + var dummy = $document.createElement("div") + dummy.key = data[index].attrs.key + insertNode(parentElement, dummy, index) + newCached.splice(index, 0, { + attrs: {key: data[index].attrs.key}, + nodes: [dummy] + }) + newCached.nodes[index] = dummy + } + + if (change.action === MOVE) { + var changeElement = change.element + var maybeChanged = parentElement.childNodes[index] + if (maybeChanged !== changeElement && changeElement !== null) { + parentElement.insertBefore(changeElement, + maybeChanged || null) + } + newCached[index] = cached[change.from] + newCached.nodes[index] = changeElement + } + }) + + return newCached + } + + function diffKeys(data, cached, existing, parentElement) { + var keysDiffer = data.length !== cached.length + if (!keysDiffer) { + forKeys(data, function (attrs, i) { + var cachedCell = cached[i] + keysDiffer = cachedCell && + cachedCell.attrs && + cachedCell.attrs.key !== attrs.key + return keysDiffer + }) + } + + if (keysDiffer) { + return handleKeysDiffer(data, existing, cached, parentElement) + } else { + return cached + } + } + + function diffArray(data, cached, nodes) { + // diff the array itself + + // update the list of DOM nodes by collecting the nodes from + // each item + forEach(data, function (_, i) { + if (cached[i] != null) { + nodes.push.apply(nodes, cached[i].nodes) + } + }) + // remove items from the end of the array if the new array is + // shorter than the old one. if errors ever happen here, the + // issue is most likely a bug in the construction of the + // `cached` data structure somewhere earlier in the program + forEach(cached.nodes, function (node, i) { + if (node.parentNode != null && nodes.indexOf(node) < 0) { + clear([node], [cached[i]]) + } + }) + if (data.length < cached.length) cached.length = data.length + cached.nodes = nodes + } + + function buildArrayKeys(data) { + var guid = 0 + forKeys(data, function () { + forEach(data, function (attrs) { + if ((attrs = attrs && attrs.attrs) && attrs.key == null) { + attrs.key = "__mithril__" + guid++ + } + }) + return 1 + }) + } + + function maybeRecreateObject(data, cached, dataAttrKeys) { + // if an element is different enough from the one in cache, recreate it + if (data.tag !== cached.tag || + dataAttrKeys.sort().join() !== + Object.keys(cached.attrs).sort().join() || + data.attrs.id !== cached.attrs.id || + data.attrs.key !== cached.attrs.key || + (m.redraw.strategy() === "all" && (!cached.configContext || + cached.configContext.retain !== true)) || + (m.redraw.strategy() === "diff" && cached.configContext && + cached.configContext.retain === false)) { + if (cached.nodes.length) clear(cached.nodes) + if (cached.configContext && + isFunction(cached.configContext.onunload)) { + cached.configContext.onunload() + } + if (cached.controllers) { + forEach(cached.controllers, function (controller) { + if (controller.unload) { + controller.onunload({preventDefault: noop}) + } + }) + } + } + } + + function getObjectNamespace(data, namespace) { + if (data.attrs.xmlns) { + return data.attrs.xmlns + } else if (data.tag === "svg") { + return "http://www.w3.org/2000/svg" + } else if (data.tag === "math") { + return "http://www.w3.org/1998/Math/MathML" + } else { + return namespace + } + } + + function unloadCachedControllers(cached, views, controllers) { + if (controllers.length) { + cached.views = views + cached.controllers = controllers + forEach(controllers, function (controller) { + if (controller.onunload && controller.onunload.$old) { + controller.onunload = controller.onunload.$old + } + if (pendingRequests && controller.onunload) { + var onunload = controller.onunload + controller.onunload = noop + controller.onunload.$old = onunload + } + }) + } + } + + function scheduleConfigsToBeCalled(configs, data, node, isNew, cached) { + // schedule configs to be called. They are called after `build` + // finishes running + if (isFunction(data.attrs.config)) { + var context = cached.configContext = cached.configContext || {} + + // bind + configs.push(function() { + return data.attrs.config.call(data, node, !isNew, context, + cached) + }) + } + } + + function buildUpdatedNode( + cached, + data, + editable, + hasKeys, + namespace, + views, + configs, + controllers) { + var node = cached.nodes[0] + if (hasKeys) { + setAttributes( + node, + data.tag, + data.attrs, + cached.attrs, + namespace) + } + + cached.children = build( + node, + data.tag, + undefined, + undefined, + data.children, + cached.children, + false, + 0, + data.attrs.contenteditable ? node : editable, + namespace, + configs) + + cached.nodes.intact = true + if (controllers.length) { + cached.views = views + cached.controllers = controllers + } + + return node + } + + function handleNonexistentNodes(data, parentElement, index) { + var nodes + if (data.$trusted) { + nodes = injectHTML(parentElement, index, data) + } else { + nodes = [$document.createTextNode(data)] + if (!parentElement.nodeName.match(voidElements)) { + insertNode(parentElement, nodes[0], index) + } + } + + var cached + if (typeof data === "string" || + typeof data === "number" || + typeof data === "boolean") { + cached = new data.constructor(data) + } else { + cached = data + } + cached.nodes = nodes + return cached + } + + function reattachNodes( + data, + cached, + parentElement, + editable, + index, + parentTag) { + var nodes = cached.nodes + if (!editable || editable !== $document.activeElement) { + if (data.$trusted) { + clear(nodes, cached) + nodes = injectHTML(parentElement, index, data) + } else { + // corner case: replacing the nodeValue of a text node + // that is a child of a textarea/contenteditable doesn't + // work. we need to update the value property of the + // parent textarea or the innerHTML of the + // contenteditable element instead + if (parentTag === "textarea") { + parentElement.value = data + } else if (editable) { + editable.innerHTML = data + } else { + // was a trusted string + if (nodes[0].nodeType === 1 || nodes.length > 1) { + clear(cached.nodes, cached) + nodes = [$document.createTextNode(data)] + } + injectTextNode(parentElement, nodes[0], index, data) + } + } + } + cached = new data.constructor(data) + cached.nodes = nodes + return cached + } + + function handleText( + cached, + data, + index, + parentElement, + shouldReattach, + editable, + parentTag) { + // handle text nodes + if (cached.nodes.length === 0) { + return handleNonexistentNodes(data, parentElement, index) + } else if (cached.valueOf() !== data.valueOf() || + shouldReattach === true) { + return reattachNodes( + data, + cached, + parentElement, + editable, + index, + parentTag) + } else { + cached.nodes.intact = true + return cached + } + } + + function getSubArrayCount(item) { + if (item.$trusted) { + // fix offset of next element if item was a trusted + // string w/ more than one html element + // the first clause in the regexp matches elements + // the second clause (after the pipe) matches text nodes + var match = item.match(/<[^\/]|\>\s*[^<]/g) + if (match != null) { + return match.length + } + } else if (isArray(item)) { + return item.length + } + return 1 + } + + function buildArray( + data, + cached, + parentElement, + index, + parentTag, + shouldReattach, + editable, + namespace, + configs) { + data = flatten(data) + var nodes = [] + var intact = cached.length === data.length + var subArrayCount = 0 + + // keys algorithm: sort elements without recreating them if keys are + // present + // 1) create a map of all existing keys, and mark all for deletion + // 2) add new keys to map and mark them for addition + // 3) if key exists in new list, change action from deletion to a + // move + // 4) for each key, handle its corresponding action as marked in + // previous steps + var existing = {} + var shouldMaintainIdentities = false + forKeys(cached, function (attrs, i) { + shouldMaintainIdentities = true + existing[cached[i].attrs.key] = {action: DELETION, index: i} + }) + + buildArrayKeys(data) + + if (shouldMaintainIdentities) { + cached = diffKeys(data, cached, existing, parentElement) + } + // end key algorithm + + var cacheCount = 0 + for (var i = 0, len = data.length; i < len; i++) { + // diff each item in the array + var item = build( + parentElement, + parentTag, + cached, + index, + data[i], + cached[cacheCount], + shouldReattach, + index + subArrayCount || subArrayCount, + editable, + namespace, + configs) + + if (item !== undefined) { + intact = intact && item.nodes.intact + subArrayCount += getSubArrayCount(item) + cached[cacheCount++] = item + } + } + + if (!intact) diffArray(data, cached, nodes) + + return cached + } + + function makeCache(data, cached, index, parentIndex, parentCache) { + if (cached != null) { + if (type.call(cached) === type.call(data)) return cached + + if (parentCache && parentCache.nodes) { + var offset = index - parentIndex + var end = offset + + (isArray(data) ? data : cached.nodes).length + clear( + parentCache.nodes.slice(offset, end), + parentCache.slice(offset, end)) + } else if (cached.nodes) { + clear(cached.nodes, cached) + } + } + + cached = new data.constructor() + // if constructor creates a virtual dom element, use a blank object + // as the base cached node instead of copying the virtual el (#277) + if (cached.tag) cached = {} + + cached.nodes = [] + + return cached + } + + function constructNode(data, namespace) { + if (data.attrs.is) { + if (namespace === undefined) { + return $document.createElement(data.tag, data.attrs.is) + } else { + return $document.createElementNS(namespace, data.tag, + data.attrs.is) + } + } else { + if (namespace === undefined) { + return $document.createElement(data.tag) + } else { + return $document.createElementNS(namespace, data.tag) + } + } + } + + function constructAttrs(data, node, namespace, hasKeys) { + if (hasKeys) { + return setAttributes( + node, + data.tag, + data.attrs, + {}, + namespace) + } else { + return data.attrs + } + } + + function constructChildren( + data, + node, + cached, + editable, + namespace, + configs) { + if (data.children != null && data.children.length > 0) { + return build( + node, + data.tag, + undefined, + undefined, + data.children, + cached.children, + true, + 0, + data.attrs.contenteditable ? node : editable, + namespace, + configs) + } else { + return data.children + } + } + + function reconstructCached( + data, + cached, + attrs, + children, + node, + namespace, + views, + controllers) { + cached = { + tag: data.tag, + attrs: attrs, + children: children, + nodes: [node] + } + + unloadCachedControllers(cached, views, controllers) + + if (cached.children && !cached.children.nodes) { + cached.children.nodes = [] + } + // edge case: setting value on doesn't work before children exist, so set it again after children have been created - if (data.tag === "select" && "value" in data.attrs) setAttributes(node, data.tag, {value: data.attrs.value}, {}, namespace); - parentElement.insertBefore(node, parentElement.childNodes[index] || null); - } - else { - node = cached.nodes[0]; - if (hasKeys) setAttributes(node, data.tag, data.attrs, cached.attrs, namespace); - cached.children = build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs); - cached.nodes.intact = true; - if (controllers.length) { - cached.views = views; - cached.controllers = controllers; - } - if (shouldReattach === true && node != null) parentElement.insertBefore(node, parentElement.childNodes[index] || null); - } - //schedule configs to be called. They are called after `build` finishes running - if (isFunction(data.attrs["config"])) { - var context = cached.configContext = cached.configContext || {}; - - // bind - var callback = function(data, args) { - return function() { - return data.attrs["config"].apply(data, args); - }; - }; - configs.push(callback(data, [node, !isNew, context, cached])); - } - } - else if (!isFunction(data)) { - //handle text nodes - var nodes; - if (cached.nodes.length === 0) { - if (data.$trusted) { - nodes = injectHTML(parentElement, index, data); - } - else { - nodes = [$document.createTextNode(data)]; - if (!parentElement.nodeName.match(voidElements)) parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null); - } - cached = "string number boolean".indexOf(typeof data) > -1 ? new data.constructor(data) : data; - cached.nodes = nodes; - } - else if (cached.valueOf() !== data.valueOf() || shouldReattach === true) { - nodes = cached.nodes; - if (!editable || editable !== $document.activeElement) { - if (data.$trusted) { - clear(nodes, cached); - nodes = injectHTML(parentElement, index, data); - } - else { - //corner case: replacing the nodeValue of a text node that is a child of a textarea/contenteditable doesn't work - //we need to update the value property of the parent textarea or the innerHTML of the contenteditable element instead - if (parentTag === "textarea") parentElement.value = data; - else if (editable) editable.innerHTML = data; - else { - if (nodes[0].nodeType === 1 || nodes.length > 1) { //was a trusted string - clear(cached.nodes, cached); - nodes = [$document.createTextNode(data)]; - } - injectTextNode(parentElement, nodes[0], index, data) - } - } - } - cached = new data.constructor(data); - cached.nodes = nodes; - } - else cached.nodes.intact = true; + return buildArray( + data, + cached, + parentElement, + index, + parentTag, + shouldReattach, + editable, + namespace, + configs) + } else if (data != null && isObject(data)) { + return buildObject( + data, + cached, + editable, + parentElement, + index, + shouldReattach, + namespace, + configs) + } else if (!isFunction(data)) { + return handleText( + cached, + data, + index, + parentElement, + shouldReattach, + editable, + parentTag) + } else { + return cached } - return cached; } - function sortChanges(a, b) { return a.action - b.action || a.index - b.index; } + function sortChanges(a, b) { + return a.action - b.action || a.index - b.index + } function setAttributes(node, tag, dataAttrs, cachedAttrs, namespace) { for (var attrName in dataAttrs) { - var dataAttr = dataAttrs[attrName]; - var cachedAttr = cachedAttrs[attrName]; + var dataAttr = dataAttrs[attrName] + var cachedAttr = cachedAttrs[attrName] + var rule if (!(attrName in cachedAttrs) || (cachedAttr !== dataAttr)) { - cachedAttrs[attrName] = dataAttr; + cachedAttrs[attrName] = dataAttr try { - //`config` isn't a real attributes, so ignore it - if (attrName === "config" || attrName == "key") continue; - //hook event handlers to the auto-redrawing system - else if (isFunction(dataAttr) && attrName.indexOf("on") === 0) { - node[attrName] = autoredraw(dataAttr, node); - } - //handle `style: {...}` - else if (attrName === "style" && dataAttr != null && isObject(dataAttr)) { - for (var rule in dataAttr) { - if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule]; + if (attrName === "config" || attrName === "key") { + // `config` isn't a real attributes, so ignore it + } else if (isFunction(dataAttr) && + attrName.slice(0, 2) === "on") { + // hook event handlers to the auto-redrawing system + node[attrName] = autoredraw(dataAttr, node) + } else if (attrName === "style" && + dataAttr != null && + isObject(dataAttr)) { + // handle `style: {...}` + for (rule in dataAttr) { + if (cachedAttr == null || + cachedAttr[rule] !== dataAttr[rule]) { + node.style[rule] = dataAttr[rule] + } } - for (var rule in cachedAttr) { - if (!(rule in dataAttr)) node.style[rule] = ""; + for (rule in cachedAttr) { + if (!(rule in dataAttr)) node.style[rule] = "" } + } else if (namespace != null) { + // handle SVG + if (attrName === "href") { + node.setAttributeNS( + "http://www.w3.org/1999/xlink", + "href", + dataAttr) + } else if (attrName === "className") { + node.setAttribute("class", dataAttr) + } else { + node.setAttribute(attrName, dataAttr) + } + } else if (attrName in node && + !(attrName === "list" || + attrName === "style" || + attrName === "form" || + attrName === "type" || + attrName === "width" || + attrName === "height")) { + // handle cases that are properties (but ignore cases + // where we should use setAttribute instead) + // - list and form are typically used as strings, but + // are DOM element references in js + // - when using CSS selectors (e.g. `m("[style='']")`), + // style is used as a string, but it's an object in js + + // #348 don't set the value if not needed otherwise + // cursor placement breaks in Chrome + if (tag !== "input" || node[attrName] !== dataAttr) { + node[attrName] = dataAttr + } + } else { + node.setAttribute(attrName, dataAttr) } - //handle SVG - else if (namespace != null) { - if (attrName === "href") node.setAttributeNS("http://www.w3.org/1999/xlink", "href", dataAttr); - else if (attrName === "className") node.setAttribute("class", dataAttr); - else node.setAttribute(attrName, dataAttr); - } - //handle cases that are properties (but ignore cases where we should use setAttribute instead) - //- list and form are typically used as strings, but are DOM element references in js - //- when using CSS selectors (e.g. `m("[style='']")`), style is used as a string, but it's an object in js - else if (attrName in node && !(attrName === "list" || attrName === "style" || attrName === "form" || attrName === "type" || attrName === "width" || attrName === "height")) { - //#348 don't set the value if not needed otherwise cursor placement breaks in Chrome - if (tag !== "input" || node[attrName] !== dataAttr) node[attrName] = dataAttr; - } - else node.setAttribute(attrName, dataAttr); + } catch (e) { + // swallow IE's invalid argument errors to mimic HTML's + // fallback-to-doing-nothing-on-invalid-attributes behavior + if (e.message.indexOf("Invalid argument") < 0) throw e } - catch (e) { - //swallow IE's invalid argument errors to mimic HTML's fallback-to-doing-nothing-on-invalid-attributes behavior - if (e.message.indexOf("Invalid argument") < 0) throw e; - } - } - //#348 dataAttr may not be a string, so use loose comparison (double equal) instead of strict (triple equal) - else if (attrName === "value" && tag === "input" && node.value != dataAttr) { - node.value = dataAttr; + } else if (attrName === "value" && + tag === "input" && + node.value !== dataAttr) { + // #348 dataAttr may not be a string, so use loose comparison + // (double equal) instead of strict (triple equal) + node.value = dataAttr } } - return cachedAttrs; + + return cachedAttrs } + function clear(nodes, cached) { for (var i = nodes.length - 1; i > -1; i--) { if (nodes[i] && nodes[i].parentNode) { - try { nodes[i].parentNode.removeChild(nodes[i]); } - catch (e) {} //ignore if this fails due to order of events (see http://stackoverflow.com/questions/21926083/failed-to-execute-removechild-on-node) - cached = [].concat(cached); - if (cached[i]) unload(cached[i]); + try { + nodes[i].parentNode.removeChild(nodes[i]) + } catch (e) { + /* eslint-disable max-len */ + // ignore if this fails due to order of events (see + // http://stackoverflow.com/questions/21926083/failed-to-execute-removechild-on-node) + /* eslint-enable max-len */ + } + cached = [].concat(cached) + if (cached[i]) unload(cached[i]) } } - if (nodes.length != 0) nodes.length = 0; + nodes.length = 0 } + function unload(cached) { if (cached.configContext && isFunction(cached.configContext.onunload)) { - cached.configContext.onunload(); - cached.configContext.onunload = null; + cached.configContext.onunload() + cached.configContext.onunload = null } if (cached.controllers) { - for (var i = 0, controller; controller = cached.controllers[i]; i++) { - if (isFunction(controller.onunload)) controller.onunload({preventDefault: noop}); - } + forEach(cached.controllers, function (controller) { + if (isFunction(controller.onunload)) { + controller.onunload({preventDefault: noop}) + } + }) } if (cached.children) { if (isArray(cached.children)) { - for (var i = 0, child; child = cached.children[i]; i++) unload(child); + forEach(cached.children, unload) + } else if (cached.children.tag) { + unload(cached.children) } - else if (cached.children.tag) unload(cached.children); } } - function injectHTML(parentElement, index, data) { - var nextSibling = parentElement.childNodes[index]; - if (nextSibling) { - var isElement = nextSibling.nodeType != 1; - var placeholder = $document.createElement("span"); - if (isElement) { - parentElement.insertBefore(placeholder, nextSibling || null); - placeholder.insertAdjacentHTML("beforebegin", data); - parentElement.removeChild(placeholder); - } - else nextSibling.insertAdjacentHTML("beforebegin", data); - } - else parentElement.insertAdjacentHTML("beforeend", data); - var nodes = []; - while (parentElement.childNodes[index] !== nextSibling) { - nodes.push(parentElement.childNodes[index]); - index++; - } - return nodes; - } - function autoredraw(callback, object) { - return function(e) { - e = e || event; - m.redraw.strategy("diff"); - m.startComputation(); - try { return callback.call(object, e); } - finally { - endFirstComputation(); - } - }; - } - var html; + function injectHTML(parentElement, index, data) { + var nextSibling = parentElement.childNodes[index] + if (nextSibling) { + var isElement = nextSibling.nodeType !== 1 + var placeholder = $document.createElement("span") + if (isElement) { + parentElement.insertBefore(placeholder, nextSibling || null) + placeholder.insertAdjacentHTML("beforebegin", data) + parentElement.removeChild(placeholder) + } else { + nextSibling.insertAdjacentHTML("beforebegin", data) + } + } else { + parentElement.insertAdjacentHTML("beforeend", data) + } + var nodes = [] + while (parentElement.childNodes[index] !== nextSibling) { + nodes.push(parentElement.childNodes[index]) + index++ + } + return nodes + } + + function autoredraw(callback, object) { + return function(e) { + e = e || event + m.redraw.strategy("diff") + m.startComputation() + try { + return callback.call(object, e) + } finally { + endFirstComputation() + } + } + } + + var html var documentNode = { appendChild: function(node) { - if (html === undefined) html = $document.createElement("html"); - if ($document.documentElement && $document.documentElement !== node) { - $document.replaceChild(node, $document.documentElement); + if (html === undefined) html = $document.createElement("html") + if ($document.documentElement && + $document.documentElement !== node) { + $document.replaceChild(node, $document.documentElement) + } else { + $document.appendChild(node) } - else $document.appendChild(node); - this.childNodes = $document.childNodes; + this.childNodes = $document.childNodes }, insertBefore: function(node) { - this.appendChild(node); + this.appendChild(node) }, childNodes: [] - }; - var nodeCache = [], cellCache = {}; + } + + var nodeCache = [] + var cellCache = {} + m.render = function(root, cell, forceRecreation) { - var configs = []; - if (!root) throw new Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined."); - var id = getCellCacheKey(root); - var isDocumentRoot = root === $document; - var node = isDocumentRoot || root === $document.documentElement ? documentNode : root; - if (isDocumentRoot && cell.tag != "html") cell = {tag: "html", attrs: {}, children: cell}; - if (cellCache[id] === undefined) clear(node.childNodes); - if (forceRecreation === true) reset(root); - cellCache[id] = build(node, null, undefined, undefined, cell, cellCache[id], false, 0, null, undefined, configs); - for (var i = 0, len = configs.length; i < len; i++) configs[i](); - }; + var configs = [] + if (!root) { + throw new Error("Ensure the DOM element being passed to " + + "m.route/m.mount/m.render is not undefined.") + } + var id = getCellCacheKey(root) + var isDocumentRoot = root === $document + var node + if (isDocumentRoot || root === $document.documentElement) { + node = documentNode + } else { + node = root + } + if (isDocumentRoot && cell.tag !== "html") { + cell = {tag: "html", attrs: {}, children: cell} + } + if (cellCache[id] === undefined) clear(node.childNodes) + if (forceRecreation === true) reset(root) + + cellCache[id] = build( + node, + null, + undefined, + undefined, + cell, + cellCache[id], + false, + 0, + null, + undefined, + configs) + + forEach(configs, function (config) { + config() + }) + } + function getCellCacheKey(element) { - var index = nodeCache.indexOf(element); - return index < 0 ? nodeCache.push(element) - 1 : index; + var index = nodeCache.indexOf(element) + return index < 0 ? nodeCache.push(element) - 1 : index } m.trust = function(value) { - value = new String(value); - value.$trusted = true; - return value; - }; + /* eslint-disable no-new-wrappers */ + value = new String(value) + /* eslint-enable no-new-wrappers */ + value.$trusted = true + return value + } function gettersetter(store) { var prop = function() { - if (arguments.length) store = arguments[0]; - return store; - }; + if (arguments.length) store = arguments[0] + return store + } prop.toJSON = function() { - return store; - }; + return store + } - return prop; + return prop } m.prop = function (store) { - //note: using non-strict equality check here because we're checking if store is null OR undefined - if ((store != null && isObject(store) || isFunction(store)) && isFunction(store.then)) { - return propify(store); + // note: using non-strict equality check here because we're checking if + // store is null OR undefined + if ((store != null && isObject(store) || isFunction(store)) && + isFunction(store.then)) { + return propify(store) } - return gettersetter(store); - }; + return gettersetter(store) + } - var roots = [], components = [], controllers = [], lastRedrawId = null, lastRedrawCallTime = 0, computePreRedrawHook = null, computePostRedrawHook = null, topComponent, unloaders = []; - var FRAME_BUDGET = 16; //60 frames per second = 1 call per 16 ms function parameterize(component, args) { var controller = function() { - return (component.controller || noop).apply(this, args) || this; - }; + return (component.controller || noop).apply(this, args) || this + } var view = function(ctrl) { - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - return component.view.apply(component, args ? [ctrl].concat(args) : [ctrl]); - }; - view.$original = component.view; - var output = {controller: controller, view: view}; - if (args[0] && args[0].key != null) output.attrs = {key: args[0].key}; - return output; + for (var i = 1; i < arguments.length; i++) { + args.push(arguments[i]) + } + return component.view.apply(component, [ctrl].concat(args)) + } + view.$original = component.view + var output = {controller: controller, view: view} + if (args[0] && args[0].key != null) output.attrs = {key: args[0].key} + return output } m.component = function(component) { - for (var args = [], i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; - return parameterize(component, args); - }; + for (var args = [], i = 1; i < arguments.length; i++) { + args.push(arguments[i]) + } + return parameterize(component, args) + } m.mount = m.module = function(root, component) { - if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it."); - var index = roots.indexOf(root); - if (index < 0) index = roots.length; + if (!root) { + throw new Error("Please ensure the DOM element exists before " + + "rendering a template into it.") + } + var index = roots.indexOf(root) + if (index < 0) index = roots.length - var isPrevented = false; - var event = {preventDefault: function() { - isPrevented = true; - computePreRedrawHook = computePostRedrawHook = null; - }}; - for (var i = 0, unloader; unloader = unloaders[i]; i++) { - unloader.handler.call(unloader.controller, event); - unloader.controller.onunload = null; + var isPrevented = false + var event = { + preventDefault: function() { + isPrevented = true + computePreRedrawHook = computePostRedrawHook = null + } } + + forEach(unloaders, function (unloader) { + unloader.handler.call(unloader.controller, event) + unloader.controller.onunload = null + }) + if (isPrevented) { - for (var i = 0, unloader; unloader = unloaders[i]; i++) unloader.controller.onunload = unloader.handler; + forEach(unloaders, function (unloader) { + unloader.controller.onunload = unloader.handler + }) + } else { + unloaders = [] } - else unloaders = []; if (controllers[index] && isFunction(controllers[index].onunload)) { - controllers[index].onunload(event); + controllers[index].onunload(event) } if (!isPrevented) { - m.redraw.strategy("all"); - m.startComputation(); - roots[index] = root; - if (arguments.length > 2) component = subcomponent(component, [].slice.call(arguments, 2)); - var currentComponent = topComponent = component = component || {controller: noop}; - var constructor = component.controller || noop; - var controller = new constructor; - //controllers may call m.mount recursively (via m.route redirects, for example) - //this conditional ensures only the last recursive m.mount call is applied + m.redraw.strategy("all") + m.startComputation() + roots[index] = root + var currentComponent + if (component) { + currentComponent = topComponent = component + } else { + currentComponent = topComponent = component = {controller: noop} + } + var constructor = component.controller || noop + var controller = new constructor() + // controllers may call m.mount recursively (via m.route redirects, + // for example). this conditional ensures only the last recursive + // m.mount call is applied if (currentComponent === topComponent) { - controllers[index] = controller; - components[index] = component; + controllers[index] = controller + components[index] = component } - endFirstComputation(); - return controllers[index]; + endFirstComputation() + return controllers[index] } - }; - var redrawing = false, forcing = false; + } m.redraw = function(force) { - if (redrawing) return; - redrawing = true; - if (force) forcing = true; + if (redrawing) return + redrawing = true + if (force) forcing = true try { - //lastRedrawId is a positive number if a second redraw is requested before the next animation frame - //lastRedrawID is null if it's the first redraw and not an event handler + // lastRedrawId is a positive number if a second redraw is requested + // before the next animation frame + // lastRedrawID is null if it's the first redraw and not an event + // handler if (lastRedrawId && !force) { - //when setTimeout: only reschedule redraw if time between now and previous redraw is bigger than a frame, otherwise keep currently scheduled timeout - //when rAF: always reschedule redraw - if ($requestAnimationFrame === window.requestAnimationFrame || new Date - lastRedrawCallTime > FRAME_BUDGET) { - if (lastRedrawId > 0) $cancelAnimationFrame(lastRedrawId); - lastRedrawId = $requestAnimationFrame(redraw, FRAME_BUDGET); + // when setTimeout: only reschedule redraw if time between now + // and previous redraw is bigger than a frame, otherwise keep + // currently scheduled timeout + // when rAF: always reschedule redraw + if ($requestAnimationFrame === window.requestAnimationFrame || + new Date() - lastRedrawCallTime > FRAME_BUDGET) { + if (lastRedrawId > 0) $cancelAnimationFrame(lastRedrawId) + lastRedrawId = $requestAnimationFrame(redraw, FRAME_BUDGET) } + } else { + redraw() + lastRedrawId = $requestAnimationFrame(function() { + lastRedrawId = null + }, FRAME_BUDGET) } - else { - redraw(); - lastRedrawId = $requestAnimationFrame(function() { lastRedrawId = null; }, FRAME_BUDGET); - } + } finally { + redrawing = forcing = false } - finally { - redrawing = forcing = false; - } - }; - m.redraw.strategy = m.prop(); + } + m.redraw.strategy = m.prop() function redraw() { if (computePreRedrawHook) { - computePreRedrawHook(); - computePreRedrawHook = null; + computePreRedrawHook() + computePreRedrawHook = null } - for (var i = 0, root; root = roots[i]; i++) { + forEach(roots, function (root, i) { + var component = components[i] if (controllers[i]) { - var args = components[i].controller && components[i].controller.$$args ? [controllers[i]].concat(components[i].controller.$$args) : [controllers[i]]; - m.render(root, components[i].view ? components[i].view(controllers[i], args) : ""); + var args + if (component.controller && component.controller.$$args) { + args = [controllers[i]].concat(component.controller.$$args) + } else { + args = [controllers[i]] + } + var view + if (component.view) { + view = component.view(controllers[i], args) + } else { + view = "" + } + m.render(root, view) } - } - //after rendering within a routed context, we need to scroll back to the top, and fetch the document title for history.pushState + }) + // after rendering within a routed context, we need to scroll back to + // the top, and fetch the document title for history.pushState if (computePostRedrawHook) { - computePostRedrawHook(); - computePostRedrawHook = null; + computePostRedrawHook() + computePostRedrawHook = null } - lastRedrawId = null; - lastRedrawCallTime = new Date; - m.redraw.strategy("diff"); + lastRedrawId = null + lastRedrawCallTime = new Date() + m.redraw.strategy("diff") } - var pendingRequests = 0; - m.startComputation = function() { pendingRequests++; }; + m.startComputation = function() { pendingRequests++ } m.endComputation = function() { - pendingRequests = Math.max(pendingRequests - 1, 0); - if (pendingRequests === 0) m.redraw(); - }; - var endFirstComputation = function() { - if (m.redraw.strategy() == "none") { - pendingRequests--; - m.redraw.strategy("diff"); + if (pendingRequests > 1) { + pendingRequests-- + } else { + pendingRequests = 0 + m.redraw() } - else m.endComputation(); - }; + } + + function endFirstComputation() { + if (m.redraw.strategy() === "none") { + pendingRequests-- + m.redraw.strategy("diff") + } else { + m.endComputation() + } + } m.withAttr = function(prop, withAttrCallback) { return function(e) { - e = e || event; - var currentTarget = e.currentTarget || this; - withAttrCallback(prop in currentTarget ? currentTarget[prop] : currentTarget.getAttribute(prop)); - }; - }; + e = e || event + var currentTarget = e.currentTarget || this + var arg + if (prop in currentTarget) { + arg = currentTarget[prop] + } else { + arg = currentTarget.getAttribute(prop) + } + withAttrCallback(arg) + } + } - //routing - var modes = {pathname: "", hash: "#", search: "?"}; - var redirect = noop, routeParams, currentRoute, isDefaultRoute = false; + // routing + var modes = {pathname: "", hash: "#", search: "?"} + var redirect = noop + var isDefaultRoute = false + var routeParams, currentRoute m.route = function(root, arg1, arg2, vdom) { - //m.route() - if (arguments.length === 0) return currentRoute; - //m.route(el, defaultRoute, routes) - else if (arguments.length === 3 && isString(arg1)) { + // m.route() + if (arguments.length === 0) { + return currentRoute + } else if (arguments.length === 3 && isString(arg1)) { + // m.route(el, defaultRoute, routes) redirect = function(source) { - var path = currentRoute = normalizeRoute(source); + var path = currentRoute = normalizeRoute(source) if (!routeByValue(root, arg2, path)) { - if (isDefaultRoute) throw new Error("Ensure the default route matches one of the routes defined in m.route"); - isDefaultRoute = true; - m.route(arg1, true); - isDefaultRoute = false; + if (isDefaultRoute) { + throw new Error("Ensure the default route matches " + + "one of the routes defined in m.route") + } + isDefaultRoute = true + m.route(arg1, true) + isDefaultRoute = false } - }; - var listener = m.route.mode === "hash" ? "onhashchange" : "onpopstate"; - window[listener] = function() { - var path = $location[m.route.mode]; - if (m.route.mode === "pathname") path += $location.search; - if (currentRoute != normalizeRoute(path)) { - redirect(path); - } - }; - computePreRedrawHook = setScroll; - window[listener](); - } - //config: m.route - else if (root.addEventListener || root.attachEvent) { - root.href = (m.route.mode !== 'pathname' ? $location.pathname : '') + modes[m.route.mode] + vdom.attrs.href; - if (root.addEventListener) { - root.removeEventListener("click", routeUnobtrusive); - root.addEventListener("click", routeUnobtrusive); } - else { - root.detachEvent("onclick", routeUnobtrusive); - root.attachEvent("onclick", routeUnobtrusive); + var listener + if (m.route.mode === "hash") { + listener = "onhashchange" + } else { + listener = "onpopstate" } - } - //m.route(route, params, shouldReplaceHistoryEntry) - else if (isString(root)) { - var oldRoute = currentRoute; - currentRoute = root; - arg1 || {}; - var queryIndex = currentRoute.indexOf("?"); - var params = queryIndex > -1 ? parseQueryString(currentRoute.slice(queryIndex + 1)) : {}; - for (var i in arg1) params[i] = arg1[i]; - var querystring = buildQueryString(params); - var currentPath = queryIndex > -1 ? currentRoute.slice(0, queryIndex) : currentRoute; - if (querystring) currentRoute = currentPath + (currentPath.indexOf("?") === -1 ? "?" : "&") + querystring; - var shouldReplaceHistoryEntry = (arguments.length === 3 ? arg2 : arg1) === true || oldRoute === root; + window[listener] = function() { + var path = $location[m.route.mode] + if (m.route.mode === "pathname") path += $location.search + if (currentRoute !== normalizeRoute(path)) { + redirect(path) + } + } + + computePreRedrawHook = setScroll + window[listener]() + } else if (root.addEventListener || root.attachEvent) { + // config: m.route + var pathname = m.route.mode !== "pathname" ? $location.pathname : "" + root.href = pathname + modes[m.route.mode] + vdom.attrs.href + if (root.addEventListener) { + root.removeEventListener("click", routeUnobtrusive) + root.addEventListener("click", routeUnobtrusive) + } else { + root.detachEvent("onclick", routeUnobtrusive) + root.attachEvent("onclick", routeUnobtrusive) + } + } else if (isString(root)) { + // m.route(route, params, shouldReplaceHistoryEntry) + var oldRoute = currentRoute + currentRoute = root + arg1 = arg1 || {} + var queryIndex = currentRoute.indexOf("?") + var params + if (queryIndex > -1) { + params = parseQueryString(currentRoute.slice(queryIndex + 1)) + } else { + params = {} + } + for (var i in arg1) params[i] = arg1[i] + var querystring = buildQueryString(params) + var currentPath + + if (queryIndex > -1) { + currentPath = currentRoute.slice(0, queryIndex) + } else { + currentPath = currentRoute + } + + var separator = currentPath.indexOf("?") === -1 ? "?" : "&" + + if (querystring) { + currentRoute = currentPath + separator + querystring + } + + var shouldReplaceHistoryEntry + if (arguments.length === 3) { + shouldReplaceHistoryEntry = arg2 + } else { + shouldReplaceHistoryEntry = arg1 + } + + shouldReplaceHistoryEntry = shouldReplaceHistoryEntry === true || + oldRoute === root if (window.history.pushState) { - computePreRedrawHook = setScroll; + computePreRedrawHook = setScroll computePostRedrawHook = function() { - window.history[shouldReplaceHistoryEntry ? "replaceState" : "pushState"](null, $document.title, modes[m.route.mode] + currentRoute); - }; - redirect(modes[m.route.mode] + currentRoute); - } - else { - $location[m.route.mode] = currentRoute; - redirect(modes[m.route.mode] + currentRoute); + var listener + if (shouldReplaceHistoryEntry) { + listener = "replaceState" + } else { + listener = "pushState" + } + window.history[listener]( + null, + $document.title, + modes[m.route.mode] + currentRoute) + } + redirect(modes[m.route.mode] + currentRoute) + } else { + $location[m.route.mode] = currentRoute + redirect(modes[m.route.mode] + currentRoute) } } - }; + } m.route.param = function(key) { - if (!routeParams) throw new Error("You must call m.route(element, defaultRoute, routes) before calling m.route.param()"); - return routeParams[key]; - }; - m.route.mode = "search"; + if (!routeParams) { + throw new Error("You must call m.route(element, defaultRoute, " + + "routes) before calling m.route.param()") + } + return routeParams[key] + } + m.route.mode = "search" function normalizeRoute(route) { - return route.slice(modes[m.route.mode].length); + return route.slice(modes[m.route.mode].length) } function routeByValue(root, router, path) { - routeParams = {}; + routeParams = {} - var queryStart = path.indexOf("?"); + var queryStart = path.indexOf("?") if (queryStart !== -1) { - routeParams = parseQueryString(path.substr(queryStart + 1, path.length)); - path = path.substr(0, queryStart); + routeParams = parseQueryString( + path.substr(queryStart + 1, path.length)) + path = path.substr(0, queryStart) } // Get all routes and check if there's // an exact match for the current path - var keys = Object.keys(router); - var index = keys.indexOf(path); + var keys = Object.keys(router) + var index = keys.indexOf(path) if(index !== -1){ - m.mount(root, router[keys [index]]); - return true; + m.mount(root, router[keys [index]]) + return true } for (var route in router) { if (route === path) { - m.mount(root, router[route]); - return true; + m.mount(root, router[route]) + return true } - var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$"); + var matcher = new RegExp("^" + route + .replace(/:[^\/]+?\.{3}/g, "(.*?)") + .replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$") if (matcher.test(path)) { + /* eslint-disable no-loop-func */ path.replace(matcher, function() { - var keys = route.match(/:[^\/]+/g) || []; - var values = [].slice.call(arguments, 1, -2); - for (var i = 0, len = keys.length; i < len; i++) routeParams[keys[i].replace(/:|\./g, "")] = decodeURIComponent(values[i]); - m.mount(root, router[route]); - }); - return true; + var keys = route.match(/:[^\/]+/g) || [] + var values = [].slice.call(arguments, 1, -2) + forEach(keys, function (key, i) { + routeParams[key.replace(/:|\./g, "")] = + decodeURIComponent(values[i]) + }) + m.mount(root, router[route]) + }) + /* eslint-enable no-loop-func */ + return true } } } function routeUnobtrusive(e) { - e = e || event; - if (e.ctrlKey || e.metaKey || e.which === 2) return; - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - var currentTarget = e.currentTarget || e.srcElement; - var args = m.route.mode === "pathname" && currentTarget.search ? parseQueryString(currentTarget.search.slice(1)) : {}; - while (currentTarget && currentTarget.nodeName.toUpperCase() != "A") currentTarget = currentTarget.parentNode; - m.route(currentTarget[m.route.mode].slice(modes[m.route.mode].length), args); + e = e || event + + if (e.ctrlKey || e.metaKey || e.which === 2) return + + if (e.preventDefault) e.preventDefault() + else e.returnValue = false + + var currentTarget = e.currentTarget || e.srcElement + var hasQuery = m.route.mode === "pathname" && currentTarget.search + var args + + if (hasQuery) { + args = parseQueryString(currentTarget.search.slice(1)) + } else { + args = {} + } + + while (currentTarget && currentTarget.nodeName.toUpperCase() !== "A") { + currentTarget = currentTarget.parentNode + } + + var target = currentTarget[m.route.mode] + .slice(modes[m.route.mode].length) + + m.route(target, args) } function setScroll() { - if (m.route.mode != "hash" && $location.hash) $location.hash = $location.hash; - else window.scrollTo(0, 0); + if (m.route.mode !== "hash" && $location.hash) { + $location.hash = $location.hash + } else { + window.scrollTo(0, 0) + } } function buildQueryString(object, prefix) { - var duplicates = {}; - var str = []; + var duplicates = {} + var str = [] for (var prop in object) { - var key = prefix ? prefix + "[" + prop + "]" : prop; - var value = object[prop]; - var valueType = type.call(value); - var pair = (value === null) ? encodeURIComponent(key) : - isObject(value) ? buildQueryString(value, key) : - isArray(value) ? value.reduce(function(memo, item) { - if (!duplicates[key]) duplicates[key] = {}; + var key = prefix ? prefix + "[" + prop + "]" : prop + var value = object[prop] + + if (value === null) { + str.push(encodeURIComponent(key)) + } else if (isObject(value)) { + str.push(buildQueryString(value, key)) + } else if (isArray(value)) { + var keys = [] + /* eslint-disable no-loop-func */ + forEach(value, function (item) { + if (!duplicates[key]) duplicates[key] = {} if (!duplicates[key][item]) { - duplicates[key][item] = true; - return memo.concat(encodeURIComponent(key) + "=" + encodeURIComponent(item)); + duplicates[key][item] = true + keys.push(encodeURIComponent(key) + "=" + + encodeURIComponent(item)) } - return memo; - }, []).join("&") : - encodeURIComponent(key) + "=" + encodeURIComponent(value); - if (value !== undefined) str.push(pair); + }) + /* eslint-enable no-loop-func */ + str.push(keys.join("&")) + } else if (value !== undefined) { + str.push(encodeURIComponent(key) + "=" + + encodeURIComponent(value)) + } } - return str.join("&"); + return str.join("&") } function parseQueryString(str) { - if (str.charAt(0) === "?") str = str.substring(1); + if (str.charAt(0) === "?") str = str.substring(1) - var pairs = str.split("&"), params = {}; - for (var i = 0, len = pairs.length; i < len; i++) { - var pair = pairs[i].split("="); - var key = decodeURIComponent(pair[0]); - var value = pair.length == 2 ? decodeURIComponent(pair[1]) : null; + var pairs = str.split("&") + var params = {} + + forEach(pairs, function (string) { + var pair = string.split("=") + var key = decodeURIComponent(pair[0]) + var value = pair.length === 2 ? decodeURIComponent(pair[1]) : null if (params[key] != null) { - if (!isArray(params[key])) params[key] = [params[key]]; - params[key].push(value); + if (!isArray(params[key])) params[key] = [params[key]] + params[key].push(value) + } else { + params[key] = value } - else params[key] = value; - } - return params; + }) + + return params } - m.route.buildQueryString = buildQueryString; - m.route.parseQueryString = parseQueryString; + m.route.buildQueryString = buildQueryString + m.route.parseQueryString = parseQueryString function reset(root) { - var cacheKey = getCellCacheKey(root); - clear(root.childNodes, cellCache[cacheKey]); - cellCache[cacheKey] = undefined; + var cacheKey = getCellCacheKey(root) + clear(root.childNodes, cellCache[cacheKey]) + cellCache[cacheKey] = undefined } m.deferred = function () { - var deferred = new Deferred(); - deferred.promise = propify(deferred.promise); - return deferred; - }; - function propify(promise, initialValue) { - var prop = m.prop(initialValue); - promise.then(prop); - prop.then = function(resolve, reject) { - return propify(promise.then(resolve, reject), initialValue); - }; - prop["catch"] = prop.then.bind(null, null); - return prop; + var deferred = new Deferred() + deferred.promise = propify(deferred.promise) + return deferred } - //Promiz.mithril.js | Zolmeister | MIT - //a modified version of Promiz.js, which does not conform to Promises/A+ for two reasons: - //1) `then` callbacks are called synchronously (because setTimeout is too slow, and the setImmediate polyfill is too big - //2) throwing subclasses of Error cause the error to be bubbled up instead of triggering rejection (because the spec does not account for the important use case of default browser error handling, i.e. message w/ line number) - function Deferred(successCallback, failureCallback) { - var RESOLVING = 1, REJECTING = 2, RESOLVED = 3, REJECTED = 4; - var self = this, state = 0, promiseValue = 0, next = []; + function propify(promise, initialValue) { + var prop = m.prop(initialValue) - self["promise"] = {}; + promise.then(prop) - self["resolve"] = function(value) { - if (!state) { - promiseValue = value; - state = RESOLVING; - - fire(); - } - return this; - }; - - self["reject"] = function(value) { - if (!state) { - promiseValue = value; - state = REJECTING; - - fire(); - } - return this; - }; - - self.promise["then"] = function(successCallback, failureCallback) { - var deferred = new Deferred(successCallback, failureCallback); - if (state === RESOLVED) { - deferred.resolve(promiseValue); - } - else if (state === REJECTED) { - deferred.reject(promiseValue); - } - else { - next.push(deferred); - } - return deferred.promise; - }; - - function finish(type) { - state = type || REJECTED; - next.map(function(deferred) { - state === RESOLVED && deferred.resolve(promiseValue) || deferred.reject(promiseValue); - }); + prop.then = function(resolve, reject) { + return propify(promise.then(resolve, reject), initialValue) } - function thennable(then, successCallback, failureCallback, notThennableCallback) { - if (((promiseValue != null && isObject(promiseValue)) || isFunction(promiseValue)) && isFunction(then)) { + prop.catch = prop.then.bind(null, null) + + return prop + } + // Promiz.mithril.js | Zolmeister | MIT + // a modified version of Promiz.js, which does not conform to Promises/A+ + // for two reasons: + // 1) `then` callbacks are called synchronously (because setTimeout is too + // slow, and the setImmediate polyfill is too big + // 2) throwing subclasses of Error cause the error to be bubbled up instead + // of triggering rejection (because the spec does not account for the + // important use case of default browser error handling, i.e. message w/ + // line number) + function Deferred(successCallback, failureCallback) { + var RESOLVING = 1 + var REJECTING = 2 + var RESOLVED = 3 + var REJECTED = 4 + var self = this + var state = 0 + var promiseValue = 0 + var next = [] + + self.promise = {} + + self.resolve = function(value) { + if (!state) { + promiseValue = value + state = RESOLVING + + fire() + } + return this + } + + self.reject = function(value) { + if (!state) { + promiseValue = value + state = REJECTING + + fire() + } + return this + } + + self.promise.then = function(successCallback, failureCallback) { + var deferred = new Deferred(successCallback, failureCallback) + if (state === RESOLVED) { + deferred.resolve(promiseValue) + } else if (state === REJECTED) { + deferred.reject(promiseValue) + } else { + next.push(deferred) + } + return deferred.promise + } + + function finish(type) { + state = type || REJECTED + next.map(function(deferred) { + if (state === RESOLVED) { + deferred.resolve(promiseValue) + } else { + deferred.reject(promiseValue) + } + }) + } + + function thennable( + then, + successCallback, + failureCallback, + notThennableCallback) { + if (((promiseValue != null && isObject(promiseValue)) || + isFunction(promiseValue)) && isFunction(then)) { try { // count protects against abuse calls from spec checker - var count = 0; + var count = 0 then.call(promiseValue, function(value) { - if (count++) return; - promiseValue = value; - successCallback(); + if (count++) return + promiseValue = value + successCallback() }, function (value) { - if (count++) return; - promiseValue = value; - failureCallback(); - }); - } - catch (e) { - m.deferred.onerror(e); - promiseValue = e; - failureCallback(); + if (count++) return + promiseValue = value + failureCallback() + }) + } catch (e) { + m.deferred.onerror(e) + promiseValue = e + failureCallback() } } else { - notThennableCallback(); + notThennableCallback() } } function fire() { // check if it's a thenable - var then; + var then try { - then = promiseValue && promiseValue.then; - } - catch (e) { - m.deferred.onerror(e); - promiseValue = e; - state = REJECTING; - return fire(); + then = promiseValue && promiseValue.then + } catch (e) { + m.deferred.onerror(e) + promiseValue = e + state = REJECTING + return fire() } + thennable(then, function() { - state = RESOLVING; - fire(); + state = RESOLVING + fire() }, function() { - state = REJECTING; - fire(); + state = REJECTING + fire() }, function() { try { if (state === RESOLVING && isFunction(successCallback)) { - promiseValue = successCallback(promiseValue); + promiseValue = successCallback(promiseValue) + } else if (state === REJECTING && + isFunction(failureCallback)) { + promiseValue = failureCallback(promiseValue) + state = RESOLVING } - else if (state === REJECTING && isFunction(failureCallback)) { - promiseValue = failureCallback(promiseValue); - state = RESOLVING; - } - } - catch (e) { - m.deferred.onerror(e); - promiseValue = e; - return finish(); + } catch (e) { + m.deferred.onerror(e) + promiseValue = e + return finish() } if (promiseValue === self) { - promiseValue = TypeError(); - finish(); - } - else { + promiseValue = TypeError() + finish() + } else { thennable(then, function () { - finish(RESOLVED); + finish(RESOLVED) }, finish, function () { - finish(state === RESOLVING && RESOLVED); - }); + finish(state === RESOLVING && RESOLVED) + }) } - }); + }) } } m.deferred.onerror = function(e) { - if (type.call(e) === "[object Error]" && !e.constructor.toString().match(/ Error/)) { - pendingRequests = 0; - throw e; + if (type.call(e) === "[object Error]" && + !e.constructor.toString().match(/ Error/)) { + pendingRequests = 0 + throw e } - }; + } m.sync = function(args) { - var method = "resolve"; + var method = "resolve" + var deferred = m.deferred() + var outstanding = args.length + var results = new Array(outstanding) + function synchronizer(pos, resolved) { return function(value) { - results[pos] = value; - if (!resolved) method = "reject"; + results[pos] = value + if (!resolved) method = "reject" if (--outstanding === 0) { - deferred.promise(results); - deferred[method](results); + deferred.promise(results) + deferred[method](results) } - return value; - }; - } - - var deferred = m.deferred(); - var outstanding = args.length; - var results = new Array(outstanding); - if (args.length > 0) { - for (var i = 0; i < args.length; i++) { - args[i].then(synchronizer(i, true), synchronizer(i, false)); + return value } } - else deferred.resolve([]); - return deferred.promise; - }; - function identity(value) { return value; } + if (args.length > 0) { + forEach(args, function (arg, i) { + arg.then(synchronizer(i, true), synchronizer(i, false)) + }) + } else { + deferred.resolve([]) + } + + return deferred.promise + } + function identity(value) { return value } function ajax(options) { if (options.dataType && options.dataType.toLowerCase() === "jsonp") { - var callbackKey = "mithril_callback_" + new Date().getTime() + "_" + (Math.round(Math.random() * 1e16)).toString(36); - var script = $document.createElement("script"); + var callbackKey = "mithril_callback_" + new Date().getTime() + "_" + + (Math.round(Math.random() * 1e16)).toString(36) + var script = $document.createElement("script") window[callbackKey] = function(resp) { - script.parentNode.removeChild(script); + script.parentNode.removeChild(script) options.onload({ type: "load", target: { responseText: resp } - }); - window[callbackKey] = undefined; - }; + }) + window[callbackKey] = undefined + } - script.onerror = function(e) { - script.parentNode.removeChild(script); + script.onerror = function() { + script.parentNode.removeChild(script) options.onerror({ type: "error", target: { status: 500, - responseText: JSON.stringify({error: "Error making jsonp request"}) + responseText: JSON.stringify({ + error: "Error making jsonp request" + }) } - }); - window[callbackKey] = undefined; + }) + window[callbackKey] = undefined - return false; - }; + return false + } - script.onload = function(e) { - return false; - }; + script.onload = function() { + return false + } script.src = options.url + (options.url.indexOf("?") > 0 ? "&" : "?") + (options.callbackKey ? options.callbackKey : "callback") + "=" + callbackKey - + "&" + buildQueryString(options.data || {}); - $document.body.appendChild(script); - } - else { - var xhr = new window.XMLHttpRequest; - xhr.open(options.method, options.url, true, options.user, options.password); + + "&" + buildQueryString(options.data || {}) + $document.body.appendChild(script) + } else { + var xhr = new window.XMLHttpRequest() + xhr.open( + options.method, + options.url, + true, + options.user, + options.password) + xhr.onreadystatechange = function() { if (xhr.readyState === 4) { - if (xhr.status >= 200 && xhr.status < 300) options.onload({type: "load", target: xhr}); - else options.onerror({type: "error", target: xhr}); + if (xhr.status >= 200 && xhr.status < 300) { + options.onload({type: "load", target: xhr}) + } else { + options.onerror({type: "error", target: xhr}) + } } - }; - if (options.serialize === JSON.stringify && options.data && options.method !== "GET") { - xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); + } + if (options.serialize === JSON.stringify && + options.data && options.method !== "GET") { + xhr.setRequestHeader( + "Content-Type", + "application/json; charset=utf-8") } if (options.deserialize === JSON.parse) { - xhr.setRequestHeader("Accept", "application/json, text/*"); + xhr.setRequestHeader("Accept", "application/json, text/*") } if (isFunction(options.config)) { - var maybeXhr = options.config(xhr, options); - if (maybeXhr != null) xhr = maybeXhr; + var maybeXhr = options.config(xhr, options) + if (maybeXhr != null) xhr = maybeXhr } - var data = options.method === "GET" || !options.data ? "" : options.data; - if (data && (!isString(data) && data.constructor != window.FormData)) { - throw "Request data should be either be a string or FormData. Check the `serialize` option in `m.request`"; + var data + + if (options.method === "GET" || !options.data) { + data = "" + } else { + data = options.data } - xhr.send(data); - return xhr; + + if (data && (!isString(data) && + data.constructor !== window.FormData)) { + throw new Error("Request data should be either be a string " + + "or FormData. Check the `serialize` option in `m.request`") + } + xhr.send(data) + return xhr } } + function bindData(xhrOptions, data, serialize) { - if (xhrOptions.method === "GET" && xhrOptions.dataType != "jsonp") { - var prefix = xhrOptions.url.indexOf("?") < 0 ? "?" : "&"; - var querystring = buildQueryString(data); - xhrOptions.url = xhrOptions.url + (querystring ? prefix + querystring : ""); + if (xhrOptions.method === "GET" && xhrOptions.dataType !== "jsonp") { + var prefix = xhrOptions.url.indexOf("?") < 0 ? "?" : "&" + var querystring = buildQueryString(data) + var suffix = querystring ? prefix + querystring : "" + xhrOptions.url = xhrOptions.url + suffix + } else { + xhrOptions.data = serialize(data) } - else xhrOptions.data = serialize(data); - return xhrOptions; + return xhrOptions } + function parameterizeUrl(url, data) { - var tokens = url.match(/:[a-z]\w+/gi); + var tokens = url.match(/:[a-z]\w+/gi) if (tokens && data) { - for (var i = 0; i < tokens.length; i++) { - var key = tokens[i].slice(1); - url = url.replace(tokens[i], data[key]); - delete data[key]; - } + forEach(tokens, function (token) { + var key = token.slice(1) + url = url.replace(token, data[key]) + delete data[key] + }) } - return url; + return url } m.request = function(xhrOptions) { - if (xhrOptions.background !== true) m.startComputation(); - var deferred = new Deferred(); - var isJSONP = xhrOptions.dataType && xhrOptions.dataType.toLowerCase() === "jsonp"; - var serialize = xhrOptions.serialize = isJSONP ? identity : xhrOptions.serialize || JSON.stringify; - var deserialize = xhrOptions.deserialize = isJSONP ? identity : xhrOptions.deserialize || JSON.parse; - var extract = isJSONP ? function(jsonp) { return jsonp.responseText; } : xhrOptions.extract || function(xhr) { - return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText; - }; - xhrOptions.method = (xhrOptions.method || 'GET').toUpperCase(); - xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data); - xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize); + if (xhrOptions.background !== true) { + m.startComputation() + } + + var deferred = new Deferred() + var isJSONP = xhrOptions.dataType && + xhrOptions.dataType.toLowerCase() === "jsonp" + + var serialize + + if (isJSONP) { + serialize = xhrOptions.serialize = identity + } else { + serialize = xhrOptions.serialize = xhrOptions.serialize || + JSON.stringify + } + + var deserialize + + if (isJSONP) { + deserialize = xhrOptions.deserialize = identity + } else { + deserialize = xhrOptions.deserialize = xhrOptions.deserialize || + JSON.parse + } + + var extract + + if (isJSONP) { + extract = function(jsonp) { return jsonp.responseText } + } else if (xhrOptions.extract) { + extract = xhrOptions.extract + } else { + extract = function(xhr) { + if (xhr.responseText.length === 0 && + deserialize === JSON.parse) { + return null + } else { + return xhr.responseText + } + } + } + + xhrOptions.method = (xhrOptions.method || "GET").toUpperCase() + xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data) + xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize) xhrOptions.onload = xhrOptions.onerror = function(e) { try { - e = e || event; - var unwrap = (e.type === "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity; - var response = unwrap(deserialize(extract(e.target, xhrOptions)), e.target); + e = e || event + var unwrap + + if (e.type === "load") { + unwrap = xhrOptions.unwrapSuccess + } else { + unwrap = xhrOptions.unwrapError + } + + var response = (unwrap || identity)( + deserialize(extract(e.target, xhrOptions)), e.target) + if (e.type === "load") { if (isArray(response) && xhrOptions.type) { forEach(response, function (res, i) { - response[i] = new xhrOptions.type(res); - }); + response[i] = new xhrOptions.type(res) + }) + } else if (xhrOptions.type) { + response = new xhrOptions.type(response) } - else if (xhrOptions.type) response = new xhrOptions.type(response); } - deferred[e.type === "load" ? "resolve" : "reject"](response); - } - catch (e) { - m.deferred.onerror(e); - deferred.reject(e); - } - if (xhrOptions.background !== true) m.endComputation(); - }; - ajax(xhrOptions); - deferred.promise = propify(deferred.promise, xhrOptions.initialValue); - return deferred.promise; - }; - //testing API + deferred[e.type === "load" ? "resolve" : "reject"](response) + } catch (e) { // eslint-disable-line + m.deferred.onerror(e) + deferred.reject(e) + } + + if (xhrOptions.background !== true) m.endComputation() + } + + ajax(xhrOptions) + deferred.promise = propify(deferred.promise, xhrOptions.initialValue) + return deferred.promise + } + + // testing API m.deps = function(mock) { - initialize(window = mock || window); - return window; - }; - //for internal testing only, do not use `m.deps.factory` - m.deps.factory = app; + initialize(window = mock || window) + return window + } - return m; -})(typeof window != "undefined" ? window : {}); + // for internal testing only, do not use `m.deps.factory` + m.deps.factory = app -if (typeof module != "undefined" && module !== null && module.exports) module.exports = m; -else if (typeof define === "function" && define.amd) define(function() { return m; }); + return m +})(typeof window !== "undefined" ? window : {}) + +/* eslint-disable no-undef, strict */ +if (typeof module === "object" && module !== null && module.exports) { + module.exports = m +} else if (typeof define === "function" && define.amd) { + define(function() { return m }) +} +/* eslint-enable no-undef, strict */ diff --git a/package.json b/package.json index 819228f7..f2955287 100644 --- a/package.json +++ b/package.json @@ -1,46 +1,55 @@ { - "name": "mithril", - "description": "Mithril.js beta build - use this to help us test the releases before they are released", - "version": "0.1.34-beta.0", - "repository": { - "type": "git", - "url": "git@github.com:lhorie/mithril.js.git" - }, - "scripts": { - "test": "grunt test" - }, - "main": "mithril.js", - "devDependencies": { - "grunt": "*", - "grunt-cli": "*", - "grunt-contrib-copy": "*", - "grunt-contrib-uglify": "*", - "grunt-contrib-clean": "*", - "grunt-contrib-concat": "*", - "grunt-execute": "*", - "grunt-md2html": "*", - "grunt-replace": "*", - "grunt-contrib-qunit": "*", - "grunt-zip": "*", - "grunt-jsfmt": "git://github.com/ysimonson/grunt-jsfmt", - - "grunt-contrib-connect": "~0.7.1", - "grunt-contrib-jshint": "~0.10.0", - "grunt-contrib-watch": "~0.6.1", - "grunt-jscs": "^1.1.0", - "grunt-sauce-tunnel": "^0.2.1", - "load-grunt-config": "^0.9.2", - "merge": "^1.1.3", - "publish": "~0.3.2", - "grunt-saucelabs": "*", - "request": "~2.35.0", - "q": "~1.0.0", - "saucelabs": "~0.1.1", - "sauce-tunnel": "~2.0.6", - "colors": "~0.6.2", - "lodash": "~2.4.1" - }, - "main": "mithril.js", - "licenses": [{"type": "MIT", "url": "http://opensource.org/licenses/MIT"}], - "files": ["mithril.min.js", "mithril.min.js.map", "mithril.js", "README.*"] + "name": "mithril", + "description": "Mithril.js beta build - use this to help us test the releases before they are released", + "version": "0.1.34-beta.0", + "repository": { + "type": "git", + "url": "git@github.com:lhorie/mithril.js.git" + }, + "scripts": { + "test": "grunt test" + }, + "main": "mithril.js", + "devDependencies": { + "colors": "~0.6.2", + "grunt": "*", + "grunt-cli": "*", + "grunt-contrib-clean": "*", + "grunt-contrib-concat": "*", + "grunt-contrib-connect": "~0.7.1", + "grunt-contrib-copy": "*", + "grunt-contrib-jshint": "~0.10.0", + "grunt-contrib-qunit": "*", + "grunt-contrib-uglify": "*", + "grunt-contrib-watch": "~0.6.1", + "grunt-eslint": "^16.0.0", + "grunt-execute": "*", + "grunt-jscs": "^1.1.0", + "grunt-jsfmt": "git://github.com/ysimonson/grunt-jsfmt", + "grunt-md2html": "*", + "grunt-replace": "*", + "grunt-sauce-tunnel": "^0.2.1", + "grunt-saucelabs": "*", + "grunt-zip": "*", + "load-grunt-config": "^0.9.2", + "lodash": "~2.4.1", + "merge": "^1.1.3", + "publish": "~0.3.2", + "q": "~1.0.0", + "request": "~2.35.0", + "sauce-tunnel": "~2.0.6", + "saucelabs": "~0.1.1" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://opensource.org/licenses/MIT" + } + ], + "files": [ + "mithril.min.js", + "mithril.min.js.map", + "mithril.js", + "README.*" + ] } diff --git a/tests/e2e/.eslintrc b/tests/e2e/.eslintrc new file mode 100644 index 00000000..a351ac0b --- /dev/null +++ b/tests/e2e/.eslintrc @@ -0,0 +1,23 @@ +{ + "extend": "../../.eslintrc", + "globals": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + } +} diff --git a/tests/e2e/tests.js b/tests/e2e/tests.js index 1dd8de03..ea1b389a 100644 --- a/tests/e2e/tests.js +++ b/tests/e2e/tests.js @@ -1,8 +1,13 @@ -//saucelabs reporting; see https://github.com/axemclion/grunt-saucelabs#test-result-details-with-qunit +/* eslint-disable camelcase */ +/* global m, Syn */ + +// saucelabs reporting; see +// https://github.com/axemclion/grunt-saucelabs#test-result-details-with-qunit + var log = [] -var testName QUnit.done(function (test_results) { + "use strict" var tests = [] for (var i = 0, len = log.length; i < len; i++) { var details = log[i] @@ -19,6 +24,7 @@ QUnit.done(function (test_results) { window.global_test_results = test_results }) QUnit.testStart(function (testDetails) { + "use strict" QUnit.log(function (details) { if (!details.result) { details.name = testDetails.name @@ -27,9 +33,11 @@ QUnit.testStart(function (testDetails) { }) }) -//qunit doesn't support Function.prototype.bind... +// qunit doesn't support Function.prototype.bind... if (!Function.prototype.bind) { + /* eslint-disable */ Function.prototype.bind = function (oThis) { + "use strict" if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 // internal IsCallable function @@ -51,165 +59,181 @@ if (!Function.prototype.bind) { return fBound } + /* eslint-enable */ } //tests -var dummyEl = document.getElementById('dummy') +var dummyEl = document.getElementById("dummy") -test('Mithril accessible as window.m', function() { +test("Mithril accessible as window.m", function() { + "use strict" expect(1) ok(window.m) }) -test('m.trust w/ html entities', function() { +test("m.trust w/ html entities", function() { + "use strict" expect(1) - var view1 = m('div', "a", m.trust("&"), "b") + var view1 = m("div", "a", m.trust("&"), "b") m.render(dummyEl, view1) - equal(dummyEl.innerHTML, '
a&b
', 'view1 rendered correctly') + equal(dummyEl.innerHTML, "
a&b
", "view1 rendered correctly") }) -test('m.trust w/ html entities 2', function() { +test("m.trust w/ html entities 2", function() { + "use strict" expect(1) - var view1 = m('div', "a", m.trust("&"), "b", m.trust("&"), "c") + var view1 = m("div", "a", m.trust("&"), "b", m.trust("&"), "c") m.render(dummyEl, view1) - equal(dummyEl.innerHTML, '
a&b&c
', 'view1 rendered correctly') + equal(dummyEl.innerHTML, "
a&b&c
", + "view1 rendered correctly") }) -test('array item removal', function() { +test("array item removal", function() { + "use strict" expect(2) - var view1 = m('div', {}, [ - m('div', {}, '0'), - m('div', {}, '1'), - m('div', {}, '2') + var view1 = m("div", {}, [ + m("div", {}, "0"), + m("div", {}, "1"), + m("div", {}, "2") ]) - var view2= m('div', {}, [ - m('div', {}, '0') + var view2 = m("div", {}, [ + m("div", {}, "0") ]) m.render(dummyEl, view1) - equal(dummyEl.innerHTML, '
0
1
2
', 'view1 rendered correctly') + equal(dummyEl.innerHTML, "
0
1
2
", + "view1 rendered correctly") m.render(dummyEl, view2) - equal(dummyEl.innerHTML, '
0
', 'view2 should be rendered correctly') + equal(dummyEl.innerHTML, "
0
", + "view2 should be rendered correctly") }) -test('issue99 regression', function() { +test("issue99 regression", function() { + "use strict" // see https://github.com/lhorie/mithril.js/issues/99 expect(2) - var view1 = m('div', {}, [ - m('div', {}, '0'), - m('div', {}, '1'), - m('div', {}, '2') + var view1 = m("div", {}, [ + m("div", {}, "0"), + m("div", {}, "1"), + m("div", {}, "2") ]) - var view2= m('div', {}, [ - m('span', {}, '0') + var view2 = m("div", {}, [ + m("span", {}, "0") ]) m.render(dummyEl, view1) - equal(dummyEl.innerHTML, '
0
1
2
', 'view1 rendered correctly') + equal(dummyEl.innerHTML, "
0
1
2
", + "view1 rendered correctly") m.render(dummyEl, view2) - equal(dummyEl.innerHTML, '
0
', 'view2 should be rendered correctly') + equal(dummyEl.innerHTML, "
0
", + "view2 should be rendered correctly") }) -test('config handler context', function() { +test("config handler context", function() { + "use strict" expect(3) - var view = m('div', {config: function(evt, isInitialized, context) { + var view = m("div", {config: function(evt, isInitialized, context) { equal(context instanceof Object, true) context.data = 1 }}) m.render(dummyEl, view) - var view = m('div', {config: function(evt, isInitialized, context) { + view = m("div", {config: function(evt, isInitialized, context) { equal(context instanceof Object, true) equal(context.data, 1) }}) m.render(dummyEl, view) }) -test('node identity remove firstChild', function() { +test("node identity remove firstChild", function() { + "use strict" expect(2) - var view1 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2') + var view1 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2") ]) m.render(dummyEl, view1) var node2 = dummyEl.firstChild.lastChild - equal(node2.innerHTML, 'E2') + equal(node2.innerHTML, "E2") - var view2 = m('div', {}, [ - m('div', {key:2}, 'E2') + var view2 = m("div", {}, [ + m("div", {key: 2}, "E2") ]) m.render(dummyEl, view2) equal(dummyEl.firstChild.firstChild, node2) }) -test('node identity change order', function() { +test("node identity change order", function() { + "use strict" expect(2) - var view1 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2'), - m('div', {key:3}, 'E3') + var view1 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2"), + m("div", {key: 3}, "E3") ]) m.render(dummyEl, view1) var e2 = dummyEl.firstChild.firstChild.nextSibling - equal(e2.innerHTML, 'E2') + equal(e2.innerHTML, "E2") - var view2 = m('div', {}, [ - m('div', {key:2}, 'E2'), - m('div', {key:1}, 'E1'), - m('div', {key:3}, 'E3') + var view2 = m("div", {}, [ + m("div", {key: 2}, "E2"), + m("div", {key: 1}, "E1"), + m("div", {key: 3}, "E3") ]) m.render(dummyEl, view2) equal(dummyEl.firstChild.firstChild, e2) }) -test('node identity remove in the middle', function() { +test("node identity remove in the middle", function() { + "use strict" expect(2) - var view1 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2'), - m('div', {key:3}, 'E3') + var view1 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2"), + m("div", {key: 3}, "E3") ]) m.render(dummyEl, view1) var e3 = dummyEl.firstChild.lastChild - equal(e3.innerHTML, 'E3') + equal(e3.innerHTML, "E3") - var view2 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:3}, 'E3') + var view2 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 3}, "E3") ]) m.render(dummyEl, view2) equal(dummyEl.firstChild.firstChild.nextSibling, e3) }) -test('node identity remove last', function() { +test("node identity remove last", function() { + "use strict" expect(4) - var view1 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2'), - m('div', {key:3}, 'E3') + var view1 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2"), + m("div", {key: 3}, "E3") ]) m.render(dummyEl, view1) var e1 = dummyEl.firstChild.firstChild - equal(e1.innerHTML, 'E1') + equal(e1.innerHTML, "E1") var e2 = dummyEl.firstChild.firstChild.nextSibling - equal(e2.innerHTML, 'E2') + equal(e2.innerHTML, "E2") - var view2 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2') + var view2 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2") ]) m.render(dummyEl, view2) @@ -217,168 +241,176 @@ test('node identity remove last', function() { equal(dummyEl.firstChild.firstChild.nextSibling, e2) }) -test('node identity shuffle and remove', function() { +test("node identity shuffle and remove", function() { + "use strict" expect(8) - var view1 = m('div', {}, [ - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2'), - m('div', {key:3}, 'E3'), - m('div', {key:4}, 'E4'), - m('div', {key:5}, 'E5') + var view1 = m("div", {}, [ + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2"), + m("div", {key: 3}, "E3"), + m("div", {key: 4}, "E4"), + m("div", {key: 5}, "E5") ]) m.render(dummyEl, view1) var e1 = dummyEl.firstChild.firstChild - equal(e1.innerHTML, 'E1') + equal(e1.innerHTML, "E1") var e2 = e1.nextSibling - equal(e2.innerHTML, 'E2') + equal(e2.innerHTML, "E2") var e3 = e2.nextSibling - equal(e3.innerHTML, 'E3') + equal(e3.innerHTML, "E3") var e4 = e3.nextSibling - equal(e4.innerHTML, 'E4') + equal(e4.innerHTML, "E4") var e5 = e4.nextSibling - equal(e5.innerHTML, 'E5') + equal(e5.innerHTML, "E5") - var view2 = m('div', {}, [ - m('div', {key:4}, 'E4'), - m('div', {key:10}, 'E10'), - m('div', {key:1}, 'E1'), - m('div', {key:2}, 'E2') + var view2 = m("div", {}, [ + m("div", {key: 4}, "E4"), + m("div", {key: 10}, "E10"), + m("div", {key: 1}, "E1"), + m("div", {key: 2}, "E2") ]) m.render(dummyEl, view2) - equal(dummyEl.firstChild.firstChild, e4, 'e4 is first element') - equal(dummyEl.firstChild.firstChild.nextSibling.nextSibling, e1, 'e1 is third element') - equal(dummyEl.firstChild.firstChild.nextSibling.nextSibling.nextSibling, e2, 'e2 is fourth element') + equal(dummyEl.firstChild.firstChild, e4, "e4 is first element") + equal(dummyEl.firstChild.firstChild.nextSibling.nextSibling, e1, + "e1 is third element") + equal(dummyEl.firstChild.firstChild.nextSibling.nextSibling.nextSibling, e2, + "e2 is fourth element") }) -asyncTest('issue214 regression', function() { +asyncTest("issue214 regression", function() { + "use strict" // see https://github.com/lhorie/mithril.js/issues/214 expect(2) function controller() { - this.inputValue = m.prop('') + this.inputValue = m.prop("") } function view(ctrl) { - return m('input#testinput', { + return m("input#testinput", { value: ctrl.inputValue(), - onkeyup: m.withAttr('value', ctrl.inputValue) + onkeyup: m.withAttr("value", ctrl.inputValue) }) } var ctrl = m.module(dummyEl, { controller: controller, view: view }) - Syn.click({}, 'testinput') - .type('0').delay(10) - .type('1').delay(10) - .type('2').delay(10) - .type('3').delay(10) - .type('4').delay(10) - .type('5').delay(10) - .type('6').delay(10) - .type('7').delay(10) - .type('8').delay(10) - .type('9').delay(10) - .type('a').delay(10) - .type('b').delay(10) - .type('c').delay(10) - .type('d').delay(10) - .type('e').delay(10) - .type('f').delay(10) - .type('0').delay(10) - .type('1').delay(10) - .type('2').delay(10) - .type('3').delay(10) - .type('4').delay(10) - .type('5').delay(10) - .type('6').delay(10) - .type('7').delay(10) - .type('8').delay(10) - .type('9').delay(10) - .type('a').delay(10) - .type('b').delay(10) - .type('c').delay(10) - .type('d').delay(10) - .type('e').delay(10) - .type('f').delay(10) - .type('0').delay(10) - .type('1').delay(10) - .type('2').delay(10) - .type('3').delay(10) - .type('4').delay(10) - .type('5').delay(10) - .type('6').delay(10) - .type('7').delay(10) - .type('8').delay(10) - .type('9').delay(10) - .type('a').delay(10) - .type('b').delay(10) - .type('c').delay(10) - .type('d').delay(10) - .type('e').delay(10) - .type('f').delay(10) - .type('0').delay(10) - .type('1').delay(10) - .type('2').delay(10) - .type('3').delay(10) - .type('4').delay(10) - .type('5').delay(10) - .type('6').delay(10) - .type('7').delay(10) - .type('8').delay(10) - .type('9').delay(10) - .type('a').delay(10) - .type('b').delay(10) - .type('c').delay(10) - .type('d').delay(10) - .type('e').delay(10) - .type('f', function() { - equal(ctrl.inputValue(), '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef') - equal(document.getElementById('testinput').value, '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef') + Syn.click({}, "testinput") + .type("0").delay(10) + .type("1").delay(10) + .type("2").delay(10) + .type("3").delay(10) + .type("4").delay(10) + .type("5").delay(10) + .type("6").delay(10) + .type("7").delay(10) + .type("8").delay(10) + .type("9").delay(10) + .type("a").delay(10) + .type("b").delay(10) + .type("c").delay(10) + .type("d").delay(10) + .type("e").delay(10) + .type("f").delay(10) + .type("0").delay(10) + .type("1").delay(10) + .type("2").delay(10) + .type("3").delay(10) + .type("4").delay(10) + .type("5").delay(10) + .type("6").delay(10) + .type("7").delay(10) + .type("8").delay(10) + .type("9").delay(10) + .type("a").delay(10) + .type("b").delay(10) + .type("c").delay(10) + .type("d").delay(10) + .type("e").delay(10) + .type("f").delay(10) + .type("0").delay(10) + .type("1").delay(10) + .type("2").delay(10) + .type("3").delay(10) + .type("4").delay(10) + .type("5").delay(10) + .type("6").delay(10) + .type("7").delay(10) + .type("8").delay(10) + .type("9").delay(10) + .type("a").delay(10) + .type("b").delay(10) + .type("c").delay(10) + .type("d").delay(10) + .type("e").delay(10) + .type("f").delay(10) + .type("0").delay(10) + .type("1").delay(10) + .type("2").delay(10) + .type("3").delay(10) + .type("4").delay(10) + .type("5").delay(10) + .type("6").delay(10) + .type("7").delay(10) + .type("8").delay(10) + .type("9").delay(10) + .type("a").delay(10) + .type("b").delay(10) + .type("c").delay(10) + .type("d").delay(10) + .type("e").delay(10) + .type("f", function() { + equal(ctrl.inputValue(), + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") + equal(document.getElementById("testinput").value, + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") start() }) }) -asyncTest('issue288 regression', function() { +asyncTest("issue288 regression", function() { + "use strict" // see https://github.com/lhorie/mithril.js/issues/288 expect(2) function controller() { - this.inputValue = m.prop('') + this.inputValue = m.prop("") this.submit = function() { if (this.inputValue()) { - this.inputValue('') + this.inputValue("") } - }.bind(this); + }.bind(this) } function view(ctrl) { - return m('form', { onsubmit: ctrl.submit }, [ - m('input#testinput', { - onkeyup: m.withAttr('value', ctrl.inputValue), + return m("form", { onsubmit: ctrl.submit }, [ + m("input#testinput", { + onkeyup: m.withAttr("value", ctrl.inputValue), value: ctrl.inputValue() }), - m('button[type=submit]') + m("button[type=submit]") ]) } var ctrl = m.module(dummyEl, { controller: controller, view: view }) - Syn.click({}, 'testinput') - .type('a').delay(10) - .type('b').delay(10) - .type('c').delay(10) - .type('d').delay(10) - .type('[enter]', function() { - equal(ctrl.inputValue(), '') - equal(document.getElementById('testinput').value, '') + Syn.click({}, "testinput") + .type("a").delay(10) + .type("b").delay(10) + .type("c").delay(10) + .type("d").delay(10) + .type("[enter]", function() { + equal(ctrl.inputValue(), "") + equal(document.getElementById("testinput").value, "") start() }) }) -test('issue278 regression', function() { +test("issue278 regression", function() { + "use strict" // see https://github.com/lhorie/mithril.js/issues/278 expect(1) @@ -389,22 +421,24 @@ test('issue278 regression', function() { }, view: function(ctrl) { - return m('select#testselect', { + return m("select#testselect", { size: ctrl.values.length, - multiple: 'multiple' + multiple: "multiple" }, [ ctrl.values.map(function(v){ var opts = {value: v} - if (ctrl.value().indexOf(v) !== -1) opts.selected = 'selected' - return m('option', opts, v) + if (ctrl.value().indexOf(v) !== -1) { + opts.selected = "selected" + } + return m("option", opts, v) }) ]) } } - m.render(dummyEl, test.view(new test.controller)) + m.render(dummyEl, test.view(new test.controller())) - var select = document.getElementById('testselect') + var select = document.getElementById("testselect") for (var i = 0, selected = 0; i < select.options.length; i++) { if (select.options[i].selected) selected++ @@ -413,25 +447,30 @@ test('issue278 regression', function() { equal(selected, 2) }) test("mixing trusted content", function() { + "use strict" m.render(dummyEl, [m.trust("

1

2

"), m("i", "foo")]) equal(dummyEl.childNodes[2].nodeName, "I") }) test("mixing trusted content w/ text nodes", function() { + "use strict" m.render(dummyEl, [m.trust("

1

123

2

"), m("i", "foo")]) equal(dummyEl.childNodes[3].nodeName, "I") }) test("mixing trusted content w/ td", function() { + "use strict" m.render(dummyEl, [m.trust("12"), m("i", "foo")]) equal(dummyEl.childNodes[1].nodeName, "I") }) test("0 should not be treated as empty string", function() { + "use strict" m.render(dummyEl, m("input", {value: ""})) m.render(dummyEl, m("input", {value: 0})) equal(dummyEl.childNodes[0].value, "0") }) test("empty value in ') }) diff --git a/tests/mithril-tests.js b/tests/mithril-tests.js index 7194f61a..4b7a2a1a 100644 --- a/tests/mithril-tests.js +++ b/tests/mithril-tests.js @@ -1,7 +1,12 @@ +/* global m, test, mock */ +/* eslint-disable no-console */ + function testMithril(mock) { + "use strict" + m.deps(mock) - - //m + + // m test(function() {return m("div").tag === "div"}) test(function() {return m(".foo").tag === "div"}) test(function() {return m(".foo").attrs.className === "foo"}) @@ -12,48 +17,90 @@ function testMithril(mock) { test(function() {return m("div", "test").children[0] === "test"}) test(function() {return m("div", "test", "test2").children[1] === "test2"}) test(function() {return m("div", ["test"]).children[0] === "test"}) - test(function() {return m("div", {title: "bar"}, "test").attrs.title === "bar"}) - test(function() {return m("div", {title: "bar"}, "test").children[0] === "test"}) - test(function() {return m("div", {title: "bar"}, ["test"]).children[0] === "test"}) - test(function() {return m("div", {title: "bar"}, m("div")).children[0].tag === "div"}) - test(function() {return m("div", {title: "bar"}, [m("div")]).children[0].tag === "div"}) - test(function() {return m("div", {title: "bar"}, "test0", "test1", "test2", "test3").children[3] === "test3"}) // splat - test(function() {return m("div", {title: "bar"}, m("div"), m("i"), m("span")).children[2].tag === "span"}) + test(function() { + return m("div", {title: "bar"}, "test").attrs.title === "bar" + }) + test(function() { + return m("div", {title: "bar"}, "test").children[0] === "test" + }) + test(function() { + return m("div", {title: "bar"}, ["test"]).children[0] === "test" + }) + test(function() { + return m("div", {title: "bar"}, m("div")).children[0].tag === "div" + }) + test(function() { + return m("div", {title: "bar"}, [m("div")]).children[0].tag === "div" + }) + test(function() { + // splat + return m("div", {title: "bar"}, + "test0", "test1", "test2", "test3").children[3] === "test3" + }) + test(function() { + return m("div", {title: "bar"}, + m("div"), m("i"), m("span")).children[2].tag === "span" + }) test(function() {return m("div", ["a", "b"]).children.length === 2}) test(function() {return m("div", [m("div")]).children[0].tag === "div"}) - test(function() {return m("div", m("div")).children[0].tag === "div"}) //yes, this is expected behavior: see method signature + test(function() { + // yes, this is expected behavior: see method signature + return m("div", m("div")).children[0].tag === "div" + }) test(function() {return m("div", [undefined]).tag === "div"}) - test(function() {return m("div", [{foo: "bar"}])}) //as long as it doesn't throw errors, it's fine + test(function() { + // as long as it doesn't throw errors, it's fine + return m("div", [{foo: "bar"}]) + }) test(function() {return m("svg", [m("g")])}) test(function() {return m("svg", [m("a[href='http://google.com']")])}) - test(function() {return m(".foo", {"class": "bar"}).attrs["class"] == "foo bar"}) - test(function() {return m(".foo", {className: "bar"}).attrs.className == "foo bar"}) - test(function() {return m(".foo", {className: ""}).attrs.className == "foo"}) - test(function() {return m("div", {className: ""}).attrs.className === ""}) //https://github.com/lhorie/mithril.js/issues/382 and 512 - test(function() {return m("div", {class: ""}).attrs.className === undefined}) - test(function() {return m("div", {className: ""}).attrs.class === undefined}) + test(function() { + return m(".foo", {class: "bar"}).attrs.class === "foo bar" + }) + test(function() { + return m(".foo", {className: "bar"}).attrs.className === "foo bar" + }) + test(function() { + return m(".foo", {className: ""}).attrs.className === "foo" + }) + test(function() { + // https://github.com/lhorie/mithril.js/issues/382 and 512 + return m("div", {className: ""}).attrs.className === "" + }) + test(function() { + return m("div", {class: ""}).attrs.className === undefined + }) + test(function() { + return m("div", {className: ""}).attrs.class === undefined + }) test(function() {return m("div", {class: ""}).attrs.class === ""}) test(function() {return m("div", [1, 2, 3], 4).children.length === 2}) test(function() {return m("div", [1, 2, 3], 4).children[0].length === 3}) test(function() {return m("div", [1, 2, 3], 4).children[1] === 4}) test(function() {return m("div", [1, 2, 3]).children.length === 3}) - test(function() {return m("div", [1, 2, 3], [4, 5, 6, 7]).children.length === 2}) - test(function() {return m("div", [1, 2, 3], [4, 5, 6, 7]).children[0].length === 3}) - test(function() {return m("div", [1, 2, 3], [4, 5, 6, 7]).children[1].length === 4}) + test(function() { + return m("div", [1, 2, 3], [4, 5, 6, 7]).children.length === 2 + }) + test(function() { + return m("div", [1, 2, 3], [4, 5, 6, 7]).children[0].length === 3 + }) + test(function() { + return m("div", [1, 2, 3], [4, 5, 6, 7]).children[1].length === 4 + }) test(function() {return m("div", [1], [2], [3]).children.length === 3}) test(function() { - //class changes shouldn't trigger dom recreation + // class changes shouldn't trigger dom recreation var v1 = m(".foo", {class: "", onclick: function() {}}) var v2 = m(".foo", {class: "bar", onclick: function() {}}) return Object.keys(v1.attrs).join() === Object.keys(v2.attrs).join() }) test(function() { - //m should proxy object first arg to m.component + // m should proxy object first arg to m.component var component = { controller: function(args) { this.args = args }, - view: function(ctrl) { + view: function () { return m("div", "testing") } } @@ -61,33 +108,33 @@ function testMithril(mock) { var c1 = m(component, args).controller() var c2 = m.component(component, args).controller() - return c1.args === args && c1.args == c2.args + return c1.args === args && c1.args === c2.args }) - //m.mount + // m.mount test(function() { var root = mock.document.createElement("div") var whatever = 1 var app = { view: function() { return [ - whatever % 2 ? m('span', '% 2') : undefined, - m('div', 'bugs'), - m('a'), + whatever % 2 ? m("span", "% 2") : undefined, + m("div", "bugs"), + m("a") ] } } m.mount(root, app) mock.requestAnimationFrame.$resolve() - + whatever++ m.redraw() mock.requestAnimationFrame.$resolve() - + whatever++ m.redraw() mock.requestAnimationFrame.$resolve() - + return root.childNodes.length }) test(function() { @@ -107,15 +154,17 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() - return (root1.childNodes[0].nodeValue === "test1" && root2.childNodes[0].nodeValue === "test2") - && (mod1.value && mod1.value === "test1") && (mod2.value && mod2.value === "test2") + return root1.childNodes[0].nodeValue === "test1" && + root2.childNodes[0].nodeValue === "test2" && + mod1.value && mod1.value === "test1" && + mod2.value && mod2.value === "test2" }) test(function() { mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var unloaded = false - var mod = m.mount(root, { + m.mount(root, { controller: function() { this.value = "test1" this.onunload = function() { @@ -128,13 +177,13 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.mount(root, null) - + mock.requestAnimationFrame.$resolve() - + return unloaded }) test(function() { - //component should pass args to both controller and view + // component should pass args to both controller and view mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") @@ -147,14 +196,14 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() - return slot1 == 1 && slot2 == 1 + return slot1 === 1 && slot2 === 1 }) test(function() { - //component should work without controller + // component should work without controller mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") - var slot1, slot2 + var slot2 var component = { view: function(ctrl, options) {slot2 = options.a} } @@ -162,124 +211,126 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() - return slot2 == 1 + return slot2 === 1 }) test(function() { - //component controller should only run once + // component controller should only run once mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") - var count1 = 0, count2 = 0 - var component = { - view: function(ctrl) { - return sub - } - } + var count1 = 0 + var count2 = 0 var sub = { controller: function() { count1++ }, - view: function(ctrl) { + view: function() { count2++ return m("div", "test") } } + var component = { + view: function() { + return sub + } + } m.mount(root, component) mock.requestAnimationFrame.$resolve() - + m.redraw(true) mock.requestAnimationFrame.$resolve() - - return count1 == 1 && count2 == 2 + + return count1 === 1 && count2 === 2 }) test(function() { - //sub component controller should only run once + // sub component controller should only run once mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") - var count1 = 0, count2 = 0, count3 = 0, count4 = 0 - var component = { - view: function(ctrl) { - return sub - } - } - var sub = { - controller: function() { - count1++ - }, - view: function(ctrl) { - count2++ - return subsub - } - } + var count1 = 0 + var count2 = 0 + var count3 = 0 + var count4 = 0 var subsub = { controller: function() { count3++ }, - view: function(ctrl) { + view: function() { count4++ return m("div", "test") } } + var sub = { + controller: function() { + count1++ + }, + view: function() { + count2++ + return subsub + } + } + var component = { + view: function() { + return sub + } + } m.mount(root, component) mock.requestAnimationFrame.$resolve() - + m.redraw(true) mock.requestAnimationFrame.$resolve() - - return count1 == 1 && count2 == 2 && count3 == 1 && count4 == 2 + + return count1 === 1 && count2 === 2 && count3 === 1 && count4 === 2 }) test(function() { - //keys in components should work + // keys in components should work mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] - var component = { - controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m.component(sub, {key: i}) - }) - } - } var sub = { controller: function() {}, view: function() { return m("div") } } + var component = { + controller: function() {}, + view: function() { + return list.map(function(i) { + return m.component(sub, {key: i}) + }) + } + } m.mount(root, component) - + var firstBefore = root.childNodes[0] - + mock.requestAnimationFrame.$resolve() - + list.reverse() m.redraw(true) mock.requestAnimationFrame.$resolve() - + var firstAfter = root.childNodes[2] - + return firstBefore === firstAfter }) test(function() { - //keys in subcomponents should work + // keys in subcomponents should work mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] - var component = { + var subsub = { controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m.component(sub, {key: i}) - }) + view: function() { + return m("div") } } var sub = { @@ -287,150 +338,154 @@ function testMithril(mock) { return subsub } } - var subsub = { - controller: function() {}, - view: function() { - return m("div") - } - } - m.mount(root, component) - - var firstBefore = root.childNodes[0] - - mock.requestAnimationFrame.$resolve() - - list.reverse() - m.redraw(true) - - mock.requestAnimationFrame.$resolve() - - var firstAfter = root.childNodes[2] - - return firstBefore === firstAfter - }) - test(function() { - //keys in components should work even if component internally messes them up - mock.requestAnimationFrame.$resolve() - - var root = mock.document.createElement("div") - var list = [1, 2, 3] var component = { controller: function() {}, - view: function(ctrl) { + view: function() { return list.map(function(i) { return m.component(sub, {key: i}) }) } } + m.mount(root, component) + + var firstBefore = root.childNodes[0] + + mock.requestAnimationFrame.$resolve() + + list.reverse() + m.redraw(true) + + mock.requestAnimationFrame.$resolve() + + var firstAfter = root.childNodes[2] + + return firstBefore === firstAfter + }) + test(function() { + // keys in components should work even if component internally messes + // them up + mock.requestAnimationFrame.$resolve() + + var root = mock.document.createElement("div") + var list = [1, 2, 3] var sub = { controller: function() {}, view: function() { return m("div", {key: 1}) } } - m.mount(root, component) - - var firstBefore = root.childNodes[0] - - mock.requestAnimationFrame.$resolve() - - list.reverse() - m.redraw(true) - - mock.requestAnimationFrame.$resolve() - - var firstAfter = root.childNodes[2] - - return firstBefore === firstAfter - }) - test(function() { - //keys in subcomponents should work even if component internally messes them up - mock.requestAnimationFrame.$resolve() - - var root = mock.document.createElement("div") - var list = [1, 2, 3] var component = { controller: function() {}, - view: function(ctrl) { + view: function() { return list.map(function(i) { return m.component(sub, {key: i}) }) } } - var sub = { - controller: function() {}, - view: function() { - return subsub - } - } + m.mount(root, component) + + var firstBefore = root.childNodes[0] + + mock.requestAnimationFrame.$resolve() + + list.reverse() + m.redraw(true) + + mock.requestAnimationFrame.$resolve() + + var firstAfter = root.childNodes[2] + + return firstBefore === firstAfter + }) + test(function() { + // keys in subcomponents should work even if component internally messes + // them up + mock.requestAnimationFrame.$resolve() + + var root = mock.document.createElement("div") + var list = [1, 2, 3] var subsub = { controller: function() {}, view: function() { return m("div", {key: 1}) } } + var sub = { + controller: function() {}, + view: function() { + return subsub + } + } + var component = { + controller: function() {}, + view: function() { + return list.map(function(i) { + return m.component(sub, {key: i}) + }) + } + } m.mount(root, component) - + var firstBefore = root.childNodes[0] - + mock.requestAnimationFrame.$resolve() - + list.reverse() m.redraw(true) mock.requestAnimationFrame.$resolve() - + var firstAfter = root.childNodes[2] - + return firstBefore === firstAfter }) test(function() { - //component identity should stay intact if components are descendants of keyed elements + // component identity should stay intact if components are descendants + // of keyed elements mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] - var component = { - controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m("div", {key: i}, sub) - }) - } - } var sub = { controller: function() {}, view: function() { return m("div") } } + var component = { + controller: function() {}, + view: function() { + return list.map(function(i) { + return m("div", {key: i}, sub) + }) + } + } m.mount(root, component) - + var firstBefore = root.childNodes[0].childNodes[0] - + mock.requestAnimationFrame.$resolve() - + list.reverse() m.redraw(true) mock.requestAnimationFrame.$resolve() - + var firstAfter = root.childNodes[2].childNodes[0] - + return firstBefore === firstAfter }) test(function() { - //subcomponent identity should stay intact if components are descendants of keyed elements + // subcomponent identity should stay intact if components are + // descendants of keyed elements mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] - var component = { + var subsub = { controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m("div", {key: i}, sub) - }) + view: function() { + return m("div") } } var sub = { @@ -439,42 +494,36 @@ function testMithril(mock) { return subsub } } - var subsub = { + var component = { controller: function() {}, view: function() { - return m("div") + return list.map(function(i) { + return m("div", {key: i}, sub) + }) } } m.mount(root, component) - + var firstBefore = root.childNodes[0].childNodes[0] - + mock.requestAnimationFrame.$resolve() - + list.reverse() m.redraw(true) mock.requestAnimationFrame.$resolve() - + var firstAfter = root.childNodes[2].childNodes[0] - + return firstBefore === firstAfter }) test(function() { - //component should call onunload when removed from template + // component should call onunload when removed from template mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] var unloaded - var component = { - controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m.component(sub, {key: i}) - }) - } - } var sub = { controller: function(opts) { this.onunload = function() { @@ -485,32 +534,40 @@ function testMithril(mock) { return m("div") } } + var component = { + controller: function() {}, + view: function() { + return list.map(function(i) { + return m.component(sub, {key: i}) + }) + } + } m.mount(root, component) - - var firstBefore = root.childNodes[0] - + mock.requestAnimationFrame.$resolve() - + list.pop() m.redraw(true) mock.requestAnimationFrame.$resolve() - + return unloaded === 3 }) test(function() { - //subcomponent should call onunload when removed from template + // subcomponent should call onunload when removed from template mock.requestAnimationFrame.$resolve() var root = mock.document.createElement("div") var list = [1, 2, 3] var unloaded1, unloaded2 - var component = { - controller: function() {}, - view: function(ctrl) { - return list.map(function(i) { - return m.component(sub, {key: i}) - }) + var subsub = { + controller: function(opts) { + this.onunload = function() { + unloaded2 = opts.key + } + }, + view: function() { + return m("div") } } var sub = { @@ -523,248 +580,253 @@ function testMithril(mock) { return m.component(subsub, {key: opts.key}) } } + var component = { + controller: function() {}, + view: function() { + return list.map(function(i) { + return m.component(sub, {key: i}) + }) + } + } + m.mount(root, component) + + mock.requestAnimationFrame.$resolve() + + list.pop() + m.redraw(true) + + mock.requestAnimationFrame.$resolve() + + return unloaded1 === 3 && unloaded2 === 3 + }) + test(function() { + // calling m.redraw synchronously from controller constructor should not + // trigger extra redraws + mock.requestAnimationFrame.$resolve() + + var root = mock.document.createElement("div") + var count = 0 + var sub = { + controller: function() { + m.redraw() + }, + view: function() { + count++ + return m("div") + } + } + var component = { + controller: function() {}, + view: function() { + return sub + } + } + m.mount(root, component) + + mock.requestAnimationFrame.$resolve() + + return count === 1 + }) + test(function() { + // calling m.redraw synchronously from controller constructor should not + // trigger extra redraws + mock.requestAnimationFrame.$resolve() + + var root = mock.document.createElement("div") + var count = 0 var subsub = { - controller: function(opts) { - this.onunload = function() { - unloaded2 = opts.key + controller: function() { + m.redraw() + }, + view: function() { + count++ + return m("div") + } + } + var sub = { + controller: function() {}, + view: function() { + return subsub + } + } + var component = { + controller: function() {}, + view: function() { + return sub + } + } + m.mount(root, component) + + mock.requestAnimationFrame.$resolve() + + return count === 1 + }) + test(function() { + // calling preventDefault from component's onunload should prevent route + // change + mock.requestAnimationFrame.$resolve() + mock.location.search = "?" + + var root = mock.document.createElement("div") + var loaded = false + var testEnabled = true + var sub = { + controller: function() { + this.onunload = function(e) { + if (testEnabled) e.preventDefault() } }, view: function() { return m("div") } } - m.mount(root, component) - - var firstBefore = root.childNodes[0] - - mock.requestAnimationFrame.$resolve() - - list.pop() - m.redraw(true) - - mock.requestAnimationFrame.$resolve() - - return unloaded1 === 3 && unloaded2 === 3 - }) - test(function() { - //calling m.redraw synchronously from controller constructor should not trigger extra redraws - mock.requestAnimationFrame.$resolve() - - var root = mock.document.createElement("div") - var count = 0 var component = { controller: function() {}, - view: function(ctrl) { + view: function() { return sub } } - var sub = { - controller: function(opts) { - m.redraw() + m.route(root, "/a", { + "/a": component, + "/b": {controller: function() {loaded = true}, view: function() {}} + }) + + mock.requestAnimationFrame.$resolve() + + m.route("/b") + + mock.requestAnimationFrame.$resolve() + testEnabled = false + + return loaded === false + }) + test(function() { + // calling preventDefault from subcomponent's onunload should prevent + // route change + mock.requestAnimationFrame.$resolve() + mock.location.search = "?" + + var root = mock.document.createElement("div") + var loaded = false + var testEnabled = true + var subsub = { + controller: function() { + this.onunload = function(e) { + if (testEnabled) e.preventDefault() + } }, view: function() { - count++ return m("div") } } - m.mount(root, component) - - mock.requestAnimationFrame.$resolve() - - return count === 1 - }) - test(function() { - //calling m.redraw synchronously from controller constructor should not trigger extra redraws - mock.requestAnimationFrame.$resolve() - - var root = mock.document.createElement("div") - var count = 0 - var component = { - controller: function() {}, - view: function(ctrl) { - return sub - } - } var sub = { - controller: function(opts) {}, + controller: function() {}, view: function() { return subsub } } - var subsub = { - controller: function(opts) { - m.redraw() - }, - view: function() { - count++ - return m("div") - } - } - m.mount(root, component) - - mock.requestAnimationFrame.$resolve() - - return count === 1 - }) - test(function() { - //calling preventDefault from component's onunload should prevent route change - mock.requestAnimationFrame.$resolve() - mock.location.search = "?" - - var root = mock.document.createElement("div") - var loaded = false - var testEnabled = true var component = { controller: function() {}, view: function() { return sub } } - var sub = { - controller: function(opts) { - controller = this - this.onunload = function(e) {if (testEnabled) e.preventDefault()} - }, - view: function() { - return m("div") - } - } m.route(root, "/a", { "/a": component, "/b": {controller: function() {loaded = true}, view: function() {}} }) - + mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() testEnabled = false - + return loaded === false }) test(function() { - //calling preventDefault from subcomponent's onunload should prevent route change + // calling preventDefault from non-curried component's onunload should + // prevent route change mock.requestAnimationFrame.$resolve() mock.location.search = "?" var root = mock.document.createElement("div") var loaded = false var testEnabled = true + var sub = { + controller: function() { + this.onunload = function(e) { + if (testEnabled) e.preventDefault() + } + }, + view: function() { + return m("div") + } + } var component = { controller: function() {}, view: function() { return sub } } - var sub = { - controller: function(opts) { + m.route(root, "/a", { + "/a": component, + "/b": {controller: function() {loaded = true}, view: function() {}} + }) + + mock.requestAnimationFrame.$resolve() + + m.route("/b") + + mock.requestAnimationFrame.$resolve() + testEnabled = false + + return loaded === false + }) + test(function() { + // calling preventDefault from non-curried subcomponent's onunload + // should prevent route change + mock.requestAnimationFrame.$resolve() + mock.location.search = "?" + + var root = mock.document.createElement("div") + var loaded = false + var testEnabled = true + var subsub = { + controller: function() { + this.onunload = function(e) { + if (testEnabled) e.preventDefault() + } }, + view: function() { + return m("div") + } + } + var sub = { + controller: function() {}, view: function() { return subsub } } - var subsub = { - controller: function(opts) { - controller = this - this.onunload = function(e) {if (testEnabled) e.preventDefault()} - }, - view: function() { - return m("div") - } - } - m.route(root, "/a", { - "/a": component, - "/b": {controller: function() {loaded = true}, view: function() {}} - }) - - mock.requestAnimationFrame.$resolve() - - m.route("/b") - - mock.requestAnimationFrame.$resolve() - testEnabled = false - - return loaded === false - }) - test(function() { - //calling preventDefault from non-curried component's onunload should prevent route change - mock.requestAnimationFrame.$resolve() - mock.location.search = "?" - - var root = mock.document.createElement("div") - var loaded = false - var testEnabled = true var component = { controller: function() {}, view: function() { return sub } } - var sub = { - controller: function(opts) { - controller = this - this.onunload = function(e) {if (testEnabled) e.preventDefault()} - }, - view: function() { - return m("div") - } - } m.route(root, "/a", { "/a": component, "/b": {controller: function() {loaded = true}, view: function() {}} }) - - mock.requestAnimationFrame.$resolve() - - m.route("/b") - - mock.requestAnimationFrame.$resolve() - testEnabled = false - - return loaded === false - }) - test(function() { - //calling preventDefault from non-curried subcomponent's onunload should prevent route change - mock.requestAnimationFrame.$resolve() - mock.location.search = "?" - var root = mock.document.createElement("div") - var loaded = false - var testEnabled = true - var component = { - controller: function() {}, - view: function() { - return sub - } - } - var sub = { - controller: function(opts) {}, - view: function() { - return subsub - } - } - var subsub = { - controller: function(opts) { - controller = this - this.onunload = function(e) {if (testEnabled) e.preventDefault()} - }, - view: function() { - return m("div") - } - } - m.route(root, "/a", { - "/a": component, - "/b": {controller: function() {loaded = true}, view: function() {}} - }) - mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() testEnabled = false - + return loaded === false }) test(function() { @@ -773,24 +835,6 @@ function testMithril(mock) { var root = mock.document.createElement("div") var count = 0 - var App = { - controller: function() {}, - view: function(ctrl) { - return m('.outer', [ - m('.inner', m.component(CommentList, { list: [1, 2, 3] })) - ]) - } - } - var CommentList = { - controller: function() {}, - view: function(ctrl, props) { - return m('.list', props.list.map(function(i) { - return m('.comment', [ - m.component(Reply, {key: i}) - ]) - })) - } - } var Reply = { controller: function() {}, view: function() { @@ -798,6 +842,24 @@ function testMithril(mock) { return m(".reply") } } + var CommentList = { + controller: function() {}, + view: function(ctrl, props) { + return m(".list", props.list.map(function(i) { + return m(".comment", [ + m.component(Reply, {key: i}) + ]) + })) + } + } + var App = { + controller: function() {}, + view: function() { + return m(".outer", [ + m(".inner", m.component(CommentList, { list: [1, 2, 3] })) + ]) + } + } m.mount(root, App) mock.requestAnimationFrame.$resolve() @@ -823,15 +885,15 @@ function testMithril(mock) { m.route(root, "/a", { "/a": { view: function () { - return m('.page-a', [ - m('h1'), m.component(subA, { x: 11 }) + return m(".page-a", [ + m("h1"), m.component(subA, { x: 11 }) ]) } }, "/b": { view: function() { - return m('.page-b', [ - m('h2'), m.component(subB, { y: 22 }) + return m(".page-b", [ + m("h2"), m.component(subB, { y: 22 }) ]) } } @@ -851,19 +913,20 @@ function testMithril(mock) { }) test(function() { var root = mock.document.createElement("div") - var component = {}, unloaded = false + var component = {} + var unloaded = false component.controller = function() { this.onunload = function() {unloaded = true} } component.view = function() {} m.mount(root, component) m.mount(root, {controller: function() {}, view: function() {}}) - + return unloaded === true }) test(function() { mock.requestAnimationFrame.$resolve() - + var root = mock.document.createElement("div") var initCount = 0 var component = {} @@ -873,26 +936,30 @@ function testMithril(mock) { }}) } m.mount(root, component) - + mock.requestAnimationFrame.$resolve() - + m.redraw() - + mock.requestAnimationFrame.$resolve() - - return initCount == 1 + + return initCount === 1 }) test(function() { var root = mock.document.createElement("div") - + var dom = mock.document.createElement("div") - + var show = true var component = { view: function() { return [ - m(".foo", {key: 1, config: test, onclick: function() {show = !show}}), + m(".foo", { + key: 1, + config: test, + onclick: function() {show = !show} + }), show ? m(".bar", {key: 2}) : null ] } @@ -905,20 +972,20 @@ function testMithril(mock) { } m.mount(root, component) - + mock.requestAnimationFrame.$resolve() - + show = false m.redraw() - + mock.requestAnimationFrame.$resolve() - + show = true m.redraw() - + mock.requestAnimationFrame.$resolve() - - return root.childNodes.length == 3 + + return root.childNodes.length === 3 }) test(function() { var root = mock.document.createElement("div") @@ -926,36 +993,36 @@ function testMithril(mock) { var testcomponent = { controller: function() {}, view: function() { - return m('div', 'component'); + return m("div", "component") } - }; + } var app = { - view: function(scope) { + view: function() { return show ? [ - m('h1', '1'), + m("h1", "1"), testcomponent ] : [ - m('h1', '2'), - ]; + m("h1", "2") + ] } - }; + } + + m.mount(root, app) - m.mount(root, app); - mock.requestAnimationFrame.$resolve() - + show = false m.redraw() - + mock.requestAnimationFrame.$resolve() - + show = true m.redraw() - + mock.requestAnimationFrame.$resolve() - - return root.childNodes.length == 2 + + return root.childNodes.length === 2 }) test(function() { // Components should not require a view @@ -964,7 +1031,7 @@ function testMithril(mock) { var Component = { view: function () { - return m('.comp') + return m(".comp") } } @@ -980,17 +1047,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() - return root.childNodes[0].nodeName == "DIV" + return root.childNodes[0].nodeName === "DIV" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/551 + // https://github.com/lhorie/mithril.js/issues/551 var root = mock.document.createElement("div") - var a = false, found = false, unloaded = false, redraws = 0 - var Root = { - view: function() { - return Comp - } - } + var a = false + var found = false + var unloaded = false + var redraws = 0 var Comp = { view: function() { redraws++ @@ -1005,29 +1070,34 @@ function testMithril(mock) { ]) }, config: function(el, init, ctx) { - if (!init) ctx.onunload = function() { - unloaded = true + if (!init) { + ctx.onunload = function() { + unloaded = true + } } } } - m.mount(root, Root) - - var target = root.childNodes[0].childNodes[0] - target.onclick({currentTarget: target}) - - mock.requestAnimationFrame.$resolve() - - return !unloaded && found.id === "a" && redraws == 3 - }) - test(function() { - //https://github.com/lhorie/mithril.js/issues/551 - var root = mock.document.createElement("div") - var a = false, found = false, unloaded = false, redraws = 0 var Root = { view: function() { return Comp } } + m.mount(root, Root) + + var target = root.childNodes[0].childNodes[0] + target.onclick({currentTarget: target}) + + mock.requestAnimationFrame.$resolve() + + return !unloaded && found.id === "a" && redraws === 3 + }) + test(function() { + // https://github.com/lhorie/mithril.js/issues/551 + var root = mock.document.createElement("div") + var a = false + var found = false + var unloaded = false + var redraws = 0 var Comp = { view: function() { redraws++ @@ -1043,19 +1113,26 @@ function testMithril(mock) { ]) }, config: function(el, init, ctx) { - if (!init) ctx.onunload = function() { - unloaded = true + if (!init) { + ctx.onunload = function() { + unloaded = true + } } } } + var Root = { + view: function() { + return Comp + } + } m.mount(root, Root) - + var target = root.childNodes[0].childNodes[0] target.onclick({currentTarget: target}) - + mock.requestAnimationFrame.$resolve() - return !unloaded && found.id === "a" && redraws == 2 + return !unloaded && found.id === "a" && redraws === 2 }) test(function() { var root = mock.document.createElement("div") @@ -1066,67 +1143,63 @@ function testMithril(mock) { return m("div", {onclick: function() {m.redraw(true)}}) } } - + m.mount(root, Root) - + var target = root.childNodes[0] target.onclick({currentTarget: target}) - + mock.requestAnimationFrame.$resolve() - - return redraws == 3 + + return redraws === 3 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/555 + // https://github.com/lhorie/mithril.js/issues/555 var root = mock.document.createElement("div") var MyComponent = { controller: function(args) { - this.name = args.name; + this.name = args.name }, view: function(ctrl) { - return m('div', ctrl.name); + return m("div", ctrl.name) } } var FooPage = { view: function() { - return m('div', [ - m('a[href=/]', {config: m.route}, 'foo'), - m('a[href=/bar]', {config: m.route}, 'bar'), - m.component(MyComponent, {name: 'Jane'}) - ]); + return m("div", [ + m("a[href=/]", {config: m.route}, "foo"), + m("a[href=/bar]", {config: m.route}, "bar"), + m.component(MyComponent, {name: "Jane"}) + ]) } - }; + } var BarPage = { view: function() { - return m('div', [ - m('a[href=/]', {config: m.route}, 'foo'), - m('a[href=/bar]', {config: m.route}, 'bar'), - m.component(MyComponent, {name: 'Bob'}) - ]); + return m("div", [ + m("a[href=/]", {config: m.route}, "foo"), + m("a[href=/bar]", {config: m.route}, "bar"), + m.component(MyComponent, {name: "Bob"}) + ]) } - }; - m.route(root, '/', { - '/': FooPage, - '/bar': BarPage + } + m.route(root, "/", { + "/": FooPage, + "/bar": BarPage }) - + mock.requestAnimationFrame.$resolve() - + m.route("/bar") - + mock.requestAnimationFrame.$resolve() - - return root.childNodes[0].childNodes[2].childNodes[0].nodeValue == "Bob" + + return root.childNodes[0].childNodes[2] + .childNodes[0].nodeValue === "Bob" }) test(function() { var root = mock.document.createElement("div") - var redraws = 0, data - var Root = { - view: function() { - return Comp - } - } - + var redraws = 0 + var data var Comp = { controller: function() { this.foo = m.request({method: "GET", url: "/foo"}) @@ -1137,24 +1210,48 @@ function testMithril(mock) { return m("div") } } - + var Root = { + view: function() { + return Comp + } + } + m.mount(root, Root) - + mock.requestAnimationFrame.$resolve() mock.XMLHttpRequest.$instances.pop().onreadystatechange() - + mock.requestAnimationFrame.$resolve() m.mount(root, null) mock.requestAnimationFrame.$resolve() - - return redraws == 1 && data.url == "/foo" + + return redraws === 1 && data.url === "/foo" }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" var root = mock.document.createElement("div") - var redraws1 = 0, redraws2 = 0 + var redraws1 = 0 + var redraws2 = 0 + var Comp2 = { + controller: function() { + this.bar = m.request({method: "GET", url: "/bar"}) + }, + view: function() { + redraws2++ + return m("div") + } + } + var Comp1 = { + controller: function() { + this.foo = m.request({method: "GET", url: "/foo"}) + }, + view: function() { + redraws1++ + return m("div") + } + } var Root = { view: function() { return m("div", [ @@ -1163,12 +1260,30 @@ function testMithril(mock) { ]) } } - + + m.mount(root, Root) + + mock.requestAnimationFrame.$resolve() + mock.XMLHttpRequest.$instances.pop().onreadystatechange() + + mock.requestAnimationFrame.$resolve() + mock.XMLHttpRequest.$instances.pop().onreadystatechange() + + mock.requestAnimationFrame.$resolve() + m.mount(root, null) + mock.requestAnimationFrame.$resolve() + + return redraws1 === 1 && redraws2 === 1 + }) + test(function() { + var root = mock.document.createElement("div") + var redraws1 = 0 + var redraws2 = 0 var Comp1 = { controller: function() { this.foo = m.request({method: "GET", url: "/foo"}) }, - view: function(ctrl) { + view: function() { redraws1++ return m("div") } @@ -1177,29 +1292,11 @@ function testMithril(mock) { controller: function() { this.bar = m.request({method: "GET", url: "/bar"}) }, - view: function(ctrl) { + view: function() { redraws2++ return m("div") } } - - m.mount(root, Root) - - mock.requestAnimationFrame.$resolve() - mock.XMLHttpRequest.$instances.pop().onreadystatechange() - - mock.requestAnimationFrame.$resolve() - mock.XMLHttpRequest.$instances.pop().onreadystatechange() - - mock.requestAnimationFrame.$resolve() - m.mount(root, null) - mock.requestAnimationFrame.$resolve() - - return redraws1 == 1 && redraws2 == 1 - }) - test(function() { - var root = mock.document.createElement("div") - var redraws1 = 0, redraws2 = 0 var Root1 = { view: function() { return Comp1 @@ -1210,57 +1307,34 @@ function testMithril(mock) { return Comp2 } } - - var Comp1 = { - controller: function() { - this.foo = m.request({method: "GET", url: "/foo"}) - }, - view: function(ctrl) { - redraws1++ - return m("div") - } - } - var Comp2 = { - controller: function() { - this.bar = m.request({method: "GET", url: "/bar"}) - }, - view: function(ctrl) { - redraws2++ - return m("div") - } - } - + + m.route(root, "/", { "/": Root1, "/root2": Root2 }) - + mock.requestAnimationFrame.$resolve() mock.XMLHttpRequest.$instances.pop().onreadystatechange() - + m.route("/root2") - - + + mock.requestAnimationFrame.$resolve() mock.XMLHttpRequest.$instances.pop().onreadystatechange() - + mock.requestAnimationFrame.$resolve() m.mount(root, null) mock.requestAnimationFrame.$resolve() - - return redraws1 == 1 && redraws2 == 1 + + return redraws1 === 1 && redraws2 === 1 }) test(function() { var root = mock.document.createElement("div") - + var cond = true - var controller1 = null, controller2 = null - var Root = { - view: function() { - return cond ? Comp1 : Comp2 - } - } - + var controller1 = null + var controller2 = null var Comp1 = { view: function(ctrl) { controller1 = ctrl @@ -1273,116 +1347,119 @@ function testMithril(mock) { return m("div") } } - - m.mount(root, Root) - - mock.requestAnimationFrame.$resolve() - - cond = false - m.redraw(true) - - mock.requestAnimationFrame.$resolve() - - return controller1 !== controller2 - }) - test(function() { - var root = mock.document.createElement("div") - - var cond = true - var unloaded = false var Root = { view: function() { return cond ? Comp1 : Comp2 } } - + + m.mount(root, Root) + + mock.requestAnimationFrame.$resolve() + + cond = false + m.redraw(true) + + mock.requestAnimationFrame.$resolve() + + return controller1 !== controller2 + }) + test(function() { + var root = mock.document.createElement("div") + + var cond = true + var unloaded = false var Comp1 = { - view: function(ctrl) { + view: function() { return m("div", {config: function(el, init, ctx) { ctx.onunload = function() {unloaded = true} }}) } } var Comp2 = { - view: function(ctrl) { + view: function() { return m("div") } } - - m.mount(root, Root) - - mock.requestAnimationFrame.$resolve() - - cond = false - m.redraw(true) - - mock.requestAnimationFrame.$resolve() - - return unloaded - }) - test(function() { - var root = mock.document.createElement("div") - - var cond = true - var initialized = null var Root = { view: function() { return cond ? Comp1 : Comp2 } } - + + m.mount(root, Root) + + mock.requestAnimationFrame.$resolve() + + cond = false + m.redraw(true) + + mock.requestAnimationFrame.$resolve() + + return unloaded + }) + test(function() { + var root = mock.document.createElement("div") + + var cond = true + var initialized = null var Comp1 = { - view: function(ctrl) { + view: function() { return m("div") } } var Comp2 = { - view: function(ctrl) { + view: function() { return m("div", {config: function(el, init) { initialized = init }}) } } - + var Root = { + view: function() { + return cond ? Comp1 : Comp2 + } + } + m.mount(root, Root) - + mock.requestAnimationFrame.$resolve() - + cond = false m.redraw(true) - + mock.requestAnimationFrame.$resolve() - + return initialized === false }) test(function() { var root = mock.document.createElement("div") var el - var FooPage = { - view: function(ctrl) { - return m('div', [ - m('button', {onclick: function() { - ctrl.bar = true; - m.redraw(true); - el = root.childNodes[0].childNodes[1] - }}, 'click me'), - ctrl.bar ? m.component(BarComponent) : '' - ]); - } - }; var BarComponent = { view: function() { - return m('#bar', 'test'); + return m("#bar", "test") } - }; - m.mount(root, FooPage); - + } + var FooPage = { + view: function(ctrl) { + return m("div", [ + m("button", {onclick: function() { + ctrl.bar = true + m.redraw(true) + el = root.childNodes[0].childNodes[1] + }}, "click me"), + ctrl.bar ? m.component(BarComponent) : "" + ]) + } + } + m.mount(root, FooPage) + root.childNodes[0].childNodes[0].onclick({}) - - return el.id == "bar" + + return el.id === "bar" }) - - //m.withAttr + + // m.withAttr test(function() { var value var handler = m.withAttr("test", function(data) {value = data}) @@ -1390,10 +1467,10 @@ function testMithril(mock) { return value === "foo" }) - //m.trust + // m.trust test(function() {return m.trust("test").valueOf() === "test"}) - //m.render + // m.render test(function() { var root = mock.document.createElement("div") m.render(root, "test") @@ -1401,9 +1478,9 @@ function testMithril(mock) { }) test(function() { var root = mock.document.createElement("div") - m.render(root, m("div", {"class": "a"})) + m.render(root, m("div", {class: "a"})) var elementBefore = root.childNodes[0] - m.render(root, m("div", {"class": "b"})) + m.render(root, m("div", {class: "b"})) var elementAfter = root.childNodes[0] return elementBefore === elementAfter }) @@ -1442,13 +1519,14 @@ function testMithril(mock) { test(function() { var root = mock.document.createElement("div") m.render(root, m("div", [undefined])) - return root.childNodes[0].childNodes[0].nodeValue == "" + return root.childNodes[0].childNodes[0].nodeValue === "" }) test(function() { var root = mock.document.createElement("div") m.render(root, m("svg", [m("g")])) var g = root.childNodes[0].childNodes[0] - return g.nodeName === "G" && g.namespaceURI == "http://www.w3.org/2000/svg" + return g.nodeName === "G" && + g.namespaceURI === "http://www.w3.org/2000/svg" }) test(function() { var root = mock.document.createElement("div") @@ -1459,25 +1537,25 @@ function testMithril(mock) { var root = mock.document.createElement("div") m.render(root, m("div.classname", [m("a", {href: "/first"})])) m.render(root, m("div", [m("a", {href: "/second"})])) - return root.childNodes[0].childNodes.length == 1 + return root.childNodes[0].childNodes.length === 1 }) test(function() { var root = mock.document.createElement("div") m.render(root, m("ul", [m("li")])) m.render(root, m("ul", [m("li"), undefined])) - return root.childNodes[0].childNodes[1].nodeValue == "" + return root.childNodes[0].childNodes[1].nodeValue === "" }) test(function() { var root = mock.document.createElement("div") m.render(root, m("ul", [m("li"), m("li")])) m.render(root, m("ul", [m("li"), undefined])) - return root.childNodes[0].childNodes[1].nodeValue == "" + return root.childNodes[0].childNodes[1].nodeValue === "" }) test(function() { var root = mock.document.createElement("div") m.render(root, m("ul", [m("li")])) m.render(root, m("ul", [undefined])) - return root.childNodes[0].childNodes[0].nodeValue == "" + return root.childNodes[0].childNodes[0].nodeValue === "" }) test(function() { var root = mock.document.createElement("div") @@ -1489,13 +1567,15 @@ function testMithril(mock) { var root = mock.document.createElement("div") m.render(root, m("ul", [m("li")])) m.render(root, m("ul", [{tag: "b", attrs: {}}])) - return root.childNodes[0].childNodes[0].nodeName == "B" + return root.childNodes[0].childNodes[0].nodeName === "B" }) test(function() { + /* eslint-disable no-new-wrappers */ var root = mock.document.createElement("div") m.render(root, m("ul", [m("li")])) m.render(root, m("ul", [{tag: new String("b"), attrs: {}}])) - return root.childNodes[0].childNodes[0].nodeName == "B" + return root.childNodes[0].childNodes[0].nodeName === "B" + /* eslint-enable no-new-wrappers */ }) test(function() { var root = mock.document.createElement("div") @@ -1504,49 +1584,49 @@ function testMithril(mock) { return root.childNodes[0].childNodes[0].childNodes[0].nodeName === "A" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/43 + // https://github.com/lhorie/mithril.js/issues/43 var root = mock.document.createElement("div") m.render(root, m("a", {config: m.route}, "test")) m.render(root, m("a", {config: m.route}, "test")) return root.childNodes[0].childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/44 (1) + // https://github.com/lhorie/mithril.js/issues/44 (1) var root = mock.document.createElement("div") m.render(root, m("#foo", [null, m("#bar")])) m.render(root, m("#foo", ["test", m("#bar")])) return root.childNodes[0].childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/44 (2) + // https://github.com/lhorie/mithril.js/issues/44 (2) var root = mock.document.createElement("div") m.render(root, m("#foo", [null, m("#bar")])) m.render(root, m("#foo", [m("div"), m("#bar")])) return root.childNodes[0].childNodes[0].nodeName === "DIV" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/44 (3) + // https://github.com/lhorie/mithril.js/issues/44 (3) var root = mock.document.createElement("div") m.render(root, m("#foo", ["test", m("#bar")])) m.render(root, m("#foo", [m("div"), m("#bar")])) return root.childNodes[0].childNodes[0].nodeName === "DIV" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/44 (4) + // https://github.com/lhorie/mithril.js/issues/44 (4) var root = mock.document.createElement("div") m.render(root, m("#foo", [m("div"), m("#bar")])) m.render(root, m("#foo", ["test", m("#bar")])) return root.childNodes[0].childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/44 (5) + // https://github.com/lhorie/mithril.js/issues/44 (5) var root = mock.document.createElement("div") m.render(root, m("#foo", [m("#bar")])) m.render(root, m("#foo", [m("#bar"), [m("#baz")]])) return root.childNodes[0].childNodes[1].id === "baz" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/48 + // https://github.com/lhorie/mithril.js/issues/48 var root = mock.document m.render(root, m("html", [m("#foo")])) var result = root.childNodes[0].childNodes[0].id === "foo" @@ -1554,87 +1634,120 @@ function testMithril(mock) { return result }) test(function() { - //https://github.com/lhorie/mithril.js/issues/49 + // https://github.com/lhorie/mithril.js/issues/49 var root = mock.document.createElement("div") m.render(root, m("a", "test")) m.render(root, m("a.foo", "test")) return root.childNodes[0].childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/49 + // https://github.com/lhorie/mithril.js/issues/49 var root = mock.document.createElement("div") m.render(root, m("a.foo", "test")) m.render(root, m("a", "test")) return root.childNodes[0].childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/49 + // https://github.com/lhorie/mithril.js/issues/49 var root = mock.document.createElement("div") m.render(root, m("a.foo", "test")) m.render(root, m("a", "test1")) return root.childNodes[0].childNodes[0].nodeValue === "test1" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/49 + // https://github.com/lhorie/mithril.js/issues/49 var root = mock.document.createElement("div") m.render(root, m("a", "test")) m.render(root, m("a", "test1")) return root.childNodes[0].childNodes[0].nodeValue === "test1" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/50 + // https://github.com/lhorie/mithril.js/issues/50 var root = mock.document.createElement("div") m.render(root, m("#foo", [[m("div", "a"), m("div", "b")], m("#bar")])) return root.childNodes[0].childNodes[1].childNodes[0].nodeValue === "b" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/50 + // https://github.com/lhorie/mithril.js/issues/50 var root = mock.document.createElement("div") m.render(root, m("#foo", [[m("div", "a"), m("div", "b")], m("#bar")])) - m.render(root, m("#foo", [[m("div", "a"), m("div", "b"), m("div", "c")], m("#bar")])) + m.render(root, m("#foo", [ + [m("div", "a"), m("div", "b"), m("div", "c")], + m("#bar") + ])) return root.childNodes[0].childNodes[2].childNodes[0].nodeValue === "c" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/50 + // https://github.com/lhorie/mithril.js/issues/50 var root = mock.document.createElement("div") - m.render(root, m("#foo", [[m("div", "a"), m("div", "b")], [m("div", "c"), m("div", "d")], m("#bar")])) - return root.childNodes[0].childNodes[3].childNodes[0].nodeValue === "d" && root.childNodes[0].childNodes[4].id === "bar" + m.render(root, m("#foo", [ + [m("div", "a"), m("div", "b")], + [m("div", "c"), m("div", "d")], + m("#bar") + ])) + var children = root.childNodes[0] + return children.childNodes[3].childNodes[0].nodeValue === "d" && + children.childNodes[4].id === "bar" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/50 + // https://github.com/lhorie/mithril.js/issues/50 var root = mock.document.createElement("div") m.render(root, m("#foo", [[m("div", "a"), m("div", "b")], "test"])) - return root.childNodes[0].childNodes[1].childNodes[0].nodeValue === "b" && root.childNodes[0].childNodes[2].nodeValue === "test" + var children = root.childNodes[0] + return children.childNodes[1].childNodes[0].nodeValue === "b" && + children.childNodes[2].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/50 + // https://github.com/lhorie/mithril.js/issues/50 var root = mock.document.createElement("div") m.render(root, m("#foo", [["a", "b"], "test"])) - return root.childNodes[0].childNodes[1].nodeValue === "b" && root.childNodes[0].childNodes[2].nodeValue === "test" + return root.childNodes[0].childNodes[1].nodeValue === "b" && + root.childNodes[0].childNodes[2].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/51 + // https://github.com/lhorie/mithril.js/issues/51 var root = mock.document.createElement("div") - m.render(root, m("main", [m("button"), m("article", [m("section"), m("nav")])])) - m.render(root, m("main", [m("button"), m("article", [m("span"), m("nav")])])) - return root.childNodes[0].childNodes[1].childNodes[0].nodeName === "SPAN" + m.render(root, m("main", [ + m("button"), + m("article", [m("section"), m("nav")]) + ])) + m.render(root, m("main", [ + m("button"), + m("article", [m("span"), m("nav")]) + ])) + return root.childNodes[0].childNodes[1] + .childNodes[0].nodeName === "SPAN" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/51 + // https://github.com/lhorie/mithril.js/issues/51 var root = mock.document.createElement("div") - m.render(root, m("main", [m("button"), m("article", [m("section"), m("nav")])])) - m.render(root, m("main", [m("button"), m("article", ["test", m("nav")])])) - return root.childNodes[0].childNodes[1].childNodes[0].nodeValue === "test" + m.render(root, m("main", [ + m("button"), + m("article", [m("section"), m("nav")]) + ])) + m.render(root, m("main", [ + m("button"), + m("article", ["test", m("nav")]) + ])) + return root.childNodes[0].childNodes[1] + .childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/51 + // https://github.com/lhorie/mithril.js/issues/51 var root = mock.document.createElement("div") - m.render(root, m("main", [m("button"), m("article", [m("section"), m("nav")])])) - m.render(root, m("main", [m("button"), m("article", [m.trust("test"), m("nav")])])) - return root.childNodes[0].childNodes[1].childNodes[0].nodeValue === "test" + m.render(root, m("main", [ + m("button"), + m("article", [m("section"), m("nav")]) + ])) + m.render(root, m("main", [ + m("button"), + m("article", [m.trust("test"), m("nav")]) + ])) + return root.childNodes[0].childNodes[1] + .childNodes[0].nodeValue === "test" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/55 + // https://github.com/lhorie/mithril.js/issues/55 var root = mock.document.createElement("div") m.render(root, m("#a")) var elementBefore = root.childNodes[0] @@ -1643,17 +1756,17 @@ function testMithril(mock) { return elementBefore !== elementAfter }) test(function() { - //https://github.com/lhorie/mithril.js/issues/56 + // https://github.com/lhorie/mithril.js/issues/56 var root = mock.document.createElement("div") m.render(root, [null, "foo"]) m.render(root, ["bar"]) - return root.childNodes.length == 1 + return root.childNodes.length === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/56 + // https://github.com/lhorie/mithril.js/issues/56 var root = mock.document.createElement("div") m.render(root, m("div", "foo")) - return root.childNodes.length == 1 + return root.childNodes.length === 1 }) test(function() { var root = mock.document.createElement("div") @@ -1671,10 +1784,13 @@ function testMithril(mock) { m.render(root, m("div", [undefined, m("ul")])) var valueAfter1 = root.childNodes[0].childNodes[0].nodeValue var valueAfter2 = root.childNodes[0].childNodes[1].nodeName - return valueBefore1 === "UL" && valueAfter1 === "" && valueBefore2 === "" && valueAfter2 === "UL" + return valueBefore1 === "UL" && + valueAfter1 === "" && + valueBefore2 === "" && + valueAfter2 === "UL" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/79 + // https://github.com/lhorie/mithril.js/issues/79 var root = mock.document.createElement("div") m.render(root, m("div", {style: {background: "red"}})) var valueBefore = root.childNodes[0].style.background @@ -1696,218 +1812,328 @@ function testMithril(mock) { return valueBefore === "red" && valueAfter === undefined }) test(function() { - //https://github.com/lhorie/mithril.js/issues/87 + // https://github.com/lhorie/mithril.js/issues/87 var root = mock.document.createElement("div") m.render(root, m("div", [[m("a"), m("a")], m("button")])) m.render(root, m("div", [[m("a")], m("button")])) - return root.childNodes[0].childNodes.length == 2 && root.childNodes[0].childNodes[1].nodeName == "BUTTON" + return root.childNodes[0].childNodes.length === 2 && + root.childNodes[0].childNodes[1].nodeName === "BUTTON" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/87 + // https://github.com/lhorie/mithril.js/issues/87 var root = mock.document.createElement("div") m.render(root, m("div", [m("a"), m("b"), m("button")])) m.render(root, m("div", [m("a"), m("button")])) - return root.childNodes[0].childNodes.length == 2 && root.childNodes[0].childNodes[1].nodeName == "BUTTON" + return root.childNodes[0].childNodes.length === 2 && + root.childNodes[0].childNodes[1].nodeName === "BUTTON" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/99 + // https://github.com/lhorie/mithril.js/issues/99 var root = mock.document.createElement("div") m.render(root, m("div", [m("img"), m("h1")])) m.render(root, m("div", [m("a")])) - return root.childNodes[0].childNodes.length == 1 && root.childNodes[0].childNodes[0].nodeName == "A" + return root.childNodes[0].childNodes.length === 1 && + root.childNodes[0].childNodes[0].nodeName === "A" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["a", "b", "c", "d"])) m.render(root, m("div", [["d", "e"]])) var children = root.childNodes[0].childNodes - return children.length == 2 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 2 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", [["a", "b", "c", "d"]])) m.render(root, m("div", ["d", "e"])) var children = root.childNodes[0].childNodes - return children.length == 2 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 2 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["x", [["a"], "b", "c", "d"]])) m.render(root, m("div", ["d", ["e"]])) var children = root.childNodes[0].childNodes - return children.length == 2 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 2 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["b"])) m.render(root, m("div", [["e"]])) var children = root.childNodes[0].childNodes - return children.length == 1 && children[0].nodeValue == "e" + return children.length === 1 && children[0].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["a", ["b"]])) m.render(root, m("div", ["d", [["e"]]])) var children = root.childNodes[0].childNodes - return children.length == 2 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 2 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["a", [["b"]]])) m.render(root, m("div", ["d", ["e"]])) var children = root.childNodes[0].childNodes - return children.length == 2 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 2 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/120 + // https://github.com/lhorie/mithril.js/issues/120 var root = mock.document.createElement("div") m.render(root, m("div", ["a", [["b"], "c"]])) m.render(root, m("div", ["d", [[["e"]], "x"]])) var children = root.childNodes[0].childNodes - return children.length == 3 && children[0].nodeValue == "d" && children[1].nodeValue == "e" + return children.length === 3 && + children[0].nodeValue === "d" && + children[1].nodeValue === "e" }) test(function() { var root = mock.document.createElement("div") - + var success = false - m.render(root, m("div", {config: function(elem, isInitialized, ctx) {ctx.data = 1}})) - m.render(root, m("div", {config: function(elem, isInitialized, ctx) {success = ctx.data === 1}})) + m.render(root, m("div", { + config: function(elem, isInitialized, ctx) { ctx.data = 1 } + })) + m.render(root, m("div", { + config: function(elem, isInitialized, ctx) { + success = ctx.data === 1 + } + })) return success }) test(function() { var root = mock.document.createElement("div") - var index = 0; - var success = true; - var statefulConfig = function(elem, isInitialized, ctx) {ctx.data = index++} - var node = m("div", {config: statefulConfig}); - m.render(root, [node, node]); + var index = 0 + var success = true + var statefulConfig = function(elem, isInitialized, ctx) { + ctx.data = index++ + } + var node = m("div", {config: statefulConfig}) + m.render(root, [node, node]) - index = 0; + index = 0 var checkConfig = function(elem, isInitialized, ctx) { success = success && (ctx.data === index++) } - node = m("div", {config: checkConfig}); - m.render(root, [node, node]); - return success; + node = m("div", {config: checkConfig}) + m.render(root, [node, node]) + return success }) test(function() { var root = mock.document.createElement("div") var parent m.render(root, m("div", m("a", { - config: function(el) {parent = el.parentNode.parentNode} - }))); + config: function(el) { parent = el.parentNode.parentNode } + }))) return parent === root }) test(function() { var root = mock.document.createElement("div") var count = 0 m.render(root, m("div", m("a", { - config: function(el) { + config: function() { var island = mock.document.createElement("div") count++ - if (count > 2) throw "too much recursion..." + if (count > 2) throw new Error("too much recursion...") m.render(island, m("div")) } - }))); - return count == 1 + }))) + return count === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/129 + // https://github.com/lhorie/mithril.js/issues/129 var root = mock.document.createElement("div") - m.render(root, m("div", [["foo", "bar"], ["foo", "bar"], ["foo", "bar"]])); - m.render(root, m("div", ["asdf", "asdf2", "asdf3"])); + m.render(root, m("div", [ + ["foo", "bar"], + ["foo", "bar"], + ["foo", "bar"] + ])) + m.render(root, m("div", ["asdf", "asdf2", "asdf3"])) return true }) test(function() { - //https://github.com/lhorie/mithril.js/issues/98 - //insert at beginning + // https://github.com/lhorie/mithril.js/issues/98 + // insert at beginning var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3)]) + m.render(root, [ + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3) + ]) var firstBefore = root.childNodes[0] - m.render(root, [m("a", {key: 4}, 4), m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3)]) + m.render(root, [ + m("a", {key: 4}, 4), + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3) + ]) var firstAfter = root.childNodes[1] - return firstBefore == firstAfter && root.childNodes[0].childNodes[0].nodeValue == "4" && root.childNodes.length == 4 + return firstBefore === firstAfter && + root.childNodes[0].childNodes[0].nodeValue === "4" && + root.childNodes.length === 4 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/98 + // https://github.com/lhorie/mithril.js/issues/98 var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3)]) + m.render(root, [ + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3) + ]) var firstBefore = root.childNodes[0] - m.render(root, [m("a", {key: 4}, 4), m("a", {key: 1}, 1), m("a", {key: 2}, 2)]) + m.render(root, [ + m("a", {key: 4}, 4), + m("a", {key: 1}, 1), + m("a", {key: 2}, 2) + ]) var firstAfter = root.childNodes[1] - return firstBefore == firstAfter && root.childNodes[0].childNodes[0].nodeValue == 4 && root.childNodes.length == 3 + return firstBefore === firstAfter && + root.childNodes[0].childNodes[0].nodeValue === "4" && + root.childNodes.length === 3 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/98 + // https://github.com/lhorie/mithril.js/issues/98 var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3)]) + m.render(root, [ + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3) + ]) var firstBefore = root.childNodes[1] - m.render(root, [m("a", {key: 2}, 2), m("a", {key: 3}, 3), m("a", {key: 4}, 4)]) + m.render(root, [ + m("a", {key: 2}, 2), + m("a", {key: 3}, 3), + m("a", {key: 4}, 4) + ]) var firstAfter = root.childNodes[0] - return firstBefore == firstAfter && root.childNodes[0].childNodes[0].nodeValue === "2" && root.childNodes.length === 3 + return firstBefore === firstAfter && + root.childNodes[0].childNodes[0].nodeValue === "2" && + root.childNodes.length === 3 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/98 + // https://github.com/lhorie/mithril.js/issues/98 var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3), m("a", {key: 4}, 4), m("a", {key: 5}, 5)]) + m.render(root, [ + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3), + m("a", {key: 4}, 4), + m("a", {key: 5}, 5) + ]) var firstBefore = root.childNodes[0] var secondBefore = root.childNodes[1] var fourthBefore = root.childNodes[3] - m.render(root, [m("a", {key: 4}, 4), m("a", {key: 10}, 10), m("a", {key: 1}, 1), m("a", {key: 2}, 2)]) + m.render(root, [ + m("a", {key: 4}, 4), + m("a", {key: 10}, 10), + m("a", {key: 1}, 1), + m("a", {key: 2}, 2) + ]) var firstAfter = root.childNodes[2] var secondAfter = root.childNodes[3] var fourthAfter = root.childNodes[0] - return firstBefore === firstAfter && secondBefore === secondAfter && fourthBefore === fourthAfter && root.childNodes[1].childNodes[0].nodeValue == "10" && root.childNodes.length === 4 + return firstBefore === firstAfter && + secondBefore === secondAfter && + fourthBefore === fourthAfter && + root.childNodes[1].childNodes[0].nodeValue === "10" && + root.childNodes.length === 4 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/98 + // https://github.com/lhorie/mithril.js/issues/98 var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}, 1), m("a", {key: 2}, 2), m("a", {key: 3}, 3), m("a", {key: 4}, 4), m("a", {key: 5}, 5)]) + m.render(root, [ + m("a", {key: 1}, 1), + m("a", {key: 2}, 2), + m("a", {key: 3}, 3), + m("a", {key: 4}, 4), + m("a", {key: 5}, 5) + ]) var firstBefore = root.childNodes[0] var secondBefore = root.childNodes[1] var fourthBefore = root.childNodes[3] - m.render(root, [m("a", {key: 4}, 4), m("a", {key: 10}, 10), m("a", {key: 2}, 2), m("a", {key: 1}, 1), m("a", {key: 6}, 6), m("a", {key: 7}, 7)]) + m.render(root, [ + m("a", {key: 4}, 4), + m("a", {key: 10}, 10), + m("a", {key: 2}, 2), + m("a", {key: 1}, 1), + m("a", {key: 6}, 6), + m("a", {key: 7}, 7) + ]) var firstAfter = root.childNodes[3] var secondAfter = root.childNodes[2] var fourthAfter = root.childNodes[0] - return firstBefore === firstAfter && secondBefore === secondAfter && fourthBefore === fourthAfter && root.childNodes[1].childNodes[0].nodeValue == "10" && root.childNodes[4].childNodes[0].nodeValue == "6" && root.childNodes[5].childNodes[0].nodeValue == "7" && root.childNodes.length === 6 + return firstBefore === firstAfter && + secondBefore === secondAfter && + fourthBefore === fourthAfter && + root.childNodes[1].childNodes[0].nodeValue === "10" && + root.childNodes[4].childNodes[0].nodeValue === "6" && + root.childNodes[5].childNodes[0].nodeValue === "7" && + root.childNodes.length === 6 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/149 + // https://github.com/lhorie/mithril.js/issues/149 var root = mock.document.createElement("div") - m.render(root, [m("a", {key: 1}), m("a", {key: 2}), m("a"), m("a", {key: 4}), m("a", {key: 5})]) + m.render(root, [ + m("a", {key: 1}), + m("a", {key: 2}), + m("a"), + m("a", {key: 4}), + m("a", {key: 5}) + ]) var firstBefore = root.childNodes[0] var secondBefore = root.childNodes[1] var thirdBefore = root.childNodes[2] var fourthBefore = root.childNodes[3] var fifthBefore = root.childNodes[4] - m.render(root, [m("a", {key: 4}), m("a", {key: 5}), m("a"), m("a", {key: 1}), m("a", {key: 2})]) + m.render(root, [ + m("a", {key: 4}), + m("a", {key: 5}), + m("a"), + m("a", {key: 1}), + m("a", {key: 2}) + ]) var firstAfter = root.childNodes[3] var secondAfter = root.childNodes[4] var thirdAfter = root.childNodes[2] var fourthAfter = root.childNodes[0] var fifthAfter = root.childNodes[1] - return firstBefore === firstAfter && secondBefore === secondAfter && thirdBefore === thirdAfter && fourthBefore === fourthAfter && fifthBefore === fifthAfter + return firstBefore === firstAfter && + secondBefore === secondAfter && + thirdBefore === thirdAfter && + fourthBefore === fourthAfter && + fifthBefore === fifthAfter }) test(function() { - //https://github.com/lhorie/mithril.js/issues/246 - //insert at beginning with non-keyed in the middle + // https://github.com/lhorie/mithril.js/issues/246 + // insert at beginning with non-keyed in the middle var root = mock.document.createElement("div") m.render(root, [m("a", {key: 1}, 1)]) var firstBefore = root.childNodes[0] m.render(root, [m("a", {key: 2}, 2), m("br"), m("a", {key: 1}, 1)]) var firstAfter = root.childNodes[2] - return firstBefore == firstAfter && root.childNodes[0].childNodes[0].nodeValue == 2 && root.childNodes.length == 3 + return firstBefore === firstAfter && + root.childNodes[0].childNodes[0].nodeValue === "2" && + root.childNodes.length === 3 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/134 + // https://github.com/lhorie/mithril.js/issues/134 var root = mock.document.createElement("div") m.render(root, m("div", {contenteditable: true}, "test")) mock.document.activeElement = root.childNodes[0] @@ -1916,7 +2142,7 @@ function testMithril(mock) { return root.childNodes[0].childNodes[0].nodeValue === "test2" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/136 + // https://github.com/lhorie/mithril.js/issues/136 var root = mock.document.createElement("div") m.render(root, m("textarea", ["test"])) m.render(root, m("textarea", ["test1"])) @@ -1946,7 +2172,7 @@ function testMithril(mock) { } }) ]) - return unloaded == 0 + return unloaded === 0 }) test(function() { var root = mock.document.createElement("div") @@ -1962,9 +2188,12 @@ function testMithril(mock) { unloadedChild++ } } - var unloaded = 0 - m.render(root, m("div", {config: configParent}, m("a", {config: configChild}))) - m.render(root, m("main", {config: configParent}, m("a", {config: configChild}))) + m.render(root, m("div", { + config: configParent + }, m("a", {config: configChild}))) + m.render(root, m("main", { + config: configParent + }, m("a", {config: configChild}))) return unloadedParent === 1 && unloadedChild === 0 }) test(function() { @@ -1981,20 +2210,24 @@ function testMithril(mock) { unloadedChild++ } } - var unloaded = 0 - m.render(root, m("div", {config: configParent}, m("a", {config: configChild}))) - m.render(root, m("main", {config: configParent}, m("b", {config: configChild}))) + m.render(root, m("div", { + config: configParent + }, m("a", {config: configChild}))) + m.render(root, m("main", { + config: configParent + }, m("b", {config: configChild}))) return unloadedParent === 1 && unloadedChild === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/150 + // https://github.com/lhorie/mithril.js/issues/150 var root = mock.document.createElement("div") m.render(root, [m("a"), m("div")]) m.render(root, [[], m("div")]) - return root.childNodes.length == 1 && root.childNodes[0].nodeName == "DIV" + return root.childNodes.length === 1 && + root.childNodes[0].nodeName === "DIV" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/156 + // https://github.com/lhorie/mithril.js/issues/156 var root = mock.document.createElement("div") m.render(root, m("div", [ ["a", "b", "c", "d"].map(function() { @@ -2002,60 +2235,111 @@ function testMithril(mock) { }), m("span") ])) - return root.childNodes[0].childNodes[8].nodeName == "SPAN" + return root.childNodes[0].childNodes[8].nodeName === "SPAN" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/157 + // https://github.com/lhorie/mithril.js/issues/157 var root = mock.document.createElement("div") - m.render(root, m("ul", [m("li", {key: 0}, 0), m("li", {key: 2}, 2), m("li", {key: 4}, 4)])) - m.render(root, m("ul", [m("li", {key: 0}, 0), m("li", {key: 1}, 1), m("li", {key: 2}, 2), m("li", {key: 3}, 3), m("li", {key: 4}, 4), m("li", {key: 5}, 5)])) - return root.childNodes[0].childNodes.map(function(n) {return n.childNodes[0].nodeValue}).join("") == "012345" + m.render(root, m("ul", [ + m("li", {key: 0}, 0), + m("li", {key: 2}, 2), + m("li", {key: 4}, 4) + ])) + m.render(root, m("ul", [ + m("li", {key: 0}, 0), + m("li", {key: 1}, 1), + m("li", {key: 2}, 2), + m("li", {key: 3}, 3), + m("li", {key: 4}, 4), + m("li", {key: 5}, 5) + ])) + return root.childNodes[0].childNodes + .map(function(n) {return n.childNodes[0].nodeValue}) + .join("") === "012345" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/157 + // https://github.com/lhorie/mithril.js/issues/157 var root = mock.document.createElement("div") m.render(root, m("input", {value: "a"})) m.render(root, m("input", {value: "aa"})) - return root.childNodes[0].childNodes.length == 0 + return root.childNodes[0].childNodes.length === 0 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/157 + // https://github.com/lhorie/mithril.js/issues/157 var root = mock.document.createElement("div") - m.render(root, m("br", {"class": "a"})) - m.render(root, m("br", {"class": "aa"})) - return root.childNodes[0].childNodes.length == 0 + m.render(root, m("br", {class: "a"})) + m.render(root, m("br", {class: "aa"})) + return root.childNodes[0].childNodes.length === 0 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/194 + // https://github.com/lhorie/mithril.js/issues/194 var root = mock.document.createElement("div") - m.render(root, m("ul", [m("li", {key: 0}, 0), m("li", {key: 1}, 1), m("li", {key: 2}, 2), m("li", {key: 3}, 3), m("li", {key: 4}, 4), m("li", {key: 5}, 5)])) - m.render(root, m("ul", [m("li", {key: 0}, 0), m("li", {key: 1}, 1), m("li", {key: 2}, 2), m("li", {key: 4}, 4), m("li", {key: 5}, 5)])) - return root.childNodes[0].childNodes.map(function(n) {return n.childNodes[0].nodeValue}).join("") == "01245" + m.render(root, m("ul", [ + m("li", {key: 0}, 0), + m("li", {key: 1}, 1), + m("li", {key: 2}, 2), + m("li", {key: 3}, 3), + m("li", {key: 4}, 4), + m("li", {key: 5}, 5) + ])) + m.render(root, m("ul", [ + m("li", {key: 0}, 0), + m("li", {key: 1}, 1), + m("li", {key: 2}, 2), + m("li", {key: 4}, 4), + m("li", {key: 5}, 5) + ])) + return root.childNodes[0].childNodes + .map(function(n) {return n.childNodes[0].nodeValue}) + .join("") === "01245" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/194 + // https://github.com/lhorie/mithril.js/issues/194 var root = mock.document.createElement("div") - m.render(root, m("ul", [m("li", {key: 0}, 0), m("li", {key: 1}, 1), m("li", {key: 2}, 2), m("li", {key: 3}, 3), m("li", {key: 4}, 4), m("li", {key: 5}, 5)])) - m.render(root, m("ul", [m("li", {key: 1}, 1), m("li", {key: 2}, 2), m("li", {key: 3}, 3), m("li", {key: 4}, 4), m("li", {key: 5}, 5), m("li", {key: 6}, 6)])) - m.render(root, m("ul", [m("li", {key: 12}, 12), m("li", {key: 13}, 13), m("li", {key: 14}, 14), m("li", {key: 15}, 15), m("li", {key: 16}, 16), m("li", {key: 17}, 17)])) - return root.childNodes[0].childNodes.map(function(n) {return n.childNodes[0].nodeValue}).join(",") == "12,13,14,15,16,17" + m.render(root, m("ul", [ + m("li", {key: 0}, 0), + m("li", {key: 1}, 1), + m("li", {key: 2}, 2), + m("li", {key: 3}, 3), + m("li", {key: 4}, 4), + m("li", {key: 5}, 5) + ])) + m.render(root, m("ul", [ + m("li", {key: 1}, 1), + m("li", {key: 2}, 2), + m("li", {key: 3}, 3), + m("li", {key: 4}, 4), + m("li", {key: 5}, 5), + m("li", {key: 6}, 6) + ])) + m.render(root, m("ul", [ + m("li", {key: 12}, 12), + m("li", {key: 13}, 13), + m("li", {key: 14}, 14), + m("li", {key: 15}, 15), + m("li", {key: 16}, 16), + m("li", {key: 17}, 17) + ])) + return root.childNodes[0].childNodes + .map(function(n) {return n.childNodes[0].nodeValue}) + .join(",") === "12,13,14,15,16,17" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/206 + // https://github.com/lhorie/mithril.js/issues/206 var root = mock.document.createElement("div") m.render(root, m("div", undefined)) m.render(root, m("div", [m("div")])) - return root.childNodes[0].childNodes.length == 1 + return root.childNodes[0].childNodes.length === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/206 + // https://github.com/lhorie/mithril.js/issues/206 var root = mock.document.createElement("div") m.render(root, m("div", null)) m.render(root, m("div", [m("div")])) - return root.childNodes[0].childNodes.length == 1 + return root.childNodes[0].childNodes.length === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/200 + // https://github.com/lhorie/mithril.js/issues/200 var root = mock.document.createElement("div") var unloaded1 = false @@ -2082,42 +2366,94 @@ function testMithril(mock) { var root = mock.document.createElement("div") m.render(root, [m("div.blue")]) m.render(root, [m("div.green", [m("div")]), m("div.blue")]) - return root.childNodes.length == 2 + return root.childNodes.length === 2 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/277 + // https://github.com/lhorie/mithril.js/issues/277 var root = mock.document.createElement("div") function Field() { - this.tag = "div"; - this.attrs = {}; - this.children = "hello"; + this.tag = "div" + this.attrs = {} + this.children = "hello" } m.render(root, new Field()) - return root.childNodes.length == 1 + return root.childNodes.length === 1 }) test(function() { var root = mock.document.createElement("div") m.render(root, {foo: 123}) - return root.childNodes.length == 0 + return root.childNodes.length === 0 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/299 + // https://github.com/lhorie/mithril.js/issues/299 var root = mock.document.createElement("div") - m.render(root, m("div", [m("div", {key: 1}, 1), m("div", {key: 2}, 2), m("div", {key: 3}, 3), m("div", {key: 4}, 4), m("div", {key: 5}, 5), null, null, null, null, null, null, null, null, null, null])) - m.render(root, m("div", [null, null, m("div", {key: 3}, 3), null, null, m("div", {key: 6}, 6), null, null, m("div", {key: 9}, 9), null, null, m("div", {key: 12}, 12), null, null, m("div", {key: 15}, 15)])) - m.render(root, m("div", [m("div", {key: 1}, 1), m("div", {key: 2}, 2), m("div", {key: 3}, 3), m("div", {key: 4}, 4), m("div", {key: 5}, 5), null, null, null, null, null, null, null, null, null, null])) - return root.childNodes[0].childNodes.map(function(c) {return c.childNodes ? c.childNodes[0].nodeValue: c.nodeValue}).slice(0, 5).join("") == "12345" + m.render(root, m("div", [ + m("div", {key: 1}, 1), + m("div", {key: 2}, 2), + m("div", {key: 3}, 3), + m("div", {key: 4}, 4), + m("div", {key: 5}, 5), + null, null, null, null, null, null, null, null, null, null + ])) + m.render(root, m("div", [ + null, null, + m("div", {key: 3}, 3), + null, null, + m("div", {key: 6}, 6), + null, null, + m("div", {key: 9}, 9), + null, null, + m("div", {key: 12}, 12), + null, null, + m("div", {key: 15}, 15) + ])) + m.render(root, m("div", [ + m("div", {key: 1}, 1), + m("div", {key: 2}, 2), + m("div", {key: 3}, 3), + m("div", {key: 4}, 4), + m("div", {key: 5}, 5), + null, null, null, null, null, null, null, null, null, null + ])) + return root.childNodes[0].childNodes + .map(function(c) { + return c.childNodes ? c.childNodes[0].nodeValue : c.nodeValue + }) + .slice(0, 5) + .join("") === "12345" }) test(function() { - //https://github.com/lhorie/mithril.js/issues/377 + // https://github.com/lhorie/mithril.js/issues/377 var root = mock.document.createElement("div") - m.render(root, m("div", [m("div", 1), m("div", 2), [m("div", {key: 3}, 3), m("div", {key: 4}, 4), m("div", {key:5}, 5)], [m("div", {key: 6}, 6)]])) - m.render(root, m("div", [m("div", 1), null, [m("div", {key: 3}, 3), m("div", {key: 4}, 4), m("div", {key:5}, 5)], [m("div", {key: 6}, 6)]])) - return root.childNodes[0].childNodes.map(function(c) {return c.childNodes ? c.childNodes[0].nodeValue: c.nodeValue}).join("") == "13456" + m.render(root, m("div", [ + m("div", 1), + m("div", 2), + [ + m("div", {key: 3}, 3), + m("div", {key: 4}, 4), + m("div", {key: 5}, 5) + ], + [m("div", {key: 6}, 6)] + ])) + m.render(root, m("div", [ + m("div", 1), + null, + [ + m("div", {key: 3}, 3), + m("div", {key: 4}, 4), + m("div", {key: 5}, 5) + ], + [m("div", {key: 6}, 6)] + ])) + return root.childNodes[0].childNodes + .map(function(c) { + return c.childNodes ? c.childNodes[0].nodeValue : c.nodeValue + }) + .join("") === "13456" }) test(function() { var root = mock.document.createElement("div") - m.render(root, m("div", [console.log()])) //don't throw in Firefox + m.render(root, m("div", [console.log()])) // don't throw in Firefox return true }) test(function() { @@ -2133,21 +2469,24 @@ function testMithril(mock) { m("#div-3", {key: 3}), m("#div-2", {key: 2}) ]) - return root.childNodes.map(function(node) {return node.id}).join() == "div-1,div-3,div-2" + return root.childNodes + .map(function(node) {return node.id}) + .join() === "div-1,div-3,div-2" }) test(function() { var root = mock.document.createElement("div") m.render(root, m("div", function() {})) - return root.childNodes[0].childNodes.length == 0 + return root.childNodes[0].childNodes.length === 0 }) test(function() { var root = mock.document.createElement("div") m.render(root, m("div", "foo", m("a"))) m.render(root, m("div", "test")) - return root.childNodes[0].childNodes.length == 1 + return root.childNodes[0].childNodes.length === 1 }) test(function() { - //if an element is preceded by a conditional, it should not lose its identity + // if an element is preceded by a conditional, it should not lose its + // identity var root = mock.document.createElement("div") m.render(root, m("div", [m("a"), m("input[autofocus]")])) var before = root.childNodes[0].childNodes[1] @@ -2156,44 +2495,104 @@ function testMithril(mock) { return before === after }) test(function() { - //unkeyed element should maintain identity if mixed w/ keyed elements and identity can be inferred + // unkeyed element should maintain identity if mixed w/ keyed elements + // and identity can be inferred var root = mock.document.createElement("div") - m.render(root, m("div", [m("a", {key: 1}), m("a", {key: 2}), m("a", {key: 3}), m("i")])) + m.render(root, m("div", [ + m("a", {key: 1}), + m("a", {key: 2}), + m("a", {key: 3}), + m("i") + ])) var before = root.childNodes[0].childNodes[3] - m.render(root, m("div", [m("b", {key: 3}), m("b", {key: 4}), m("i"), m("b", {key: 1})])) + m.render(root, m("div", [ + m("b", {key: 3}), + m("b", {key: 4}), + m("i"), + m("b", {key: 1}) + ])) var after = root.childNodes[0].childNodes[2] return before === after }) test(function() { - //unkeyed element should maintain identity if mixed w/ keyed elements and text nodes and identity can be inferred + // unkeyed element should maintain identity if mixed w/ keyed elements + // and text nodes and identity can be inferred var root = mock.document.createElement("div") - m.render(root, m("div", [m("a", {key: 1}), m("a", {key: 2}), "foo", m("a", {key: 3}), m("i")])) + m.render(root, m("div", [ + m("a", {key: 1}), + m("a", {key: 2}), + "foo", + m("a", {key: 3}), + m("i") + ])) var before = root.childNodes[0].childNodes[4] - m.render(root, m("div", [m("a", {key: 3}), m("a", {key: 4}), "bar", m("i"), m("a", {key: 1})])) + m.render(root, m("div", [ + m("a", {key: 3}), + m("a", {key: 4}), + "bar", + m("i"), + m("a", {key: 1}) + ])) var after = root.childNodes[0].childNodes[3] return before === after }) test(function() { var root = mock.document.createElement("div") - m.render(root, m("div", [m("a", {key: 1}), m("a", {key: 2}), null, m("a", {key: 3}), m("i")])) + m.render(root, m("div", [ + m("a", {key: 1}), + m("a", {key: 2}), + null, + m("a", {key: 3}), + m("i") + ])) var before = root.childNodes[0].childNodes[4] - m.render(root, m("div", [m("a", {key: 3}), m("a", {key: 4}), null, m("i"), m("a", {key: 1})])) + m.render(root, m("div", [ + m("a", {key: 3}), + m("a", {key: 4}), + null, + m("i"), + m("a", {key: 1}) + ])) var after = root.childNodes[0].childNodes[3] return before === after }) test(function() { var root = mock.document.createElement("div") - m.render(root, m("div", [m("a", {key: 1}), m("a", {key: 2}), undefined, m("a", {key: 3}), m("i")])) + m.render(root, m("div", [ + m("a", {key: 1}), + m("a", {key: 2}), + undefined, + m("a", {key: 3}), + m("i") + ])) var before = root.childNodes[0].childNodes[4] - m.render(root, m("div", [m("a", {key: 3}), m("a", {key: 4}), undefined, m("i"), m("a", {key: 1})])) + m.render(root, m("div", [ + m("a", {key: 3}), + m("a", {key: 4}), + undefined, + m("i"), + m("a", {key: 1}) + ])) var after = root.childNodes[0].childNodes[3] return before === after }) test(function() { var root = mock.document.createElement("div") - m.render(root, m("div", [m("a", {key: 1}), m("a", {key: 2}), m.trust("a"), m("a", {key: 3}), m("i")])) + m.render(root, m("div", [ + m("a", {key: 1}), + m("a", {key: 2}), + m.trust("a"), + m("a", {key: 3}), + m("i") + ])) var before = root.childNodes[0].childNodes[4] - m.render(root, m("div", [m("a", {key: 3}), m("a", {key: 4}), m.trust("a"), m("i"), m("a", {key: 1})])) + m.render(root, m("div", [ + m("a", {key: 3}), + m("a", {key: 4}), + m.trust("a"), + m("i"), + m("a", {key: 1}) + ])) var after = root.childNodes[0].childNodes[3] return before === after }) @@ -2201,19 +2600,19 @@ function testMithril(mock) { var root = mock.document.createElement("div") var vdom = m("div.a", {class: undefined}) m.render(root, vdom) - return root.childNodes[0].class == "a" + return root.childNodes[0].class === "a" }) test(function() { var root = mock.document.createElement("div") m.render(root, m(".a", [1])) m.render(root, m(".a", [])) - return root.childNodes[0].childNodes.length == 0 + return root.childNodes[0].childNodes.length === 0 }) - //end m.render + // end m.render - //m.redraw + // m.redraw test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup var controller var root = mock.document.createElement("div") m.mount(root, { @@ -2228,65 +2627,69 @@ function testMithril(mock) { return valueBefore === "" && root.childNodes[0].nodeValue === "foo" }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup var count = 0 var root = mock.document.createElement("div") m.mount(root, { controller: function() {}, - view: function(ctrl) { + view: function() { count++ } }) - mock.requestAnimationFrame.$resolve() //teardown - m.redraw() //should run synchronously + mock.requestAnimationFrame.$resolve() // teardown + m.redraw() // should run synchronously - m.redraw() //rest should run asynchronously since they're spamming + m.redraw() // rest should run asynchronously since they're spamming m.redraw() m.redraw() - mock.requestAnimationFrame.$resolve() //teardown - + mock.requestAnimationFrame.$resolve() // teardown + return count === 3 }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup var count = 0 var root = mock.document.createElement("div") m.mount(root, { controller: function() {}, - view: function(ctrl) { + view: function() { count++ } }) - mock.requestAnimationFrame.$resolve() //teardown - m.redraw(true) //should run synchronously + mock.requestAnimationFrame.$resolve() // teardown + m.redraw(true) // should run synchronously - m.redraw(true) //forced to run synchronously + m.redraw(true) // forced to run synchronously m.redraw(true) m.redraw(true) - mock.requestAnimationFrame.$resolve() //teardown + mock.requestAnimationFrame.$resolve() // teardown return count === 5 }) - //m.route + // m.route test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/test1", { - "/test1": {controller: function() {}, view: function() {return "foo"}} + "/test1": { + controller: function() {}, + view: function() {return "foo"} + } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test1" && root.childNodes[0].nodeValue === "foo" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test1" && + root.childNodes[0].nodeValue === "foo" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.pathname = "/" var root = mock.document.createElement("div") @@ -2303,52 +2706,65 @@ function testMithril(mock) { } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.pathname == "/test2" && root.childNodes[0].nodeValue === "foo" && root.childNodes[1].href == "/test2" - - m.mount(root, null) //teardown - + + var result = mock.location.pathname === "/test2" && + root.childNodes[0].nodeValue === "foo" && + root.childNodes[1].href === "/test2" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.hash = "#" var root = mock.document.createElement("div") m.route.mode = "hash" m.route(root, "/test3", { - "/test3": {controller: function() {}, view: function() {return "foo"}} + "/test3": { + controller: function() {}, + view: function() {return "foo"} + } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.hash == "#/test3" && root.childNodes[0].nodeValue === "foo" - - m.mount(root, null) //teardown - + + var result = mock.location.hash === "#/test3" && + root.childNodes[0].nodeValue === "foo" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/test4/foo", { - "/test4/:test": {controller: function() {}, view: function() {return m.route.param("test")}} + "/test4/:test": { + controller: function() {}, + view: function() {return m.route.param("test")} + } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test4/foo" && root.childNodes[0].nodeValue === "foo" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test4/foo" && + root.childNodes[0].nodeValue === "foo" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" - var component = {controller: function() {}, view: function() {return m.route.param("test")}} + var component = { + controller: function() {}, + view: function() {return m.route.param("test")} + } var root = mock.document.createElement("div") m.route.mode = "search" @@ -2361,18 +2777,23 @@ function testMithril(mock) { m.route("/") var paramValueAfter = m.route.param("test") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/" && paramValueBefore === "foo" && paramValueAfter === undefined - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/" && + paramValueBefore === "foo" && + paramValueAfter === undefined + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" - var component = {controller: function() {}, view: function() {return m.route.param("a1")}} + var component = { + controller: function() {}, + view: function() {return m.route.param("a1")} + } var root = mock.document.createElement("div") m.route.mode = "search" @@ -2385,19 +2806,24 @@ function testMithril(mock) { m.route("/") var paramValueAfter = m.route.param("a1") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/" && paramValueBefore === "foo" && paramValueAfter === undefined - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/" && + paramValueBefore === "foo" && + paramValueAfter === undefined + + m.mount(root, null) // teardown + return result }) test(function() { - //https://github.com/lhorie/mithril.js/issues/61 - mock.requestAnimationFrame.$resolve() //setup + // https://github.com/lhorie/mithril.js/issues/61 + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" - var component = {controller: function() {}, view: function() {return m.route.param("a1")}} + var component = { + controller: function() {}, + view: function() {return m.route.param("a1")} + } var root = mock.document.createElement("div") m.route.mode = "search" @@ -2410,15 +2836,16 @@ function testMithril(mock) { m.route("/") var routeValueAfter = m.route() mock.requestAnimationFrame.$resolve() - - var result = routeValueBefore === "/test7/foo" && routeValueAfter === "/" - - m.mount(root, null) //teardown - + + var result = routeValueBefore === "/test7/foo" && + routeValueAfter === "/" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2432,15 +2859,16 @@ function testMithril(mock) { } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test8/foo/SEP/bar/baz" && root.childNodes[0].nodeValue === "foo_bar/baz" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test8/foo/SEP/bar/baz" && + root.childNodes[0].nodeValue === "foo_bar/baz" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2454,15 +2882,16 @@ function testMithril(mock) { } }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test9/foo/bar/SEP/baz" && root.childNodes[0].nodeValue === "foo/bar_baz" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test9/foo/bar/SEP/baz" && + root.childNodes[0].nodeValue === "foo/bar_baz" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2476,136 +2905,180 @@ function testMithril(mock) { } }) mock.requestAnimationFrame.$resolve() - + var result = root.childNodes[0].nodeValue === "foo bar" - - m.mount(root, null) //teardown - + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {return "foo"}}, - "/test11": {controller: function() {}, view: function() {return "bar"}} + "/": { + controller: function() {}, + view: function() {return "foo"} + }, + "/test11": { + controller: function() {}, + view: function() {return "bar"} + } }) mock.requestAnimationFrame.$resolve() m.route("/test11/") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test11/" && root.childNodes[0].nodeValue === "bar" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test11/" && + root.childNodes[0].nodeValue === "bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {}}, - "/test12": {controller: function() {}, view: function() {}} + "/": { + controller: function() {}, + view: function() {} + }, + "/test12": { + controller: function() {}, + view: function() {} + } }) mock.requestAnimationFrame.$resolve() m.route("/test12?a=foo&b=bar") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test12?a=foo&b=bar" && m.route.param("a") == "foo" && m.route.param("b") == "bar" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test12?a=foo&b=bar" && + m.route.param("a") === "foo" && + m.route.param("b") === "bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {return "bar"}}, - "/test13/:test": {controller: function() {}, view: function() {return m.route.param("test")}} + "/": { + controller: function() {}, + view: function() {return "bar"} + }, + "/test13/:test": { + controller: function() {}, + view: function() {return m.route.param("test")} + } }) mock.requestAnimationFrame.$resolve() m.route("/test13/foo?test=bar") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test13/foo?test=bar" && root.childNodes[0].nodeValue === "foo" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test13/foo?test=bar" && + root.childNodes[0].nodeValue === "foo" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {return "bar"}}, - "/test14": {controller: function() {}, view: function() {return "foo"}} + "/": { + controller: function() {}, + view: function() {return "bar"} + }, + "/test14": { + controller: function() {}, + view: function() {return "foo"} + } }) mock.requestAnimationFrame.$resolve() m.route("/test14?test&test2=") mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test14?test&test2=" && m.route.param("test") === null && m.route.param("test2") === "" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test14?test&test2=" && + m.route.param("test") == null && + m.route.param("test2") === "" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {}}, - "/test12": {controller: function() {}, view: function() {}} + "/": { + controller: function() {}, + view: function() {} + }, + "/test12": { + controller: function() {}, + view: function() {} + } }) mock.requestAnimationFrame.$resolve() m.route("/test12", {a: "foo", b: "bar"}) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test12?a=foo&b=bar" && m.route.param("a") == "foo" && m.route.param("b") == "bar" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test12?a=foo&b=bar" && + m.route.param("a") === "foo" && + m.route.param("b") === "bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") var route1, route2 m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {route1 = m.route()}, view: function() {}}, - "/test13": {controller: function() {route2 = m.route()}, view: function() {}} + "/": { + controller: function() {route1 = m.route()}, + view: function() {} + }, + "/test13": { + controller: function() {route2 = m.route()}, + view: function() {} + } }) mock.requestAnimationFrame.$resolve() m.route("/test13") mock.requestAnimationFrame.$resolve() - - var result = route1 == "/" && route2 == "/test13" - - m.mount(root, null) //teardown - + + var result = route1 === "/" && route2 === "/test13" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2629,15 +3102,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test14") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2669,15 +3142,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test15") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2706,15 +3179,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test16") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2745,15 +3218,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test17") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2782,15 +3255,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test18") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2831,17 +3304,17 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test20") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" - + var root = mock.document.createElement("div") var unloaded = 0 m.route.mode = "search" @@ -2879,15 +3352,15 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() m.route("/test21") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2896,30 +3369,30 @@ function testMithril(mock) { "/foo": { controller: function() {}, view: function() { - return m("div", "foo"); + return m("div", "foo") } }, "/bar": { controller: function() {}, view: function() { - return m("div", "bar"); + return m("div", "bar") } - }, + } }) mock.requestAnimationFrame.$resolve() - var foo = root.childNodes[0].childNodes[0].nodeValue; + var foo = root.childNodes[0].childNodes[0].nodeValue m.route("/bar") mock.requestAnimationFrame.$resolve() - var bar = root.childNodes[0].childNodes[0].nodeValue; - + var bar = root.childNodes[0].childNodes[0].nodeValue + var result = (foo === "foo" && bar === "bar") - - m.mount(root, null) //teardown - + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2934,28 +3407,28 @@ function testMithril(mock) { "/foo1": { controller: function() {}, view: function() { - return m("div", m("a", {config: config}, "foo")); + return m("div", m("a", {config: config}, "foo")) } }, "/bar1": { controller: function() {}, view: function() { - return m("main", m("a", {config: config}, "foo")); + return m("main", m("a", {config: config}, "foo")) } - }, + } }) mock.requestAnimationFrame.$resolve() m.route("/bar1") mock.requestAnimationFrame.$resolve() - - var result = unloaded == 1 - - m.mount(root, null) //teardown - + + var result = unloaded === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -2968,31 +3441,32 @@ function testMithril(mock) { m.redraw.strategy("none") }, view: function() { - return m("div"); + return m("div") } } }) mock.requestAnimationFrame.$resolve() - - var result = strategy == "all" && root.childNodes.length == 0 - - m.mount(root, null) //teardown - + + var result = strategy === "all" && root.childNodes.length === 0 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") - var strategy, count = 0 + var count = 0 + var strategy var config = function(el, init) {if (!init) count++} m.route.mode = "search" m.route(root, "/foo1", { "/foo1": { controller: function() {}, view: function() { - return m("div", {config: config}); + return m("div", {config: config}) } }, "/bar1": { @@ -3001,22 +3475,22 @@ function testMithril(mock) { m.redraw.strategy("redraw") }, view: function() { - return m("div", {config: config}); + return m("div", {config: config}) } - }, + } }) mock.requestAnimationFrame.$resolve() m.route("/bar1") mock.requestAnimationFrame.$resolve() - - var result = strategy == "all" && count == 1 - - m.mount(root, null) //teardown - + + var result = strategy === "all" && count === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -3030,21 +3504,22 @@ function testMithril(mock) { strategy = m.redraw.strategy() ctrl.number++ m.redraw.strategy("none") - }}, ctrl.number); + }}, ctrl.number) } } }) root.childNodes[0].onclick({}) mock.requestAnimationFrame.$resolve() - - var result = strategy == "diff" && root.childNodes[0].childNodes[0].nodeValue == "1" - - m.mount(root, null) //teardown - + + var result = strategy === "diff" && + root.childNodes[0].childNodes[0].nodeValue === "1" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -3054,24 +3529,24 @@ function testMithril(mock) { m.route(root, "/foo1", { "/foo1": { controller: function() {}, - view: function(ctrl) { + view: function() { return m("div", {config: config, onclick: function() { m.redraw.strategy("all") - }}); + }}) } } }) root.childNodes[0].onclick({}) mock.requestAnimationFrame.$resolve() - - var result = count == 2 - - m.mount(root, null) //teardown - + + var result = count === 2 + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -3079,59 +3554,73 @@ function testMithril(mock) { m.route(root, "/foo+bar", { "/:arg": { controller: function() {value = m.route.param("arg")}, - view: function(ctrl) { + view: function() { return "" } } }) - var result = value == "foo+bar" - - m.mount(root, null) //teardown - + var result = value === "foo+bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {return "foo"}}, - "/test22": {controller: function() {}, view: function() {return "bar"}} + "/": { + controller: function() {}, + view: function() {return "foo"} + }, + "/test22": { + controller: function() {}, + view: function() {return "bar"} + } }) mock.requestAnimationFrame.$resolve() m.route(String("/test22/")) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test22/" && root.childNodes[0].nodeValue === "bar" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test22/" && + root.childNodes[0].nodeValue === "bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") m.route.mode = "search" m.route(root, "/", { - "/": {controller: function() {}, view: function() {return "foo"}}, - "/test23": {controller: function() {}, view: function() {return "bar"}} + "/": { + controller: function() {}, + view: function() {return "foo"} + }, + "/test23": { + controller: function() {}, + view: function() {return "bar"} + } }) mock.requestAnimationFrame.$resolve() - m.route(new String("/test23/")) + m.route(new String("/test23/")) // eslint-disable-line no-new-wrappers mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/test23/" && root.childNodes[0].nodeValue === "bar" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/test23/" && + root.childNodes[0].nodeValue === "bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") @@ -3139,89 +3628,91 @@ function testMithril(mock) { m.route(root, String("/foo+bar"), { "/:arg": { controller: function() {value = m.route.param("arg")}, - view: function(ctrl) { + view: function() { return "" } } }) - var result = value == "foo+bar" - - m.mount(root, null) //teardown - + var result = value === "foo+bar" + + m.mount(root, null) // teardown + return result }) test(function() { - mock.requestAnimationFrame.$resolve() //setup + mock.requestAnimationFrame.$resolve() // setup mock.location.search = "?" var root = mock.document.createElement("div") var value + /* eslint-disable no-new-wrappers */ m.route(root, new String("/foo+bar"), { + /* eslint-enable no-new-wrappers */ "/:arg": { controller: function() {value = m.route.param("arg")}, - view: function(ctrl) { + view: function() { return "" } } }) - var result = value == "foo+bar" - - m.mount(root, null) //teardown - + var result = value === "foo+bar" + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") - + var a = {} a.controller = function() {m.route("/b")} a.view = function() {return "a"} var b = {} b.controller = function() {} - b.view = function(ctrl) {return "b"} + b.view = function() {return "b"} m.route(root, "/a", { "/a": a, "/b": b }) mock.requestAnimationFrame.$resolve() - - var result = root.childNodes[0].nodeValue == "b" - - m.mount(root, null) //teardown - + + var result = root.childNodes[0].nodeValue === "b" + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") - + var a = {} a.controller = function() { m.route("/b?foo=1", {foo: 2}) } a.view = function() {return "a"} - + var b = {} b.controller = function() {} b.view = function() {return "b"} m.route(root, "/", { "/": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - - var result = mock.location.search == "?/b?foo=2" - - m.mount(root, null) //teardown - + + var result = mock.location.search === "?/b?foo=2" + + m.mount(root, null) // teardown + return result }) @@ -3229,31 +3720,31 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() mock.location.search = "?" mock.history.$$length = 0 - + var root = mock.document.createElement("div") - + var a = {} a.controller = function() {} a.view = function() {return "a"} - + var b = {} b.controller = function() {} b.view = function() {return "b"} m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = mock.history.$$length == 1 - - m.mount(root, null) //teardown - + + var result = mock.history.$$length === 1 + + m.mount(root, null) // teardown + return result }) @@ -3261,75 +3752,75 @@ function testMithril(mock) { mock.requestAnimationFrame.$resolve() mock.location.search = "?" mock.history.$$length = 0 - + var root = mock.document.createElement("div") - + var a = {} a.controller = function() {} a.view = function() {return "a"} - + var b = {} b.controller = function() {} b.view = function() {return "b"} m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/a") - + mock.requestAnimationFrame.$resolve() - - var result = mock.history.$$length == 0 - - m.mount(root, null) //teardown - + + var result = mock.history.$$length === 0 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { - return m("a", {config: function(el, init, ctx) { + return m("a", {config: function(el, init) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { @@ -3338,34 +3829,34 @@ function testMithril(mock) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { @@ -3374,69 +3865,69 @@ function testMithril(mock) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { - return m("a", {config: function(el, init, ctx) { + return m("a", {config: function(el, init) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { @@ -3445,34 +3936,34 @@ function testMithril(mock) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { @@ -3481,34 +3972,34 @@ function testMithril(mock) { if (!init) initCount++ }}) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = a.view m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { @@ -3517,7 +4008,7 @@ function testMithril(mock) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {} b.view = function() { @@ -3529,27 +4020,27 @@ function testMithril(mock) { m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { @@ -3558,7 +4049,7 @@ function testMithril(mock) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {} b.view = function() { @@ -3570,66 +4061,66 @@ function testMithril(mock) { m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { - return m("div", m("a", {config: function(el, init, ctx) { + return m("div", m("a", {config: function(el, init) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {} b.view = function() { - return m("section", m("a", {config: function(el, init, ctx) { + return m("section", m("a", {config: function(el, init) { if (!init) initCount++ }})) } m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { @@ -3638,7 +4129,7 @@ function testMithril(mock) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = function() { @@ -3650,27 +4141,27 @@ function testMithril(mock) { m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { @@ -3679,7 +4170,7 @@ function testMithril(mock) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = function() { @@ -3691,67 +4182,67 @@ function testMithril(mock) { m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 2 - - m.mount(root, null) //teardown - + + var result = initCount === 2 + + m.mount(root, null) // teardown + return result }) test(function() { mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {m.redraw.strategy("diff")} a.view = function() { - return m("div", m("a", {config: function(el, init, ctx) { + return m("div", m("a", {config: function(el, init) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = function() { - return m("section", m("a", {config: function(el, init, ctx) { + return m("section", m("a", {config: function(el, init) { if (!init) initCount++ }})) } m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - - var result = initCount == 1 - - m.mount(root, null) //teardown - + + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { - //retain flag should work inside component + // retain flag should work inside component mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") var initCount = 0 - + var a = {} a.controller = function() {} a.view = function() { @@ -3760,7 +4251,7 @@ function testMithril(mock) { if (!init) initCount++ }})) } - + var b = {} b.controller = function() {m.redraw.strategy("diff")} b.view = function() { @@ -3772,34 +4263,34 @@ function testMithril(mock) { m.route(root, "/a", { "/a": {view: function() {return m("div", a)}}, - "/b": {view: function() {return m("div", b)}}, + "/b": {view: function() {return m("div", b)}} }) mock.requestAnimationFrame.$resolve() - - m.route("/b") - - mock.requestAnimationFrame.$resolve() - var result = initCount == 1 - m.mount(root, null) //teardown - + m.route("/b") + + mock.requestAnimationFrame.$resolve() + var result = initCount === 1 + + m.mount(root, null) // teardown + return result }) test(function() { // https://github.com/lhorie/mithril.js/pull/571 mock.requestAnimationFrame.$resolve() mock.location.search = "?" - + var root = mock.document.createElement("div") - + var a = {} a.controller = function() {} a.view = function() { - return m("div", {config: function(elm, init, ctx) { + return m("div", {config: function(elm) { elm.childNodes[0].modified = true }}, m("div")) } - + var b = {} b.controller = function() {} b.view = function() { @@ -3808,47 +4299,57 @@ function testMithril(mock) { m.route(root, "/a", { "/a": a, - "/b": b, + "/b": b }) mock.requestAnimationFrame.$resolve() - + m.route("/b") - + mock.requestAnimationFrame.$resolve() - var result = !root.childNodes[0].childNodes[0].modified; + var result = !root.childNodes[0].childNodes[0].modified + + m.mount(root, null) // teardown - m.mount(root, null) //teardown - return result - }); - //end m.route + }) + // end m.route - //m.route.parseQueryString + // m.route.parseQueryString test(function() { - var args = m.route.parseQueryString("foo=bar&hello%5B%5D=world&hello%5B%5D=mars&hello%5B%5D=pluto") - return args["hello[]"] instanceof Array && args["hello[]"].indexOf("world") > -1 && args["hello[]"].indexOf("mars") > -1 && args["hello[]"].indexOf("pluto") > -1 + var args = m.route.parseQueryString( + "foo=bar&hello%5B%5D=world&hello%5B%5D=mars&hello%5B%5D=pluto") + return args["hello[]"] instanceof Array && + args["hello[]"].indexOf("world") > -1 && + args["hello[]"].indexOf("mars") > -1 && + args["hello[]"].indexOf("pluto") > -1 }) test(function() { - var args = m.route.parseQueryString("foo=bar&hello=world&hello=mars&bam=&yup") - return args.foo === "bar" && args.hello[0] === "world" && args.hello[1] === "mars" && args.bam === "" && args.yup === null + var args = m.route.parseQueryString( + "foo=bar&hello=world&hello=mars&bam=&yup") + return args.foo === "bar" && + args.hello[0] === "world" && + args.hello[1] === "mars" && + args.bam === "" && + args.yup == null }) - - //m.route.buildQueryString + + // m.route.buildQueryString test(function() { var string = m.route.buildQueryString({ foo: "bar", hello: ["world", "mars", "mars"], world: { - test:3 + test: 3 }, bam: "", yup: null, removed: undefined }) - return string === "foo=bar&hello=world&hello=mars&world%5Btest%5D=3&bam=&yup" + return string === + "foo=bar&hello=world&hello=mars&world%5Btest%5D=3&bam=&yup" }) - - //m.prop + + // m.prop test(function() { var prop = m.prop("test") return prop() === "test" @@ -3884,79 +4385,115 @@ function testMithril(mock) { }) test(function() { var prop = m.prop(null) - return prop() === null + return prop() == null }) - //m.request + // m.request test(function() { var prop = m.request({method: "GET", url: "test"}) mock.XMLHttpRequest.$instances.pop().onreadystatechange() return prop().method === "GET" && prop().url === "test" }) test(function() { - var prop = m.request({method: "GET", url: "test"}).then(function(value) {return "foo"}) + var prop = m.request({method: "GET", url: "test"}) + .then(function() {return "foo"}) mock.XMLHttpRequest.$instances.pop().onreadystatechange() return prop() === "foo" }) test(function() { - var prop = m.request({method: "POST", url: "http://domain.com:80", data: {}}).then(function(value) {return value}) + var prop = m.request({ + method: "POST", + url: "http://domain.com:80", + data: {} + }).then(function(value) {return value}) mock.XMLHttpRequest.$instances.pop().onreadystatechange() return prop().url === "http://domain.com:80" }) test(function() { - var prop = m.request({method: "POST", url: "http://domain.com:80/:test1", data: {test1: "foo"}}).then(function(value) {return value}) + var prop = m.request({ + method: "POST", + url: "http://domain.com:80/:test1", + data: {test1: "foo"} + }).then(function(value) {return value}) mock.XMLHttpRequest.$instances.pop().onreadystatechange() return prop().url === "http://domain.com:80/foo" }) test(function() { var error = m.prop("no error") - var prop = m.request({method: "GET", url: "test", deserialize: function() {throw new Error("error occurred")}}).then(null, error) + var prop = m.request({ + method: "GET", + url: "test", + deserialize: function() {throw new Error("error occurred")} + }).then(null, error) mock.XMLHttpRequest.$instances.pop().onreadystatechange() - return prop().message === "error occurred" && error().message === "error occurred" + return prop().message === "error occurred" && + error().message === "error occurred" }) test(function() { var error = m.prop("no error") - var prop = m.request({method: "GET", url: "test", deserialize: function() {throw new Error("error occurred")}}).catch(error) + var prop = m.request({ + method: "GET", + url: "test", + deserialize: function() {throw new Error("error occurred")} + }).catch(error) mock.XMLHttpRequest.$instances.pop().onreadystatechange() - return prop().message === "error occurred" && error().message === "error occurred" - }) - test(function() { - var error = m.prop("no error"), exception - var prop = m.request({method: "GET", url: "test", deserialize: function() {throw new TypeError("error occurred")}}).then(null, error) - try {mock.XMLHttpRequest.$instances.pop().onreadystatechange()} - catch (e) {exception = e} - return prop() === undefined && error() === "no error" && exception.message == "error occurred" + return prop().message === "error occurred" && + error().message === "error occurred" }) test(function() { var error = m.prop("no error") - var prop = m.request({method: "POST", url: "test", data: {foo: 1}}).then(null, error) + var exception + var prop = m.request({ + method: "GET", + url: "test", + deserialize: function() {throw new TypeError("error occurred")} + }).then(null, error) + try { + mock.XMLHttpRequest.$instances.pop().onreadystatechange() + } catch (e) { + exception = e + } + return prop() === undefined && + error() === "no error" && + exception.message === "error occurred" + }) + test(function() { + var error = m.prop("no error") + m.request({ + method: "POST", + url: "test", + data: {foo: 1} + }).then(null, error) var xhr = mock.XMLHttpRequest.$instances.pop() xhr.onreadystatechange() - return xhr.$headers["Content-Type"] == "application/json; charset=utf-8" + return xhr.$headers["Content-Type"] === + "application/json; charset=utf-8" }) test(function() { var error = m.prop("no error") - var prop = m.request({method: "POST", url: "test"}).then(null, error) + m.request({method: "POST", url: "test"}).then(null, error) var xhr = mock.XMLHttpRequest.$instances.pop() xhr.onreadystatechange() return xhr.$headers["Content-Type"] === undefined }) test(function() { - var prop = m.request({method: "POST", url: "test", initialValue: "foo"}).then(function(data) { return data; }) - var initialValue = prop(); + var prop = m.request({method: "POST", url: "test", initialValue: "foo"}) + .then(function(data) { return data }) + var initialValue = prop() mock.XMLHttpRequest.$instances.pop().onreadystatechange() return initialValue === "foo" }) test(function() { var prop = m.request({method: "POST", url: "test", initialValue: "foo"}) - var initialValue = prop(); + var initialValue = prop() mock.XMLHttpRequest.$instances.pop().onreadystatechange() return initialValue === "foo" }) test(function() { - var prop = m.request({method: "POST", url: "test", initialValue: "foo"}).then(function(value) {return "bar"}) + var prop = m.request({method: "POST", url: "test", initialValue: "foo"}) + .then(function() {return "bar"}) mock.XMLHttpRequest.$instances.pop().onreadystatechange() return prop() === "bar" }) @@ -3984,7 +4521,11 @@ function testMithril(mock) { var prop3 = prop1.then(function(v) {value = v}) var val3 = prop3() mock.XMLHttpRequest.$instances.pop().onreadystatechange() - return val1 === 123 && val2 === 123 && val3 === 123 && value.method === "GET" && value.url === "test" + return val1 === 123 && + val2 === 123 && + val3 === 123 && + value.method === "GET" && + value.url === "test" }) // m.request over jsonp @@ -3996,16 +4537,20 @@ function testMithril(mock) { var error = m.prop("no error") var data - var req = m.request({url: "/test", dataType: "jsonp"}).then(function(received) {data = received}, error) + m.request({url: "/test", dataType: "jsonp"}) + .then(function(received) {data = received}, error) var callbackKey = Object.keys(mock).filter(function(globalKey){ return globalKey.indexOf("mithril_callback") > -1 }).pop() - var scriptTag = [].slice.call(mock.document.getElementsByTagName("script")).filter(function(script){ - return script.src.indexOf(callbackKey) > -1 - }).pop() + var scriptTag = [].slice.call( + mock.document.getElementsByTagName("script")) + .filter(function(script){ + return script.src.indexOf(callbackKey) > -1 + }).pop() mock[callbackKey]({foo: "bar"}) mock.document.removeChild(body) - return scriptTag.src.indexOf("/test?callback=mithril_callback") > -1 && data.foo == "bar" + return scriptTag.src.indexOf("/test?callback=mithril_callback") > -1 && + data.foo === "bar" }) test(function(){ // script tags cannot be appended directly on the document @@ -4015,16 +4560,24 @@ function testMithril(mock) { var error = m.prop("no error") var data - var req = m.request({url: "/test", dataType: "jsonp", callbackKey: "jsonpCallback"}).then(function(received) {data = received}, error); + m.request({ + url: "/test", + dataType: "jsonp", + callbackKey: "jsonpCallback" + }).then(function(received) {data = received}, error) var callbackKey = Object.keys(mock).filter(function(globalKey){ return globalKey.indexOf("mithril_callback") > -1 }).pop() - var scriptTag = [].slice.call(mock.document.getElementsByTagName("script")).filter(function(script){ - return script.src.indexOf(callbackKey) > -1 - }).pop() + var scriptTag = [].slice.call( + mock.document.getElementsByTagName("script")) + .filter(function(script){ + return script.src.indexOf(callbackKey) > -1 + }).pop() mock[callbackKey]({foo: "bar1"}) mock.document.removeChild(body) - return scriptTag.src.indexOf("/test?jsonpCallback=mithril_callback") > -1 && data.foo == "bar1" + return scriptTag.src.indexOf( + "/test?jsonpCallback=mithril_callback") > -1 && + data.foo === "bar1" }) test(function(){ var body = mock.document.createElement("body") @@ -4035,9 +4588,11 @@ function testMithril(mock) { var callbackKey = Object.keys(mock).filter(function(globalKey){ return globalKey.indexOf("mithril_callback") > -1 }).pop() - var scriptTag = [].slice.call(mock.document.getElementsByTagName("script")).filter(function(script){ - return script.src.indexOf(callbackKey) > -1 - }).pop(); + ;[].slice.call( + mock.document.getElementsByTagName("script")) + .filter(function(script){ + return script.src.indexOf(callbackKey) > -1 + }).pop() mock[callbackKey]({foo: "bar1"}) var out = {foo: "bar1"} mock.document.removeChild(body) @@ -4048,36 +4603,47 @@ function testMithril(mock) { mock.document.body = body mock.document.appendChild(body) - var req = m.request({url: "/test", dataType: "jsonp", data: {foo: "bar"}}) + m.request({ + url: "/test", + dataType: "jsonp", + data: {foo: "bar"} + }) var callbackKey = Object.keys(mock).filter(function(globalKey){ return globalKey.indexOf("mithril_callback") > -1 }).pop() - var scriptTag = [].slice.call(mock.document.getElementsByTagName("script")).filter(function(script){ - return script.src.indexOf(callbackKey) > -1 - }).pop(); + var scriptTag = [].slice.call( + mock.document.getElementsByTagName("script")) + .filter(function(script){ + return script.src.indexOf(callbackKey) > -1 + }).pop() mock[callbackKey]({foo: "bar"}) return scriptTag.src.indexOf("foo=bar") > -1 }) test(function(){ - var body = mock.document.createElement("body"); - mock.document.body = body; - mock.document.appendChild(body); + var body = mock.document.createElement("body") + mock.document.body = body + mock.document.appendChild(body) - var _window = mock; - var error = m.prop(false); - var req = m.request({url: "/test", dataType: "jsonp", method: "GET", data: {foo: "bar"}}); + m.request({ + url: "/test", + dataType: "jsonp", + method: "GET", + data: {foo: "bar"} + }) var callbackKey = Object.keys(mock).filter(function(globalKey){ return globalKey.indexOf("mithril_callback") > -1 }).pop() - var scriptTag = [].slice.call(mock.document.getElementsByTagName("script")).filter(function(script){ - return script.src.indexOf(callbackKey) > -1 - }).pop(); + var scriptTag = [].slice.call( + mock.document.getElementsByTagName("script")) + .filter(function(script){ + return script.src.indexOf(callbackKey) > -1 + }).pop() mock[callbackKey]({foo: "bar"}) - mock.document.removeChild(body); - return scriptTag.src.match(/foo=bar/g).length == 1; + mock.document.removeChild(body) + return scriptTag.src.match(/foo=bar/g).length === 1 }) - //m.deferred + // m.deferred test(function() { var value var deferred = m.deferred() @@ -4088,7 +4654,8 @@ function testMithril(mock) { test(function() { var value var deferred = m.deferred() - deferred.promise.then(function(data) {return "foo"}).then(function(data) {value = data}) + deferred.promise.then(function() {return "foo"}) + .then(function(data) {value = data}) deferred.resolve("test") return value === "foo" }) @@ -4109,41 +4676,70 @@ function testMithril(mock) { test(function() { var value var deferred = m.deferred() - deferred.promise.then(null, function(data) {return "foo"}).then(function(data) {value = data}) + deferred.promise.then(null, function() {return "foo"}) + .then(function(data) {value = data}) deferred.reject("test") return value === "foo" }) test(function() { var value var deferred = m.deferred() - deferred.promise.catch(function(data) {return "foo"}).then(function(data) {value = data}) + deferred.promise.catch(function() {return "foo"}) + .then(function(data) {value = data}) deferred.reject("test") return value === "foo" }) test(function() { var value1, value2 var deferred = m.deferred() - deferred.promise.then(function(data) {throw new Error}).then(function(data) {value1 = 1}, function(data) {value2 = data}) + deferred.promise.then(function() {throw new Error()}) + .then(function() {value1 = 1}, function(data) {value2 = data}) deferred.resolve("test") return value1 === undefined && value2 instanceof Error }) test(function() { - //Let unchecked exceptions bubble up in order to allow meaningful error messages in common cases like null reference exceptions due to typos - //An unchecked exception is defined as an object that is a subclass of Error (but not a direct instance of Error itself) - basically anything that can be thrown without an explicit `throw` keyword and that we'd never want to programmatically manipulate. In other words, an unchecked error is one where we only care about its line number and where the only reasonable way to deal with it is to change the buggy source code that caused the error to be thrown in the first place. - //By contrast, a checked exception is defined as anything that is explicitly thrown via the `throw` keyword and that can be programmatically handled, for example to display a validation error message on the UI. If an exception is a subclass of Error for whatever reason, but it is meant to be handled as a checked exception (i.e. follow the rejection rules for A+), it can be rethrown as an instance of Error - //This test tests two implementation details that differ from the Promises/A+ spec: - //1) A+ requires the `then` callback to be called in a different event loop from the resolve call, i.e. it must be asynchronous (this requires a setImmediate polyfill, which cannot be implemented in a reasonable way for Mithril's purpose - the possible polyfills are either too big or too slow) - //2) A+ swallows exceptions in a unrethrowable way, i.e. it's not possible to see default error messages on the console for runtime errors thrown from within a promise chain + // Let unchecked exceptions bubble up in order to allow meaningful error + // messages in common cases like null reference exceptions due to typos + // An unchecked exception is defined as an object that is a subclass of + // Error (but not a direct instance of Error itself) - basically + // anything that can be thrown without an explicit `throw` keyword and + // that we'd never want to programmatically manipulate. In other words, + // an unchecked error is one where we only care about its line number + // and where the only reasonable way to deal with it is to change the + // buggy source code that caused the error to be thrown in the first + // place. By contrast, a checked exception is defined as anything that + // is explicitly thrown via the `throw` keyword and that can be + // programmatically handled, for example to display a validation error + // message on the UI. If an exception is a subclass of Error for + // whatever reason, but it is meant to be handled as a checked exception + // (i.e. follow the rejection rules for A+), it can be rethrown as an + // instance of Error + // + // This test tests two implementation details that differ from the + // Promises/A+ spec: + // 1) A+ requires the `then` callback to be called in a different event + // loop from the resolve call, i.e. it must be asynchronous (this + // requires a setImmediate polyfill, which cannot be implemented in a + // reasonable way for Mithril's purpose - the possible polyfills are + // either too big or too slow) + // 2) A+ swallows exceptions in a unrethrowable way, i.e. it's not + // possible to see default error messages on the console for runtime + // errors thrown from within a promise chain var value1, value2, value3 var deferred = m.deferred() try { deferred.promise - .then(function(data) {foo.bar.baz}) //throws ReferenceError - .then(function(data) {value1 = 1}, function(data) {value2 = data}) + /* eslint-disable no-undef, no-unused-expressions */ + .then(function() {foo.bar.baz}) // throws ReferenceError + /* eslint-enable no-undef, no-unused-expressions */ + .then(function() {value1 = 1}, function(data) {value2 = data}) deferred.resolve("test") + } catch (e) { + value3 = e } - catch (e) {value3 = e} - return value1 === undefined && value2 === undefined && (value3 instanceof ReferenceError || value3 instanceof TypeError) + return value1 === undefined && + value2 === undefined && + (value3 instanceof ReferenceError || value3 instanceof TypeError) }) test(function() { var deferred1 = m.deferred() @@ -4160,8 +4756,9 @@ function testMithril(mock) { return value1 === 1 && value2 === 2 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value deferred.resolve(1) deferred.promise.then(function(data) { value = data @@ -4169,8 +4766,9 @@ function testMithril(mock) { return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value deferred.reject(1) deferred.promise.then(null, function(data) { value = data @@ -4178,8 +4776,9 @@ function testMithril(mock) { return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value deferred.resolve(1) deferred.resolve(2) deferred.promise.then(function(data) { @@ -4188,8 +4787,9 @@ function testMithril(mock) { return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value deferred.promise.then(function(data) { value = data }) @@ -4198,8 +4798,9 @@ function testMithril(mock) { return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value1, value2 + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value1, value2 deferred.promise.then(function(data) { value1 = data }, function(data) { @@ -4210,9 +4811,10 @@ function testMithril(mock) { return value1 === 1 && value2 === undefined }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value1, value2 - deferred.promise.then(function() { + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value1, value2 + deferred.promise.then(function(data) { value1 = data }, function(data) { value2 = data @@ -4222,8 +4824,9 @@ function testMithril(mock) { return value1 === undefined && value2 === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/80 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/80 + var deferred = m.deferred() + var value deferred.promise.then(null, function(data) { value = data }) @@ -4232,46 +4835,49 @@ function testMithril(mock) { return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/85 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/85 + var deferred = m.deferred() + var value deferred.resolve() - deferred.promise.then(function(data) { + deferred.promise.then(function() { value = 1 }) return value === 1 }) test(function() { - //https://github.com/lhorie/mithril.js/issues/85 - var deferred = m.deferred(), value + // https://github.com/lhorie/mithril.js/issues/85 + var deferred = m.deferred() + var value deferred.reject() - deferred.promise.then(null, function(data) { + deferred.promise.then(null, function() { value = 1 }) return value === 1 }) test(function() { - var deferred = m.deferred(), value + var deferred = m.deferred() deferred.resolve(1) return deferred.promise() === 1 }) test(function() { - var deferred = m.deferred(), value + var deferred = m.deferred() var promise = deferred.promise.then(function(data) {return data + 1}) deferred.resolve(1) return promise() === 2 }) test(function() { - var deferred = m.deferred(), value + var deferred = m.deferred() deferred.reject(1) return deferred.promise() === undefined }) - //m.sync + // m.sync test(function() { var value var deferred1 = m.deferred() var deferred2 = m.deferred() - m.sync([deferred1.promise, deferred2.promise]).then(function(data) {value = data}) + m.sync([deferred1.promise, deferred2.promise]) + .then(function(data) {value = data}) deferred1.resolve("test") deferred2.resolve("foo") return value[0] === "test" && value[1] === "foo" @@ -4280,7 +4886,8 @@ function testMithril(mock) { var value var deferred1 = m.deferred() var deferred2 = m.deferred() - m.sync([deferred1.promise, deferred2.promise]).then(function(data) {value = data}) + m.sync([deferred1.promise, deferred2.promise]) + .then(function(data) {value = data}) deferred2.resolve("foo") deferred1.resolve("test") return value[0] === "test" && value[1] === "foo" @@ -4295,7 +4902,7 @@ function testMithril(mock) { test(function() { var value = 1 m.sync([]).then(function() {value = 2}) - return value == 2 + return value === 2 }) test(function() { var success @@ -4303,7 +4910,7 @@ function testMithril(mock) { return success }) - //m.startComputation/m.endComputation + // m.startComputation/m.endComputation test(function() { mock.requestAnimationFrame.$resolve() @@ -4326,32 +4933,40 @@ function testMithril(mock) { test(function() { var root = mock.document.createElement("div") - var success = false; - m.render(root, m("div", {config: function(elem, isInitialized, ctx) {ctx.data=1}})); - m.render(root, m("div", {config: function(elem, isInitialized, ctx) {success = ctx.data===1}})); - return success; + var success = false + m.render(root, m("div", { + config: function(elem, isInitialized, ctx) {ctx.data = 1} + })) + m.render(root, m("div", { + config: function(elem, isInitialized, ctx) { + success = ctx.data === 1 + } + })) + return success }) // more complex config context test(function() { var root = mock.document.createElement("div") - var idx = 0; - var success = true; - var statefulConfig = function(elem, isInitialized, ctx) {ctx.data=idx++} - var node = m("div", {config: statefulConfig}); - m.render(root, [node, node]); + var idx = 0 + var success = true + var statefulConfig = function(elem, isInitialized, ctx) { + ctx.data = idx++ + } + var node = m("div", {config: statefulConfig}) + m.render(root, [node, node]) - idx = 0; + idx = 0 var checkConfig = function(elem, isInitialized, ctx) { success = success && (ctx.data === idx++) } - node = m("div", {config: checkConfig}); - m.render(root, [node, node]); - return success; + node = m("div", {config: checkConfig}) + m.render(root, [node, node]) + return success }) - //console.log presence + // console.log presence test(function() { return m.deps.factory.toString().indexOf("console") < 0 }) @@ -4360,7 +4975,9 @@ function testMithril(mock) { }) } -//mock -testMithril(mock.window); - -test.print(function(value) {console.log(value)}) +// mock +testMithril(mock.window) +test.print(function(value) { + "use strict" + console.log(value) +}) diff --git a/tests/mock.js b/tests/mock.js index 30c8712c..f4080b3e 100644 --- a/tests/mock.js +++ b/tests/mock.js @@ -1,3 +1,4 @@ +/* eslint-disable no-extend-native, strict */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(item) { for (var i = 0; i < this.length; i++) { @@ -31,9 +32,11 @@ if (!Object.keys) { return keys } } +/* eslint-enable no-extend-native, strict */ var mock = {} mock.window = (function() { + "use strict" var window = {} window.document = {} window.document.childNodes = [] @@ -55,11 +58,12 @@ mock.window = (function() { else this.childNodes.splice(referenceIndex, 0, node) }, insertAdjacentHTML: function(position, html) { - //todo: accept markup - if (position == "beforebegin") { - this.parentNode.insertBefore(window.document.createTextNode(html), this) - } - else if (position == "beforeend") { + // todo: accept markup + if (position === "beforebegin") { + this.parentNode.insertBefore( + window.document.createTextNode(html), + this) + } else if (position === "beforeend") { this.appendChild(window.document.createTextNode(html)) } }, @@ -70,7 +74,7 @@ mock.window = (function() { this.namespaceURI = namespace this[name] = value.toString() }, - getAttribute: function(name, value) { + getAttribute: function(name) { return this[name] }, addEventListener: function () {}, @@ -104,23 +108,25 @@ mock.window = (function() { this.childNodes.splice(index, 1) child.parentNode = null } - //getElementsByTagName is only used by JSONP tests, it's not required by Mithril + // getElementsByTagName is only used by JSONP tests, it's not required by + // Mithril window.document.getElementsByTagName = function(name){ - name = name.toLowerCase(); - var out = []; + name = name.toLowerCase() + var out = [] var traverse = function(node){ if(node.childNodes && node.childNodes.length > 0){ node.childNodes.map(function(curr){ - if(curr.nodeName.toLowerCase() === name) - out.push(curr); - traverse(curr); - }); + if (curr.nodeName.toLowerCase() === name) { + out.push(curr) + } + traverse(curr) + }) } - }; + } - traverse(window.document); - return out; + traverse(window.document) + return out } window.scrollTo = function() {} window.cancelAnimationFrame = function() {} @@ -156,15 +162,17 @@ mock.window = (function() { request.$instances = [] return request }()) - window.location = {search: "", pathname: "", hash: ""}, + window.location = {search: "", pathname: "", hash: ""} window.history = {} window.history.$$length = 0 window.history.pushState = function(data, title, url) { window.history.$$length++ - window.location.pathname = window.location.search = window.location.hash = url - }, + window.location.pathname = window.location.search = + window.location.hash = url + } window.history.replaceState = function(data, title, url) { - window.location.pathname = window.location.search = window.location.hash = url + window.location.pathname = window.location.search = + window.location.hash = url } return window -}()) \ No newline at end of file +}()) diff --git a/tests/test.js b/tests/test.js index 844cf8aa..984e15ee 100644 --- a/tests/test.js +++ b/tests/test.js @@ -1,15 +1,19 @@ +/* eslint-disable no-console */ if (!this.console) { - var log = function(value) {document.write("
" + value + "
")} + var log = function(value) { + "use strict" + document.write("
" + value + "
") + } this.console = {log: log, error: log} } function test(condition) { + "use strict" test.total++ try { if (!condition()) throw new Error("failed") - } - catch (e) { + } catch (e) { console.error(e) test.failures.push(condition) } @@ -17,6 +21,7 @@ function test(condition) { test.total = 0 test.failures = [] test.print = function(print) { + "use strict" for (var i = 0; i < test.failures.length; i++) { print(test.failures[i].toString()) }