Commit ff084f06 authored by Arthur Verschaeve's avatar Arthur Verschaeve

Migrate `mithril` example to `todomvc-app-css`

Ref #1110
parent 095b477a
node_modules/todomvc-app-css/*
!node_modules/todomvc-app-css/index.css
node_modules/todomvc-common/*
!node_modules/todomvc-common/base.js
!node_modules/todomvc-common/base.css
node_modules/mithril/*
!node_modules/mithril/mithril.js
{
"name": "todomvc-mithril",
"version": "0.0.0",
"dependencies": {
"mithril": "0.1.20",
"todomvc-common": "~0.3.0"
}
}
Mithril = m = new function app(window, undefined) {
var type = {}.toString
var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/
function m() {
var args = arguments
var hasAttrs = args[1] !== undefined && type.call(args[1]) == "[object Object]" && !("tag" in args[1]) && !("subtree" in args[1])
var attrs = hasAttrs ? args[1] : {}
var classAttrName = "class" in attrs ? "class" : "className"
var cell = {tag: "div", attrs: {}}
var match, classes = []
while (match = parser.exec(args[0])) {
if (match[1] == "") cell.tag = match[2]
else if (match[1] == "#") cell.attrs.id = match[2]
else if (match[1] == ".") classes.push(match[2])
else if (match[3][0] == "[") {
var pair = attrParser.exec(match[3])
cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" :true)
}
}
if (classes.length > 0) cell.attrs[classAttrName] = classes.join(" ")
cell.children = hasAttrs ? args[2] : args[1]
for (var attrName in attrs) {
if (attrName == classAttrName) cell.attrs[attrName] = (cell.attrs[attrName] || "") + " " + attrs[attrName]
else cell.attrs[attrName] = attrs[attrName]
}
return cell
}
function build(parentElement, parentTag, parentCache, parentIndex, data, cached, shouldReattach, index, editable, namespace, configs) {
//`build` is a recursive function that manages creation/diffing/removal of DOM elements based on comparison between `data` and `cached`
//`parentElement` is a DOM element used for W3C DOM API calls
//`parentTag` is only used for handling a corner case for textarea values
//`parentCache` is used to remove nodes in some multi-node cases
//`parentIndex` and `index` are used to figure out the offset of nodes. They're artifacts from before arrays started being flattened and are likely refactorable
//`data` and `cached` are, respectively, the new and old nodes being diffed
//`shouldReattach` is a flag indicating whether a parent node was recreated (if so, and if this node is reused, then this node must reattach itself to the new parent)
//`editable` is a flag that indicates whether an ancestor is contenteditable
//`namespace` indicates the closest HTML namespace as it cascades down from an ancestor
//`configs` is a list of config functions to run after the topmost `build` call finishes running
//there's logic that relies on the assumption that null and undefined data are equivalent to empty strings
//- this prevents lifecycle surprises from procedural helpers that mix implicit and explicit return statements
//- it simplifies diffing code
if (data === undefined || data === null) data = ""
if (data.subtree === "retain") return cached
var cachedType = type.call(cached), dataType = type.call(data)
if (cached === undefined || cached === null || cachedType != dataType) {
if (cached !== null && cached !== undefined) {
if (parentCache && parentCache.nodes) {
var offset = index - parentIndex
var end = offset + (dataType == "[object Array]" ? data : cached.nodes).length
clear(parentCache.nodes.slice(offset, end), parentCache.slice(offset, end))
}
else if (cached.nodes) clear(cached.nodes, cached)
}
cached = new data.constructor
cached.nodes = []
}
if (dataType == "[object Array]") {
data = flatten(data)
var nodes = [], intact = cached.length === data.length, subArrayCount = 0
//key algorithm: sort elements without recreating them if keys are present
//1) create a map of all existing keys, and mark all for deletion
//2) add new keys to map and mark them for addition
//3) if key exists in new list, change action from deletion to a move
//4) for each key, handle its corresponding action as marked in previous steps
//5) copy unkeyed items into their respective gaps
var DELETION = 1, INSERTION = 2 , MOVE = 3
var existing = {}, unkeyed = [], shouldMaintainIdentities = false
for (var i = 0; i < cached.length; i++) {
if (cached[i] && cached[i].attrs && cached[i].attrs.key !== undefined) {
shouldMaintainIdentities = true
existing[cached[i].attrs.key] = {action: DELETION, index: i}
}
}
if (shouldMaintainIdentities) {
for (var i = 0; i < data.length; i++) {
if (data[i] && data[i].attrs) {
if (data[i].attrs.key !== undefined) {
var key = data[i].attrs.key
if (!existing[key]) existing[key] = {action: INSERTION, index: i}
else existing[key] = {action: MOVE, index: i, from: existing[key].index, element: parentElement.childNodes[existing[key].index]}
}
else unkeyed.push({index: i, element: parentElement.childNodes[i]})
}
}
var actions = Object.keys(existing).map(function(key) {return existing[key]})
var changes = actions.sort(function(a, b) {return a.action - b.action || a.index - b.index})
var newCached = cached.slice()
for (var i = 0, change; change = changes[i]; i++) {
if (change.action == DELETION) {
clear(cached[change.index].nodes, cached[change.index])
newCached.splice(change.index, 1)
}
if (change.action == INSERTION) {
var dummy = window.document.createElement("div")
dummy.key = data[change.index].attrs.key
parentElement.insertBefore(dummy, parentElement.childNodes[change.index])
newCached.splice(change.index, 0, {attrs: {key: data[change.index].attrs.key}, nodes: [dummy]})
}
if (change.action == MOVE) {
if (parentElement.childNodes[change.index] !== change.element && change.element !== null) {
parentElement.insertBefore(change.element, parentElement.childNodes[change.index])
}
newCached[change.index] = cached[change.from]
}
}
for (var i = 0; i < unkeyed.length; i++) {
var change = unkeyed[i]
parentElement.insertBefore(change.element, parentElement.childNodes[change.index])
newCached[change.index] = cached[change.index]
}
cached = newCached
cached.nodes = []
for (var i = 0, child; child = parentElement.childNodes[i]; i++) cached.nodes.push(child)
}
//end key algorithm
for (var i = 0, cacheCount = 0; i < data.length; i++) {
var item = build(parentElement, parentTag, cached, index, data[i], cached[cacheCount], shouldReattach, index + subArrayCount || subArrayCount, editable, namespace, configs)
if (item === undefined) continue
if (!item.nodes.intact) intact = false
var isArray = type.call(item) == "[object Array]"
subArrayCount += isArray ? item.length : 1
cached[cacheCount++] = item
}
if (!intact) {
for (var i = 0; i < data.length; i++) {
if (cached[i] !== undefined) nodes = nodes.concat(cached[i].nodes)
}
for (var i = 0, node; node = cached.nodes[i]; i++) {
if (node.parentNode !== null && nodes.indexOf(node) < 0) node.parentNode.removeChild(node)
}
for (var i = cached.nodes.length, node; node = nodes[i]; i++) {
if (node.parentNode === null) parentElement.appendChild(node)
}
if (data.length < cached.length) cached.length = data.length
cached.nodes = nodes
}
}
else if (data !== undefined && dataType == "[object Object]") {
//if an element is different enough from the one in cache, recreate it
if (data.tag != cached.tag || Object.keys(data.attrs).join() != Object.keys(cached.attrs).join() || data.attrs.id != cached.attrs.id) {
clear(cached.nodes)
if (cached.configContext && typeof cached.configContext.onunload == "function") cached.configContext.onunload()
}
if (typeof data.tag != "string") return
var node, isNew = cached.nodes.length === 0
if (data.attrs.xmlns) namespace = data.attrs.xmlns
else if (data.tag === "svg") namespace = "http://www.w3.org/2000/svg"
else if (data.tag === "math") namespace = "http://www.w3.org/1998/Math/MathML"
if (isNew) {
node = namespace === undefined ? window.document.createElement(data.tag) : window.document.createElementNS(namespace, data.tag)
cached = {
tag: data.tag,
//process children before attrs so that select.value works correctly
children: data.children !== undefined ? build(node, data.tag, undefined, undefined, data.children, cached.children, true, 0, data.attrs.contenteditable ? node : editable, namespace, configs) : [],
attrs: setAttributes(node, data.tag, data.attrs, {}, namespace),
nodes: [node]
}
parentElement.insertBefore(node, parentElement.childNodes[index] || null)
}
else {
node = cached.nodes[0]
setAttributes(node, data.tag, data.attrs, cached.attrs, namespace)
cached.children = data.children !== undefined ? build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs) : []
cached.nodes.intact = true
if (shouldReattach === true && node !== null) parentElement.insertBefore(node, parentElement.childNodes[index] || null)
}
//schedule configs to be called. They are called after `build` finishes running
if (typeof data.attrs["config"] === "function") {
configs.push(data.attrs["config"].bind(window, node, !isNew, cached.configContext = cached.configContext || {}, cached))
}
}
else if (typeof dataType != "function") {
//handle text nodes
var nodes
if (cached.nodes.length === 0) {
if (data.$trusted) {
nodes = injectHTML(parentElement, index, data)
}
else {
nodes = [window.document.createTextNode(data)]
parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null)
}
cached = "string number boolean".indexOf(typeof data) > -1 ? new data.constructor(data) : data
cached.nodes = nodes
}
else if (cached.valueOf() !== data.valueOf() || shouldReattach === true) {
nodes = cached.nodes
if (!editable || editable !== window.document.activeElement) {
if (data.$trusted) {
clear(nodes, cached)
nodes = injectHTML(parentElement, index, data)
}
else {
//corner case: replacing the nodeValue of a text node that is a child of a textarea/contenteditable doesn't work
if (parentTag === "textarea") parentElement.value = data
else if (editable) editable.innerHTML = data
else {
if (nodes[0].nodeType == 1 || nodes.length > 1) { //was a trusted string
clear(cached.nodes, cached)
nodes = [window.document.createTextNode(data)]
}
parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null)
nodes[0].nodeValue = data
}
}
}
cached = new data.constructor(data)
cached.nodes = nodes
}
else cached.nodes.intact = true
}
return cached
}
function setAttributes(node, tag, dataAttrs, cachedAttrs, namespace) {
var groups = {}
for (var attrName in dataAttrs) {
var dataAttr = dataAttrs[attrName]
var cachedAttr = cachedAttrs[attrName]
if (!(attrName in cachedAttrs) || (cachedAttr !== dataAttr) || node === window.document.activeElement) {
cachedAttrs[attrName] = dataAttr
if (attrName === "config") continue
else if (typeof dataAttr == "function" && attrName.indexOf("on") == 0) {
node[attrName] = autoredraw(dataAttr, node)
}
else if (attrName === "style" && typeof dataAttr == "object") {
for (var rule in dataAttr) {
if (cachedAttr === undefined || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule]
}
for (var rule in cachedAttr) {
if (!(rule in dataAttr)) node.style[rule] = ""
}
}
else if (namespace !== undefined) {
if (attrName === "href") node.setAttributeNS("http://www.w3.org/1999/xlink", "href", dataAttr)
else if (attrName === "className") node.setAttribute("class", dataAttr)
else node.setAttribute(attrName, dataAttr)
}
else if (attrName === "value" && tag === "input") {
if (node.value !== dataAttr) node.value = dataAttr
}
else if (attrName in node && !(attrName == "list" || attrName == "style")) {
node[attrName] = dataAttr
}
else node.setAttribute(attrName, dataAttr)
}
}
return cachedAttrs
}
function clear(nodes, cached) {
for (var i = nodes.length - 1; i > -1; i--) {
if (nodes[i] && nodes[i].parentNode) {
nodes[i].parentNode.removeChild(nodes[i])
cached = [].concat(cached)
if (cached[i]) unload(cached[i])
}
}
if (nodes.length != 0) nodes.length = 0
}
function unload(cached) {
if (cached.configContext && typeof cached.configContext.onunload == "function") cached.configContext.onunload()
if (cached.children) {
if (type.call(cached.children) == "[object Array]") for (var i = 0; i < cached.children.length; i++) unload(cached.children[i])
else if (cached.children.tag) unload(cached.children)
}
}
function injectHTML(parentElement, index, data) {
var nextSibling = parentElement.childNodes[index]
if (nextSibling) {
var isElement = nextSibling.nodeType != 1
var placeholder = window.document.createElement("span")
if (isElement) {
parentElement.insertBefore(placeholder, nextSibling)
placeholder.insertAdjacentHTML("beforebegin", data)
parentElement.removeChild(placeholder)
}
else nextSibling.insertAdjacentHTML("beforebegin", data)
}
else parentElement.insertAdjacentHTML("beforeend", data)
var nodes = []
while (parentElement.childNodes[index] !== nextSibling) {
nodes.push(parentElement.childNodes[index])
index++
}
return nodes
}
function flatten(data) {
var flattened = []
for (var i = 0; i < data.length; i++) {
var item = data[i]
if (type.call(item) == "[object Array]") flattened.push.apply(flattened, flatten(item))
else flattened.push(item)
}
return flattened
}
function autoredraw(callback, object, group) {
return function(e) {
e = e || event
m.redraw.strategy("diff")
m.startComputation()
try {return callback.call(object, e)}
finally {
if (!lastRedrawId) lastRedrawId = -1;
m.endComputation()
}
}
}
var html
var documentNode = {
insertAdjacentHTML: function(_, data) {
window.document.write(data)
window.document.close()
},
appendChild: function(node) {
if (html === undefined) html = window.document.createElement("html")
if (node.nodeName == "HTML") html = node
else html.appendChild(node)
if (window.document.documentElement && window.document.documentElement !== html) {
window.document.replaceChild(html, window.document.documentElement)
}
else window.document.appendChild(html)
},
insertBefore: function(node) {
this.appendChild(node)
},
childNodes: []
}
var nodeCache = [], cellCache = {}
m.render = function(root, cell, forceRecreation) {
var configs = []
if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it.")
var id = getCellCacheKey(root)
var node = root == window.document || root == window.document.documentElement ? documentNode : root
if (cellCache[id] === undefined) clear(node.childNodes)
if (forceRecreation === true) reset(root)
cellCache[id] = build(node, null, undefined, undefined, cell, cellCache[id], false, 0, null, undefined, configs)
for (var i = 0; i < configs.length; i++) configs[i]()
}
function getCellCacheKey(element) {
var index = nodeCache.indexOf(element)
return index < 0 ? nodeCache.push(element) - 1 : index
}
m.trust = function(value) {
value = new String(value)
value.$trusted = true
return value
}
m.prop = function(store) {
var prop = function() {
if (arguments.length) store = arguments[0]
return store
}
prop.toJSON = function() {
return store
}
return prop
}
var roots = [], modules = [], controllers = [], lastRedrawId = 0, computePostRedrawHook = null, prevented = false
m.module = function(root, module) {
var index = roots.indexOf(root)
if (index < 0) index = roots.length
var isPrevented = false
if (controllers[index] && typeof controllers[index].onunload == "function") {
var event = {
preventDefault: function() {isPrevented = true}
}
controllers[index].onunload(event)
}
if (!isPrevented) {
m.redraw.strategy("all")
m.startComputation()
roots[index] = root
modules[index] = module
controllers[index] = new module.controller
m.endComputation()
}
}
m.redraw = function() {
var cancel = window.cancelAnimationFrame || window.clearTimeout
var defer = window.requestAnimationFrame || window.setTimeout
if (lastRedrawId) {
cancel(lastRedrawId)
lastRedrawId = defer(redraw, 0)
}
else {
redraw()
lastRedrawId = defer(function() {lastRedrawId = null}, 0)
}
}
m.redraw.strategy = m.prop()
function redraw() {
var mode = m.redraw.strategy()
for (var i = 0; i < roots.length; i++) {
if (controllers[i] && mode != "none") m.render(roots[i], modules[i].view(controllers[i]), mode == "all")
}
if (computePostRedrawHook) {
computePostRedrawHook()
computePostRedrawHook = null
}
lastRedrawId = null
m.redraw.strategy("diff")
}
var pendingRequests = 0
m.startComputation = function() {pendingRequests++}
m.endComputation = function() {
pendingRequests = Math.max(pendingRequests - 1, 0)
if (pendingRequests == 0) m.redraw()
}
m.withAttr = function(prop, withAttrCallback) {
return function(e) {
e = e || event
var currentTarget = e.currentTarget || this
withAttrCallback(prop in currentTarget ? currentTarget[prop] : currentTarget.getAttribute(prop))
}
}
//routing
var modes = {pathname: "", hash: "#", search: "?"}
var redirect = function() {}, routeParams = {}, currentRoute
m.route = function() {
if (arguments.length === 0) return currentRoute
else if (arguments.length === 3 && typeof arguments[1] == "string") {
var root = arguments[0], defaultRoute = arguments[1], router = arguments[2]
redirect = function(source) {
var path = currentRoute = normalizeRoute(source)
if (!routeByValue(root, router, path)) {
m.route(defaultRoute, true)
}
}
var listener = m.route.mode == "hash" ? "onhashchange" : "onpopstate"
window[listener] = function() {
if (currentRoute != normalizeRoute(window.location[m.route.mode])) {
redirect(window.location[m.route.mode])
}
}
computePostRedrawHook = setScroll
window[listener]()
}
else if (arguments[0].addEventListener) {
var element = arguments[0]
var isInitialized = arguments[1]
if (element.href.indexOf(modes[m.route.mode]) < 0) {
element.href = window.location.pathname + modes[m.route.mode] + element.pathname
}
if (!isInitialized) {
element.removeEventListener("click", routeUnobtrusive)
element.addEventListener("click", routeUnobtrusive)
}
}
else if (typeof arguments[0] == "string") {
currentRoute = arguments[0]
var querystring = typeof arguments[1] == "object" ? buildQueryString(arguments[1]) : null
if (querystring) currentRoute += (currentRoute.indexOf("?") === -1 ? "?" : "&") + querystring
var shouldReplaceHistoryEntry = (arguments.length == 3 ? arguments[2] : arguments[1]) === true
if (window.history.pushState) {
computePostRedrawHook = function() {
window.history[shouldReplaceHistoryEntry ? "replaceState" : "pushState"](null, window.document.title, modes[m.route.mode] + currentRoute)
setScroll()
}
redirect(modes[m.route.mode] + currentRoute)
}
else window.location[m.route.mode] = currentRoute
}
}
m.route.param = function(key) {return routeParams[key]}
m.route.mode = "search"
function normalizeRoute(route) {return route.slice(modes[m.route.mode].length)}
function routeByValue(root, router, path) {
routeParams = {}
var queryStart = path.indexOf("?")
if (queryStart !== -1) {
routeParams = parseQueryString(path.substr(queryStart + 1, path.length))
path = path.substr(0, queryStart)
}
for (var route in router) {
if (route == path) {
m.module(root, router[route])
return true
}
var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$")
if (matcher.test(path)) {
path.replace(matcher, function() {
var keys = route.match(/:[^\/]+/g) || []
var values = [].slice.call(arguments, 1, -2)
for (var i = 0; i < keys.length; i++) routeParams[keys[i].replace(/:|\./g, "")] = decodeSpace(values[i])
m.module(root, router[route])
})
return true
}
}
}
function routeUnobtrusive(e) {
e = e || event
if (e.ctrlKey || e.metaKey || e.which == 2) return
e.preventDefault()
m.route(e.currentTarget[m.route.mode].slice(modes[m.route.mode].length))
}
function setScroll() {
if (m.route.mode != "hash" && window.location.hash) window.location.hash = window.location.hash
else window.scrollTo(0, 0)
}
function buildQueryString(object, prefix) {
var str = []
for(var prop in object) {
var key = prefix ? prefix + "[" + prop + "]" : prop, value = object[prop]
str.push(typeof value == "object" ? buildQueryString(value, key) : encodeURIComponent(key) + "=" + encodeURIComponent(value))
}
return str.join("&")
}
function parseQueryString(str) {
var pairs = str.split("&"), params = {}
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=")
params[decodeSpace(pair[0])] = pair[1] ? decodeSpace(pair[1]) : (pair.length === 1 ? true : "")
}
return params
}
function decodeSpace(string) {
return decodeURIComponent(string.replace(/\+/g, " "))
}
function reset(root) {
var cacheKey = getCellCacheKey(root)
clear(root.childNodes, cellCache[cacheKey])
cellCache[cacheKey] = undefined
}
var none = {}
m.deferred = function() {
var resolvers = [], rejecters = [], resolved = none, rejected = none, promise = m.prop()
var object = {
resolve: function(value) {
if (resolved === none) promise(resolved = value)
for (var i = 0; i < resolvers.length; i++) resolvers[i](value)
resolvers.length = rejecters.length = 0
},
reject: function(value) {
if (rejected === none) rejected = value
for (var i = 0; i < rejecters.length; i++) rejecters[i](value)
resolvers.length = rejecters.length = 0
},
promise: promise
}
object.promise.resolvers = resolvers
object.promise.then = function(success, error) {
var next = m.deferred()
if (!success) success = identity
if (!error) error = identity
function callback(method, callback) {
return function(value) {
try {
var result = callback(value)
if (result && typeof result.then == "function") result.then(next[method], error)
else next[method](result !== undefined ? result : value)
}
catch (e) {
if (type.call(e) == "[object Error]" && e.constructor !== Error) throw e
else next.reject(e)
}
}
}
if (resolved !== none) callback("resolve", success)(resolved)
else if (rejected !== none) callback("reject", error)(rejected)
else {
resolvers.push(callback("resolve", success))
rejecters.push(callback("reject", error))
}
return next.promise
}
return object
}
m.sync = function(args) {
var method = "resolve"
function synchronizer(pos, resolved) {
return function(value) {
results[pos] = value
if (!resolved) method = "reject"
if (--outstanding == 0) {
deferred.promise(results)
deferred[method](results)
}
return value
}
}
var deferred = m.deferred()
var outstanding = args.length
var results = new Array(outstanding)
if (args.length > 0) {
for (var i = 0; i < args.length; i++) {
args[i].then(synchronizer(i, true), synchronizer(i, false))
}
}
else deferred.resolve()
return deferred.promise
}
function identity(value) {return value}
function ajax(options) {
var xhr = new window.XMLHttpRequest
xhr.open(options.method, options.url, true, options.user, options.password)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) options.onload({type: "load", target: xhr})
else options.onerror({type: "error", target: xhr})
}
}
if (options.serialize == JSON.stringify && options.method != "GET") {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
}
if (typeof options.config == "function") {
var maybeXhr = options.config(xhr, options)
if (maybeXhr !== undefined) xhr = maybeXhr
}
xhr.send(options.method == "GET" ? "" : options.data)
return xhr
}
function bindData(xhrOptions, data, serialize) {
if (data && Object.keys(data).length > 0) {
if (xhrOptions.method == "GET") {
xhrOptions.url = xhrOptions.url + (xhrOptions.url.indexOf("?") < 0 ? "?" : "&") + buildQueryString(data)
}
else xhrOptions.data = serialize(data)
}
return xhrOptions
}
function parameterizeUrl(url, data) {
var tokens = url.match(/:[a-z]\w+/gi)
if (tokens && data) {
for (var i = 0; i < tokens.length; i++) {
var key = tokens[i].slice(1)
url = url.replace(tokens[i], data[key])
delete data[key]
}
}
return url
}
m.request = function(xhrOptions) {
if (xhrOptions.background !== true) m.startComputation()
var deferred = m.deferred()
var serialize = xhrOptions.serialize = xhrOptions.serialize || JSON.stringify
var deserialize = xhrOptions.deserialize = xhrOptions.deserialize || JSON.parse
var extract = xhrOptions.extract || function(xhr) {
return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText
}
xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data)
xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize)
xhrOptions.onload = xhrOptions.onerror = function(e) {
try {
e = e || event
var unwrap = (e.type == "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity
var response = unwrap(deserialize(extract(e.target, xhrOptions)))
if (e.type == "load") {
if (type.call(response) == "[object Array]" && xhrOptions.type) {
for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i])
}
else if (xhrOptions.type) response = new xhrOptions.type(response)
}
deferred[e.type == "load" ? "resolve" : "reject"](response)
}
catch (e) {
if (e instanceof SyntaxError) throw new SyntaxError("Could not parse HTTP response. See http://lhorie.github.io/mithril/mithril.request.html#using-variable-data-formats")
else if (type.call(e) == "[object Error]" && e.constructor !== Error) throw e
else deferred.reject(e)
}
if (xhrOptions.background !== true) m.endComputation()
}
ajax(xhrOptions)
return deferred.promise
}
//testing API
m.deps = function(mock) {return window = mock}
//for internal testing only, do not use `m.deps.factory`
m.deps.factory = app
return m
}(typeof window != "undefined" ? window : {})
if (typeof module != "undefined" && module !== null) module.exports = m
if (typeof define == "function" && define.amd) define(function() {return m})
;;;
......@@ -3,7 +3,8 @@
<head>
<meta charset="utf-8">
<title>Mithril • TodoMVC</title>
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
</head>
<body>
<section id="todoapp"></section>
......@@ -13,8 +14,8 @@
href="https://github.com/lhorie/">Leo Horie</a>)</p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/mithril/mithril.js"></script>
<script src="node_modules/todomvc-common/base.js"></script>
<script src="node_modules/mithril/mithril.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/models/storage.js"></script>
<script src="js/controllers/todo.js"></script>
......
var m = (function app(window, undefined) {
var OBJECT = "[object Object]", ARRAY = "[object Array]", STRING = "[object String]", FUNCTION = "function";
var type = {}.toString;
var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/;
var voidElements = /^(AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR)$/;
// caching commonly used variables
var $document, $location, $requestAnimationFrame, $cancelAnimationFrame;
// self invoking function needed because of the way mocks work
function initialize(window){
$document = window.document;
$location = window.location;
$cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout;
$requestAnimationFrame = window.requestAnimationFrame || window.setTimeout;
}
initialize(window);
/**
* @typedef {String} Tag
* A string that looks like -> div.classname#id[param=one][param2=two]
* Which describes a DOM node
*/
/**
*
* @param {Tag} The DOM node tag
* @param {Object=[]} optional key-value pairs to be mapped to DOM attrs
* @param {...mNode=[]} Zero or more Mithril child nodes. Can be an array, or splat (optional)
*
*/
function m() {
var args = [].slice.call(arguments);
var hasAttrs = args[1] != null && type.call(args[1]) === OBJECT && !("tag" in args[1]) && !("subtree" in args[1]);
var attrs = hasAttrs ? args[1] : {};
var classAttrName = "class" in attrs ? "class" : "className";
var cell = {tag: "div", attrs: {}};
var match, classes = [];
if (type.call(args[0]) != STRING) throw new Error("selector in m(selector, attrs, children) should be a string")
while (match = parser.exec(args[0])) {
if (match[1] === "" && match[2]) cell.tag = match[2];
else if (match[1] === "#") cell.attrs.id = match[2];
else if (match[1] === ".") classes.push(match[2]);
else if (match[3][0] === "[") {
var pair = attrParser.exec(match[3]);
cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" :true)
}
}
if (classes.length > 0) cell.attrs[classAttrName] = classes.join(" ");
var children = hasAttrs ? args[2] : args[1];
if (type.call(children) === ARRAY) {
cell.children = children
}
else {
cell.children = hasAttrs ? args.slice(2) : args.slice(1)
}
for (var attrName in attrs) {
if (attrName === classAttrName) {
if (attrs[attrName] !== "") cell.attrs[attrName] = (cell.attrs[attrName] || "") + " " + attrs[attrName];
}
else cell.attrs[attrName] = attrs[attrName]
}
return cell
}
function build(parentElement, parentTag, parentCache, parentIndex, data, cached, shouldReattach, index, editable, namespace, configs) {
//`build` is a recursive function that manages creation/diffing/removal of DOM elements based on comparison between `data` and `cached`
//the diff algorithm can be summarized as this:
//1 - compare `data` and `cached`
//2 - if they are different, copy `data` to `cached` and update the DOM based on what the difference is
//3 - recursively apply this algorithm for every array and for the children of every virtual element
//the `cached` data structure is essentially the same as the previous redraw's `data` data structure, with a few additions:
//- `cached` always has a property called `nodes`, which is a list of DOM elements that correspond to the data represented by the respective virtual element
//- in order to support attaching `nodes` as a property of `cached`, `cached` is *always* a non-primitive object, i.e. if the data was a string, then cached is a String instance. If data was `null` or `undefined`, cached is `new String("")`
//- `cached also has a `configContext` property, which is the state storage object exposed by config(element, isInitialized, context)
//- when `cached` is an Object, it represents a virtual element; when it's an Array, it represents a list of elements; when it's a String, Number or Boolean, it represents a text node
//`parentElement` is a DOM element used for W3C DOM API calls
//`parentTag` is only used for handling a corner case for textarea values
//`parentCache` is used to remove nodes in some multi-node cases
//`parentIndex` and `index` are used to figure out the offset of nodes. They're artifacts from before arrays started being flattened and are likely refactorable
//`data` and `cached` are, respectively, the new and old nodes being diffed
//`shouldReattach` is a flag indicating whether a parent node was recreated (if so, and if this node is reused, then this node must reattach itself to the new parent)
//`editable` is a flag that indicates whether an ancestor is contenteditable
//`namespace` indicates the closest HTML namespace as it cascades down from an ancestor
//`configs` is a list of config functions to run after the topmost `build` call finishes running
//there's logic that relies on the assumption that null and undefined data are equivalent to empty strings
//- this prevents lifecycle surprises from procedural helpers that mix implicit and explicit return statements (e.g. function foo() {if (cond) return m("div")}
//- it simplifies diffing code
//data.toString() is null if data is the return value of Console.log in Firefox
if (data == null || data.toString() == null) data = "";
if (data.subtree === "retain") return cached;
var cachedType = type.call(cached), dataType = type.call(data);
if (cached == null || cachedType !== dataType) {
if (cached != null) {
if (parentCache && parentCache.nodes) {
var offset = index - parentIndex;
var end = offset + (dataType === ARRAY ? data : cached.nodes).length;
clear(parentCache.nodes.slice(offset, end), parentCache.slice(offset, end))
}
else if (cached.nodes) clear(cached.nodes, cached)
}
cached = new data.constructor;
if (cached.tag) cached = {}; //if constructor creates a virtual dom element, use a blank object as the base cached node instead of copying the virtual el (#277)
cached.nodes = []
}
if (dataType === ARRAY) {
//recursively flatten array
for (var i = 0, len = data.length; i < len; i++) {
if (type.call(data[i]) === ARRAY) {
data = data.concat.apply([], data);
i-- //check current index again and flatten until there are no more nested arrays at that index
}
}
var nodes = [], intact = cached.length === data.length, subArrayCount = 0;
//keys algorithm: sort elements without recreating them if keys are present
//1) create a map of all existing keys, and mark all for deletion
//2) add new keys to map and mark them for addition
//3) if key exists in new list, change action from deletion to a move
//4) for each key, handle its corresponding action as marked in previous steps
//5) copy unkeyed items into their respective gaps
var DELETION = 1, INSERTION = 2 , MOVE = 3;
var existing = {}, unkeyed = [], shouldMaintainIdentities = false;
for (var i = 0; i < cached.length; i++) {
if (cached[i] && cached[i].attrs && cached[i].attrs.key != null) {
shouldMaintainIdentities = true;
existing[cached[i].attrs.key] = {action: DELETION, index: i}
}
}
if (shouldMaintainIdentities) {
if (data.indexOf(null) > -1) data = data.filter(function(x) {return x != null})
var keysDiffer = false
if (data.length != cached.length) keysDiffer = true
else for (var i = 0, cachedCell, dataCell; cachedCell = cached[i], dataCell = data[i]; i++) {
if (cachedCell.attrs && dataCell.attrs && cachedCell.attrs.key != dataCell.attrs.key) {
keysDiffer = true
break
}
}
if (keysDiffer) {
for (var i = 0, len = data.length; i < len; i++) {
if (data[i] && data[i].attrs) {
if (data[i].attrs.key != null) {
var key = data[i].attrs.key;
if (!existing[key]) existing[key] = {action: INSERTION, index: i};
else existing[key] = {
action: MOVE,
index: i,
from: existing[key].index,
element: cached.nodes[existing[key].index] || $document.createElement("div")
}
}
else unkeyed.push({index: i, element: parentElement.childNodes[i] || $document.createElement("div")})
}
}
var actions = []
for (var prop in existing) actions.push(existing[prop])
var changes = actions.sort(sortChanges);
var newCached = new Array(cached.length)
for (var i = 0, change; change = changes[i]; i++) {
if (change.action === DELETION) {
clear(cached[change.index].nodes, cached[change.index]);
newCached.splice(change.index, 1)
}
if (change.action === INSERTION) {
var dummy = $document.createElement("div");
dummy.key = data[change.index].attrs.key;
parentElement.insertBefore(dummy, parentElement.childNodes[change.index] || null);
newCached.splice(change.index, 0, {attrs: {key: data[change.index].attrs.key}, nodes: [dummy]})
}
if (change.action === MOVE) {
if (parentElement.childNodes[change.index] !== change.element && change.element !== null) {
parentElement.insertBefore(change.element, parentElement.childNodes[change.index] || null)
}
newCached[change.index] = cached[change.from]
}
}
for (var i = 0, len = unkeyed.length; i < len; i++) {
var change = unkeyed[i];
parentElement.insertBefore(change.element, parentElement.childNodes[change.index] || null);
newCached[change.index] = cached[change.index]
}
cached = newCached;
cached.nodes = new Array(parentElement.childNodes.length);
for (var i = 0, child; child = parentElement.childNodes[i]; i++) cached.nodes[i] = child
}
}
//end key algorithm
for (var i = 0, cacheCount = 0, len = data.length; i < len; i++) {
//diff each item in the array
var item = build(parentElement, parentTag, cached, index, data[i], cached[cacheCount], shouldReattach, index + subArrayCount || subArrayCount, editable, namespace, configs);
if (item === undefined) continue;
if (!item.nodes.intact) intact = false;
if (item.$trusted) {
//fix offset of next element if item was a trusted string w/ more than one html element
//the first clause in the regexp matches elements
//the second clause (after the pipe) matches text nodes
subArrayCount += (item.match(/<[^\/]|\>\s*[^<]/g) || []).length
}
else subArrayCount += type.call(item) === ARRAY ? item.length : 1;
cached[cacheCount++] = item
}
if (!intact) {
//diff the array itself
//update the list of DOM nodes by collecting the nodes from each item
for (var i = 0, len = data.length; i < len; i++) {
if (cached[i] != null) nodes.push.apply(nodes, cached[i].nodes)
}
//remove items from the end of the array if the new array is shorter than the old one
//if errors ever happen here, the issue is most likely a bug in the construction of the `cached` data structure somewhere earlier in the program
for (var i = 0, node; node = cached.nodes[i]; i++) {
if (node.parentNode != null && nodes.indexOf(node) < 0) clear([node], [cached[i]])
}
if (data.length < cached.length) cached.length = data.length;
cached.nodes = nodes
}
}
else if (data != null && dataType === OBJECT) {
if (!data.attrs) data.attrs = {};
if (!cached.attrs) cached.attrs = {};
var dataAttrKeys = Object.keys(data.attrs)
var hasKeys = dataAttrKeys.length > ("key" in data.attrs ? 1 : 0)
//if an element is different enough from the one in cache, recreate it
if (data.tag != cached.tag || dataAttrKeys.join() != Object.keys(cached.attrs).join() || data.attrs.id != cached.attrs.id) {
if (cached.nodes.length) clear(cached.nodes);
if (cached.configContext && typeof cached.configContext.onunload === FUNCTION) cached.configContext.onunload()
}
if (type.call(data.tag) != STRING) return;
var node, isNew = cached.nodes.length === 0;
if (data.attrs.xmlns) namespace = data.attrs.xmlns;
else if (data.tag === "svg") namespace = "http://www.w3.org/2000/svg";
else if (data.tag === "math") namespace = "http://www.w3.org/1998/Math/MathML";
if (isNew) {
if (data.attrs.is) node = namespace === undefined ? $document.createElement(data.tag, data.attrs.is) : $document.createElementNS(namespace, data.tag, data.attrs.is);
else node = namespace === undefined ? $document.createElement(data.tag) : $document.createElementNS(namespace, data.tag);
cached = {
tag: data.tag,
//set attributes first, then create children
attrs: hasKeys ? setAttributes(node, data.tag, data.attrs, {}, namespace) : data.attrs,
children: data.children != null && data.children.length > 0 ?
build(node, data.tag, undefined, undefined, data.children, cached.children, true, 0, data.attrs.contenteditable ? node : editable, namespace, configs) :
data.children,
nodes: [node]
};
if (cached.children && !cached.children.nodes) cached.children.nodes = [];
//edge case: setting value on <select> doesn't work before children exist, so set it again after children have been created
if (data.tag === "select" && data.attrs.value) setAttributes(node, data.tag, {value: data.attrs.value}, {}, namespace);
parentElement.insertBefore(node, parentElement.childNodes[index] || null)
}
else {
node = cached.nodes[0];
if (hasKeys) setAttributes(node, data.tag, data.attrs, cached.attrs, namespace);
cached.children = build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs);
cached.nodes.intact = true;
if (shouldReattach === true && node != null) parentElement.insertBefore(node, parentElement.childNodes[index] || null)
}
//schedule configs to be called. They are called after `build` finishes running
if (typeof data.attrs["config"] === FUNCTION) {
var context = cached.configContext = cached.configContext || {};
// bind
var callback = function(data, args) {
return function() {
return data.attrs["config"].apply(data, args)
}
};
configs.push(callback(data, [node, !isNew, context, cached]))
}
}
else if (typeof dataType != FUNCTION) {
//handle text nodes
var nodes;
if (cached.nodes.length === 0) {
if (data.$trusted) {
nodes = injectHTML(parentElement, index, data)
}
else {
nodes = [$document.createTextNode(data)];
if (!parentElement.nodeName.match(voidElements)) parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null)
}
cached = "string number boolean".indexOf(typeof data) > -1 ? new data.constructor(data) : data;
cached.nodes = nodes
}
else if (cached.valueOf() !== data.valueOf() || shouldReattach === true) {
nodes = cached.nodes;
if (!editable || editable !== $document.activeElement) {
if (data.$trusted) {
clear(nodes, cached);
nodes = injectHTML(parentElement, index, data)
}
else {
//corner case: replacing the nodeValue of a text node that is a child of a textarea/contenteditable doesn't work
//we need to update the value property of the parent textarea or the innerHTML of the contenteditable element instead
if (parentTag === "textarea") parentElement.value = data;
else if (editable) editable.innerHTML = data;
else {
if (nodes[0].nodeType === 1 || nodes.length > 1) { //was a trusted string
clear(cached.nodes, cached);
nodes = [$document.createTextNode(data)]
}
parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null);
nodes[0].nodeValue = data
}
}
}
cached = new data.constructor(data);
cached.nodes = nodes
}
else cached.nodes.intact = true
}
return cached
}
function sortChanges(a, b) {return a.action - b.action || a.index - b.index}
function setAttributes(node, tag, dataAttrs, cachedAttrs, namespace) {
for (var attrName in dataAttrs) {
var dataAttr = dataAttrs[attrName];
var cachedAttr = cachedAttrs[attrName];
if (!(attrName in cachedAttrs) || (cachedAttr !== dataAttr)) {
cachedAttrs[attrName] = dataAttr;
try {
//`config` isn't a real attributes, so ignore it
if (attrName === "config" || attrName == "key") continue;
//hook event handlers to the auto-redrawing system
else if (typeof dataAttr === FUNCTION && attrName.indexOf("on") === 0) {
node[attrName] = autoredraw(dataAttr, node)
}
//handle `style: {...}`
else if (attrName === "style" && dataAttr != null && type.call(dataAttr) === OBJECT) {
for (var rule in dataAttr) {
if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule]
}
for (var rule in cachedAttr) {
if (!(rule in dataAttr)) node.style[rule] = ""
}
}
//handle SVG
else if (namespace != null) {
if (attrName === "href") node.setAttributeNS("http://www.w3.org/1999/xlink", "href", dataAttr);
else if (attrName === "className") node.setAttribute("class", dataAttr);
else node.setAttribute(attrName, dataAttr)
}
//handle cases that are properties (but ignore cases where we should use setAttribute instead)
//- list and form are typically used as strings, but are DOM element references in js
//- when using CSS selectors (e.g. `m("[style='']")`), style is used as a string, but it's an object in js
else if (attrName in node && !(attrName === "list" || attrName === "style" || attrName === "form" || attrName === "type")) {
//#348 don't set the value if not needed otherwise cursor placement breaks in Chrome
if (tag !== "input" || node[attrName] !== dataAttr) node[attrName] = dataAttr
}
else node.setAttribute(attrName, dataAttr)
}
catch (e) {
//swallow IE's invalid argument errors to mimic HTML's fallback-to-doing-nothing-on-invalid-attributes behavior
if (e.message.indexOf("Invalid argument") < 0) throw e
}
}
//#348 dataAttr may not be a string, so use loose comparison (double equal) instead of strict (triple equal)
else if (attrName === "value" && tag === "input" && node.value != dataAttr) {
node.value = dataAttr
}
}
return cachedAttrs
}
function clear(nodes, cached) {
for (var i = nodes.length - 1; i > -1; i--) {
if (nodes[i] && nodes[i].parentNode) {
try {nodes[i].parentNode.removeChild(nodes[i])}
catch (e) {} //ignore if this fails due to order of events (see http://stackoverflow.com/questions/21926083/failed-to-execute-removechild-on-node)
cached = [].concat(cached);
if (cached[i]) unload(cached[i])
}
}
if (nodes.length != 0) nodes.length = 0
}
function unload(cached) {
if (cached.configContext && typeof cached.configContext.onunload === FUNCTION) cached.configContext.onunload();
if (cached.children) {
if (type.call(cached.children) === ARRAY) {
for (var i = 0, child; child = cached.children[i]; i++) unload(child)
}
else if (cached.children.tag) unload(cached.children)
}
}
function injectHTML(parentElement, index, data) {
var nextSibling = parentElement.childNodes[index];
if (nextSibling) {
var isElement = nextSibling.nodeType != 1;
var placeholder = $document.createElement("span");
if (isElement) {
parentElement.insertBefore(placeholder, nextSibling || null);
placeholder.insertAdjacentHTML("beforebegin", data);
parentElement.removeChild(placeholder)
}
else nextSibling.insertAdjacentHTML("beforebegin", data)
}
else parentElement.insertAdjacentHTML("beforeend", data);
var nodes = [];
while (parentElement.childNodes[index] !== nextSibling) {
nodes.push(parentElement.childNodes[index]);
index++
}
return nodes
}
function autoredraw(callback, object) {
return function(e) {
e = e || event;
m.redraw.strategy("diff");
m.startComputation();
try {return callback.call(object, e)}
finally {
endFirstComputation()
}
}
}
var html;
var documentNode = {
appendChild: function(node) {
if (html === undefined) html = $document.createElement("html");
if ($document.documentElement && $document.documentElement !== node) {
$document.replaceChild(node, $document.documentElement)
}
else $document.appendChild(node);
this.childNodes = $document.childNodes
},
insertBefore: function(node) {
this.appendChild(node)
},
childNodes: []
};
var nodeCache = [], cellCache = {};
m.render = function(root, cell, forceRecreation) {
var configs = [];
if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it.");
var id = getCellCacheKey(root);
var isDocumentRoot = root === $document;
var node = isDocumentRoot || root === $document.documentElement ? documentNode : root;
if (isDocumentRoot && cell.tag != "html") cell = {tag: "html", attrs: {}, children: cell};
if (cellCache[id] === undefined) clear(node.childNodes);
if (forceRecreation === true) reset(root);
cellCache[id] = build(node, null, undefined, undefined, cell, cellCache[id], false, 0, null, undefined, configs);
for (var i = 0, len = configs.length; i < len; i++) configs[i]()
};
function getCellCacheKey(element) {
var index = nodeCache.indexOf(element);
return index < 0 ? nodeCache.push(element) - 1 : index
}
m.trust = function(value) {
value = new String(value);
value.$trusted = true;
return value
};
function gettersetter(store) {
var prop = function() {
if (arguments.length) store = arguments[0];
return store
};
prop.toJSON = function() {
return store
};
return prop
}
m.prop = function (store) {
//note: using non-strict equality check here because we're checking if store is null OR undefined
if (((store != null && type.call(store) === OBJECT) || typeof store === FUNCTION) && typeof store.then === FUNCTION) {
return propify(store)
}
return gettersetter(store)
};
var roots = [], modules = [], controllers = [], lastRedrawId = null, lastRedrawCallTime = 0, computePostRedrawHook = null, prevented = false, topModule;
var FRAME_BUDGET = 16; //60 frames per second = 1 call per 16 ms
m.module = function(root, module) {
if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it.");
var index = roots.indexOf(root);
if (index < 0) index = roots.length;
var isPrevented = false;
if (controllers[index] && typeof controllers[index].onunload === FUNCTION) {
var event = {
preventDefault: function() {isPrevented = true}
};
controllers[index].onunload(event)
}
if (!isPrevented) {
m.redraw.strategy("all");
m.startComputation();
roots[index] = root;
var currentModule = topModule = module = module || {};
var controller = new (module.controller || function() {});
//controllers may call m.module recursively (via m.route redirects, for example)
//this conditional ensures only the last recursive m.module call is applied
if (currentModule === topModule) {
controllers[index] = controller;
modules[index] = module
}
endFirstComputation();
return controllers[index]
}
};
m.redraw = function(force) {
//lastRedrawId is a positive number if a second redraw is requested before the next animation frame
//lastRedrawID is null if it's the first redraw and not an event handler
if (lastRedrawId && force !== true) {
//when setTimeout: only reschedule redraw if time between now and previous redraw is bigger than a frame, otherwise keep currently scheduled timeout
//when rAF: always reschedule redraw
if (new Date - lastRedrawCallTime > FRAME_BUDGET || $requestAnimationFrame === window.requestAnimationFrame) {
if (lastRedrawId > 0) $cancelAnimationFrame(lastRedrawId);
lastRedrawId = $requestAnimationFrame(redraw, FRAME_BUDGET)
}
}
else {
redraw();
lastRedrawId = $requestAnimationFrame(function() {lastRedrawId = null}, FRAME_BUDGET)
}
};
m.redraw.strategy = m.prop();
var blank = function() {return ""}
function redraw() {
var forceRedraw = m.redraw.strategy() === "all";
for (var i = 0, root; root = roots[i]; i++) {
if (controllers[i]) {
m.render(root, modules[i].view ? modules[i].view(controllers[i]) : blank(), forceRedraw)
}
}
//after rendering within a routed context, we need to scroll back to the top, and fetch the document title for history.pushState
if (computePostRedrawHook) {
computePostRedrawHook();
computePostRedrawHook = null
}
lastRedrawId = null;
lastRedrawCallTime = new Date;
m.redraw.strategy("diff")
}
var pendingRequests = 0;
m.startComputation = function() {pendingRequests++};
m.endComputation = function() {
pendingRequests = Math.max(pendingRequests - 1, 0);
if (pendingRequests === 0) m.redraw()
};
var endFirstComputation = function() {
if (m.redraw.strategy() == "none") {
pendingRequests--
m.redraw.strategy("diff")
}
else m.endComputation();
}
m.withAttr = function(prop, withAttrCallback) {
return function(e) {
e = e || event;
var currentTarget = e.currentTarget || this;
withAttrCallback(prop in currentTarget ? currentTarget[prop] : currentTarget.getAttribute(prop))
}
};
//routing
var modes = {pathname: "", hash: "#", search: "?"};
var redirect = function() {}, routeParams, currentRoute;
m.route = function() {
//m.route()
if (arguments.length === 0) return currentRoute;
//m.route(el, defaultRoute, routes)
else if (arguments.length === 3 && type.call(arguments[1]) === STRING) {
var root = arguments[0], defaultRoute = arguments[1], router = arguments[2];
redirect = function(source) {
var path = currentRoute = normalizeRoute(source);
if (!routeByValue(root, router, path)) {
m.route(defaultRoute, true)
}
};
var listener = m.route.mode === "hash" ? "onhashchange" : "onpopstate";
window[listener] = function() {
var path = $location[m.route.mode]
if (m.route.mode === "pathname") path += $location.search
if (currentRoute != normalizeRoute(path)) {
redirect(path)
}
};
computePostRedrawHook = setScroll;
window[listener]()
}
//config: m.route
else if (arguments[0].addEventListener) {
var element = arguments[0];
var isInitialized = arguments[1];
var context = arguments[2];
element.href = (m.route.mode !== 'pathname' ? $location.pathname : '') + modes[m.route.mode] + this.attrs.href;
element.removeEventListener("click", routeUnobtrusive);
element.addEventListener("click", routeUnobtrusive)
}
//m.route(route, params)
else if (type.call(arguments[0]) === STRING) {
var oldRoute = currentRoute;
currentRoute = arguments[0];
var args = arguments[1] || {}
var queryIndex = currentRoute.indexOf("?")
var params = queryIndex > -1 ? parseQueryString(currentRoute.slice(queryIndex + 1)) : {}
for (var i in args) params[i] = args[i]
var querystring = buildQueryString(params)
var currentPath = queryIndex > -1 ? currentRoute.slice(0, queryIndex) : currentRoute
if (querystring) currentRoute = currentPath + (currentPath.indexOf("?") === -1 ? "?" : "&") + querystring;
var shouldReplaceHistoryEntry = (arguments.length === 3 ? arguments[2] : arguments[1]) === true || oldRoute === arguments[0];
if (window.history.pushState) {
computePostRedrawHook = function() {
window.history[shouldReplaceHistoryEntry ? "replaceState" : "pushState"](null, $document.title, modes[m.route.mode] + currentRoute);
setScroll()
};
redirect(modes[m.route.mode] + currentRoute)
}
else $location[m.route.mode] = currentRoute
}
};
m.route.param = function(key) {
if (!routeParams) throw new Error("You must call m.route(element, defaultRoute, routes) before calling m.route.param()")
return routeParams[key]
};
m.route.mode = "search";
function normalizeRoute(route) {
return route.slice(modes[m.route.mode].length)
}
function routeByValue(root, router, path) {
routeParams = {};
var queryStart = path.indexOf("?");
if (queryStart !== -1) {
routeParams = parseQueryString(path.substr(queryStart + 1, path.length));
path = path.substr(0, queryStart)
}
for (var route in router) {
if (route === path) {
m.module(root, router[route]);
return true
}
var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$");
if (matcher.test(path)) {
path.replace(matcher, function() {
var keys = route.match(/:[^\/]+/g) || [];
var values = [].slice.call(arguments, 1, -2);
for (var i = 0, len = keys.length; i < len; i++) routeParams[keys[i].replace(/:|\./g, "")] = decodeURIComponent(values[i])
m.module(root, router[route])
});
return true
}
}
}
function routeUnobtrusive(e) {
e = e || event;
if (e.ctrlKey || e.metaKey || e.which === 2) return;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
var currentTarget = e.currentTarget || this;
var args = m.route.mode === "pathname" && currentTarget.search ? parseQueryString(currentTarget.search.slice(1)) : {};
m.route(currentTarget[m.route.mode].slice(modes[m.route.mode].length), args)
}
function setScroll() {
if (m.route.mode != "hash" && $location.hash) $location.hash = $location.hash;
else window.scrollTo(0, 0)
}
function buildQueryString(object, prefix) {
var str = [];
for(var prop in object) {
var key = prefix ? prefix + "[" + prop + "]" : prop, value = object[prop];
var valueType = type.call(value)
var pair = value != null && (valueType === OBJECT) ?
buildQueryString(value, key) :
valueType === ARRAY ?
value.map(function(item) {return encodeURIComponent(key + "[]") + "=" + encodeURIComponent(item)}).join("&") :
encodeURIComponent(key) + "=" + encodeURIComponent(value)
str.push(pair)
}
return str.join("&")
}
function parseQueryString(str) {
var pairs = str.split("&"), params = {};
for (var i = 0, len = pairs.length; i < len; i++) {
var pair = pairs[i].split("=");
params[decodeURIComponent(pair[0])] = pair[1] ? decodeURIComponent(pair[1]) : ""
}
return params
}
function reset(root) {
var cacheKey = getCellCacheKey(root);
clear(root.childNodes, cellCache[cacheKey]);
cellCache[cacheKey] = undefined
}
m.deferred = function () {
var deferred = new Deferred();
deferred.promise = propify(deferred.promise);
return deferred
};
function propify(promise) {
var prop = m.prop();
promise.then(prop);
prop.then = function(resolve, reject) {
return propify(promise.then(resolve, reject))
};
return prop
}
//Promiz.mithril.js | Zolmeister | MIT
//a modified version of Promiz.js, which does not conform to Promises/A+ for two reasons:
//1) `then` callbacks are called synchronously (because setTimeout is too slow, and the setImmediate polyfill is too big
//2) throwing subclasses of Error cause the error to be bubbled up instead of triggering rejection (because the spec does not account for the important use case of default browser error handling, i.e. message w/ line number)
function Deferred(successCallback, failureCallback) {
var RESOLVING = 1, REJECTING = 2, RESOLVED = 3, REJECTED = 4;
var self = this, state = 0, promiseValue = 0, next = [];
self["promise"] = {};
self["resolve"] = function(value) {
if (!state) {
promiseValue = value;
state = RESOLVING;
fire()
}
return this
};
self["reject"] = function(value) {
if (!state) {
promiseValue = value;
state = REJECTING;
fire()
}
return this
};
self.promise["then"] = function(successCallback, failureCallback) {
var deferred = new Deferred(successCallback, failureCallback);
if (state === RESOLVED) {
deferred.resolve(promiseValue)
}
else if (state === REJECTED) {
deferred.reject(promiseValue)
}
else {
next.push(deferred)
}
return deferred.promise
};
function finish(type) {
state = type || REJECTED;
next.map(function(deferred) {
state === RESOLVED && deferred.resolve(promiseValue) || deferred.reject(promiseValue)
})
}
function thennable(then, successCallback, failureCallback, notThennableCallback) {
if (((promiseValue != null && type.call(promiseValue) === OBJECT) || typeof promiseValue === FUNCTION) && typeof then === FUNCTION) {
try {
// count protects against abuse calls from spec checker
var count = 0;
then.call(promiseValue, function(value) {
if (count++) return;
promiseValue = value;
successCallback()
}, function (value) {
if (count++) return;
promiseValue = value;
failureCallback()
})
}
catch (e) {
m.deferred.onerror(e);
promiseValue = e;
failureCallback()
}
} else {
notThennableCallback()
}
}
function fire() {
// check if it's a thenable
var then;
try {
then = promiseValue && promiseValue.then
}
catch (e) {
m.deferred.onerror(e);
promiseValue = e;
state = REJECTING;
return fire()
}
thennable(then, function() {
state = RESOLVING;
fire()
}, function() {
state = REJECTING;
fire()
}, function() {
try {
if (state === RESOLVING && typeof successCallback === FUNCTION) {
promiseValue = successCallback(promiseValue)
}
else if (state === REJECTING && typeof failureCallback === "function") {
promiseValue = failureCallback(promiseValue);
state = RESOLVING
}
}
catch (e) {
m.deferred.onerror(e);
promiseValue = e;
return finish()
}
if (promiseValue === self) {
promiseValue = TypeError();
finish()
}
else {
thennable(then, function () {
finish(RESOLVED)
}, finish, function () {
finish(state === RESOLVING && RESOLVED)
})
}
})
}
}
m.deferred.onerror = function(e) {
if (type.call(e) === "[object Error]" && !e.constructor.toString().match(/ Error/)) throw e
};
m.sync = function(args) {
var method = "resolve";
function synchronizer(pos, resolved) {
return function(value) {
results[pos] = value;
if (!resolved) method = "reject";
if (--outstanding === 0) {
deferred.promise(results);
deferred[method](results)
}
return value
}
}
var deferred = m.deferred();
var outstanding = args.length;
var results = new Array(outstanding);
if (args.length > 0) {
for (var i = 0; i < args.length; i++) {
args[i].then(synchronizer(i, true), synchronizer(i, false))
}
}
else deferred.resolve([]);
return deferred.promise
};
function identity(value) {return value}
function ajax(options) {
if (options.dataType && options.dataType.toLowerCase() === "jsonp") {
var callbackKey = "mithril_callback_" + new Date().getTime() + "_" + (Math.round(Math.random() * 1e16)).toString(36);
var script = $document.createElement("script");
window[callbackKey] = function(resp) {
script.parentNode.removeChild(script);
options.onload({
type: "load",
target: {
responseText: resp
}
});
window[callbackKey] = undefined
};
script.onerror = function(e) {
script.parentNode.removeChild(script);
options.onerror({
type: "error",
target: {
status: 500,
responseText: JSON.stringify({error: "Error making jsonp request"})
}
});
window[callbackKey] = undefined;
return false
};
script.onload = function(e) {
return false
};
script.src = options.url
+ (options.url.indexOf("?") > 0 ? "&" : "?")
+ (options.callbackKey ? options.callbackKey : "callback")
+ "=" + callbackKey
+ "&" + buildQueryString(options.data || {});
$document.body.appendChild(script)
}
else {
var xhr = new window.XMLHttpRequest;
xhr.open(options.method, options.url, true, options.user, options.password);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) options.onload({type: "load", target: xhr});
else options.onerror({type: "error", target: xhr})
}
};
if (options.serialize === JSON.stringify && options.data && options.method !== "GET") {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
}
if (options.deserialize === JSON.parse) {
xhr.setRequestHeader("Accept", "application/json, text/*");
}
if (typeof options.config === FUNCTION) {
var maybeXhr = options.config(xhr, options);
if (maybeXhr != null) xhr = maybeXhr
}
var data = options.method === "GET" || !options.data ? "" : options.data
if (data && (type.call(data) != STRING && data.constructor != window.FormData)) {
throw "Request data should be either be a string or FormData. Check the `serialize` option in `m.request`";
}
xhr.send(data);
return xhr
}
}
function bindData(xhrOptions, data, serialize) {
if (xhrOptions.method === "GET" && xhrOptions.dataType != "jsonp") {
var prefix = xhrOptions.url.indexOf("?") < 0 ? "?" : "&";
var querystring = buildQueryString(data);
xhrOptions.url = xhrOptions.url + (querystring ? prefix + querystring : "")
}
else xhrOptions.data = serialize(data);
return xhrOptions
}
function parameterizeUrl(url, data) {
var tokens = url.match(/:[a-z]\w+/gi);
if (tokens && data) {
for (var i = 0; i < tokens.length; i++) {
var key = tokens[i].slice(1);
url = url.replace(tokens[i], data[key]);
delete data[key]
}
}
return url
}
m.request = function(xhrOptions) {
if (xhrOptions.background !== true) m.startComputation();
var deferred = m.deferred();
var isJSONP = xhrOptions.dataType && xhrOptions.dataType.toLowerCase() === "jsonp";
var serialize = xhrOptions.serialize = isJSONP ? identity : xhrOptions.serialize || JSON.stringify;
var deserialize = xhrOptions.deserialize = isJSONP ? identity : xhrOptions.deserialize || JSON.parse;
var extract = xhrOptions.extract || function(xhr) {
return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText
};
xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data);
xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize);
xhrOptions.onload = xhrOptions.onerror = function(e) {
try {
e = e || event;
var unwrap = (e.type === "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity;
var response = unwrap(deserialize(extract(e.target, xhrOptions)));
if (e.type === "load") {
if (type.call(response) === ARRAY && xhrOptions.type) {
for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i])
}
else if (xhrOptions.type) response = new xhrOptions.type(response)
}
deferred[e.type === "load" ? "resolve" : "reject"](response)
}
catch (e) {
m.deferred.onerror(e);
deferred.reject(e)
}
if (xhrOptions.background !== true) m.endComputation()
};
ajax(xhrOptions);
deferred.promise(xhrOptions.initialValue);
return deferred.promise
};
//testing API
m.deps = function(mock) {
initialize(window = mock || window);
return window;
};
//for internal testing only, do not use `m.deps.factory`
m.deps.factory = app;
return m
})(typeof window != "undefined" ? window : {});
if (typeof module != "undefined" && module !== null && module.exports) module.exports = m;
else if (typeof define === "function" && define.amd) define(function() {return m});
......@@ -12,104 +12,81 @@ button {
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
-ms-appearance: none;
-o-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
font-smoothing: antialiased;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #eaeaea url('bg.png');
background: #f5f5f5;
color: #4d4d4d;
width: 550px;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
font-weight: 300;
}
button,
input[type="checkbox"] {
outline: none;
outline: none;
}
.hidden {
display: none;
}
#todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
border: 1px solid #ccc;
position: relative;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
#todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
width: 2px;
position: absolute;
top: 0;
left: 40px;
height: 100%;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
#todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
#todoapp input::-moz-placeholder {
font-style: italic;
color: #a9a9a9;
font-weight: 300;
color: #e6e6e6;
}
#todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
#todoapp h1 {
position: absolute;
top: -120px;
top: -155px;
width: 100%;
font-size: 70px;
font-weight: bold;
font-size: 100px;
font-weight: 100;
text-align: center;
color: #b3b3b3;
color: rgba(255, 255, 255, 0.3);
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
#header {
padding-top: 15px;
border-radius: inherit;
}
#header:before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
height: 15px;
z-index: 2;
border-bottom: 1px solid #6c615c;
background: #8d7d77;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
#new-todo,
.edit {
position: relative;
......@@ -117,6 +94,7 @@ input[type="checkbox"] {
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
outline: none;
......@@ -124,29 +102,25 @@ input[type="checkbox"] {
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
z-index: 2;
box-shadow: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
#main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
border-top: 1px solid #e6e6e6;
}
label[for='toggle-all'] {
......@@ -155,19 +129,19 @@ label[for='toggle-all'] {
#toggle-all {
position: absolute;
top: -42px;
left: -4px;
width: 40px;
top: -55px;
left: -12px;
width: 60px;
height: 34px;
text-align: center;
/* Mobile Safari */
border: none;
border: none; /* Mobile Safari */
}
#toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
content: '';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
#toggle-all:checked:before {
......@@ -183,7 +157,7 @@ label[for='toggle-all'] {
#todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
border-bottom: 1px solid #ededed;
}
#todo-list li:last-child {
......@@ -215,28 +189,18 @@ label[for='toggle-all'] {
top: 0;
bottom: 0;
margin: auto 0;
/* Mobile Safari */
border: none;
border: none; /* Mobile Safari */
-webkit-appearance: none;
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
#todo-list li .toggle:after {
content: '✔';
/* 40 + a couple of pixels visual adjustment */
line-height: 43px;
font-size: 20px;
color: #d9d9d9;
text-shadow: 0 -1px 0 #bfbfbf;
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#ededed" stroke-width="3"/></svg>');
}
#todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>');
}
#todo-list li label {
......@@ -246,12 +210,11 @@ label[for='toggle-all'] {
margin-left: 45px;
display: block;
line-height: 1.2;
-webkit-transition: color 0.4s;
transition: color 0.4s;
}
#todo-list li.completed label {
color: #a9a9a9;
color: #d9d9d9;
text-decoration: line-through;
}
......@@ -264,21 +227,18 @@ label[for='toggle-all'] {
width: 40px;
height: 40px;
margin: auto 0;
font-size: 22px;
color: #a88a8a;
-webkit-transition: all 0.2s;
transition: all 0.2s;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
#todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
transform: scale(1.3);
color: #af5b5e;
}
#todo-list li .destroy:after {
content: '';
content: '×';
}
#todo-list li:hover .destroy {
......@@ -295,29 +255,25 @@ label[for='toggle-all'] {
#footer {
color: #777;
padding: 0 15px;
position: absolute;
right: 0;
bottom: -31px;
left: 0;
padding: 10px 15px;
height: 20px;
z-index: 1;
text-align: center;
border-top: 1px solid #e6e6e6;
}
#footer:before {
content: '';
position: absolute;
right: 0;
bottom: 31px;
bottom: 0;
left: 0;
height: 50px;
z-index: -1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
0 6px 0 -3px rgba(255, 255, 255, 0.8),
0 7px 1px -3px rgba(0, 0, 0, 0.3),
0 43px 0 -6px rgba(255, 255, 255, 0.8),
0 44px 2px -6px rgba(0, 0, 0, 0.2);
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
#todo-count {
......@@ -325,6 +281,10 @@ label[for='toggle-all'] {
text-align: left;
}
#todo-count strong {
font-weight: 300;
}
#filters {
margin: 0;
padding: 0;
......@@ -339,49 +299,72 @@ label[for='toggle-all'] {
}
#filters li a {
color: #83756f;
margin: 2px;
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
#filters li a.selected,
#filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
#filters li a.selected {
font-weight: bold;
border-color: rgba(175, 47, 47, 0.2);
}
#clear-completed {
#clear-completed,
html #clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
font-size: 11px;
padding: 0 10px;
border-radius: 3px;
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
cursor: pointer;
visibility: hidden;
position: relative;
}
#clear-completed::after {
visibility: visible;
content: 'Clear completed';
position: absolute;
right: 0;
white-space: nowrap;
}
#clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
#clear-completed:hover::after {
text-decoration: underline;
}
#info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
#info p {
line-height: 1;
}
#info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
#info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
#toggle-all,
#todo-list li .toggle {
......@@ -393,10 +376,6 @@ label[for='toggle-all'] {
}
#toggle-all {
top: -56px;
left: -15px;
width: 65px;
height: 41px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
......@@ -404,151 +383,12 @@ label[for='toggle-all'] {
}
}
.hidden {
display: none;
}
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #C5C5C5;
border-bottom: 1px dashed #F7F7F7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
-webkit-transition-property: left;
transition-property: left;
-webkit-transition-duration: 500ms;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
margin: 0 0 0 300px;
}
.learn-bar > .learn {
left: 8px;
@media (max-width: 430px) {
#footer {
height: 50px;
}
.learn-bar #todoapp {
width: 550px;
margin: 130px auto 40px auto;
#filters {
bottom: 10px;
}
}
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar > .learn {
left: 8px;
}
}
/* global _ */
(function () {
'use strict';
/* jshint ignore:start */
// Underscore's Template Module
// Courtesy of underscorejs.org
var _ = (function (_) {
......@@ -114,6 +116,7 @@
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
/* jshint ignore:end */
function redirect() {
if (location.hostname === 'tastejs.github.io') {
......@@ -175,13 +178,17 @@
if (learnJSON.backend) {
this.frameworkJSON = learnJSON.backend;
this.frameworkJSON.issueLabel = framework;
this.append({
backend: true
});
} else if (learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework];
this.frameworkJSON.issueLabel = framework;
this.append();
}
this.fetchIssueCount();
}
Learn.prototype.append = function (opts) {
......@@ -212,6 +219,26 @@
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
};
Learn.prototype.fetchIssueCount = function () {
var issueLink = document.getElementById('issue-count-link');
if (issueLink) {
var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos');
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
var parsedResponse = JSON.parse(e.target.responseText);
if (parsedResponse instanceof Array) {
var count = parsedResponse.length
if (count !== 0) {
issueLink.innerHTML = 'This app has ' + count + ' open issues';
document.getElementById('issue-count').style.display = 'inline';
}
}
};
xhr.send();
}
};
redirect();
getFile('learn.json', Learn);
})();
{
"private": true,
"dependencies": {
"mithril": "^0.1.20",
"todomvc-common": "^1.0.1",
"todomvc-app-css": "^1.0.1"
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment