Bundled output for commit bcc6003bf3 [skip ci]

This commit is contained in:
Gandalf-the-Bot 2018-12-04 17:22:15 +00:00
parent bcc6003bf3
commit c6d6afbdfa
6 changed files with 446 additions and 470 deletions

View file

@ -18,7 +18,7 @@ mithril.js [![NPM Version](https://img.shields.io/npm/v/mithril.svg)](https://ww
## What is Mithril? ## What is Mithril?
A modern client-side Javascript framework for building Single Page Applications. It's small (<!-- size -->8.83 KB<!-- /size --> gzipped), fast and provides routing and XHR utilities out of the box. A modern client-side Javascript framework for building Single Page Applications. It's small (<!-- size -->8.86 KB<!-- /size --> gzipped), fast and provides routing and XHR utilities out of the box.
Mithril is used by companies like Vimeo and Nike, and open source platforms like Lichess 👍. Mithril is used by companies like Vimeo and Nike, and open source platforms like Lichess 👍.

View file

@ -1155,36 +1155,45 @@ var coreRenderer = function($window) {
// Defer the property check until *after* we check everything. // Defer the property check until *after* we check everything.
) && key in vnode.dom ) && key in vnode.dom
} }
var matchUpperCase = /[A-Z]/g
function prependDashAndLowerCase(string){
return "-" + string.toLowerCase()
}
function normalizeProp(prop) {
return "-" && prop[1] === "-"
? prop
: prop.replace(matchUpperCase, prependDashAndLowerCase)
}
//style //style
var uppercaseRegex = /[A-Z]/g
function toLowerCase(capital) { return "-" + capital.toLowerCase() }
function normalizeKey(key) {
return key[0] === "-" && key[1] === "-" ? key :
key === "cssFloat" ? "float" :
key.replace(uppercaseRegex, toLowerCase)
}
function updateStyle(element, old, style) { function updateStyle(element, old, style) {
if (old != null && style != null && typeof old === "object" && typeof style === "object" && style !== old) { if (old === style) {
// Styles are equivalent, do nothing.
} else if (style == null) {
// New style is missing, just clear it.
element.style.cssText = ""
} else if (typeof style !== "object") {
// New style is a string, let engine deal with patching.
element.style.cssText = style
} else if (old == null || typeof old !== "object") {
// `old` is missing or a string, `style` is an object.
element.style.cssText = ""
// Add new style properties
for (var key in style) {
var value = style[key]
if (value != null) element.style.setProperty(normalizeKey(key), String(value))
}
} else {
// Both old & new are (different) objects. // Both old & new are (different) objects.
// Update style properties that have changed // Update style properties that have changed
for (var key in style) { for (var key in style) {
if (style[key] !== old[key]) element.style.setProperty(normalizeProp(key), style[key]) var value = style[key]
if (value != null && (value = String(value)) !== String(old[key])) {
element.style.setProperty(normalizeKey(key), value)
}
} }
// Remove style properties that no longer exist // Remove style properties that no longer exist
for (var key in old) { for (var key in old) {
if (!(key in style)) element.style.removeProperty(normalizeProp(key)) if (old[key] != null && style[key] == null) {
} element.style.removeProperty(normalizeKey(key))
return }
}
if (old === style) element.style.cssText = "", old = null
if (style == null) element.style.cssText = ""
else if (typeof style === "string") element.style.cssText = style
else {
if (typeof old === "string") element.style.cssText = ""
for (var key in style) {
element.style.setProperty(normalizeProp(key), style[key])
} }
} }
} }
@ -1333,9 +1342,9 @@ var parseQueryString = function(string) {
for (var i = 0; i < entries.length; i++) { for (var i = 0; i < entries.length; i++) {
var entry = entries[i].split("=") var entry = entries[i].split("=")
var key2 = decodeURIComponent(entry[0]) var key2 = decodeURIComponent(entry[0])
var value = entry.length === 2 ? decodeURIComponent(entry[1]) : "" var value0 = entry.length === 2 ? decodeURIComponent(entry[1]) : ""
if (value === "true") value = true if (value0 === "true") value0 = true
else if (value === "false") value = false else if (value0 === "false") value0 = false
var levels = key2.split(/\]\[?|\[/) var levels = key2.split(/\]\[?|\[/)
var cursor = data2 var cursor = data2
if (key2.indexOf("[") > -1) levels.pop() if (key2.indexOf("[") > -1) levels.pop()
@ -1349,7 +1358,7 @@ var parseQueryString = function(string) {
level = counters[key2]++ level = counters[key2]++
} }
if (cursor[level] == null) { if (cursor[level] == null) {
cursor[level] = isValue ? value : isNumber ? [] : {} cursor[level] = isValue ? value0 : isNumber ? [] : {}
} }
cursor = cursor[level] cursor = cursor[level]
} }

2
mithril.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -6,7 +6,7 @@ Vnode.normalize = function(node) {
if (node != null && typeof node !== "object") return Vnode("#", undefined, undefined, node === false ? "" : node, undefined, undefined) if (node != null && typeof node !== "object") return Vnode("#", undefined, undefined, node === false ? "" : node, undefined, undefined)
return node return node
} }
Vnode.normalizeChildren = function normalizeChildren(input) { Vnode.normalizeChildren = function(input) {
var children = [] var children = []
for (var i = 0; i < input.length; i++) { for (var i = 0; i < input.length; i++) {
children[i] = Vnode.normalize(input[i]) children[i] = Vnode.normalize(input[i])
@ -58,7 +58,7 @@ function execSelector(state, attrs, children) {
if (className != null || state.attrs.className != null) attrs.className = if (className != null || state.attrs.className != null) attrs.className =
className != null className != null
? state.attrs.className != null ? state.attrs.className != null
? state.attrs.className + " " + className ? String(state.attrs.className) + " " + String(className)
: className : className
: state.attrs.className != null : state.attrs.className != null
? state.attrs.className ? state.attrs.className
@ -108,7 +108,10 @@ hyperscript.trust = function(html) {
hyperscript.fragment = function(attrs1, children0) { hyperscript.fragment = function(attrs1, children0) {
return Vnode("[", attrs1.key, attrs1, Vnode.normalizeChildren(children0), undefined, undefined) return Vnode("[", attrs1.key, attrs1, Vnode.normalizeChildren(children0), undefined, undefined)
} }
var m = hyperscript var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
/** @constructor */ /** @constructor */
var PromisePolyfill = function(executor) { var PromisePolyfill = function(executor) {
if (!(this instanceof PromisePolyfill)) throw new Error("Promise must be called with `new`") if (!(this instanceof PromisePolyfill)) throw new Error("Promise must be called with `new`")
@ -235,67 +238,93 @@ if (typeof window !== "undefined") {
var buildQueryString = function(object) { var buildQueryString = function(object) {
if (Object.prototype.toString.call(object) !== "[object Object]") return "" if (Object.prototype.toString.call(object) !== "[object Object]") return ""
var args = [] var args = []
for (var key0 in object) { for (var key in object) {
destructure(key0, object[key0]) destructure(key, object[key])
} }
return args.join("&") return args.join("&")
function destructure(key0, value) { function destructure(key, value) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) { for (var i = 0; i < value.length; i++) {
destructure(key0 + "[" + i + "]", value[i]) destructure(key + "[" + i + "]", value[i])
} }
} }
else if (Object.prototype.toString.call(value) === "[object Object]") { else if (Object.prototype.toString.call(value) === "[object Object]") {
for (var i in value) { for (var i in value) {
destructure(key0 + "[" + i + "]", value[i]) destructure(key + "[" + i + "]", value[i])
} }
} }
else args.push(encodeURIComponent(key0) + (value != null && value !== "" ? "=" + encodeURIComponent(value) : "")) else args.push(encodeURIComponent(key) + (value != null && value !== "" ? "=" + encodeURIComponent(value) : ""))
} }
} }
var FILE_PROTOCOL_REGEX = new RegExp("^file://", "i")
var _9 = function($window, Promise) { var _9 = function($window, Promise) {
var callbackCount = 0 var callbackCount = 0
var oncompletion var oncompletion
function setCompletionCallback(callback) {oncompletion = callback} function makeRequest(factory) {
function finalizer() { return function(url, args) {
var count = 0 if (typeof url !== "string") { args = url; url = url.url }
function complete() {if (--count === 0 && typeof oncompletion === "function") oncompletion()} else if (args == null) args = {}
return function finalize(promise0) { var promise0 = new Promise(function(resolve, reject) {
var then0 = promise0.then factory(url, args, function (data) {
promise0.then = function() { if (typeof args.type === "function") {
count++ if (Array.isArray(data)) {
var next = then0.apply(promise0, arguments) for (var i = 0; i < data.length; i++) {
next.then(complete, function(e) { data[i] = new args.type(data[i])
complete() }
if (count === 0) throw e }
}) else data = new args.type(data)
return finalize(next) }
resolve(data)
}, reject)
})
if (args.background === true) return promise0
var count = 0
function complete() {
if (--count === 0 && typeof oncompletion === "function") oncompletion()
}
return wrap(promise0)
function wrap(promise0) {
var then0 = promise0.then
promise0.then = function() {
count++
var next = then0.apply(promise0, arguments)
next.then(complete, function(e) {
complete()
if (count === 0) throw e
})
return wrap(next)
}
return promise0
} }
return promise0
} }
} }
function normalize(args, extra) { function hasHeader(args, name) {
if (typeof args === "string") { for (var key in args.headers) {
var url = args if ({}.hasOwnProperty.call(args.headers, key) && name.test(key)) return true
args = extra || {}
if (args.url == null) args.url = url
} }
return args return false
} }
function request(args, extra) { function interpolate(url, data, assemble) {
var finalize = finalizer() if (data == null) return url
args = normalize(args, extra) url = url.replace(/:([^\/]+)/gi, function (m0, key) {
var promise0 = new Promise(function(resolve, reject) { return data[key] != null ? data[key] : m0
if (args.method == null) args.method = "GET" })
args.method = args.method.toUpperCase() if (assemble && data != null) {
var useBody = (args.method === "GET" || args.method === "TRACE") ? false : (typeof args.useBody === "boolean" ? args.useBody : true) var querystring = buildQueryString(data)
if (typeof args.serialize !== "function") args.serialize = typeof FormData !== "undefined" && args.data instanceof FormData ? function(value) {return value} : JSON.stringify if (querystring) url += (url.indexOf("?") < 0 ? "?" : "&") + querystring
if (typeof args.deserialize !== "function") args.deserialize = deserialize }
if (typeof args.extract !== "function") args.extract = extract return url
args.url = interpolate(args.url, args.data) }
if (useBody) args.data = args.serialize(args.data) return {
else args.url = assemble(args.url, args.data) request: makeRequest(function(url, args, resolve, reject) {
var method = args.method != null ? args.method.toUpperCase() : "GET"
var useBody = method !== "GET" && method !== "TRACE" &&
(typeof args.useBody !== "boolean" || args.useBody)
var data = args.data
var assumeJSON = (args.serialize == null || args.serialize === JSON.serialize) && !(data instanceof $window.FormData)
if (useBody) {
if (typeof args.serialize === "function") data = args.serialize(data)
else if (!(data instanceof $window.FormData)) data = JSON.stringify(data)
}
var xhr = new $window.XMLHttpRequest(), var xhr = new $window.XMLHttpRequest(),
aborted = false, aborted = false,
_abort = xhr.abort _abort = xhr.abort
@ -303,19 +332,20 @@ var _9 = function($window, Promise) {
aborted = true aborted = true
_abort.call(xhr) _abort.call(xhr)
} }
xhr.open(args.method, args.url, typeof args.async === "boolean" ? args.async : true, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined) xhr.open(method, interpolate(url, args.data, !useBody), typeof args.async !== "boolean" || args.async, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined)
if (args.serialize === JSON.stringify && useBody && !(args.headers && args.headers.hasOwnProperty("Content-Type"))) { if (assumeJSON && useBody && !hasHeader(args, /^content-type0$/i)) {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8") xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
} }
if (args.deserialize === deserialize && !(args.headers && args.headers.hasOwnProperty("Accept"))) { if (typeof args.deserialize !== "function" && !hasHeader(args, /^accept$/i)) {
xhr.setRequestHeader("Accept", "application/json, text/*") xhr.setRequestHeader("Accept", "application/json, text/*")
} }
if (args.withCredentials) xhr.withCredentials = args.withCredentials if (args.withCredentials) xhr.withCredentials = args.withCredentials
if (args.timeout) xhr.timeout = args.timeout if (args.timeout) xhr.timeout = args.timeout
if (args.responseType) xhr.responseType = args.responseType if (args.responseType) xhr.responseType = args.responseType
for (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) { for (var key in args.headers) {
xhr.setRequestHeader(key, args.headers[key]) if ({}.hasOwnProperty.call(args.headers, key)) {
xhr.setRequestHeader(key, args.headers[key])
}
} }
if (typeof args.config === "function") xhr = args.config(xhr, args) || xhr if (typeof args.config === "function") xhr = args.config(xhr, args) || xhr
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {
@ -323,10 +353,18 @@ var _9 = function($window, Promise) {
if(aborted) return if(aborted) return
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
try { try {
var response = (args.extract !== extract) ? args.extract(xhr, args) : args.deserialize(args.extract(xhr, args)) var success = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || (/^file:\/\//i).test(url)
if (args.extract !== extract || (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) { var response = xhr.responseText
resolve(cast(args.type, response)) if (typeof args.extract === "function") {
response = args.extract(xhr, args)
success = true
} else if (typeof args.deserialize === "function") {
response = args.deserialize(response)
} else {
try {response = response ? JSON.parse(response) : null}
catch (e) {throw new Error("Invalid JSON: " + response)}
} }
if (success) resolve(response)
else { else {
var error = new Error(xhr.responseText) var error = new Error(xhr.responseText)
error.code = xhr.status error.code = xhr.status
@ -339,20 +377,15 @@ var _9 = function($window, Promise) {
} }
} }
} }
if (useBody && (args.data != null)) xhr.send(args.data) if (useBody && data != null) xhr.send(data)
else xhr.send() else xhr.send()
}) }),
return args.background === true ? promise0 : finalize(promise0) jsonp: makeRequest(function(url, args, resolve, reject) {
}
function jsonp(args, extra) {
var finalize = finalizer()
args = normalize(args, extra)
var promise0 = new Promise(function(resolve, reject) {
var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++ var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++
var script = $window.document.createElement("script") var script = $window.document.createElement("script")
$window[callbackName] = function(data) { $window[callbackName] = function(data) {
script.parentNode.removeChild(script) script.parentNode.removeChild(script)
resolve(cast(args.type, data)) resolve(data)
delete $window[callbackName] delete $window[callbackName]
} }
script.onerror = function() { script.onerror = function() {
@ -360,50 +393,16 @@ var _9 = function($window, Promise) {
reject(new Error("JSONP request failed")) reject(new Error("JSONP request failed"))
delete $window[callbackName] delete $window[callbackName]
} }
if (args.data == null) args.data = {} url = interpolate(url, args.data, true)
args.url = interpolate(args.url, args.data) script.src = url + (url.indexOf("?") < 0 ? "?" : "&") +
args.data[args.callbackKey || "callback"] = callbackName encodeURIComponent(args.callbackKey || "callback") + "=" +
script.src = assemble(args.url, args.data) encodeURIComponent(callbackName)
$window.document.documentElement.appendChild(script) $window.document.documentElement.appendChild(script)
}) }),
return args.background === true? promise0 : finalize(promise0) setCompletionCallback: function(callback) {
oncompletion = callback
},
} }
function interpolate(url, data) {
if (data == null) return url
var tokens = url.match(/:[^\/]+/gi) || []
for (var i = 0; i < tokens.length; i++) {
var key = tokens[i].slice(1)
if (data[key] != null) {
url = url.replace(tokens[i], data[key])
}
}
return url
}
function assemble(url, data) {
var querystring = buildQueryString(data)
if (querystring !== "") {
var prefix = url.indexOf("?") < 0 ? "?" : "&"
url += prefix + querystring
}
return url
}
function deserialize(data) {
try {return data !== "" ? JSON.parse(data) : null}
catch (e) {throw new Error("Invalid JSON: " + data)}
}
function extract(xhr) {return xhr.responseText}
function cast(type0, data) {
if (typeof type0 === "function") {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
data[i] = new type0(data[i])
}
}
else return new type0(data)
}
return data
}
return {request: request, jsonp: jsonp, setCompletionCallback: setCompletionCallback}
} }
var requestService = _9(window, PromisePolyfill) var requestService = _9(window, PromisePolyfill)
var coreRenderer = function($window) { var coreRenderer = function($window) {
@ -412,8 +411,8 @@ var coreRenderer = function($window) {
svg: "http://www.w3.org/2000/svg", svg: "http://www.w3.org/2000/svg",
math: "http://www.w3.org/1998/Math/MathML" math: "http://www.w3.org/1998/Math/MathML"
} }
var onevent var redraw0
function setEventCallback(callback) {return onevent = callback} function setRedraw(callback) {return redraw0 = callback}
function getNameSpace(vnode) { function getNameSpace(vnode) {
return vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag] return vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag]
} }
@ -433,6 +432,15 @@ var coreRenderer = function($window) {
checkState(vnode, original) checkState(vnode, original)
} }
} }
// IE11 (at least) throws an UnspecifiedError when accessing document.activeElement when
// inside an iframe. Catch and swallow this error1, and heavy-handidly return null.
function activeElement() {
try {
return $doc.activeElement
} catch (e) {
return null
}
}
//create //create
function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) { function createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) {
for (var i = start; i < end; i++) { for (var i = start; i < end; i++) {
@ -462,13 +470,13 @@ var coreRenderer = function($window) {
} }
var possibleParents = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"} var possibleParents = {caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup"}
function createHTML(parent, vnode, ns, nextSibling) { function createHTML(parent, vnode, ns, nextSibling) {
var match1 = vnode.children.match(/^\s*?<(\w+)/im) || [] var match0 = vnode.children.match(/^\s*?<(\w+)/im) || []
// not using the proper parent makes the child element(s) vanish. // not using the proper parent makes the child element(s) vanish.
// var div = document.createElement("div") // var div = document.createElement("div")
// div.innerHTML = "<td>i</td><td>j</td>" // div.innerHTML = "<td>i</td><td>j</td>"
// console.log(div.innerHTML) // console.log(div.innerHTML)
// --> "ij", no <td> in sight. // --> "ij", no <td> in sight.
var temp = $doc.createElement(possibleParents[match1[1]] || "div") var temp = $doc.createElement(possibleParents[match0[1]] || "div")
if (ns === "http://www.w3.org/2000/svg") { if (ns === "http://www.w3.org/2000/svg") {
temp.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\">" + vnode.children + "</svg>" temp.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\">" + vnode.children + "</svg>"
temp = temp.firstChild temp = temp.firstChild
@ -536,8 +544,8 @@ var coreRenderer = function($window) {
sentinel.$$reentrantLock$$ = true sentinel.$$reentrantLock$$ = true
vnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function") ? new vnode.tag(vnode) : vnode.tag(vnode) vnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function") ? new vnode.tag(vnode) : vnode.tag(vnode)
} }
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
initLifecycle(vnode.state, vnode, hooks) initLifecycle(vnode.state, vnode, hooks)
if (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)
vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode)) vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode))
if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument") if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
sentinel.$$reentrantLock$$ = null sentinel.$$reentrantLock$$ = null
@ -556,12 +564,12 @@ var coreRenderer = function($window) {
//update //update
/** /**
* @param {Element|Fragment} parent - the parent element * @param {Element|Fragment} parent - the parent element
* @param {Vnode[] | null} old - the list of vnodes of the last0 `render()` call for * @param {Vnode[] | null} old - the list of vnodes of the last `render()` call for
* this part of the tree * this part of the tree
* @param {Vnode[] | null} vnodes - as above, but for the current `render()` call. * @param {Vnode[] | null} vnodes - as above, but for the current `render()` call.
* @param {Function[]} hooks - an accumulator of post-render hooks (oncreate/onupdate) * @param {Function[]} hooks - an accumulator of post-render hooks (oncreate/onupdate)
* @param {Element | null} nextSibling - the next0 DOM node if we're dealing with a * @param {Element | null} nextSibling - the next0 DOM node if we're dealing with a
* fragment that is not the last0 item in its * fragment that is not the last item in its
* parent * parent
* @param {'svg' | 'math' | String | null} ns) - the current XML namespace, if any * @param {'svg' | 'math' | String | null} ns) - the current XML namespace, if any
* @returns void * @returns void
@ -594,7 +602,7 @@ var coreRenderer = function($window) {
// //
// In order to diff keyed lists, one has to // In order to diff keyed lists, one has to
// //
// 1) match1 nodes in both lists, per key2, and update them accordingly // 1) match0 nodes in both lists, per key, and update them accordingly
// 2) create the nodes present in the new list, but absent in the old one // 2) create the nodes present in the new list, but absent in the old one
// 3) remove the nodes present in the old list, but absent in the new one // 3) remove the nodes present in the old list, but absent in the new one
// 4) figure out what nodes in 1) to move in order to minimize the DOM operations. // 4) figure out what nodes in 1) to move in order to minimize the DOM operations.
@ -612,7 +620,7 @@ var coreRenderer = function($window) {
// the longest increasing subsequence is the list of nodes that can remain in place. Imagine going // the longest increasing subsequence is the list of nodes that can remain in place. Imagine going
// from `1,2,3,4,5` to `4,5,1,2,3` where the numbers are not necessarily the keys, but the indices // from `1,2,3,4,5` to `4,5,1,2,3` where the numbers are not necessarily the keys, but the indices
// corresponding to the keyed nodes in the old list (keyed nodes `e,d,c,b,a` => `b,a,e,d,c` would // corresponding to the keyed nodes in the old list (keyed nodes `e,d,c,b,a` => `b,a,e,d,c` would
// match1 the above lists, for example). // match0 the above lists, for example).
// //
// In there are two increasing subsequences: `4,5` and `1,2,3`, the latter being the longest. We // In there are two increasing subsequences: `4,5` and `1,2,3`, the latter being the longest. We
// can update those nodes without moving them, and only call `insertNode` on `4` and `5`. // can update those nodes without moving them, and only call `insertNode` on `4` and `5`.
@ -621,14 +629,14 @@ var coreRenderer = function($window) {
// the longest increasing subsequence *of old nodes still present in the new list*). // the longest increasing subsequence *of old nodes still present in the new list*).
// //
// It is a general algorithm that is fireproof in all circumstances, but it requires the allocation // It is a general algorithm that is fireproof in all circumstances, but it requires the allocation
// and the construction of a `key2 => oldIndex` map, and three arrays (one with `newIndex => oldIndex`, // and the construction of a `key => oldIndex` map, and three arrays (one with `newIndex => oldIndex`,
// the `LIS` and a temporary one to create the LIS). // the `LIS` and a temporary one to create the LIS).
// //
// So we cheat where we can: if the tails of the lists are identical, they are guaranteed to be part of // So we cheat where we can: if the tails of the lists are identical, they are guaranteed to be part of
// the LIS and can be updated without moving them. // the LIS and can be updated without moving them.
// //
// If two nodes are swapped, they are guaranteed not to be part of the LIS, and must be moved (with // If two nodes are swapped, they are guaranteed not to be part of the LIS, and must be moved (with
// the exception of the last0 node if the list is fully reversed). // the exception of the last node if the list is fully reversed).
// //
// ## Finding the next0 sibling. // ## Finding the next0 sibling.
// //
@ -636,7 +644,7 @@ var coreRenderer = function($window) {
// When the list is being traversed top-down, at any index0, the DOM nodes up to the previous // When the list is being traversed top-down, at any index0, the DOM nodes up to the previous
// vnode reflect the content of the new list, whereas the rest of the DOM nodes reflect the old // vnode reflect the content of the new list, whereas the rest of the DOM nodes reflect the old
// list. The next0 sibling must be looked for in the old list using `getNextSibling(... oldStart + 1 ...)`. // list. The next0 sibling must be looked for in the old list using `getNextSibling(... oldStart + 1 ...)`.
// //
// In the other scenarios (swaps, upwards traversal, map-based diff), // In the other scenarios (swaps, upwards traversal, map-based diff),
// the new vnodes list is traversed upwards. The DOM nodes at the bottom of the list reflect the // the new vnodes list is traversed upwards. The DOM nodes at the bottom of the list reflect the
// bottom part of the new vnodes list, and we can use the `v.dom` value of the previous node // bottom part of the new vnodes list, and we can use the `v.dom` value of the previous node
@ -887,8 +895,8 @@ var coreRenderer = function($window) {
function updateComponent(parent, old, vnode, hooks, nextSibling, ns) { function updateComponent(parent, old, vnode, hooks, nextSibling, ns) {
vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode)) vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode))
if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument") if (vnode.instance === vnode) throw Error("A view cannot return the vnode it received as argument")
if (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)
updateLifecycle(vnode.state, vnode, hooks) updateLifecycle(vnode.state, vnode, hooks)
if (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)
if (vnode.instance != null) { if (vnode.instance != null) {
if (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling) if (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling)
else updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, ns) else updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, ns)
@ -906,12 +914,12 @@ var coreRenderer = function($window) {
} }
} }
function getKeyMap(vnodes, start, end) { function getKeyMap(vnodes, start, end) {
var map = {} var map = Object.create(null)
for (; start < end; start++) { for (; start < end; start++) {
var vnode = vnodes[start] var vnode = vnodes[start]
if (vnode != null) { if (vnode != null) {
var key2 = vnode.key var key = vnode.key
if (key2 != null) map[key2] = start if (key != null) map[key] = start
} }
} }
return map return map
@ -1004,15 +1012,15 @@ var coreRenderer = function($window) {
function removeNode(vnode) { function removeNode(vnode) {
var expected = 1, called = 0 var expected = 1, called = 0
var original = vnode.state var original = vnode.state
if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") { if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeremove === "function") {
var result = callHook.call(vnode.attrs.onbeforeremove, vnode) var result = callHook.call(vnode.state.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") { if (result != null && typeof result.then === "function") {
expected++ expected++
result.then(continuation, continuation) result.then(continuation, continuation)
} }
} }
if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeremove === "function") { if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") {
var result = callHook.call(vnode.state.onbeforeremove, vnode) var result = callHook.call(vnode.attrs.onbeforeremove, vnode)
if (result != null && typeof result.then === "function") { if (result != null && typeof result.then === "function") {
expected++ expected++
result.then(continuation, continuation) result.then(continuation, continuation)
@ -1033,9 +1041,9 @@ var coreRenderer = function($window) {
} }
} }
function onremove(vnode) { function onremove(vnode) {
if (typeof vnode.tag !== "string" && typeof vnode.state.onremove === "function") callHook.call(vnode.state.onremove, vnode)
if (vnode.attrs && typeof vnode.attrs.onremove === "function") callHook.call(vnode.attrs.onremove, vnode) if (vnode.attrs && typeof vnode.attrs.onremove === "function") callHook.call(vnode.attrs.onremove, vnode)
if (typeof vnode.tag !== "string") { if (typeof vnode.tag !== "string") {
if (typeof vnode.state.onremove === "function") callHook.call(vnode.state.onremove, vnode)
if (vnode.instance != null) onremove(vnode.instance) if (vnode.instance != null) onremove(vnode.instance)
} else { } else {
var children1 = vnode.children var children1 = vnode.children
@ -1049,21 +1057,21 @@ var coreRenderer = function($window) {
} }
//attrs2 //attrs2
function setAttrs(vnode, attrs2, ns) { function setAttrs(vnode, attrs2, ns) {
for (var key2 in attrs2) { for (var key in attrs2) {
setAttr(vnode, key2, null, attrs2[key2], ns) setAttr(vnode, key, null, attrs2[key], ns)
} }
} }
function setAttr(vnode, key2, old, value, ns) { function setAttr(vnode, key, old, value, ns) {
if (key2 === "key" || key2 === "is" || value == null || isLifecycleMethod(key2) || (old === value && !isFormAttribute(vnode, key2)) && typeof value !== "object") return if (key === "key" || key === "is" || value == null || isLifecycleMethod(key) || (old === value && !isFormAttribute(vnode, key)) && typeof value !== "object") return
if (key2[0] === "o" && key2[1] === "n") return updateEvent(vnode, key2, value) if (key[0] === "o" && key[1] === "n") return updateEvent(vnode, key, value)
if (key2.slice(0, 6) === "xlink:") vnode.dom.setAttributeNS("http://www.w3.org/1999/xlink", key2.slice(6), value) if (key.slice(0, 6) === "xlink:") vnode.dom.setAttributeNS("http://www.w3.org/1999/xlink", key.slice(6), value)
else if (key2 === "style") updateStyle(vnode.dom, old, value) else if (key === "style") updateStyle(vnode.dom, old, value)
else if (hasPropertyKey(vnode, key2, ns)) { else if (hasPropertyKey(vnode, key, ns)) {
if (key2 === "value") { if (key === "value") {
// Only do the coercion if we're actually going to check the value. // Only do the coercion if we're actually going to check the value.
/* eslint-disable no-implicit-coercion */ /* eslint-disable no-implicit-coercion */
//setting input[value] to same value by typing on focused element moves cursor to end in Chrome //setting input[value] to same value by typing on focused element moves cursor to end in Chrome
if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === "" + value && vnode.dom === $doc.activeElement) return if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === "" + value && vnode.dom === activeElement()) return
//setting select[value] to same value while having select open blinks select dropdown in Chrome //setting select[value] to same value while having select open blinks select dropdown in Chrome
if (vnode.tag === "select" && old !== null && vnode.dom.value === "" + value) return if (vnode.tag === "select" && old !== null && vnode.dom.value === "" + value) return
//setting option[value] to same value while having select open blinks select dropdown in Chrome //setting option[value] to same value while having select open blinks select dropdown in Chrome
@ -1071,31 +1079,34 @@ var coreRenderer = function($window) {
/* eslint-enable no-implicit-coercion */ /* eslint-enable no-implicit-coercion */
} }
// If you assign an input type1 that is not supported by IE 11 with an assignment expression, an error1 will occur. // If you assign an input type1 that is not supported by IE 11 with an assignment expression, an error1 will occur.
if (vnode.tag === "input" && key2 === "type") vnode.dom.setAttribute(key2, value) if (vnode.tag === "input" && key === "type") vnode.dom.setAttribute(key, value)
else vnode.dom[key2] = value else vnode.dom[key] = value
} else { } else {
if (typeof value === "boolean") { if (typeof value === "boolean") {
if (value) vnode.dom.setAttribute(key2, "") if (value) vnode.dom.setAttribute(key, "")
else vnode.dom.removeAttribute(key2) else vnode.dom.removeAttribute(key)
} }
else vnode.dom.setAttribute(key2 === "className" ? "class" : key2, value) else vnode.dom.setAttribute(key === "className" ? "class" : key, value)
} }
} }
function removeAttr(vnode, key2, old, ns) { function removeAttr(vnode, key, old, ns) {
if (key2 === "key" || key2 === "is" || old == null || isLifecycleMethod(key2)) return if (key === "key" || key === "is" || old == null || isLifecycleMethod(key)) return
if (key2[0] === "o" && key2[1] === "n" && !isLifecycleMethod(key2)) updateEvent(vnode, key2, undefined) if (key[0] === "o" && key[1] === "n" && !isLifecycleMethod(key)) updateEvent(vnode, key, undefined)
else if (key2 === "style") updateStyle(vnode.dom, old, null) else if (key === "style") updateStyle(vnode.dom, old, null)
else if ( else if (
hasPropertyKey(vnode, key2, ns) hasPropertyKey(vnode, key, ns)
&& key2 !== "className" && key !== "className"
&& !(vnode.tag === "option" && key2 === "value") && !(key === "value" && (
&& !(vnode.tag === "input" && key2 === "type") vnode.tag === "option"
|| vnode.tag === "select" && vnode.dom.selectedIndex === -1 && vnode.dom === activeElement()
))
&& !(vnode.tag === "input" && key === "type")
) { ) {
vnode.dom[key2] = null vnode.dom[key] = null
} else { } else {
var nsLastIndex = key2.indexOf(":") var nsLastIndex = key.indexOf(":")
if (nsLastIndex !== -1) key2 = key2.slice(nsLastIndex + 1) if (nsLastIndex !== -1) key = key.slice(nsLastIndex + 1)
if (old !== false) vnode.dom.removeAttribute(key2 === "className" ? "class" : key2) if (old !== false) vnode.dom.removeAttribute(key === "className" ? "class" : key)
} }
} }
function setLateSelectAttrs(vnode, attrs2) { function setLateSelectAttrs(vnode, attrs2) {
@ -1113,63 +1124,81 @@ var coreRenderer = function($window) {
} }
function updateAttrs(vnode, old, attrs2, ns) { function updateAttrs(vnode, old, attrs2, ns) {
if (attrs2 != null) { if (attrs2 != null) {
for (var key2 in attrs2) { for (var key in attrs2) {
setAttr(vnode, key2, old && old[key2], attrs2[key2], ns) setAttr(vnode, key, old && old[key], attrs2[key], ns)
} }
} }
var val var val
if (old != null) { if (old != null) {
for (var key2 in old) { for (var key in old) {
if (((val = old[key2]) != null) && (attrs2 == null || attrs2[key2] == null)) { if (((val = old[key]) != null) && (attrs2 == null || attrs2[key] == null)) {
removeAttr(vnode, key2, val, ns) removeAttr(vnode, key, val, ns)
} }
} }
} }
} }
function isFormAttribute(vnode, attr) { function isFormAttribute(vnode, attr) {
return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === $doc.activeElement || vnode.tag === "option" && vnode.dom.parentNode === $doc.activeElement return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === activeElement() || vnode.tag === "option" && vnode.dom.parentNode === $doc.activeElement
} }
function isLifecycleMethod(attr) { function isLifecycleMethod(attr) {
return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate" return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate"
} }
function hasPropertyKey(vnode, key2, ns) { function hasPropertyKey(vnode, key, ns) {
// Filter out namespaced keys // Filter out namespaced keys
return ns === undefined && ( return ns === undefined && (
// If it's a custom element, just keep it. // If it's a custom element, just keep it.
vnode.tag.indexOf("-") > -1 || vnode.attrs != null && vnode.attrs.is || vnode.tag.indexOf("-") > -1 || vnode.attrs != null && vnode.attrs.is ||
// If it's a normal element, let's try to avoid a few browser bugs. // If it's a normal element, let's try to avoid a few browser bugs.
key !== "href" && key2 !== "list" && key2 !== "form" && key2 !== "width" && key2 !== "height"// && key2 !== "type" key !== "href" && key !== "list" && key !== "form" && key !== "width" && key !== "height"// && key !== "type"
// Defer the property check until *after* we check everything. // Defer the property check until *after* we check everything.
) && key2 in vnode.dom ) && key in vnode.dom
} }
//style //style
var uppercaseRegex = /[A-Z]/g
function toLowerCase(capital) { return "-" + capital.toLowerCase() }
function normalizeKey(key) {
return key[0] === "-" && key[1] === "-" ? key :
key === "cssFloat" ? "float" :
key.replace(uppercaseRegex, toLowerCase)
}
function updateStyle(element, old, style) { function updateStyle(element, old, style) {
if (old != null && style != null && typeof old === "object" && typeof style === "object" && style !== old) { if (old === style) {
// Styles are equivalent, do nothing.
} else if (style == null) {
// New style is missing, just clear it.
element.style.cssText = ""
} else if (typeof style !== "object") {
// New style is a string, let engine deal with patching.
element.style.cssText = style
} else if (old == null || typeof old !== "object") {
// `old` is missing or a string, `style` is an object.
element.style.cssText = ""
// Add new style properties
for (var key in style) {
var value = style[key]
if (value != null) element.style.setProperty(normalizeKey(key), String(value))
}
} else {
// Both old & new are (different) objects. // Both old & new are (different) objects.
// Update style properties that have changed // Update style properties that have changed
for (var key2 in style) { for (var key in style) {
if (style[key2] !== old[key2]) element.style[key2] = style[key2] var value = style[key]
if (value != null && (value = String(value)) !== String(old[key])) {
element.style.setProperty(normalizeKey(key), value)
}
} }
// Remove style properties that no longer exist // Remove style properties that no longer exist
for (var key2 in old) { for (var key in old) {
if (!(key2 in style)) element.style[key2] = "" if (old[key] != null && style[key] == null) {
} element.style.removeProperty(normalizeKey(key))
return }
}
if (old === style) element.style.cssText = "", old = null
if (style == null) element.style.cssText = ""
else if (typeof style === "string") element.style.cssText = style
else {
if (typeof old === "string") element.style.cssText = ""
for (var key2 in style) {
element.style[key2] = style[key2]
} }
} }
} }
// Here's an explanation of how this works: // Here's an explanation of how this works:
// 1. The event names are always (by design) prefixed by `on`. // 1. The event names are always (by design) prefixed by `on`.
// 2. The EventListener interface accepts either a function or an object // 2. The EventListener interface accepts either a function or an object
// with a `handleEvent` method. // with a `handleEvent` method0.
// 3. The object does not inherit from `Object.prototype`, to avoid // 3. The object does not inherit from `Object.prototype`, to avoid
// any potential interference with that (e.g. setters). // any potential interference with that (e.g. setters).
// 4. The event name is remapped to the handler0 before calling it. // 4. The event name is remapped to the handler0 before calling it.
@ -1182,29 +1211,30 @@ var coreRenderer = function($window) {
EventDict.prototype.handleEvent = function (ev) { EventDict.prototype.handleEvent = function (ev) {
var handler0 = this["on" + ev.type] var handler0 = this["on" + ev.type]
var result var result
if (typeof handler0 === "function") result = handler0.call(ev.target, ev) if (typeof handler0 === "function") result = handler0.call(ev.currentTarget, ev)
else if (typeof handler0.handleEvent === "function") handler0.handleEvent(ev) else if (typeof handler0.handleEvent === "function") handler0.handleEvent(ev)
if (typeof onevent === "function") onevent.call(ev.target, ev) if (ev.redraw === false) ev.redraw = undefined
else if (typeof redraw0 === "function") redraw0()
if (result === false) { if (result === false) {
ev.preventDefault() ev.preventDefault()
ev.stopPropagation() ev.stopPropagation()
} }
} }
//event //event
function updateEvent(vnode, key2, value) { function updateEvent(vnode, key, value) {
if (vnode.events != null) { if (vnode.events != null) {
if (vnode.events[key2] === value) return if (vnode.events[key] === value) return
if (value != null && (typeof value === "function" || typeof value === "object")) { if (value != null && (typeof value === "function" || typeof value === "object")) {
if (vnode.events[key2] == null) vnode.dom.addEventListener(key2.slice(2), vnode.events, false) if (vnode.events[key] == null) vnode.dom.addEventListener(key.slice(2), vnode.events, false)
vnode.events[key2] = value vnode.events[key] = value
} else { } else {
if (vnode.events[key2] != null) vnode.dom.removeEventListener(key2.slice(2), vnode.events, false) if (vnode.events[key] != null) vnode.dom.removeEventListener(key.slice(2), vnode.events, false)
vnode.events[key2] = undefined vnode.events[key] = undefined
} }
} else if (value != null && (typeof value === "function" || typeof value === "object")) { } else if (value != null && (typeof value === "function" || typeof value === "object")) {
vnode.events = new EventDict() vnode.events = new EventDict()
vnode.dom.addEventListener(key2.slice(2), vnode.events, false) vnode.dom.addEventListener(key.slice(2), vnode.events, false)
vnode.events[key2] = value vnode.events[key] = value
} }
} }
//lifecycle //lifecycle
@ -1216,67 +1246,59 @@ var coreRenderer = function($window) {
if (typeof source.onupdate === "function") hooks.push(callHook.bind(source.onupdate, vnode)) if (typeof source.onupdate === "function") hooks.push(callHook.bind(source.onupdate, vnode))
} }
function shouldNotUpdate(vnode, old) { function shouldNotUpdate(vnode, old) {
var forceVnodeUpdate, forceComponentUpdate do {
if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") { if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") {
forceVnodeUpdate = callHook.call(vnode.attrs.onbeforeupdate, vnode, old) var force = callHook.call(vnode.attrs.onbeforeupdate, vnode, old)
} if (force !== undefined && !force) break
if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeupdate === "function") { }
forceComponentUpdate = callHook.call(vnode.state.onbeforeupdate, vnode, old) if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeupdate === "function") {
} var force = callHook.call(vnode.state.onbeforeupdate, vnode, old)
if (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) { if (force !== undefined && !force) break
vnode.dom = old.dom }
vnode.domSize = old.domSize return false
vnode.instance = old.instance } while (false); // eslint-disable-line no-constant-condition
return true vnode.dom = old.dom
} vnode.domSize = old.domSize
return false vnode.instance = old.instance
return true
} }
function render(dom, vnodes) { function render(dom, vnodes) {
if (!dom) throw new Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.") if (!dom) throw new Error("Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.")
var hooks = [] var hooks = []
var active = $doc.activeElement var active = activeElement()
var namespace = dom.namespaceURI var namespace = dom.namespaceURI
// First time rendering0 into a node clears it out // First time rendering0 into a node clears it out
if (dom.vnodes == null) dom.textContent = "" if (dom.vnodes == null) dom.textContent = ""
if (!Array.isArray(vnodes)) vnodes = [vnodes] vnodes = Vnode.normalizeChildren(Array.isArray(vnodes) ? vnodes : [vnodes])
updateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? undefined : namespace) updateNodes(dom, dom.vnodes, vnodes, hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? undefined : namespace)
dom.vnodes = vnodes dom.vnodes = vnodes
// document.activeElement can return null in IE https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement // `document.activeElement` can return null: https://html.spec.whatwg.org/multipage/interaction.html#dom-document-activeelement
if (active != null && $doc.activeElement !== active && typeof active.focus === "function") active.focus() if (active != null && activeElement() !== active && typeof active.focus === "function") active.focus()
for (var i = 0; i < hooks.length; i++) hooks[i]() for (var i = 0; i < hooks.length; i++) hooks[i]()
} }
return {render: render, setEventCallback: setEventCallback} return {render: render, setRedraw: setRedraw}
} }
function throttle(callback) { function throttle(callback) {
//60fps translates to 16.6ms, round it down since setTimeout requires int var pending = null
var delay = 16
var last = 0, pending = null
var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout
return function() { return function() {
var elapsed = Date.now() - last
if (pending === null) { if (pending === null) {
pending = timeout(function() { pending = requestAnimationFrame(function() {
pending = null pending = null
callback() callback()
last = Date.now() })
}, delay - elapsed)
} }
} }
} }
var _12 = function($window, throttleMock) { var _12 = function($window, throttleMock) {
var renderService = coreRenderer($window) var renderService = coreRenderer($window)
renderService.setEventCallback(function(e) {
if (e.redraw === false) e.redraw = undefined
else redraw()
})
var callbacks = [] var callbacks = []
var rendering = false var rendering = false
function subscribe(key1, callback) { function subscribe(key, callback) {
unsubscribe(key1) unsubscribe(key)
callbacks.push(key1, callback) callbacks.push(key, callback)
} }
function unsubscribe(key1) { function unsubscribe(key) {
var index = callbacks.indexOf(key1) var index = callbacks.indexOf(key)
if (index > -1) callbacks.splice(index, 2) if (index > -1) callbacks.splice(index, 2)
} }
function sync() { function sync() {
@ -1287,6 +1309,7 @@ var _12 = function($window, throttleMock) {
} }
var redraw = (throttleMock || throttle)(sync) var redraw = (throttleMock || throttle)(sync)
redraw.sync = sync redraw.sync = sync
renderService.setRedraw(redraw)
return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render} return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render}
} }
var redrawService = _12(window) var redrawService = _12(window)
@ -1313,40 +1336,40 @@ var Promise = PromisePolyfill
var parseQueryString = function(string) { var parseQueryString = function(string) {
if (string === "" || string == null) return {} if (string === "" || string == null) return {}
if (string.charAt(0) === "?") string = string.slice(1) if (string.charAt(0) === "?") string = string.slice(1)
var entries = string.split("&"), data0 = {}, counters = {} var entries = string.split("&"), data2 = {}, counters = {}
for (var i = 0; i < entries.length; i++) { for (var i = 0; i < entries.length; i++) {
var entry = entries[i].split("=") var entry = entries[i].split("=")
var key5 = decodeURIComponent(entry[0]) var key2 = decodeURIComponent(entry[0])
var value = entry.length === 2 ? decodeURIComponent(entry[1]) : "" var value0 = entry.length === 2 ? decodeURIComponent(entry[1]) : ""
if (value === "true") value = true if (value0 === "true") value0 = true
else if (value === "false") value = false else if (value0 === "false") value0 = false
var levels = key5.split(/\]\[?|\[/) var levels = key2.split(/\]\[?|\[/)
var cursor = data0 var cursor = data2
if (key5.indexOf("[") > -1) levels.pop() if (key2.indexOf("[") > -1) levels.pop()
for (var j0 = 0; j0 < levels.length; j0++) { for (var j0 = 0; j0 < levels.length; j0++) {
var level = levels[j0], nextLevel = levels[j0 + 1] var level = levels[j0], nextLevel = levels[j0 + 1]
var isNumber = nextLevel == "" || !isNaN(parseInt(nextLevel, 10)) var isNumber = nextLevel == "" || !isNaN(parseInt(nextLevel, 10))
var isValue = j0 === levels.length - 1 var isValue = j0 === levels.length - 1
if (level === "") { if (level === "") {
var key5 = levels.slice(0, j0).join() var key2 = levels.slice(0, j0).join()
if (counters[key5] == null) counters[key5] = 0 if (counters[key2] == null) counters[key2] = 0
level = counters[key5]++ level = counters[key2]++
} }
if (cursor[level] == null) { if (cursor[level] == null) {
cursor[level] = isValue ? value : isNumber ? [] : {} cursor[level] = isValue ? value0 : isNumber ? [] : {}
} }
cursor = cursor[level] cursor = cursor[level]
} }
} }
return data0 return data2
} }
var coreRouter = function($window) { var coreRouter = function($window) {
var supportsPushState = typeof $window.history.pushState === "function" var supportsPushState = typeof $window.history.pushState === "function"
var callAsync0 = typeof setImmediate === "function" ? setImmediate : setTimeout var callAsync0 = typeof setImmediate === "function" ? setImmediate : setTimeout
function normalize1(fragment0) { function normalize(fragment0) {
var data = $window.location[fragment0].replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponent) var data1 = $window.location[fragment0].replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponent)
if (fragment0 === "pathname" && data[0] !== "/") data = "/" + data if (fragment0 === "pathname" && data1[0] !== "/") data1 = "/" + data1
return data return data1
} }
var asyncId var asyncId
function debounceAsync(callback) { function debounceAsync(callback) {
@ -1365,11 +1388,11 @@ var coreRouter = function($window) {
if (queryIndex > -1) { if (queryIndex > -1) {
var queryEnd = hashIndex > -1 ? hashIndex : path.length var queryEnd = hashIndex > -1 ? hashIndex : path.length
var queryParams = parseQueryString(path.slice(queryIndex + 1, queryEnd)) var queryParams = parseQueryString(path.slice(queryIndex + 1, queryEnd))
for (var key4 in queryParams) queryData[key4] = queryParams[key4] for (var key1 in queryParams) queryData[key1] = queryParams[key1]
} }
if (hashIndex > -1) { if (hashIndex > -1) {
var hashParams = parseQueryString(path.slice(hashIndex + 1)) var hashParams = parseQueryString(path.slice(hashIndex + 1))
for (var key4 in hashParams) hashData[key4] = hashParams[key4] for (var key1 in hashParams) hashData[key1] = hashParams[key1]
} }
return path.slice(0, pathEnd) return path.slice(0, pathEnd)
} }
@ -1377,19 +1400,19 @@ var coreRouter = function($window) {
router.getPath = function() { router.getPath = function() {
var type2 = router.prefix.charAt(0) var type2 = router.prefix.charAt(0)
switch (type2) { switch (type2) {
case "#": return normalize1("hash").slice(router.prefix.length) case "#": return normalize("hash").slice(router.prefix.length)
case "?": return normalize1("search").slice(router.prefix.length) + normalize1("hash") case "?": return normalize("search").slice(router.prefix.length) + normalize("hash")
default: return normalize1("pathname").slice(router.prefix.length) + normalize1("search") + normalize1("hash") default: return normalize("pathname").slice(router.prefix.length) + normalize("search") + normalize("hash")
} }
} }
router.setPath = function(path, data, options) { router.setPath = function(path, data1, options) {
var queryData = {}, hashData = {} var queryData = {}, hashData = {}
path = parsePath(path, queryData, hashData) path = parsePath(path, queryData, hashData)
if (data != null) { if (data1 != null) {
for (var key4 in data) queryData[key4] = data[key4] for (var key1 in data1) queryData[key1] = data1[key1]
path = path.replace(/:([^\/]+)/g, function(match2, token) { path = path.replace(/:([^\/]+)/g, function(match1, token) {
delete queryData[token] delete queryData[token]
return data[token] return data1[token]
}) })
} }
var query = buildQueryString(queryData) var query = buildQueryString(queryData)
@ -1445,9 +1468,9 @@ var _21 = function($window, redrawService0) {
function run1() { function run1() {
if (render1 != null) redrawService0.render(root, render1(Vnode(component, attrs3.key, attrs3))) if (render1 != null) redrawService0.render(root, render1(Vnode(component, attrs3.key, attrs3)))
} }
var redraw2 = function() { var redraw3 = function() {
run1() run1()
redraw2 = redrawService0.redraw redraw3 = redrawService0.redraw
} }
redrawService0.subscribe(root, run1) redrawService0.subscribe(root, run1)
var bail = function(path) { var bail = function(path) {
@ -1460,7 +1483,7 @@ var _21 = function($window, redrawService0) {
component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div" component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div"
attrs3 = params, currentPath = path, lastUpdate = null attrs3 = params, currentPath = path, lastUpdate = null
render1 = (routeResolver.render || identity).bind(routeResolver) render1 = (routeResolver.render || identity).bind(routeResolver)
redraw2() redraw3()
} }
if (payload.view || typeof payload === "function") update({}, payload) if (payload.view || typeof payload === "function") update({}, payload)
else { else {
@ -1473,16 +1496,16 @@ var _21 = function($window, redrawService0) {
} }
}, bail) }, bail)
} }
route.set = function(path, data, options) { route.set = function(path, data0, options) {
if (lastUpdate != null) { if (lastUpdate != null) {
options = options || {} options = options || {}
options.replace = true options.replace = true
} }
lastUpdate = null lastUpdate = null
routeService.setPath(path, data, options) routeService.setPath(path, data0, options)
} }
route.get = function() {return currentPath} route.get = function() {return currentPath}
route.prefix = function(prefix0) {routeService.prefix = prefix0} route.prefix = function(prefix) {routeService.prefix = prefix}
var link = function(options, vnode1) { var link = function(options, vnode1) {
vnode1.dom.setAttribute("href", routeService.prefix + vnode1.attrs.href) vnode1.dom.setAttribute("href", routeService.prefix + vnode1.attrs.href)
vnode1.dom.onclick = function(e) { vnode1.dom.onclick = function(e) {
@ -1498,28 +1521,24 @@ var _21 = function($window, redrawService0) {
if (args0.tag == null) return link.bind(link, args0) if (args0.tag == null) return link.bind(link, args0)
return link({}, args0) return link({}, args0)
} }
route.param = function(key3) { route.param = function(key0) {
if(typeof attrs3 !== "undefined" && typeof key3 !== "undefined") return attrs3[key3] if(typeof attrs3 !== "undefined" && typeof key0 !== "undefined") return attrs3[key0]
return attrs3 return attrs3
} }
return route return route
} }
m.route = _21(window, redrawService) m.route = _21(window, redrawService)
m.withAttr = function(attrName, callback, context) { var _28 = coreRenderer(window)
return function(e) { m.render = _28.render
callback.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName))
}
}
var _29 = coreRenderer(window)
m.render = _29.render
m.redraw = redrawService.redraw m.redraw = redrawService.redraw
m.request = requestService.request m.request = requestService.request
m.jsonp = requestService.jsonp m.jsonp = requestService.jsonp
m.parseQueryString = parseQueryString m.parseQueryString = parseQueryString
m.buildQueryString = buildQueryString m.buildQueryString = buildQueryString
m.version = "1.1.3" m.version = "2.0.0-rc.1"
m.vnode = Vnode m.vnode = Vnode
m.PromisePolyfill = PromisePolyfill m.PromisePolyfill = PromisePolyfill
export default m export default m
export var m = m.m,trust = m.trust,fragment = m.fragment,mount = m.mount,route = m.route,withAttr = m.withAttr,render = m.render,redraw = m.redraw,request = m.request,jsonp = m.jsonp,parseQueryString = m.parseQueryString,buildQueryString = m.buildQueryString,version = m.version,vnode = m.vnode,PromisePolyfill = m.PromisePolyfill var _m = m.m,_trust = m.trust,_fragment = m.fragment,_mount = m.mount,_route = m.route,_render = m.render,_redraw = m.redraw,_request = m.request,_jsonp = m.jsonp,_parseQueryString = m.parseQueryString,_buildQueryString = m.buildQueryString,_version = m.version,_vnode = m.vnode,_PromisePolyfill = m.PromisePolyfill
export {_m as m,_trust as trust,_fragment as fragment,_mount as mount,_route as route,_render as render,_redraw as redraw,_request as request,_jsonp as jsonp,_parseQueryString as parseQueryString,_buildQueryString as buildQueryString,_version as version,_vnode as vnode,_PromisePolyfill as PromisePolyfill}

View file

@ -1,156 +1,151 @@
/* eslint-enable */ /* eslint-enable */
Stream.SKIP = {}
Stream.lift = lift
Stream.scan = scan
Stream.merge = merge
Stream.combine = combine
Stream.scanMerge = scanMerge
Stream["fantasy-land/of"] = Stream
var guid = 0, HALT = {} let warnedHalt = false
function createStream() { Object.defineProperty(Stream, "HALT", {
function stream() { get: function() {
if (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0]) warnedHalt && console.log("HALT is deprecated and has been renamed to SKIP");
return stream._state.value warnedHalt = true
return Stream.SKIP
} }
initStream(stream) })
if (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0]) function Stream(value) {
var dependentStreams = []
var dependentFns = []
function stream(v) {
if (arguments.length && v !== Stream.SKIP && open(stream)) {
value = v
stream.changing()
stream.state = "active"
dependentStreams.forEach(function(s, i) { s(dependentFns[i](value)) })
}
return value
}
stream.constructor = Stream
stream.state = arguments.length && value !== Stream.SKIP ? "active" : "pending"
stream.changing = function() {
open(stream) && (stream.state = "changing")
dependentStreams.forEach(function(s) {
s.dependent && s.dependent.changing()
s.changing()
})
}
stream.map = function(fn, ignoreInitial) {
var target = stream.state === "active" && ignoreInitial !== Stream.SKIP
? Stream(fn(value))
: Stream()
dependentStreams.push(target)
dependentFns.push(fn)
return target
}
let end
function createEnd() {
end = Stream()
end.map(function(value) {
if (value === true) {
stream.state = "ended"
dependentStreams.length = dependentFns.length = 0
}
return value
})
return end
}
stream.toJSON = function() { return value != null && typeof value.toJSON === "function" ? value.toJSON() : value }
stream["fantasy-land/map"] = stream.map
stream["fantasy-land/ap"] = function(x) { return combine(function(s1, s2) { return s1()(s2()) }, [x, stream]) }
Object.defineProperty(stream, "end", {
get: function() { return end || createEnd() }
})
return stream return stream
} }
function initStream(stream) {
stream.constructor = createStream
stream._state = {id: guid++, value: undefined, state: 0, derive: undefined, recover: undefined, deps: {}, parents: [], endStream: undefined, unregister: undefined}
stream.map = stream["fantasy-land/map"] = map, stream["fantasy-land/ap"] = ap, stream["fantasy-land/of"] = createStream
stream.toJSON = toJSON
Object.defineProperties(stream, {
end: {get: function() {
if (!stream._state.endStream) {
var endStream = createStream()
endStream.map(function(value) {
if (value === true) {
unregisterStream(stream)
endStream._state.unregister = function(){unregisterStream(endStream)}
}
return value
})
stream._state.endStream = endStream
}
return stream._state.endStream
}}
})
}
function updateStream(stream, value) {
updateState(stream, value)
for (var id in stream._state.deps) updateDependency(stream._state.deps[id], false)
if (stream._state.unregister != null) stream._state.unregister()
finalize(stream)
}
function updateState(stream, value) {
stream._state.value = value
stream._state.changed = true
if (stream._state.state !== 2) stream._state.state = 1
}
function updateDependency(stream, mustSync) {
var state = stream._state, parents = state.parents
if (parents.length > 0 && parents.every(active) && (mustSync || parents.some(changed))) {
var value = stream._state.derive()
if (value === HALT) return unregisterStream(stream)
updateState(stream, value)
}
}
function finalize(stream) {
stream._state.changed = false
for (var id in stream._state.deps) stream._state.deps[id]._state.changed = false
}
function combine(fn, streams) { function combine(fn, streams) {
if (!streams.every(valid)) throw new Error("Ensure that each item passed to stream.combine/stream.merge is a stream") var ready = streams.every(function(s) {
return initDependency(createStream(), streams, function() { if (s.constructor !== Stream)
return fn.apply(this, streams.concat([streams.filter(changed)])) throw new Error("Ensure that each item passed to stream.combine/stream.merge/lift is a stream")
return s.state === "active"
}) })
var stream = ready
? Stream(fn.apply(null, streams.concat([streams])))
: Stream()
let changed = []
streams.forEach(function(s) {
s.map(function(value) {
changed.push(s)
if (ready || streams.every(function(s) { return s.state !== "pending" })) {
ready = true
stream(fn.apply(null, streams.concat([changed])))
changed = []
}
return value
}, Stream.SKIP).parent = stream
})
return stream
} }
function initDependency(dep, streams, derive) {
var state = dep._state
state.derive = derive
state.parents = streams.filter(notEnded)
registerDependency(dep, state.parents)
updateDependency(dep, true)
return dep
}
function registerDependency(stream, parents) {
for (var i = 0; i < parents.length; i++) {
parents[i]._state.deps[stream._state.id] = stream
registerDependency(stream, parents[i]._state.parents)
}
}
function unregisterStream(stream) {
for (var i = 0; i < stream._state.parents.length; i++) {
var parent = stream._state.parents[i]
delete parent._state.deps[stream._state.id]
}
for (var id in stream._state.deps) {
var dependent = stream._state.deps[id]
var index = dependent._state.parents.indexOf(stream)
if (index > -1) dependent._state.parents.splice(index, 1)
}
stream._state.state = 2 //ended
stream._state.deps = {}
}
function map(fn) {return combine(function(stream) {return fn(stream())}, [this])}
function ap(stream) {return combine(function(s1, s2) {return s1()(s2())}, [stream, this])}
function toJSON() {return this._state.value != null && typeof this._state.value.toJSON === "function" ? this._state.value.toJSON() : this._state.value}
function valid(stream) {return stream._state }
function active(stream) {return stream._state.state === 1}
function changed(stream) {return stream._state.changed}
function notEnded(stream) {return stream._state.state !== 2}
function merge(streams) { function merge(streams) {
return combine(function() { return combine(function() { return streams.map(function(s) { return s() }) }, streams)
return streams.map(function(s) {return s()})
}, streams)
} }
function scan(reducer, seed, stream) { function scan(fn, acc, origin) {
var newStream = combine(function (s) { var stream = origin.map(function(v) {
var next = reducer(seed, s._state.value) acc = fn(acc, v)
if (next !== HALT) return seed = next return acc
return HALT })
}, [stream]) stream(acc)
return stream
if (newStream._state.state === 0) newStream(seed)
return newStream
} }
function scanMerge(tuples, seed) { function scanMerge(tuples, seed) {
var streams = tuples.map(function(tuple) { var streams = tuples.map(function(tuple) { return tuple[0] })
var stream = tuple[0]
if (stream._state.state === 0) stream(undefined)
return stream
})
var newStream = combine(function() { var stream = combine(function() {
var changed = arguments[arguments.length - 1] var changed = arguments[arguments.length - 1]
streams.forEach(function(stream, i) {
streams.forEach(function(stream, idx) { if (changed.indexOf(stream) > -1)
if (changed.indexOf(stream) > -1) { seed = tuples[i][1](seed, stream())
seed = tuples[idx][1](seed, stream._state.value)
}
}) })
return seed return seed
}, streams) }, streams)
return newStream stream(seed)
return stream
} }
createStream["fantasy-land/of"] = createStream function lift() {
createStream.merge = merge var fn = arguments[0]
createStream.combine = combine var streams = Array.prototype.slice.call(arguments, 1)
createStream.scan = scan return merge(streams).map(function(streams) {
createStream.scanMerge = scanMerge return fn.apply(undefined, streams)
createStream.HALT = HALT })
}
function open(s) {
return s.state === "pending" || s.state === "active" || s.state === "changing"
}
export default createStream export default createStream