OO-ize DOM builder, improve performance (part 1), add benchmarking suite

This commit is contained in:
impinball 2015-12-15 07:07:50 -05:00
parent c202c04631
commit a7b2294c11
22 changed files with 1953 additions and 813 deletions

View file

@ -1,5 +1,5 @@
# Most of these are build artifacts.
node_modules
**/node_modules
**/*.min.js
archive
deploy

4
bench/README.md Normal file
View file

@ -0,0 +1,4 @@
This suite is taken with modifications from the Mithril example in
[Merri/nom](https://github.com/Merri/nom/tree/gh-pages/todomvc/benchmark/mithril-new).
(For example, it uses Mithril itself to help simplify the business logic.)

6
bench/app/.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
node_modules/todomvc-app-css/*
!node_modules/todomvc-app-css/index.css
node_modules/todomvc-common/*
!node_modules/todomvc-common/base.js
!node_modules/todomvc-common/base.css

26
bench/app/index.html Normal file
View file

@ -0,0 +1,26 @@
<!doctype html>
<html lang="en" data-framework="mithril">
<head>
<meta charset="utf-8">
<title>Mithril • TodoMVC</title>
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
</head>
<body>
<section id="todoapp"></section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://taylorhakes.com">Taylor Hakes</a> and <a href="http://blogue.jpmonette.net">Jean-Philippe Monette</a> <br>(Special thanks to <a
href="https://github.com/lhorie/">Leo Horie</a>)</p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<script src="node_modules/todomvc-common/base.js"></script>
<script src="../../mithril.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/models/storage.js"></script>
<script src="js/controllers/todo.js"></script>
<script src="js/views/main-view.js"></script>
<script src="js/views/footer-view.js"></script>
<script src="js/app.js"></script>
</body>
</html>

13
bench/app/js/app.js Normal file
View file

@ -0,0 +1,13 @@
/* global m */
(function (app) {
"use strict"
app.ENTER_KEY = 13
app.ESC_KEY = 27
m.route.mode = "hash"
m.route(document.getElementById("todoapp"), "/", {
"/": app,
"/:filter": app
})
})(this.app || (this.app = {}))

View file

@ -0,0 +1,111 @@
/* global m */
(function (app) {
"use strict"
app.controller = function () {
/* eslint-disable no-warning-comments */
// Todo collection, update with props
/* eslint-enable no-warning-comments */
this.list = app.storage.get().map(function (item) {
return new app.Todo(item)
})
// Temp title placeholder
this.title = m.prop("")
/* eslint-disable no-warning-comments */
// Todo list filter
/* eslint-enable no-warning-comments */
this.filter = m.prop(m.route.param("filter") || "")
this.add = function () {
var title = this.title().trim()
if (title) {
this.list.push(new app.Todo({title: title}))
app.storage.put(this.list)
}
this.title("")
}
this.isVisible = function (todo) {
switch (this.filter()) {
case "active": return !todo.completed()
case "completed": return todo.completed()
default: return true
}
}
this.complete = function (todo) {
if (todo.completed()) {
todo.completed(false)
} else {
todo.completed(true)
}
app.storage.put(this.list)
}
this.edit = function (todo) {
todo.previousTitle = todo.title()
todo.editing(true)
}
this.doneEditing = function (todo, index) {
todo.editing(false)
todo.title(todo.title().trim())
if (!todo.title()) {
this.list.splice(index, 1)
}
app.storage.put(this.list)
}
this.cancelEditing = function (todo) {
todo.title(todo.previousTitle)
todo.editing(false)
}
this.clearTitle = function () {
this.title("")
}
this.remove = function (key) {
this.list.splice(key, 1)
app.storage.put(this.list)
}
this.clearCompleted = function () {
for (var i = this.list.length - 1; i >= 0; i--) {
if (this.list[i].completed()) {
this.list.splice(i, 1)
}
}
app.storage.put(this.list)
}
this.amountCompleted = function () {
var amount = 0
for (var i = 0; i < this.list.length; i++) {
if (this.list[i].completed()) {
amount++
}
}
return amount
}
this.allCompleted = function () {
for (var i = 0; i < this.list.length; i++) {
if (!this.list[i].completed()) {
return false
}
}
return true
}
this.completeAll = function () {
var allCompleted = this.allCompleted()
for (var i = 0; i < this.list.length; i++) {
this.list[i].completed(!allCompleted)
}
app.storage.put(this.list)
}
}
})(this.app || (this.app = {}))

