Merge branch 'lint' of https://github.com/isiahmeadows/mithril.js into isiahmeadows-lint

Conflicts:
	mithril.js
	tests/mithril-tests.js
This commit is contained in:
Leo Horie 2016-01-28 18:40:19 -05:00
commit 4f0d479ee7
17 changed files with 4783 additions and 2997 deletions

View file

@ -7,7 +7,3 @@ mithril.closure-compiler-externs.js
# This is merely a dependency for the documentation. # This is merely a dependency for the documentation.
docs/layout/lib docs/layout/lib
# TODO: These are temporary, and need to be eventually enabled.
mithril.js
tests

View file

@ -1,6 +1,6 @@
/* global _ */ /* global _ */
(function () { (function () {
'use strict'; 'use strict'
/* jshint ignore:start */ /* jshint ignore:start */
// Underscore's Template Module // Underscore's Template Module
@ -8,19 +8,19 @@
var _ = (function (_) { var _ = (function (_) {
_.defaults = function (object) { _.defaults = function (object) {
if (!object) { if (!object) {
return object; return object
} }
for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
var iterable = arguments[argsIndex]; var iterable = arguments[argsIndex]
if (iterable) { if (iterable) {
for (var key in iterable) { for (var key in iterable) {
if (object[key] == null) { if (object[key] == null) {
object[key] = iterable[key]; object[key] = iterable[key]
} }
} }
} }
} }
return object; return object
} }
// By default, Underscore uses ERB-style template delimiters, change the // By default, Underscore uses ERB-style template delimiters, change the
@ -29,221 +29,221 @@
evaluate : /<%([\s\S]+?)%>/g, evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g escape : /<%-([\s\S]+?)%>/g
}; }
// When customizing `templateSettings`, if you don't want to define an // When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is // interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match. // guaranteed not to match.
var noMatch = /(.)^/; var noMatch = /(.)^/
// Certain characters need to be escaped so that they can be put into a // Certain characters need to be escaped so that they can be put into a
// string literal. // string literal.
var escapes = { var escapes = {
"'": "'", "'": "'",
'\\': '\\', "\\": "\\",
'\r': 'r', "\r": "r",
'\n': 'n', "\n": "n",
'\t': 't', "\t": "t",
'\u2028': 'u2028', "\u2028": "u2028",
'\u2029': 'u2029' "\u2029": "u2029"
}; }
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g
// JavaScript micro-templating, similar to John Resig's implementation. // JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace, // Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code. // and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) { _.template = function (text, data, settings) {
var render; var render
settings = _.defaults({}, settings, _.templateSettings); settings = _.defaults({}, settings, _.templateSettings)
// Combine delimiters into one regular expression via alternation. // Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([ var matcher = new RegExp([
(settings.escape || noMatch).source, (settings.escape || noMatch).source,
(settings.interpolate || noMatch).source, (settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source (settings.evaluate || noMatch).source
].join('|') + '|$', 'g'); ].join("|") + "|$", "g")
// Compile the template source, escaping string literals appropriately. // Compile the template source, escaping string literals appropriately.
var index = 0; var index = 0
var source = "__p+='"; var source = "__p+='"
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset) source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; }); .replace(escaper, function (match) { return "\\" + escapes[match] })
if (escape) { if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"
} }
if (interpolate) { if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"
} }
if (evaluate) { if (evaluate) {
source += "';\n" + evaluate + "\n__p+='"; source += "';\n" + evaluate + "\n__p+='"
} }
index = offset + match.length; index = offset + match.length
return match; return match
}); })
source += "';\n"; source += "';\n"
// If a variable is not specified, place data values in local scope. // If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; if (!settings.variable) source = "with(obj||{}){\n" + source + '}\n'
source = "var __t,__p='',__j=Array.prototype.join," + source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" + "print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n"; source + "return __p;\n"
try { try {
render = new Function(settings.variable || 'obj', '_', source); render = new Function(settings.variable || "obj", "_", source)
} catch (e) { } catch (e) {
e.source = source; e.source = source
throw e; throw e
} }
if (data) return render(data, _); if (data) return render(data, _)
var template = function(data) { var template = function (data) {
return render.call(this, data, _); return render.call(this, data, _)
}; }
// Provide the compiled function source as a convenience for precompilation. // Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; template.source = "function(" + (settings.variable || "obj") + "){\n" + source + '}'
return template; return template
}; }
return _; return _
})({}); })({})
if (location.hostname === 'todomvc.com') { if (location.hostname === "todomvc.com") {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (function (i, s, o, g, r, a, m){ i["GoogleAnalyticsObject"] = r;i[r] = i[r]|| function (){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date();a = s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) m = s.getElementsByTagName(o)[0];a.async = 1;a.src = g;m.parentNode.insertBefore(a, m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); })(window, document,"script","https://www.google-analytics.com/analytics.js","ga")
ga('create', 'UA-31081062-1', 'auto'); ga("create", "UA-31081062-1", "auto")
ga('send', 'pageview'); ga("send", "pageview")
} }
/* jshint ignore:end */ /* jshint ignore:end */
function redirect() { function redirect() {
if (location.hostname === 'tastejs.github.io') { if (location.hostname === "tastejs.github.io") {
location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com'); location.href = location.href.replace("tastejs.github.io/todomvc", "todomvc.com")
} }
} }
function findRoot() { function findRoot() {
var base = location.href.indexOf('examples/'); var base = location.href.indexOf("examples/")
return location.href.substr(0, base); return location.href.substr(0, base)
} }
function getFile(file, callback) { function getFile(file, callback) {
if (!location.host) { if (!location.host) {
return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.'); return console.info("Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.")
} }
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest()
xhr.open('GET', findRoot() + file, true); xhr.open("GET", findRoot() + file, true)
xhr.send(); xhr.send()
xhr.onload = function () { xhr.onload = function () {
if (xhr.status === 200 && callback) { if (xhr.status === 200 && callback) {
callback(xhr.responseText); callback(xhr.responseText)
} }
}; }
} }
function Learn(learnJSON, config) { function Learn(learnJSON, config) {
if (!(this instanceof Learn)) { if (!(this instanceof Learn)) {
return new Learn(learnJSON, config); return new Learn(learnJSON, config)
} }
var template, framework; var template, framework
if (typeof learnJSON !== 'object') { if (typeof learnJSON !== "object") {
try { try {
learnJSON = JSON.parse(learnJSON); learnJSON = JSON.parse(learnJSON)
} catch (e) { } catch (e) {
return; return
} }
} }
if (config) { if (config) {
template = config.template; template = config.template
framework = config.framework; framework = config.framework
} }
if (!template && learnJSON.templates) { if (!template && learnJSON.templates) {
template = learnJSON.templates.todomvc; template = learnJSON.templates.todomvc
} }
if (!framework && document.querySelector('[data-framework]')) { if (!framework && document.querySelector("[data-framework]")) {
framework = document.querySelector('[data-framework]').dataset.framework; framework = document.querySelector("[data-framework]").dataset.framework
} }
this.template = template; this.template = template
if (learnJSON.backend) { if (learnJSON.backend) {
this.frameworkJSON = learnJSON.backend; this.frameworkJSON = learnJSON.backend
this.frameworkJSON.issueLabel = framework; this.frameworkJSON.issueLabel = framework
this.append({ this.append({
backend: true backend: true
}); })
} else if (learnJSON[framework]) { } else if (learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework]; this.frameworkJSON = learnJSON[framework]
this.frameworkJSON.issueLabel = framework; this.frameworkJSON.issueLabel = framework
this.append(); this.append()
} }
this.fetchIssueCount(); this.fetchIssueCount()
} }
Learn.prototype.append = function (opts) { Learn.prototype.append = function (opts) {
var aside = document.createElement('aside'); var aside = document.createElement("aside")
aside.innerHTML = _.template(this.template, this.frameworkJSON); aside.innerHTML = _.template(this.template, this.frameworkJSON)
aside.className = 'learn'; aside.className = 'learn'
if (opts && opts.backend) { if (opts && opts.backend) {
// Remove demo link // Remove demo link
var sourceLinks = aside.querySelector('.source-links'); var sourceLinks = aside.querySelector(".source-links")
var heading = sourceLinks.firstElementChild; var heading = sourceLinks.firstElementChild
var sourceLink = sourceLinks.lastElementChild; var sourceLink = sourceLinks.lastElementChild
// Correct link path // Correct link path
var href = sourceLink.getAttribute('href'); var href = sourceLink.getAttribute("href")
sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http'))); sourceLink.setAttribute("href", href.substr(href.lastIndexOf("http")))
sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML; sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML
} else { } else {
// Localize demo links // Localize demo links
var demoLinks = aside.querySelectorAll('.demo-link'); var demoLinks = aside.querySelectorAll(".demo-link")
Array.prototype.forEach.call(demoLinks, function (demoLink) { Array.prototype.forEach.call(demoLinks, function (demoLink) {
if (demoLink.getAttribute('href').substr(0, 4) !== 'http') { if (demoLink.getAttribute("href").substr(0, 4) !== "http") {
demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href')); demoLink.setAttribute("href", findRoot() + demoLink.getAttribute("href"))
} }
}); })
} }
document.body.className = (document.body.className + ' learn-bar').trim(); document.body.className = (document.body.className + " learn-bar").trim()
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML); document.body.insertAdjacentHTML("afterBegin", aside.outerHTML)
}; }
Learn.prototype.fetchIssueCount = function () { Learn.prototype.fetchIssueCount = function () {
var issueLink = document.getElementById('issue-count-link'); var issueLink = document.getElementById("issue-count-link")
if (issueLink) { if (issueLink) {
var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos'); var url = issueLink.href.replace("https://github.com", "https://api.github.com/repos")
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest()
xhr.open('GET', url, true); xhr.open("GET", url, true)
xhr.onload = function (e) { xhr.onload = function (e) {
var parsedResponse = JSON.parse(e.target.responseText); var parsedResponse = JSON.parse(e.target.responseText)
if (parsedResponse instanceof Array) { if (parsedResponse instanceof Array) {
var count = parsedResponse.length; var count = parsedResponse.length
if (count !== 0) { if (count !== 0) {
issueLink.innerHTML = 'This app has ' + count + ' open issues'; issueLink.innerHTML = "This app has " + count + ' open issues'
document.getElementById('issue-count').style.display = 'inline'; document.getElementById("issue-count").style.display = 'inline'
} }
} }
}; }
xhr.send(); xhr.send()
} }
}; }
redirect(); redirect()
getFile('learn.json', Learn); getFile("learn.json", Learn)
})(); })()