View file

@ -0,0 +1,14 @@
(function (app) {
"use strict"
var STORAGE_ID = "todos-mithril"
app.storage = {
get: function () {
return JSON.parse(localStorage.getItem(STORAGE_ID) || "[]")
},
put: function (todos) {
localStorage.setItem(STORAGE_ID, JSON.stringify(todos))
}
}
})(this.app || (this.app = {}))

View file

@ -0,0 +1,12 @@
/* global m */
(function (app) {
"use strict"
// Todo Model
app.Todo = function (data) {
this.title = m.prop(data.title)
this.completed = m.prop(data.completed || false)
this.editing = m.prop(data.editing || false)
}
})(this.app || (this.app = {}))

View file

@ -0,0 +1,40 @@
/* global m */
(function (app) {
"use strict"
var filter = {
view: function (_, ctrl, expected, name, href) {
return m("li", [
m("a", {
href: href,
config: m.route,
class: ctrl.filter() === expected ? "selected" : ""
}, name)
])
}
}
app.footer = {
view: function (_, ctrl) {
var amountCompleted = ctrl.amountCompleted()
var amountActive = ctrl.list.length - amountCompleted
return m("footer#footer", [
m("span#todo-count", [
m("strong", amountActive), " item" +
(amountActive !== 1 ? "s" : "") + " left"
]),
m("ul#filters", [
m(filter, ctrl, "", "All", "/"),
m(filter, ctrl, "active", "Active", "/active"),
m(filter, ctrl, "completed", "Completed", "/completed")
]),
ctrl.amountCompleted() ? m("button#clear-completed", {
onclick: function () {
ctrl.clearCompleted()
}
}, "Clear completed") : null
])
}
}
})(this.app || (this.app = {}))

View file

@ -0,0 +1,119 @@
/* global m */
(function (app) {
"use strict"
// View utility
app.watchInput = function (onenter, onescape) {
return function (e) {
if (e.keyCode === app.ENTER_KEY) {
onenter()
} else if (e.keyCode === app.ESC_KEY) {
onescape()
}
}
}
var header = {
controller: function () {
this.focused = false
},
view: function (ctrl, parentCtrl) {
return m("header#header", [
m("h1", "todos"),
m('input#new-todo[placeholder="What needs to be done?"]', {
onkeyup: app.watchInput(
function () {
parentCtrl.add()
},
function () {
parentCtrl.clearTitle()
}),
value: parentCtrl.title(),
oninput: m.withAttr("value", parentCtrl.title),
config: function (element) {
if (!ctrl.focused) {
element.focus()
ctrl.focused = true
}
}
})
])
}
}
var todo = {
view: function (_, parentCtrl, task, index) {
return m("li", {
class: (task.completed() ? "completed" : "") +
(task.editing() ? " editing" : "")
}, [
m(".view", [
m("input.toggle[type=checkbox]", {
onclick: m.withAttr("checked", function () {
parentCtrl.complete(task)
}),
checked: task.completed()
}),
m("label", {
ondblclick: function () {
parentCtrl.edit(task)
}
}, task.title()),
m("button.destroy", {
onclick: function () {
parentCtrl.remove(index)
}
})
]),
m("input.edit", {
value: task.title(),
onkeyup: app.watchInput(
function () {
parentCtrl.doneEditing(task, index)
},
function () {
parentCtrl.cancelEditing(task)
}),
oninput: m.withAttr("value", task.title),
config: function (element) {
if (task.editing()) {
element.focus()
element.selectionStart =
element.value.length
}
},
onblur: function () {
parentCtrl.doneEditing(task, index)
}
})
])
}
}
app.view = function (ctrl) {
return m("div", [
m(header, ctrl),
m("section#main", {
style: {
display: ctrl.list.length ? "" : "none"
}
}, [
m("input#toggle-all[type=checkbox]", {
onclick: ctrl.completeAll.bind(ctrl),
checked: ctrl.allCompleted()
}),
m("ul#todo-list", [
ctrl.list
.filter(function () {
return ctrl.isVisible()
})
.map(function (task, index) {
return m(todo, ctrl, task, index)
})
])
]),
ctrl.list.length === 0 ? "" : m(app.footer, ctrl)
])
}
})(this.app || (this.app = {}))

7
bench/app/package.json Normal file
View file

@ -0,0 +1,7 @@
{
"private": true,
"dependencies": {
"todomvc-common": "^1.0.1",
"todomvc-app-css": "^1.0.1"
}
}

18
bench/app/readme.md Normal file
View file

@ -0,0 +1,18 @@
# Mithril TodoMVC Example
> [Mithril](http://lhorie.github.io/mithril/) is a client-side MVC framework - a tool to organize code in a way that is easy to think about and to maintain.
> _[Mithril - lhorie.github.io/mithril/](http://lhorie.github.io/mithril/)_
## Learning Mithril
The [Mithril website](http://lhorie.github.io/mithril/getting-started.html) is a great resource for getting started.
Here are some links you may find helpful:
* [Official Documentation](http://lhorie.github.io/mithril/mithril.html)
_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
## Credit
This TodoMVC application was created by [taylorhakes](https://github.com/taylorhakes).

81
bench/index.html Normal file
View file

@ -0,0 +1,81 @@
<!DOCTYPE html>
<title>TodoMVC Benchmark</title>
<script src="../mithril.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script src="resources/benchmark-runner.js" defer></script>
<script src="resources/tests.js" defer></script>
<style>
body {
font-family: 'Lucida Grande', 'Trebuchet MS', 'Bitstream Vera Sans', Verdana, Helvetica, sans-serif;
background-color: rgb(253, 253, 253);
}
iframe {
border: 1px solid black;
}
button {
margin: 15px 5px;
}
ol {
list-style: none;
margin: 5px 0;
padding: 0;
}
ol ol {
margin-left: 2em;
list-position: outside;
}
.running {
text-decoration: underline;
}
.ran {
color: grey;
}
nav {
position: absolute;
right: 10px;
}
#analysis {
float:left;
display: none;
border: 1px solid #888;
}
#header {
background: #EEE;
margin: -1em -1em 1em;
padding: 1em;
text-align: center;
}
#barchart-body {
width: 400px;
margin: 30px;
}
</style>
<div id="header">
Items:
<a href="#250">250</a> (default)
|
<a href="#500">500</a>
|
<a href="#1000">1000</a>
|
<a href="#2500">2500</a>
|
<a href="#5000">5000</a>
|
<a href="#10000">10000</a>
</div>
<div id="analysis">
<div id="barchart-values"></div>
<div id="barchart-body"></div>
</div>
<script src="resources/manager.js"></script>

View file

@ -0,0 +1,268 @@
(function (global) { // eslint-disable-line max-statements
"use strict"
var m = global.m
window.onhashchange = function () {
location.reload()
}
global.BenchmarkTestStep = BenchmarkTestStep
function BenchmarkTestStep(name, run) {
this.name = name
this.run = run
}
global.BenchmarkRunner = BenchmarkRunner
function BenchmarkRunner(suites, client) {
this._suites = suites
this._prepareReturnValue = null
this._measuredValues = {}
this._client = client
}
BenchmarkRunner.prototype.waitForElement = function (selector) {
var deferred = m.deferred()
var contentDocument = this._frame.contentDocument
function resolveIfReady() {
var element = contentDocument.querySelector(selector)
if (element) {
return deferred.resolve(element)
}
setTimeout(resolveIfReady, 50)
}
resolveIfReady()
return deferred.promise
}
BenchmarkRunner.prototype._removeFrame = function () {
if (this._frame) {
this._frame.parentNode.removeChild(this._frame)
this._frame = null
}
}
BenchmarkRunner.prototype._appendFrame = function () {
var frame = document.createElement("iframe")
frame.style.width = "800px"
frame.style.height = "600px"
document.body.appendChild(frame)
this._frame = frame
return frame
}
BenchmarkRunner.prototype._waitAndWarmUp = function () {
var startTime = Date.now()
function Fibonacci(n) {
if (Date.now() - startTime > 100) return
else if (n <= 0) return 0
else if (n === 1) return 1
else return Fibonacci(n - 2) + Fibonacci(n - 1)
}
var deferred = m.deferred()
setTimeout(function () {
Fibonacci(100)
deferred.resolve()
}, 200)
return deferred.promise
}
var now = window.performance && window.performance.now ?
function () { return window.performance.now() } :
function () { return +new Date() }
function logResults(document, expected, suite, test, callback) {
var count = document.querySelectorAll(".view").length
if (count !== expected) {
console.error([ // eslint-disable-line no-console
suite.name,
test.name,
"expected",
expected,
"got",
count
])
callback(NaN, NaN)
}
}
// This function must be as simple as possible, so it doesn't interfere
// with reading the times
BenchmarkRunner.prototype._runTest = function (
suite,
test,
prepareReturnValue,
callback
) {
var testFunction = test.run
var window = this._frame.contentWindow
var document = this._frame.contentDocument
var expected = this._client.numberOfItemsToAdd
var startTime = now()
testFunction(prepareReturnValue, window, document)
var endTime = now()
var syncTime = endTime - startTime
startTime = now()
setTimeout(function () {
setTimeout(function () {
var endTime = now()
// if the DOM count is wrong after a test, don't report its
// results.
if (/Adding|Completing/.test(test.name)) {
logResults(document, expected, suite, test, callback)
}
if (/Deleting/.test(test.name)) {
logResults(document, 0, suite, test, callback)
}
callback(syncTime, endTime - startTime)
}, 0)
}, 0)
}
function BenchmarkState(suites) {
this._suites = suites
this._suiteIndex = -1
this._testIndex = 0
this.next()
}
BenchmarkState.prototype.currentSuite = function () {
return this._suites[this._suiteIndex]
}
BenchmarkState.prototype.currentTest = function () {
var suite = this.currentSuite()
return suite ? suite.tests[this._testIndex] : null
}
BenchmarkState.prototype.next = function () {
this._testIndex++
var suite = this._suites[this._suiteIndex]
if (suite && this._testIndex < suite.tests.length) {
return this
}
this._testIndex = 0
var i = this._suiteIndex
var suites = this._suites
do {
i++
} while (i < suites.length && suites[i].disabled)
this._suiteIndex = i
return this
}
BenchmarkState.prototype.isFirstTest = function () {
return !this._testIndex
}
BenchmarkState.prototype.prepareCurrentSuite = function (runner, frame) {
var suite = this.currentSuite()
var deferred = m.deferred()
frame.onload = function () {
suite.prepare(runner, frame.contentWindow, frame.contentDocument)
.then(function (result) {
deferred.resolve(result)
}, function (err) {
deferred.reject(err)
})
}
frame.src = suite.url
return deferred.promise
}
BenchmarkRunner.prototype.step = function (state) {
if (!state) {
state = new BenchmarkState(this._suites)
}
var suite = state.currentSuite()
if (!suite) {
this._finalize()
var deferred = m.deferred()
deferred.resolve()
return deferred.promise
}
if (state.isFirstTest()) {
this._masuredValuesForCurrentSuite = {}
var self = this
return state.prepareCurrentSuite(this, this._appendFrame())
.then(function (prepareReturnValue) {
self._prepareReturnValue = prepareReturnValue
return self._runTestAndRecordResults(state)
})
}
return this._runTestAndRecordResults(state)
}
BenchmarkRunner.prototype._runTestAndRecordResults = function (state) {
var deferred = m.deferred()
var suite = state.currentSuite()
var test = state.currentTest()
if (this._client && this._client.willRunTest) {
this._client.willRunTest(suite, test)
}
var self = this
setTimeout(function () {
self._runTest(suite, test, self._prepareReturnValue,
function (syncTime, asyncTime) {
var suiteResults
if (self._measuredValues[suite.name]) {
suiteResults = self._measuredValues[suite.name]
} else {
suiteResults = {tests: {}, total: 0}
}
self._measuredValues[suite.name] = suiteResults
suiteResults.tests[test.name] = {
Sync: syncTime,
Async: asyncTime
}
suiteResults.total += syncTime + asyncTime
if (self._client && self._client.willRunTest) {
self._client.didRunTest(suite, test)
}
state.next()
if (state.currentSuite() !== suite) {
self._removeFrame()
}
deferred.resolve(state)
})
}, 0)
return deferred.promise
}
BenchmarkRunner.prototype._finalize = function () {
this._removeFrame()
if (this._client && this._client.didRunSuites) {
this._client.didRunSuites(this._measuredValues)
}
// FIXME: This should be done when we start running tests.
this._measuredValues = {}
}
})(this)

237
bench/resources/manager.js Normal file
View file

@ -0,0 +1,237 @@
/* global m */
/* eslint no-console: 0 */
(function (global) { // eslint-disable-line max-statements
"use strict"
var numberOfItemsToAdd = (~~location.hash.slice(1)) || 250
var runs = []
var timesRan = 0
var runButton
function forOwn(object, f) {
for (var key in object) if ({}.hasOwnProperty.call(object, key)) {
f(object[key], key)
}
}
var append = Function.call.bind(function append() {
/* eslint-disable no-invalid-this */
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i]
if (Array.isArray(arg)) append.apply(this, arg)
else this.appendChild(arg)
}
return this
/* eslint-enable no-invalid-this */
})
function n(type, attrs) {
var el = document.createElement(type)
if (!attrs) return el
forOwn(attrs, function (value, attr) {
if (attr === "style") {
forOwn(value, function (k, v) { el.style[k] = v })
} else {
el[attr] = value
}
})
return el
}
function createButton(text, onclick) {
return n("button", {textContent: text, onclick: onclick})
}
function createTest(suite, test) {
return append(n("li"),
append(test.anchor = n("a", {id: suite.name + "-" + test.name}),
document.createTextNode(suite.name + "/" + test.name)))
}
function createSuiteCheckbox(suite) {
return n("input", {
id: suite.name,
type: "checkbox",
checked: true,
onchange: function () {
suite.disabled = !this.checked
}
})
}
function createSuiteLabel(suite) {
return append(n("label", {htmlFor: suite.name}),
document.createTextNode(suite.name + " " + suite.version))
}
function createSuite(suite) {
return append(n("li"),
createSuiteCheckbox(suite),
createSuiteLabel(suite),
append(n("ol"), suite.tests.map(createTest.bind(null, suite))))
}
function createUIForSuites(suites, onstep, onrun) {
return append(n("nav"),
createButton("Step Tests", onstep),
runButton = createButton("Run All", onrun),
append(n("ol"), suites.map(createSuite)))
}
function generateResults(measured, timesToRun) {
var result = ""
var total = 0 // FIXME: Compute the total properly.
forOwn(measured, function (suiteResults, suite) {
forOwn(suiteResults.tests, function (testResults, test) {
forOwn(testResults, function (subtestResults, subtest) {
result += suite + " : " + test + " : " + subtest + ": " +
subtestResults + " ms\n"
})
})
result += suite + " : " + suiteResults.total + " ms\n"
total += suiteResults.total
})
return result + "Run " + (runs.length + 1) + "/" + timesToRun +
" - Total : " + total + " ms\n"
}
function reportFastest() {
var results = {}
runs.forEach(function (runData) {
forOwn(runData, function (data, key) {
results[key] = Math.min(
results[key] || Infinity,
data.total
)
})
})
return results
}
global.google.load("visualization", "1", {packages: ["corechart"]})
function drawChart(results) {
var V = global.google.visualization
var raw = []
forOwn(results, function (result, key) {
raw.push([key, Math.round(result), colorify(key)])
})
raw.sort(function (a, b) { return a[1] - b[1] })
raw.unshift(["Project", "Time", {role: "style"}])
var runWord = "run" + (runs.length > 1 ? "s" : "")
var title = "Best time in milliseconds over " + runs.length + " " +
runWord + " (lower is better)"
var view = new V.DataView(V.arrayToDataTable(raw))
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2])
document.getElementById("analysis").style.display = "block"
new V.BarChart(document.getElementById("barchart-values")).draw(view, {
title: "TodoMVC Benchmark",
width: 600,
height: 400,
legend: {position: "none"},
backgroundColor: "transparent",
hAxis: {title: title},
min: 0,
max: 1500
})
}
function colorPart(n, pre) {
return Math.max(
0,
((n.toLowerCase().charCodeAt(pre % n.length) - 97) / 26 * 255) | 0
)
}
function colorify(n) {
return "rgb(" +
colorPart(n, 3) + ", " +
colorPart(n, 4) + ", " +
colorPart(n, 5) + ")"
}
function shuffle(ary) {
for (var i = 0; i < ary.length; i++) {
var j = Math.floor(Math.random() * (i + 1))
var tmp = ary[i]
ary[i] = ary[j]
ary[j] = tmp
}
}
window.addEventListener("load", function () {
var match = window.location.search.match(/[\?&]r=(\d+)/)
var timesToRun = match ? +(match[1]) : 1
var Suites = global.Suites.map(function (suite) {
suite = suite(numberOfItemsToAdd)
suite.disabled = false
return suite
})
var runner = new global.BenchmarkRunner(Suites, {
numberOfItemsToAdd: numberOfItemsToAdd,
willRunTest: function (suite, test) {
if (test.anchor.classList) {
test.anchor.classList.add("running")
}
},
didRunTest: function (suite, test) {
if (test.anchor.classList) {
test.anchor.classList.remove("running")
test.anchor.classList.add("ran")
}
},
didRunSuites: function (measured) {
var results = generateResults(measured, timesToRun)
if (results) {
console.log(results)
runs.push(measured)
timesRan++
if (timesRan >= timesToRun) {
timesRan = 0
drawChart(reportFastest())
shuffle(Suites)
} else {
setTimeout(function () {
runButton.click()
}, 0)
}
}
}
})
var currentState = m.prop()
function callNextStep(state) {
runner.step(state).then(currentState).then(function (newState) {
if (newState) callNextStep(newState)
})
}
// Don't call step while step is already executing.
document.body.appendChild(createUIForSuites(Suites,
function () {
runner.step(currentState()).then(currentState)
},
function () {
document.getElementById("analysis").style.display = "none"
localStorage.clear()
callNextStep(currentState())
}))
})
})(this)