2658
mithril.js

File diff suppressed because it is too large Load diff

View file

@ -45,6 +45,9 @@ window.mock = (function () {
"use strict" "use strict"
var window = {} var window = {}
window.window = window
var document = window.document = { var document = window.document = {
// FIXME: add document.createRange().createContextualFragment() // FIXME: add document.createRange().createContextualFragment()
@ -136,7 +139,7 @@ window.mock = (function () {
name = name.toLowerCase() name = name.toLowerCase()
var out = [] var out = []
function traverse(node){ function traverse(node) {
if (node.childNodes && node.childNodes.length > 0) { if (node.childNodes && node.childNodes.length > 0) {
node.childNodes.forEach(function (curr) { node.childNodes.forEach(function (curr) {
if (curr.nodeName.toLowerCase() === name) { if (curr.nodeName.toLowerCase() === name) {
@ -156,7 +159,7 @@ window.mock = (function () {
window.scrollTo = function () {} window.scrollTo = function () {}
;(function (window) { ;(function () {
// This is an actual conforming implementation of the // This is an actual conforming implementation of the
// requestAnimationFrame spec, with the nonstandard extension of // requestAnimationFrame spec, with the nonstandard extension of
// rAF.$resolve for running the callbacks. It works in Node and the // rAF.$resolve for running the callbacks. It works in Node and the
@ -212,7 +215,7 @@ window.mock = (function () {
} }
window.requestAnimationFrame = requestAnimationFrame window.requestAnimationFrame = requestAnimationFrame
})(window) })()
window.XMLHttpRequest = (function () { window.XMLHttpRequest = (function () {
function Request() { function Request() {

8
test/isolation-test.html Normal file
View file

@ -0,0 +1,8 @@
<!doctype html>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.3/es5-shim.min.js"></script>-->
<script src="test.js"></script>
<script src="mock.js"></script>
<script src="../mithril.js"></script>
<p>Open the console to see the test report</p>
<script src="./isolation-test.js"></script>

159
test/isolation-test.js Normal file
View file

@ -0,0 +1,159 @@
/* global m, test, mock */
(function () {
"use strict"
m.deps(mock.window)
test(function () { // eslint-disable-line max-statements
var root = mock.document.createElement("div")
var retain = false
var flag = true
var loaded1 = null
var loaded2 = null
var loaded1a = null
var loaded2a = null
var Comp1 = {
controller: function () {
loaded1 = true
this.onunload = function () {
loaded1 = false
}
},
view: function () {
if (retain) {
return {subtree: "retain"}
} else {
return m("a", {
config: function (el, init, ctx) {
if (!init) {
loaded1a = true
ctx.onunload = function () {
loaded1a = false
}
}
}
})
}
}
}
var Comp2 = {
controller: function () {
loaded2 = true
this.onunload = function () {
loaded2 = false
}
},
view: function () {
if (retain) {
return {subtree: "retain"}
} else {
return m("b", {
config: function (el, init, ctx) {
if (!init) {
loaded2a = true
ctx.onunload = function () {
loaded2a = false
}
}
}
})
}
}
}
var Root = {
view: function () {
return flag ? Comp1 : Comp2
}
}
m.mount(root, Root)
mock.requestAnimationFrame.$resolve()
// loaded 1
var result1 = loaded1 === true &&
loaded2 === null &&
loaded1a === true &&
loaded2a === null
retain = true
m.redraw(true)
mock.requestAnimationFrame.$resolve()
// retained
var result2 = loaded1 === true &&
loaded2 === null &&
loaded1a === true &&
loaded2a === null
flag = false
m.redraw(true)
mock.requestAnimationFrame.$resolve()
// loaded 2 while retained: both controllers are alive at the same time
// because dom element is retained
var result3 = loaded1 === true &&
loaded2 === true &&
loaded1a === true &&
loaded2a === null
retain = false
m.redraw(true)
mock.requestAnimationFrame.$resolve()
// unretained, i.e. 2 is now dynamic
var result4 = loaded1 === false &&
loaded2 === true &&
loaded1a === false &&
loaded2a === true
flag = true
m.redraw(true)
mock.requestAnimationFrame.$resolve()
// loaded 1 while dynamic
var result5 = loaded1 === true &&
loaded2 === false &&
loaded1a === true &&
loaded2a === false
return result1 && result2 && result3 && result4 && result5
})
/*
test(function() {
var root = mock.document.createElement("div")
var redraws = 0, data
var Root = {
view: function() {
return Comp
}
}
var Comp = {
controller: function() {
this.foo = m.request({method: "GET", url: "/foo"})
},
view: function(ctrl) {
redraws++
data = ctrl.foo()
return m("div")
}
}
m.mount(root, Root)
mock.requestAnimationFrame.$resolve()
mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return redraws == 1 && data.url == "/foo"
})
*/
test.print(function (value) {
console.log(value) // eslint-disable-line no-console
})
})()

View file

@ -295,7 +295,7 @@ describe("m.deferred()", function () {
prmA.promise.then(function (A) { prmA.promise.then(function (A) {
return prmB.promise return prmB.promise
}).then(function(B) { }).then(function (B) {
expect(B).to.equal("B") expect(B).to.equal("B")
}) })
}) })
@ -303,7 +303,7 @@ describe("m.deferred()", function () {
var d = m.deferred() var d = m.deferred()
d.resolve(5) d.resolve(5)
d.resolve(6) d.resolve(6)
d.promise.then(function(v) { d.promise.then(function (v) {
expect(v).to.equal(5) expect(v).to.equal(5)
}) })
}) })

View file

@ -56,13 +56,13 @@ describe("m.trust()", function () {
it("works with trusted content in div", function () { it("works with trusted content in div", function () {
var root = document.createElement("div") var root = document.createElement("div")
m.render(root, m('div', [ m.render(root, m("div", [
m('p', '&copy;'), m("p", "&copy;"),
m('p', m.trust('&copy;')), m("p", m.trust("&copy;")),
m.trust('&copy;'), m.trust("&copy;"),
])) ]))
expect(root.innerHTML).to.equal("<div><p>&amp;copy;</p><p>©</p>©</div>") expect(root.innerHTML).to.equal("<div><p>&amp;copy;</p><p>©</p>©</div>")
}) })
}) })
}) })

View file

@ -5,4 +5,4 @@
<script src="../mithril.js"></script> <script src="../mithril.js"></script>
<script src="mithril-tests.js"></script> <script src="mithril-tests.js"></script>
<p>Open the console to see the test report</p> <p>Open the console to see the test report</p>

View file

@ -1,48 +0,0 @@
<p>Typing in the fields below should not move the cursor to the end of the input. Especially in Chrome</p>
<p>All inputs should update with the same value</p>
<p>Typing in an input should not prevent it from being updated by other inputs</p>
<div id="test"></div>
<script src="../mithril.js"></script>
<script>
var app = {}
app.controller = function() {
this.title = m.prop("hello world");
}
app.view = function(ctrl) {
return m("body", [
m("h1", ["Title: ", ctrl.title()]),
m("input[list=data]", {
onkeyup: m.withAttr("value", ctrl.title),
value: ctrl.title()
}),
m("datalist#data", [
m("option", "John"),
m("option", "Bob"),
m("option", "Mary")
]),
m("br"),
m("textarea", {
onkeyup: m.withAttr("value", ctrl.title),
value: ctrl.title()
}),
m("br"),
m("textarea", {
onkeyup: m.withAttr("value", ctrl.title)
}, ctrl.title()),
m("br"),
m("div[contenteditable]", {
style: {border: "1px solid #888"},
onkeyup: m.withAttr("innerHTML", ctrl.title)
}, ctrl.title()),
m("br"),
m("div[contenteditable]", {
style: {border: "1px solid #888"},
onkeyup: m.withAttr("innerHTML", ctrl.title)
}, m.trust(ctrl.title())),
]);
}
m.module(document.getElementById("test"), app);
</script>

View file

@ -1,135 +0,0 @@
<!doctype html>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.3/es5-shim.min.js"></script>-->
<script src="test.js"></script>
<script src="mock.js"></script>
<script src="../mithril.js"></script>
<p>Open the console to see the test report</p>
<script>
function testMithril(mock) {
m.deps(mock)
test(function() {
var root = mock.document.createElement("div")
var retain = false
var flag = true
var loaded1 = null, loaded2 = null, loaded1a = null, loaded2a = null
var Root = {
view: function() {
return flag ? Comp1 : Comp2
}
}
var Comp1 = {
controller: function() {
loaded1 = true
this.onunload = function() {
loaded1 = false
}
},
view: function(ctrl) {
return retain ? {subtree: "retain"} : m("a", {config: function(el, init, ctx) {
if (!init) {
loaded1a = true
ctx.onunload = function() {
loaded1a = false
}
}
}})
}
}
var Comp2 = {
controller: function() {
loaded2 = true
this.onunload = function() {
loaded2 = false
}
},
view: function(ctrl) {
return retain ? {subtree: "retain"} : m("b", {config: function(el, init, ctx) {
if (!init) {
loaded2a = true
ctx.onunload = function() {
loaded2a = false
}
}
}})
}
}
m.mount(root, Root)
mock.requestAnimationFrame.$resolve()
//loaded 1
var result1 = loaded1 === true && loaded2 === null && loaded1a === true && loaded2a === null
retain = true
m.redraw(true)
mock.requestAnimationFrame.$resolve()
//retained
var result2 = loaded1 === true && loaded2 === null && loaded1a === true && loaded2a === null
flag = false
m.redraw(true)
mock.requestAnimationFrame.$resolve()
//loaded 2 while retained: both controllers are alive at the same time because dom element is retained
var result3 = loaded1 === true && loaded2 === true && loaded1a === true && loaded2a === null
retain = false
m.redraw(true)
mock.requestAnimationFrame.$resolve()
//unretained, i.e. 2 is now dynamic
var result4 = loaded1 === false && loaded2 === true && loaded1a === false && loaded2a === true
flag = true
m.redraw(true)
mock.requestAnimationFrame.$resolve()
//loaded 1 while dynamic
var result5 = loaded1 === true && loaded2 === false && loaded1a === true && loaded2a === false
return result1 && result2 && result3 && result4 && result5
})
/*
test(function() {
var root = mock.document.createElement("div")
var redraws = 0, data
var Root = {
view: function() {
return Comp
}
}
var Comp = {
controller: function() {
this.foo = m.request({method: "GET", url: "/foo"})
},
view: function(ctrl) {
redraws++
data = ctrl.foo()
return m("div")
}
}
m.mount(root, Root)
mock.requestAnimationFrame.$resolve()
mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return redraws == 1 && data.url == "/foo"
})
*/
}
//mocks
testMithril(mock.window)
test.print(function(value) {console.log(value)})
</script>

File diff suppressed because it is too large Load diff

View file

@ -1,40 +1,49 @@
if (!Array.prototype.indexOf) { (function (global) { // eslint-disable-line max-statements
Array.prototype.indexOf = function (item) { "use strict"
for (var i = 0; i < this.length; i++) {
if (this[i] === item) return i
}
return -1
}
}
if (!Array.prototype.map) {
Array.prototype.map = function (callback) {
var results = []
for (var i = 0; i < this.length; i++) {
results[i] = callback(this[i], i, this)
}
return results
}
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (callback) {
var results = []
for (var i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) results.push(this[i])
}
return results
}
}
if (!Object.keys) {
Object.keys = function () {
var keys = []
for (var i in this) keys.push(i)
return keys
}
}
var mock = {} /* eslint-disable no-extend-native */
mock.window = (function () { if (!Array.prototype.indexOf) {
var window = {} Array.prototype.indexOf = function (item) {
for (var i = 0; i < this.length; i++) {
if (this[i] === item) return i
}
return -1
}
}
if (!Array.prototype.map) {
Array.prototype.map = function (callback) {
var results = []
for (var i = 0; i < this.length; i++) {
results[i] = callback(this[i], i, this)
}
return results
}
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (callback) {
var results = []
for (var i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) results.push(this[i])
}
return results
}
}
if (!Object.keys) {
Object.keys = function () {
var keys = []
for (var i in this) if ({}.hasOwnProperty.call(this, i)) {
keys.push(i)
}
return keys
}
}
/* eslint-enable no-extend-native */
var window = global.mock = {window: window}
window.window = window
window.document = {} window.document = {}
window.document.childNodes = [] window.document.childNodes = []
window.document.createElement = function (tag) { window.document.createElement = function (tag) {
@ -46,6 +55,7 @@ mock.window = (function () {
appendChild: window.document.appendChild, appendChild: window.document.appendChild,
removeChild: window.document.removeChild, removeChild: window.document.removeChild,
replaceChild: window.document.replaceChild, replaceChild: window.document.replaceChild,
insertBefore: function (node, reference) { insertBefore: function (node, reference) {
node.parentNode = this node.parentNode = this
var referenceIndex = this.childNodes.indexOf(reference) var referenceIndex = this.childNodes.indexOf(reference)
@ -54,15 +64,18 @@ mock.window = (function () {
if (referenceIndex < 0) this.childNodes.push(node) if (referenceIndex < 0) this.childNodes.push(node)
else this.childNodes.splice(referenceIndex, 0, node) else this.childNodes.splice(referenceIndex, 0, node)
}, },
insertAdjacentHTML: function (position, html) { insertAdjacentHTML: function (position, html) {
//todo: accept markup // todo: accept markup
if (position === "beforebegin") { if (position === "beforebegin") {
this.parentNode.insertBefore(window.document.createTextNode(html), this) this.parentNode.insertBefore(
} window.document.createTextNode(html),
else if (position === "beforeend") { this)
} else if (position === "beforeend") {
this.appendChild(window.document.createTextNode(html)) this.appendChild(window.document.createTextNode(html))
} }
}, },
setAttribute: function (name, value) { setAttribute: function (name, value) {
this[name] = value.toString() this[name] = value.toString()
}, },
@ -70,7 +83,7 @@ mock.window = (function () {
this.namespaceURI = namespace this.namespaceURI = namespace
this[name] = value.toString() this[name] = value.toString()
}, },
getAttribute: function (name, value) { getAttribute: function (name) {
return this[name] return this[name]
}, },
addEventListener: function () {}, addEventListener: function () {},
@ -104,16 +117,18 @@ mock.window = (function () {
this.childNodes.splice(index, 1) this.childNodes.splice(index, 1)
child.parentNode = null 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){ window.document.getElementsByTagName = function (name){
name = name.toLowerCase() name = name.toLowerCase()
var out = [] var out = []
var traverse = function (node){ function traverse(node) {
if (node.childNodes && node.childNodes.length > 0){ if (node.childNodes && node.childNodes.length > 0){
node.childNodes.map(function (curr){ node.childNodes.map(function (curr){
if (curr.nodeName.toLowerCase() === name) if (curr.nodeName.toLowerCase() === name) {
out.push(curr) out.push(curr)
}
traverse(curr) traverse(curr)
}) })
} }
@ -136,8 +151,9 @@ mock.window = (function () {
callback() callback()
} }
} }
window.XMLHttpRequest = (function () { window.XMLHttpRequest = (function () {
var request = function () { function XMLHttpRequest() {
this.$headers = {} this.$headers = {}
this.setRequestHeader = function (key, value) { this.setRequestHeader = function (key, value) {
this.$headers[key] = value this.$headers[key] = value
@ -150,21 +166,28 @@ mock.window = (function () {
this.responseText = JSON.stringify(this) this.responseText = JSON.stringify(this)
this.readyState = 4 this.readyState = 4
this.status = 200 this.status = 200
request.$instances.push(this) XMLHttpRequest.$instances.push(this)
} }
} }
request.$instances = [] XMLHttpRequest.$instances = []
return request return XMLHttpRequest
}()) })()
window.location = {search: "", pathname: "", hash: ""},
window.location = {search: "", pathname: "", hash: ""}
window.history = {} window.history = {}
window.history.$$length = 0 window.history.$$length = 0
window.history.pushState = function (data, title, url) { window.history.pushState = function (data, title, url) {
window.history.$$length++ window.history.$$length++
window.location.pathname = window.location.search = window.location.hash = url window.location.pathname =
}, window.location.search =
window.history.replaceState = function (data, title, url) { window.location.hash = url
window.location.pathname = window.location.search = window.location.hash = url
} }
return window
}()) window.history.replaceState = function (data, title, url) {
window.location.pathname =
window.location.search =
window.location.hash = url
}
})(this)

View file

@ -1,19 +0,0 @@
0 info it worked if it ends with ok
1 verbose cli [ 'c:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'c:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'test' ]
2 info using npm@1.4.3
3 info using node@v0.10.26
4 error Error: ENOENT, open 'C:\Users\Leo\Desktop\shared\work\mithril.js\tests\package.json'
5 error If you need help, you may report this *entire* log,
5 error including the npm and node versions, at:
5 error <http://github.com/npm/npm/issues>
6 error System Windows_NT 6.1.7601
7 error command "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "test"
8 error cwd C:\Users\Leo\Desktop\shared\work\mithril.js\tests
9 error node -v v0.10.26
10 error npm -v 1.4.3
11 error path C:\Users\Leo\Desktop\shared\work\mithril.js\tests\package.json
12 error code ENOENT
13 error errno 34
14 verbose exit [ 34, true ]

View file

@ -1,97 +0,0 @@
<!doctype html>
<html>
<head>
<title>SVG test</title>
<style>
.path {
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: dash 5s linear alternate infinite;
-webkit-animation: dash 5s linear alternate infinite;
}
@keyframes dash {
from {
stroke-dashoffset: 1000;
}
to {
stroke-dashoffset: 0;
}
}
@-webkit-keyframes dash {
from {
stroke-dashoffset: 1000;
}
to {
stroke-dashoffset: 0;
}
}
</style>
</head>
<body>
<p>Since it's not possible to test SVG functionality from a NodeJS environment, this page can be used to test it in a browser.</p>
<p>This page should contain:</p>
<ul>
<li>an HTML link labeled "HTML link"</li>
<li>an SVG link labeled "SVG link"</li>
<li>a tilted blue square</li>
<li>a cat picture</li>
<li>an animated line drawing</li>
<li>a clock with the current time</li>
</ul>
<p>The links should open in a new tab. All items should display title tooltips when hovered over.</p>
<div id="test"></div>
<script src="../mithril.js"></script>
<script>
var svg = [
m("a[href='http://google.com'][target='_blank'][title='HTML link']", "HTML link"),
m("br"),
m("svg[width=180][height=200]", [
m("rect[x=50][y=50][height=100][width=100][transform='translate(30) rotate(45 50 50)'][title='Square']", {style: {stroke: "#000", fill: "#0086b2"}}),
m("a[href='http://google.com'][title='SVG link'][target=_new]", {style: {textDecoration: "underline"}}, [
m("text[x=0][y=20]", "SVG Link")
])
]),
m("svg[height='201px'][width='201px']", [
m("image[href='http://placekitten.com/201/201'][height='200px'][width='200px'][title='Cat picture']")
]),
m("svg[enable-background='new 0 0 340 333'][height='333px'][viewBox='0 0 340 333'][width='340px'][x='0px'][y='0px'][title='Line drawings']", [
m("path.path[d='M66.039,133.545c0,0-21-57,18-67s49-4,65,8s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41C46.039,146.545,53.039,128.545,66.039,133.545z'][fill='#FFFFFF'][stroke='#000000'][stroke-miterlimit='10'][stroke-width='4']")
]),
m("svg[height='270px'][width='270px'][viewBox='0 0 270 270']", [
m("g[transform='translate(150,150)'][title='Clock']", [
m("g", [
m("circle[r='108'][fill='none'][stroke-width='4'][stroke='gray']"),
m("circle[r='97'][fill='none'][stroke-width='11'][stroke='black'][stroke-dasharray='4,46.789082'][transform='rotate(-1.5)']"),
m("circle[r='100'][fill='none'][stroke-width='5'][stroke='black'][stroke-dasharray='2,8.471976'][transform='rotate(-.873)']"),
]),
m("g[transform='rotate(180)']", [
m("g[id='hour']", [
m("line[stroke-width='5'][y2='75'][stroke-linecap='round'][stroke='blue'][opacity='.5']"),
m("animateTransform[attributeName='transform'][type='rotate'][repeatCount='indefinite'][dur='12h'][by='360']"),
m("circle[r='7']")
]),
m("g[id='minute']", [
m("line[stroke-width='4'][y2='93'][stroke-linecap='round'][stroke='green'][opacity='.9']"),
m("animateTransform[attributeName='transform'][type='rotate'][repeatCount='indefinite'][dur='60min'][by='360']"),
m("circle[r='6'][fill='red']")
]),
m("g[id='second']", [
m("line[stroke-width='2'][y1='-20'][y2=102][stroke-linecap='round'][stroke='red']"),
m("animateTransform[attributeName='transform'][type='rotate'][repeatCount='indefinite'][dur='60s'][by='360']"),
m("circle[r='4'][fill='blue']")
])
])
]),
m("script", 'var a=new Date,b=parseInt(a.getHours());b=b>12?b-12:b;var c=parseInt(a.getMinutes()),d=parseInt(a.getSeconds()),e=6*d,f=6*(c+d/60),g=30*(b+c/60+d/3600),h=document.getElementById("hour"),i=document.getElementById("minute"),j=document.getElementById("second");h.setAttribute("transform","rotate("+g.toString()+")"),i.setAttribute("transform","rotate("+f.toString()+")"),j.setAttribute("transform","rotate("+e.toString()+")")'),
]),
m("svg[height='200px'][width='200px']", [
m("foreignObject[x=0][y=0][width='100px'][height='100px'][transform='translate(0,0)']", m('div', {xmlns: "http://www.w3.org/1999/xhtml"}, m.trust('this is a piece of html rendered as <a href="http://www.w3.org/TR/SVG11/extend.html">SVG foreignObject</strong>')))
])
]
m.render(document.getElementById("test"), svg)
</script>
</body>
</html>

View file

@ -1,28 +1,38 @@
if (!this.console) { /* eslint-env browser */
var log = function (value) { document.write("<pre>" + value + "</pre>") }
this.console = {log: log, error: log}
}
function test(condition) { (function (global) {
test.total++ "use strict"
try { function log(value) {
if (!condition()) throw new Error("failed") document.write("<pre>" + value + "</pre>")
} }
catch (e) {
console.error(e)
test.failures.push(condition)
}
}
test.total = 0
test.failures = []
test.print = function (print) {
for (var i = 0; i < test.failures.length; i++) {
print(test.failures[i].toString())
}
print("tests: " + test.total + "\nfailures: " + test.failures.length)
if (test.failures.length > 0) { if (!global.console) {
throw new Error(test.failures.length + " tests did not pass") global.console = {log: log, error: log}
} }
}
global.test = test
function test(condition) {
test.total++
try {
if (!condition()) throw new Error("failed")
} catch (e) {
console.error(e) // eslint-disable-line no-console
test.failures.push(condition)
}
}
test.total = 0
test.failures = []
test.print = function (print) {
for (var i = 0; i < test.failures.length; i++) {
print(test.failures[i].toString())
}
print("tests: " + test.total + "\nfailures: " + test.failures.length)
if (test.failures.length > 0) {
throw new Error(test.failures.length + " tests did not pass")
}
}
})(this)

View file