51
bench/resources/tests.js Normal file
View file

@ -0,0 +1,51 @@
(function (global) {
"use strict"
var BenchmarkTestStep = global.BenchmarkTestStep
var Suites = global.Suites = []
Suites.push(function (numberOfItemsToAdd) {
return {
name: "Mithril (TodoMVC 1.3)",
url: "app/index.html",
version: "next (dev version)",
prepare: function (runner) {
return runner.waitForElement("#new-todo")
.then(function (element) {
element.focus()
return element
})
},
tests: [
new BenchmarkTestStep("Adding" + numberOfItemsToAdd + "Items",
function (newTodo) {
for (var i = 0; i < numberOfItemsToAdd; i++) {
var inputEvent = document.createEvent("Event")
inputEvent.initEvent("input", true, true)
newTodo.value = "Mithril ------- Something to do " + i
newTodo.dispatchEvent(inputEvent)
var keydownEvent = document.createEvent("Event")
keydownEvent.initEvent("keyup", true, true)
keydownEvent.keyCode = 13 // VK_ENTER
newTodo.dispatchEvent(keydownEvent)
}
}),
new BenchmarkTestStep("CompletingAllItems",
function (newTodo, contentWindow, document) {
var checkboxes = document.getElementsByClassName("toggle")
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].click()
}
}),
new BenchmarkTestStep("DeletingAllItems",
function (newTodo, contentWindow, document) {
var buttons = document.getElementsByClassName("destroy")
for (var i = buttons.length - 1; i > -1; i--) {
buttons[i].click()
}
})
]
}
})
})(this)

1678
mithril.js

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,7 @@
"url": "git@github.com:lhorie/mithril.js.git"
},
"bugs": {
"url" : "http://github.com/lhorie/mithril.js/issues"
"url": "http://github.com/lhorie/mithril.js/issues"
},
"scripts": {
"test": "grunt test"
@ -20,6 +20,7 @@
"main": "mithril.js",
"devDependencies": {
"chai": "^3.4.0",
"chai-string": "^1.1.4",
"eslint": "^1.7.3",
"grunt": "*",
"grunt-cli": "*",

View file

@ -5,8 +5,9 @@
<!-- Dependencies -->
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/sinon/pkg/sinon.js" charset="utf-8"></script>
<script src="../node_modules/sinon-chai/lib/sinon-chai.js" charset="utf-8"></script>
<script src="../node_modules/chai-string/chai-string.js"></script>
<script src="../node_modules/sinon/pkg/sinon.js"></script>
<script src="../node_modules/sinon-chai/lib/sinon-chai.js"></script>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css">
<script src="../node_modules/mocha/mocha.js"></script>

View file

@ -17,6 +17,21 @@ describe("m()", function () {
expect(m).to.be.a("function")
})
it("throws with an empty tag name", function () {
expect(function () {
m("")
}).to.throw(TypeError)
})
it("throws when the tag is not a string or object", function () {
expect(function () { m(0) }).to.throw(TypeError)
expect(function () { m(1) }).to.throw(TypeError)
expect(function () { m(true) }).to.throw(TypeError)
expect(function () { m(null) }).to.throw(TypeError)
expect(function () { m(undefined) }).to.throw(TypeError)
expect(function () { m([]) }).to.throw(TypeError)
})
it("sets correct tag name", function () {
expect(m("div")).to.have.property("tag", "div")
})

View file

@ -1315,30 +1315,31 @@ describe("m.render()", function () {
expect(before).to.equal(after)
})
// FIXME: implement document.createRange().createContextualFragment() in the
// mock document to fix this test
it("keeps unkeyed identity if mixed with elements/trusted text and identity can be inferred", function () { // eslint-disable-line
var root = mock.document.createElement("div")
// FIXME: implement document.createRange().createContextualFragment()
dom(function () {
it("keeps unkeyed identity if mixed with elements/trusted text and identity can be inferred", function () { // eslint-disable-line
var root = 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")
]))
var before = root.childNodes[0].childNodes[4]
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})
]))
var after = root.childNodes[0].childNodes[3]
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]
expect(before).to.equal(after)
expect(before).to.equal(after)
})
})
it("uses the syntax class if it's given as `undefined` in attr", function () { // eslint-disable-line
@ -1411,6 +1412,7 @@ describe("m.render()", function () {
// https://github.com/lhorie/mithril.js/issues/214
it("keeps all input events", function () {
this.timeout(3000) // eslint-disable-line no-invalid-this
var root = mock.document.createElement("div")
var ctrl = m.mount(root, {

View file

@ -29,7 +29,9 @@ describe("m.trust()", function () {
it("works with mixed trusted content in div", function () {
var root = document.createElement("div")
m.render(root, [m.trust("<p>1</p><p>2</p>"), m("i", "foo")])
expect(root.childNodes[2].tagName).to.equal("I")
// Case-insensitive test to work around weird heisenbug with the
// browser
expect(root.childNodes[2].tagName).to.equalIgnoreCase("I")
})
it("works with mixed trusted content in text nodes", function () {
@ -38,7 +40,9 @@ describe("m.trust()", function () {
m.trust("<p>1</p>123<p>2</p>"),
m("i", "foo")
])
expect(root.childNodes[3].tagName).to.equal("I")
// Case-insensitive test to work around weird heisenbug with the
// browser
expect(root.childNodes[3].tagName).to.equalIgnoreCase("I")
})
// FIXME: this is a bug (trusted string's contents rendered as just
@ -52,7 +56,9 @@ describe("m.trust()", function () {
m("td", "foo")
])
expect(root.childNodes[2].tagName).to.equal("TD")
// Case-insensitive test to work around weird heisenbug with the
// browser
expect(root.childNodes[2].tagName).to.equalIgnoreCase("TD")
})
})
})