pax_global_header00006660000000000000000000000064132422312120014502gustar00rootroot0000000000000052 comment=d8201d4262b69012dfd6d5d1f3d581b344e157b4 mithril-1.1.6/000077500000000000000000000000001324223121200131575ustar00rootroot00000000000000mithril-1.1.6/.deploy.enc000066400000000000000000000062601324223121200152240ustar00rootroot0000000000000016fd{DlgdZ5BRہreoB1ctZȕIŤt)Ҳw-NPah@( `8#t`7ֈl,(}lDs;0`UÉ>`E68С|`;8WuwaXқX ^1>dSfWnA:s.:W@~.#lU U˨~g.|\_jr`w2i$OCrN{wɮۨ姈D3f;G u"t5-PJ4ࡻ"H͞ ǚF̰>9~?sa" (cmiA{-N![<ݯP2 գ0 G#JҨ?.j|( 5ճ'9]FקKqܠvv,zUۍEA9@'n;^ C7TxKh+ fd⋵DΨQ/p`/|rCJzqwbTD*^F <3M@*sS櫼$KLAӧtIm./cTtI<jbmj0u^+ԇ^5qj=q,##褛V'V ܎pjJz `msּW%+ p$[1"u }цc{5G4fΤE5Ļ/!+찚*{-@u4b{̲DBv6';Dp=&c?eRr3?i:>ŀ. :/ǵX܄:Z;U.B{1ki+[o$yB[?mXNn3XDtHO*k]B Fk\@J,#P 0Xsq[V|{/NP]Cq[]$IˆeGLMv*xmY9rj)cN8P߃e"Ձ^Zb;y&3ʀ9aͲ:pi_nwjF%) 71c$/,$r"SWya<ž ٓaF Sֈee ŀ HzٙTMfzC5XJc1X$,ob.UO7 CP$uc|t qItK%qvlDb7YS lWidf5 Φ`"[c?߸h;8XgH?:D:̮_' .`.)زnV#3fj;!J@]Ӥk@=_(]OWX)rPS27VۮT(L ;3iU*މTuw?qU+$SL[Fm,k俵ijY$!82zOq\]c)/uY1B{~Gڋ+s Qp൹`$Zh$P_6䴃8P+-jO~nV\m 4ȿ JU@1]qbH(5h\m۩v u fpE3 ?n"ޣAF8,pZe^9BOsn*mC]"J.!C7XI#UYXEDztM݆tP]myO&~,?dz@W·=aBY$B IRLobeuCI}B_^n PF=3kA!k,u| <;;#L][:DݟĠ&avYm)%$C }$?3O'C=# :{`.#1K# "z|!'W>&ªgÚ?،+;?]p~s#m]f'瀾rAeoYd9ra´EYxtWGYj喉ЀA,ʤ?[Ҵ(hx08nut~Om\+p>vK`j|_{;HuIVd敏{64YQ[п1h#dǎW8DQKN7ESKvL-J;3|2Cۡ Pš>kЍ7_Z@(F#}%}}p*. :l.iY +_{|aB:z)DxZ)wk_WQI=/D@ J͂zI|D@_]ι%'LgmcX #m
Download size
Mithril (8kb)
Vue + Vue-Router + Vuex + fetch (40kb)
React + React-Router + Redux + fetch (64kb)
Angular (135kb)
Performance
Mithril (6.4ms)
Vue (9.8ms)
React (12.1ms)
Angular (11.5ms)
Mithril is used by companies like Vimeo and Nike, and open source platforms like Lichess. If you are an experienced developer and want to know how Mithril compares to other frameworks, see the [framework comparison](http://mithril.js.org/framework-comparison.html) page. Mithril supports browsers all the way back to IE9, no polyfills required. --- ### Getting started The easiest way to try out Mithril is to include it from a CDN, and follow this tutorial. It'll cover the majority of the API surface (including routing and XHR) but it'll only take 10 minutes. Let's create an HTML file to follow along: ```markup ``` --- ### Hello world Let's start as small as we can: render some text on screen. Copy the code below into your file (and by copy, I mean type it out - you'll learn better) ```javascript var root = document.body m.render(root, "Hello world") ``` Now, let's change the text to something else. Add this line of code under the previous one: ```javascript m.render(root, "My first app") ``` As you can see, you use the same code to both create and update HTML. Mithril automatically figures out the most efficient way of updating the text, rather than blindly recreating it from scratch. --- ### DOM elements Let's wrap our text in an `

` tag. ```javascript m.render(root, m("h1", "My first app")) ``` The `m()` function can be used to describe any HTML structure you want. So if you need to add a class to the `

`: ```javascript m("h1", {class: "title"}, "My first app") ``` If you want to have multiple elements: ```javascript [ m("h1", {class: "title"}, "My first app"), m("button", "A button"), ] ``` And so on: ```javascript m("main", [ m("h1", {class: "title"}, "My first app"), m("button", "A button"), ]) ``` Note: If you prefer `` syntax, [it's possible to use it via a Babel plugin](http://mithril.js.org/jsx.html). ```jsx // HTML syntax via Babel's JSX plugin

My first app

``` --- ### Components A Mithril component is just an object with a `view` function. Here's the code above as a component: ```javascript var Hello = { view: function() { return m("main", [ m("h1", {class: "title"}, "My first app"), m("button", "A button"), ]) } } ``` To activate the component, we use `m.mount`. ```javascript m.mount(root, Hello) ``` As you would expect, doing so creates this markup: ```markup

My first app

``` The `m.mount` function is similar to `m.render`, but instead of rendering some HTML only once, it activates Mithril's auto-redrawing system. To understand what that means, let's add some events: ```javascript var count = 0 // added a variable var Hello = { view: function() { return m("main", [ m("h1", {class: "title"}, "My first app"), // changed the next line m("button", {onclick: function() {count++}}, count + " clicks"), ]) } } m.mount(root, Hello) ``` We defined an `onclick` event on the button, which increments a variable `count` (which was declared at the top). We are now also rendering the value of that variable in the button label. You can now update the label of the button by clicking the button. Since we used `m.mount`, you don't need to manually call `m.render` to apply the changes in the `count` variable to the HTML; Mithril does it for you. If you're wondering about performance, it turns out Mithril is very fast at rendering updates, because it only touches the parts of the DOM it absolutely needs to. So in our example above, when you click the button, the text in it is the only part of the DOM Mithril actually updates. --- ### Routing Routing just means going from one screen to another in an application with several screens. Let's add a splash page that appears before our click counter. First we create a component for it: ```javascript var Splash = { view: function() { return m("a", {href: "#!/hello"}, "Enter!") } } ``` As you can see, this component simply renders a link to `#!/hello`. The `#!` part is known as a hashbang, and it's a common convention used in Single Page Applications to indicate that the stuff after it (the `/hello` part) is a route path. Now that we going to have more than one screen, we use `m.route` instead of `m.mount`. ```javascript m.route(root, "/splash", { "/splash": Splash, "/hello": Hello, }) ``` The `m.route` function still has the same auto-redrawing functionality that `m.mount` does, and it also enables URL awareness; in other words, it lets Mithril know what to do when it sees a `#!` in the URL. The `"/splash"` right after `root` means that's the default route, i.e. if the hashbang in the URL doesn't point to one of the defined routes (`/splash` and `/hello`, in our case), then Mithril redirects to the default route. So if you open the page in a browser and your URL is `http://localhost`, then you get redirected to `http://localhost/#!/splash`. Also, as you would expect, clicking on the link on the splash page takes you to the click counter screen we created earlier. Notice that now your URL will point to `http://localhost/#!/hello`. You can navigate back and forth to the splash page using the browser's back and next button. --- ### XHR Basically, XHR is just a way to talk to a server. Let's change our click counter to make it save data on a server. For the server, we'll use [REM](http://rem-rest-api.herokuapp.com), a mock REST API designed for toy apps like this tutorial. First we create a function that calls `m.request`. The `url` specifies an endpoint that represents a resource, the `method` specifies the type of action we're taking (typically the `PUT` method [upserts](https://en.wiktionary.org/wiki/upsert)), `data` is the payload that we're sending to the endpoint and `withCredentials` means to enable cookies (a requirement for the REM API to work) ```javascript var count = 0 var increment = function() { m.request({ method: "PUT", url: "//rem-rest-api.herokuapp.com/api/tutorial/1", data: {count: count + 1}, withCredentials: true, }) .then(function(data) { count = parseInt(data.count) }) } ``` Calling the increment function [upserts](https://en.wiktionary.org/wiki/upsert) an object `{count: 1}` to the `/api/tutorial/1` endpoint. This endpoint returns an object with the same `count` value that was sent to it. Notice that the `count` variable is only updated after the request completes, and it's updated with the response value from the server now. Let's replace the event handler in the component to call the `increment` function instead of incrementing the `count` variable directly: ```javascript var Hello = { view: function() { return m("main", [ m("h1", {class: "title"}, "My first app"), m("button", {onclick: increment}, count + " clicks"), ]) } } ``` Clicking the button should now update the count. --- We covered how to create and update HTML, how to create components, routes for a Single Page Application, and interacted with a server via XHR. This should be enough to get you started writing the frontend for a real application. Now that you are comfortable with the basics of the Mithril API, [be sure to check out the simple application tutorial](http://mithril.js.org/simple-application.html), which walks you through building a realistic application. mithril-1.1.6/api/000077500000000000000000000000001324223121200137305ustar00rootroot00000000000000mithril-1.1.6/api/mount.js000066400000000000000000000010331324223121200154250ustar00rootroot00000000000000"use strict" var Vnode = require("../render/vnode") module.exports = function(redrawService) { return function(root, component) { if (component === null) { redrawService.render(root, []) redrawService.unsubscribe(root) return } if (component.view == null && typeof component !== "function") throw new Error("m.mount(element, component) expects a component, not a vnode") var run = function() { redrawService.render(root, Vnode(component)) } redrawService.subscribe(root, run) redrawService.redraw() } } mithril-1.1.6/api/redraw.js000066400000000000000000000022761324223121200155610ustar00rootroot00000000000000"use strict" var coreRenderer = require("../render/render") function throttle(callback) { //60fps translates to 16.6ms, round it down since setTimeout requires int var time = 16 var last = 0, pending = null var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout return function() { var now = Date.now() if (last === 0 || now - last >= time) { last = now callback() } else if (pending === null) { pending = timeout(function() { pending = null callback() last = Date.now() }, time - (now - last)) } } } module.exports = function($window) { var renderService = coreRenderer($window) renderService.setEventCallback(function(e) { if (e.redraw === false) e.redraw = undefined else redraw() }) var callbacks = [] function subscribe(key, callback) { unsubscribe(key) callbacks.push(key, throttle(callback)) } function unsubscribe(key) { var index = callbacks.indexOf(key) if (index > -1) callbacks.splice(index, 2) } function redraw() { for (var i = 1; i < callbacks.length; i += 2) { callbacks[i]() } } return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render} } mithril-1.1.6/api/router.js000066400000000000000000000046201324223121200156100ustar00rootroot00000000000000"use strict" var Vnode = require("../render/vnode") var Promise = require("../promise/promise") var coreRouter = require("../router/router") module.exports = function($window, redrawService) { var routeService = coreRouter($window) var identity = function(v) {return v} var render, component, attrs, currentPath, lastUpdate var route = function(root, defaultRoute, routes) { if (root == null) throw new Error("Ensure the DOM element that was passed to `m.route` is not undefined") var run = function() { if (render != null) redrawService.render(root, render(Vnode(component, attrs.key, attrs))) } var bail = function(path) { if (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true}) else throw new Error("Could not resolve default route " + defaultRoute) } routeService.defineRoutes(routes, function(payload, params, path) { var update = lastUpdate = function(routeResolver, comp) { if (update !== lastUpdate) return component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div" attrs = params, currentPath = path, lastUpdate = null render = (routeResolver.render || identity).bind(routeResolver) run() } if (payload.view || typeof payload === "function") update({}, payload) else { if (payload.onmatch) { Promise.resolve(payload.onmatch(params, path)).then(function(resolved) { update(payload, resolved) }, bail) } else update(payload, "div") } }, bail) redrawService.subscribe(root, run) } route.set = function(path, data, options) { if (lastUpdate != null) { options = options || {} options.replace = true } lastUpdate = null routeService.setPath(path, data, options) } route.get = function() {return currentPath} route.prefix = function(prefix) {routeService.prefix = prefix} route.link = function(vnode) { vnode.dom.setAttribute("href", routeService.prefix + vnode.attrs.href) vnode.dom.onclick = function(e) { if (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return e.preventDefault() e.redraw = false var href = this.getAttribute("href") if (href.indexOf(routeService.prefix) === 0) href = href.slice(routeService.prefix.length) route.set(href, undefined, undefined) } } route.param = function(key) { if(typeof attrs !== "undefined" && typeof key !== "undefined") return attrs[key] return attrs } return route } mithril-1.1.6/api/tests/000077500000000000000000000000001324223121200150725ustar00rootroot00000000000000mithril-1.1.6/api/tests/index.html000066400000000000000000000026651324223121200171000ustar00rootroot00000000000000 mithril-1.1.6/api/tests/test-mount.js000066400000000000000000000126461324223121200175600ustar00rootroot00000000000000"use strict" var o = require("../../ospec/ospec") var components = require("../../test-utils/components") var domMock = require("../../test-utils/domMock") var m = require("../../render/hyperscript") var apiRedraw = require("../../api/redraw") var apiMounter = require("../../api/mount") o.spec("mount", function() { var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, mount, render o.beforeEach(function() { $window = domMock() root = $window.document.body redrawService = apiRedraw($window) mount = apiMounter(redrawService) render = redrawService.render }) o("throws on invalid component", function() { var threw = false try { mount(root, {}) } catch (e) { threw = true } o(threw).equals(true) }) components.forEach(function(cmp){ o.spec(cmp.kind, function(){ var createComponent = cmp.create o("throws on invalid `root` DOM node", function() { var threw = false try { mount(null, createComponent({view: function() {}})) } catch (e) { threw = true } o(threw).equals(true) }) o("renders into `root`", function() { mount(root, createComponent({ view : function() { return m("div") } })) o(root.firstChild.nodeName).equals("DIV") }) o("mounting null unmounts", function() { mount(root, createComponent({ view : function() { return m("div") } })) mount(root, null) o(root.childNodes.length).equals(0) }) o("redraws on events", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) mount(root, createComponent({ view : function() { return m("div", { oninit : oninit, onupdate : onupdate, onclick : onclick, }) } })) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) o(onupdate.callCount).equals(0) o(onclick.callCount).equals(1) o(onclick.this).equals(root.firstChild) o(onclick.args[0].type).equals("click") o(onclick.args[0].target).equals(root.firstChild) // Wrapped to give time for the rate-limited redraw to fire setTimeout(function() { o(onupdate.callCount).equals(1) done() }, FRAME_BUDGET) }) o("redraws several mount points on events", function(done, timeout) { timeout(60) var onupdate0 = o.spy() var oninit0 = o.spy() var onclick0 = o.spy() var onupdate1 = o.spy() var oninit1 = o.spy() var onclick1 = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) render(root, [ m("#child0"), m("#child1") ]) mount(root.childNodes[0], createComponent({ view : function() { return m("div", { oninit : oninit0, onupdate : onupdate0, onclick : onclick0, }) } })) o(oninit0.callCount).equals(1) o(onupdate0.callCount).equals(0) mount(root.childNodes[1], createComponent({ view : function() { return m("div", { oninit : oninit1, onupdate : onupdate1, onclick : onclick1, }) } })) o(oninit1.callCount).equals(1) o(onupdate1.callCount).equals(0) root.childNodes[0].firstChild.dispatchEvent(e) o(onclick0.callCount).equals(1) o(onclick0.this).equals(root.childNodes[0].firstChild) setTimeout(function() { o(onupdate0.callCount).equals(1) o(onupdate1.callCount).equals(1) root.childNodes[1].firstChild.dispatchEvent(e) o(onclick1.callCount).equals(1) o(onclick1.this).equals(root.childNodes[1].firstChild) setTimeout(function() { o(onupdate0.callCount).equals(2) o(onupdate1.callCount).equals(2) done() }, FRAME_BUDGET) }, FRAME_BUDGET) }) o("event handlers can skip redraw", function(done) { var onupdate = o.spy() var oninit = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) mount(root, createComponent({ view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: function(e) { e.redraw = false } }) } })) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) // Wrapped to ensure no redraw fired setTimeout(function() { o(onupdate.callCount).equals(0) done() }, FRAME_BUDGET) }) o("redraws when the render function is run", function(done) { var onupdate = o.spy() var oninit = o.spy() mount(root, createComponent({ view : function() { return m("div", { oninit: oninit, onupdate: onupdate }) } })) o(oninit.callCount).equals(1) o(onupdate.callCount).equals(0) redrawService.redraw() // Wrapped to give time for the rate-limited redraw to fire setTimeout(function() { o(onupdate.callCount).equals(1) done() }, FRAME_BUDGET) }) o("throttles", function(done, timeout) { timeout(200) var i = 0 mount(root, createComponent({view: function() {i++}})) var before = i redrawService.redraw() redrawService.redraw() redrawService.redraw() redrawService.redraw() var after = i setTimeout(function(){ o(before).equals(1) // mounts synchronously o(after).equals(1) // throttles rest o(i).equals(2) done() },40) }) }) }) }) mithril-1.1.6/api/tests/test-redraw.js000066400000000000000000000037531324223121200177010ustar00rootroot00000000000000"use strict" var o = require("../../ospec/ospec") var domMock = require("../../test-utils/domMock") var apiRedraw = require("../../api/redraw") o.spec("redrawService", function() { var root, redrawService, $document o.beforeEach(function() { var $window = domMock() root = $window.document.body redrawService = apiRedraw($window) $document = $window.document }) o("shouldn't error if there are no renderers", function() { redrawService.redraw() }) o("should run a single renderer entry", function(done) { var spy = o.spy() redrawService.subscribe(root, spy) o(spy.callCount).equals(0) redrawService.redraw() o(spy.callCount).equals(1) redrawService.redraw() redrawService.redraw() redrawService.redraw() o(spy.callCount).equals(1) setTimeout(function() { o(spy.callCount).equals(2) done() }, 20) }) o("should run all renderer entries", function(done) { var el1 = $document.createElement("div") var el2 = $document.createElement("div") var el3 = $document.createElement("div") var spy1 = o.spy() var spy2 = o.spy() var spy3 = o.spy() redrawService.subscribe(el1, spy1) redrawService.subscribe(el2, spy2) redrawService.subscribe(el3, spy3) redrawService.redraw() o(spy1.callCount).equals(1) o(spy2.callCount).equals(1) o(spy3.callCount).equals(1) redrawService.redraw() o(spy1.callCount).equals(1) o(spy2.callCount).equals(1) o(spy3.callCount).equals(1) setTimeout(function() { o(spy1.callCount).equals(2) o(spy2.callCount).equals(2) o(spy3.callCount).equals(2) done() }, 20) }) o("should stop running after unsubscribe", function() { var spy = o.spy() redrawService.subscribe(root, spy) redrawService.unsubscribe(root, spy) redrawService.redraw() o(spy.callCount).equals(0) }) o("does nothing on invalid unsubscribe", function() { var spy = o.spy() redrawService.subscribe(root, spy) redrawService.unsubscribe(null) redrawService.redraw() o(spy.callCount).equals(1) }) }) mithril-1.1.6/api/tests/test-router.js000066400000000000000000000647761324223121200177510ustar00rootroot00000000000000"use strict" var o = require("../../ospec/ospec") var callAsync = require("../../test-utils/callAsync") var browserMock = require("../../test-utils/browserMock") var m = require("../../render/hyperscript") var callAsync = require("../../test-utils/callAsync") var apiRedraw = require("../../api/redraw") var apiRouter = require("../../api/router") var Promise = require("../../promise/promise") o.spec("route", function() { void [{protocol: "http:", hostname: "localhost"}, {protocol: "file:", hostname: "/"}].forEach(function(env) { void ["#", "?", "", "#!", "?!", "/foo"].forEach(function(prefix) { o.spec("using prefix `" + prefix + "` starting on " + env.protocol + "//" + env.hostname, function() { var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, route o.beforeEach(function() { $window = browserMock(env) root = $window.document.body redrawService = apiRedraw($window) route = apiRouter($window, redrawService) route.prefix(prefix) }) o("throws on invalid `root` DOM node", function() { var threw = false try { route(null, "/", {"/":{view: function() {}}}) } catch (e) { threw = true } o(threw).equals(true) }) o("renders into `root`", function() { $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div") } } }) o(root.firstChild.nodeName).equals("DIV") }) o("routed mount points can redraw synchronously (POJO component)", function() { var view = o.spy() $window.location.href = prefix + "/" route(root, "/", {"/":{view:view}}) o(view.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) }) o("routed mount points can redraw synchronously (constructible component)", function() { var view = o.spy() var Cmp = function(){} Cmp.prototype.view = view $window.location.href = prefix + "/" route(root, "/", {"/":Cmp}) o(view.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) }) o("routed mount points can redraw synchronously (closure component)", function() { var view = o.spy() function Cmp() {return {view: view}} $window.location.href = prefix + "/" route(root, "/", {"/":Cmp}) o(view.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) }) o("default route doesn't break back button", function(done) { $window.location.href = "http://old.com" $window.location.href = "http://new.com" route(root, "/a", { "/a" : { view: function() { return m("div") } } }) callAsync(function() { o(root.firstChild.nodeName).equals("DIV") o(route.get()).equals("/a") $window.history.back() o($window.location.pathname).equals("/") o($window.location.hostname).equals("old.com") done() }) }) o("default route does not inherit params", function(done) { $window.location.href = "/invalid?foo=bar" route(root, "/a", { "/a" : { oninit: init, view: function() { return m("div") } } }) function init(vnode) { o(vnode.attrs.foo).equals(undefined) done() } }) o("redraws when render function is executed", function() { var onupdate = o.spy() var oninit = o.spy() $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate }) } } }) o(oninit.callCount).equals(1) redrawService.redraw() o(onupdate.callCount).equals(1) }) o("redraws on events", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: onclick, }) } } }) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) o(onclick.callCount).equals(1) o(onclick.this).equals(root.firstChild) o(onclick.args[0].type).equals("click") o(onclick.args[0].target).equals(root.firstChild) // Wrapped to give time for the rate-limited redraw to fire callAsync(function() { o(onupdate.callCount).equals(1) done() }) }) o("event handlers can skip redraw", function(done) { var onupdate = o.spy() var oninit = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: function(e) { e.redraw = false }, }) } } }) o(oninit.callCount).equals(1) root.firstChild.dispatchEvent(e) o(e.redraw).notEquals(false) // Wrapped to ensure no redraw fired callAsync(function() { o(onupdate.callCount).equals(0) done() }) }) o("changes location on route.link", function() { var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("a", { href: "/test", oncreate: route.link }) } }, "/test" : { view : function() { return m("div") } } }) var slash = prefix[0] === "/" ? "" : "/" o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "")) root.firstChild.dispatchEvent(e) o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test") }) o("accepts RouteResolver with onmatch that returns Component", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Component }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve(Component) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise", function(done) { var matchCount = 0 var renderCount = 0 var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve() }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns Promise", function(done) { var matchCount = 0 var renderCount = 0 var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve([]) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns rejected Promise", function(done) { var matchCount = 0 var renderCount = 0 var spy = o.spy() var resolver = { onmatch: function() { matchCount++ return Promise.reject(new Error("error")) }, render: function(vnode) { renderCount++ return vnode }, } $window.location.href = prefix + "/test/1" route(root, "/default", { "/default" : {view: spy}, "/test/:id" : resolver }) callAsync(function() { callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(0) o(spy.callCount).equals(1) done() }) }) }) o("accepts RouteResolver without `render` method as payload", function(done) { var matchCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") return Component }, }, }) callAsync(function() { o(matchCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("changing `vnode.key` in `render` resets the component", function(done){ var oninit = o.spy() var Component = { oninit: oninit, view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id": {render: function(vnode) { return m(Component, {key: vnode.attrs.id}) }} }) callAsync(function() { o(oninit.callCount).equals(1) route.set("/def") callAsync(function() { o(oninit.callCount).equals(2) done() }) }) }) o("accepts RouteResolver without `onmatch` method as payload", function() { var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") return m(Component) }, }, }) o(root.firstChild.nodeName).equals("DIV") o(renderCount).equals(1) }) o("RouteResolver `render` does not have component semantics", function(done) { $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { render: function() { return m("div") }, }, "/b" : { render: function() { return m("div") }, }, }) var dom = root.firstChild o(root.firstChild.nodeName).equals("DIV") route.set("/b") callAsync(function() { o(root.firstChild).equals(dom) done() }) }) o("calls onmatch and view correct number of times", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ return Component }, render: function(vnode) { renderCount++ return vnode }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) redrawService.redraw() o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("calls onmatch and view correct number of times when not onmatch returns undefined", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ }, render: function() { renderCount++ return {tag: Component} }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) redrawService.redraw() o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("onmatch can redirect to another route", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { view: function() { redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver w/ only onmatch", function(done) { var redirected = false var render = o.spy() var view = o.spy(function() {return m("div")}) $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b", {}, {state: {a: 5}}) }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) o(root.childNodes.length).equals(1) o(root.firstChild.nodeName).equals("DIV") o($window.history.state).deepEquals({a: 5}) done() }) }) }) o("onmatch can redirect to another route that has RouteResolver w/ only render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { render: function(){ redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver whose onmatch resolves asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { onmatch: function() { redirected = true return new Promise(function(fulfill){ callAsync(function(){ fulfill({view: view}) }) }) } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect to another route asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { callAsync(function() {route.set("/b")}) return new Promise(function() {}) }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect w/ window.history.back()", function(done) { var render = o.spy() var component = {view: o.spy()} $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { return component }, render: function(vnode) { return vnode } }, "/b" : { onmatch: function() { $window.history.back() return new Promise(function() {}) }, render: render } }) callAsync(function() { route.set("/b") callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(component.view.callCount).equals(2) done() }) }) }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ onmatch", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { onmatch: function(){ redirected = true return {view: function() {}} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { render: function(){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a component", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { view: function(){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("the previous view redraws while onmatch resolution is pending (#1268)", function(done) { var view = o.spy() var onmatch = o.spy(function() { return new Promise(function() {}) }) $window.location.href = prefix + "/a" route(root, "/", { "/a": {view: view}, "/b": {onmatch: onmatch} }) o(view.callCount).equals(1) o(onmatch.callCount).equals(0) route.set("/b") callAsync(function() { o(view.callCount).equals(1) o(onmatch.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) o(onmatch.callCount).equals(1) done() }) }) o("when two async routes are racing, the last one set cancels the finalization of the first", function(done) { var renderA = o.spy() var renderB = o.spy() var onmatchA = o.spy(function(){ return new Promise(function(fulfill) { setTimeout(function(){ fulfill() }, 10) }) }) $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: onmatchA, render: renderA }, "/b": { onmatch: function(){ var p = new Promise(function(fulfill) { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) setTimeout(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) fulfill() p.then(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(1) done() }) }, 20) }) return p }, render: renderB } }) callAsync(function() { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) route.set("/b") o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) }) }) o("m.route.set(m.route.get()) re-runs the resolution logic (#1180)", function(done){ var onmatch = o.spy() var render = o.spy(function() {return m("div")}) $window.location.href = prefix + "/" route(root, "/", { "/": { onmatch: onmatch, render: render } }) callAsync(function() { o(onmatch.callCount).equals(1) o(render.callCount).equals(1) route.set(route.get()) callAsync(function() { callAsync(function() { o(onmatch.callCount).equals(2) o(render.callCount).equals(2) done() }) }) }) }) o("m.route.get() returns the last fully resolved route (#1276)", function(done){ $window.location.href = prefix + "/" route(root, "/", { "/": {view: function() {}}, "/2": { onmatch: function() { return new Promise(function() {}) } } }) o(route.get()).equals("/") route.set("/2") callAsync(function() { o(route.get()).equals("/") done() }) }) o("routing with RouteResolver works more than once", function(done) { $window.location.href = prefix + "/a" route(root, "/a", { "/a": { render: function() { return m("a", "a") } }, "/b": { render: function() { return m("b", "b") } } }) route.set("/b") callAsync(function() { route.set("/a") callAsync(function() { o(root.firstChild.nodeName).equals("A") done() }) }) }) o("calling route.set invalidates pending onmatch resolution", function(done) { var rendered = false var resolved $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: function() { return new Promise(function(resolve) { callAsync(function() { callAsync(function() { resolve({view: function() {rendered = true}}) }) }) }) }, render: function() { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } } }) route.set("/b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) o("route changes activate onbeforeremove", function(done) { var spy = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onbeforeremove: spy, view: function() {} }, "/b": { view: function() {} } }) route.set("/b") callAsync(function() { o(spy.callCount).equals(1) done() }) }) o("asynchronous route.set in onmatch works", function(done) { var rendered = false, resolved route(root, "/a", { "/a": { onmatch: function() { return Promise.resolve().then(function() { route.set("/b") }) }, render: function() { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } }, }) callAsync(function() { // tick for popstate for /a callAsync(function() { // tick for promise in onmatch callAsync(function() { // tick for onpopstate for /b o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) }) o("throttles", function(done, timeout) { timeout(200) var i = 0 $window.location.href = prefix + "/" route(root, "/", { "/": {view: function() {i++}} }) var before = i redrawService.redraw() redrawService.redraw() redrawService.redraw() redrawService.redraw() var after = i setTimeout(function() { o(before).equals(1) // routes synchronously o(after).equals(2) // redraws synchronously o(i).equals(3) // throttles rest done() }, FRAME_BUDGET * 2) }) o("m.route.param is available outside of route handlers", function(done) { $window.location.href = prefix + "/" route(root, "/1", { "/:id" : { view : function() { o(route.param("id")).equals("1") return m("div") } } }) o(route.param("id")).equals(undefined); o(route.param()).deepEquals(undefined); callAsync(function() { o(route.param("id")).equals("1") o(route.param()).deepEquals({id:"1"}) done() }) }) }) }) }) }) mithril-1.1.6/browser.js000066400000000000000000000001641324223121200152010ustar00rootroot00000000000000"use strict" var m = require("./index") if (typeof module !== "undefined") module["exports"] = m else window.m = m mithril-1.1.6/bundler/000077500000000000000000000000001324223121200146125ustar00rootroot00000000000000mithril-1.1.6/bundler/README.md000066400000000000000000000045561324223121200161030ustar00rootroot00000000000000# bundler.js Simplistic CommonJS module bundler Version: 0.1 License: MIT ## About This bundler attempts to aggressively bundle CommonJS modules by assuming the dependency tree is static, similar to what Rollup does for ES6 modules. Most browsers don't support ES6 `import/export` syntax, but we can achieve modularity by using CommonJS module syntax and employing [`module.js`](../module/README.md) in browser environments. Webpack is conservative and treats CommonJS modules as non-statically-analyzable since `require` and `module.exports` are legally allowed everywhere. Therefore, it must generate extra code to resolve dependencies at runtime (i.e. `__webpack_require()`). Rollup only works with ES6 modules. ES6 modules can be bundled more efficiently because they are statically analyzable, but some use cases are difficult to handle due to ES6's support for cyclic dependencies and hosting rules. This bundler assumes code is written in CommonJS style but follows a strict set of rules that emulate statically analyzable code and favors the usage of the factory pattern instead of relying on obscure corners of the Javascript language (hoisting rules and binding semantics). ### Caveats - Only supports modules that have the `require` and `module.exports` statement declared at the top-level scope before all other code, i.e. it does not support CommonJS modules that rely on dynamic importing/exporting. This means modules should only export a pure function or export a factory function if there are multiple statements and/or internal module state. The factory function pattern allows easier dependency injection in stateful modules, thus making modules testable. - Changes the semantics of value/binding exporting between unbundled and bundled code, and therefore relying on those semantics is discouraged. Instead, it is recommended that module consumers inject dependencies via the factory function pattern - Top level strictness is infectious (i.e. if entry file is in `"use strict"` mode, all modules inherit strict mode, and conversely, if the entry file is not in strict mode, all modules are pulled out of strict mode) - Currently only supports assignments to `module.exports` (i.e. `module.exports.foo = bar` will not work) - It is tiny and dependency-free because it uses regular expressions, and it only supports the narrow range of import/export declaration patterns outlined above. mithril-1.1.6/bundler/bin/000077500000000000000000000000001324223121200153625ustar00rootroot00000000000000mithril-1.1.6/bundler/bin/bundle000077500000000000000000000000641324223121200165610ustar00rootroot00000000000000#!/usr/bin/env node "use strict" require("../cli") mithril-1.1.6/bundler/bin/bundle.cmd000066400000000000000000000000141324223121200173130ustar00rootroot00000000000000node bundle mithril-1.1.6/bundler/bundle.js000066400000000000000000000127401324223121200164250ustar00rootroot00000000000000"use strict" var fs = require("fs") var path = require("path") var proc = require("child_process") function read(filepath) { try {return fs.readFileSync(filepath, "utf8")} catch (e) {throw new Error("File does not exist: " + filepath)} } function isFile(filepath) { try {return fs.statSync(filepath).isFile()} catch (e) {return false} } function parse(file) { var json = read(file) try {return JSON.parse(json)} catch (e) {throw new Error("invalid JSON: " + json)} } var error function run(input, output) { try { var modules = {} var bindings = {} var declaration = /^\s*(?:var|let|const|function)[\t ]+([\w_$]+)/gm var include = /(?:((?:var|let|const|,|)[\t ]*)([\w_$\.\[\]"'`]+)(\s*=\s*))?require\(([^\)]+)\)(\s*[`\.\(\[])?/gm var uuid = 0 var process = function(filepath, data) { data.replace(declaration, function(match, binding) {bindings[binding] = 0}) return data.replace(include, function(match, def, variable, eq, dep, rest) { var filename = new Function("return " + dep).call(), pre = "" def = def || "", variable = variable || "", eq = eq || "", rest = rest || "" if (def[0] === ",") def = "\nvar ", pre = "\n" var dependency = resolve(filepath, filename) var localUUID = uuid // global uuid can update from nested `process` call, ensure same id is used on declaration and consumption var code = process(dependency, pre + (modules[dependency] == null ? exportCode(filename, dependency, def, variable, eq, rest, localUUID) : def + variable + eq + modules[dependency])) modules[dependency] = rest ? "_" + localUUID : variable uuid++ return code + rest }) } var resolve = function(filepath, filename) { if (filename[0] !== ".") { // resolve as npm dependency var packagePath = "./node_modules/" + filename + "/package.json" var meta = isFile(packagePath) ? parse(packagePath) : {} var main = "./node_modules/" + filename + "/" + (meta.main || filename + ".js") return path.resolve(isFile(main) ? main : "./node_modules/" + filename + "/index.js") } else { // resolve as local dependency return path.resolve(path.dirname(filepath), filename + ".js") } } var exportCode = function(filename, filepath, def, variable, eq, rest, uuid) { var code = read(filepath) // if there's a syntax error, report w/ proper stack trace try {new Function(code)} catch (e) { proc.exec("node " + filepath, function(e) { if (e !== null && e.message !== error) { error = e.message console.log("\x1b[31m" + e.message + "\x1b[0m") } }) } // disambiguate collisions var ignored = {} code.replace(include, function(match, def, variable, eq, dep) { var filename = new Function("return " + dep).call() var binding = modules[resolve(filepath, filename)] if (binding != null) ignored[binding] = true }) if (code.match(new RegExp("module\\.exports\\s*=\\s*" + variable + "\s*$", "m"))) ignored[variable] = true for (var binding in bindings) { if (!ignored[binding]) { var before = code code = code.replace(new RegExp("(\\b)" + binding + "\\b", "g"), binding + bindings[binding]) if (before !== code) bindings[binding]++ } } // fix strings that got mangled by collision disambiguation var string = /(["'])((?:\\\1|.)*?)(\1)/g var candidates = Object.keys(bindings).map(function(binding) {return binding + (bindings[binding] - 1)}).join("|") code = code.replace(string, function(match, open, data, close) { var variables = new RegExp(Object.keys(bindings).map(function(binding) {return binding + (bindings[binding] - 1)}).join("|"), "g") var fixed = data.replace(variables, function(match) { return match.replace(/\d+$/, "") }) return open + fixed + close }) //fix props var props = new RegExp("(\\.\\s*)(" + candidates + ")|([\\{,]\\s*)(" + candidates + ")(\\s*:)", "gm") code = code.replace(props, function(match, dot, a, pre, b, post) { if (dot) return dot + a.replace(/\d+$/, "") else return pre + b.replace(/\d+$/, "") + post }) return code .replace(/("|')use strict\1;?/gm, "") // remove extraneous "use strict" .replace(/module\.exports\s*=\s*/gm, rest ? "var _" + uuid + eq : def + (rest ? "_" : "") + variable + eq) // export + (rest ? "\n" + def + variable + eq + "_" + uuid : "") // if `rest` is truthy, it means the expression is fluent or higher-order (e.g. require(path).foo or require(path)(foo) } var versionTag = "bleeding-edge" var packageFile = __dirname + "/../package.json" var code = process(path.resolve(input), read(input)) .replace(/^\s*((?:var|let|const|)[\t ]*)([\w_$\.]+)(\s*=\s*)(\2)(?=[\s]+(\w)|;|$)/gm, "") // remove assignments to self .replace(/;+(\r|\n|$)/g, ";$1") // remove redundant semicolons .replace(/(\r|\n)+/g, "\n").replace(/(\r|\n)$/, "") // remove multiline breaks .replace(versionTag, isFile(packageFile) ? parse(packageFile).version : versionTag) // set version code = ";(function() {\n" + code + "\n}());" if (!isFile(output) || code !== read(output)) { //try {new Function(code); console.log("build completed at " + new Date())} catch (e) {} error = null fs.writeFileSync(output, code, "utf8") } } catch (e) { console.error(e.message) } } module.exports = function(input, output, options) { run(input, output) if (options && options.watch) { fs.watch(process.cwd(), {recursive: true}, function(file) { if (typeof file === "string" && path.resolve(output) !== path.resolve(file)) run(input, output) }) } } mithril-1.1.6/bundler/cli.js000066400000000000000000000026761324223121200157320ustar00rootroot00000000000000"use strict" var fs = require("fs"); var bundle = require("./bundle") var minify = require("./minify") var aliases = {o: "output", m: "minify", w: "watch", a: "aggressive"} var params = {} var args = process.argv.slice(2), command = null for (var i = 0; i < args.length; i++) { if (args[i][0] === '"') args[i] = JSON.parse(args[i]) if (args[i][0] === "-") { if (command != null) add(true) command = args[i].replace(/\-+/g, "") } else if (command != null) add(args[i]) else params.input = args[i] } if (command != null) add(true) function add(value) { params[aliases[command] || command] = value command = null } bundle(params.input, params.output, {watch: params.watch}) if (params.minify) { minify(params.output, params.output, {watch: params.watch, advanced: params.aggressive}, function(stats) { var readme, kb; function format(n) { return n.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") } console.log("Original size: " + format(stats.originalGzipSize) + " bytes gzipped (" + format(stats.originalSize) + " bytes uncompressed)") console.log("Compiled size: " + format(stats.compressedGzipSize) + " bytes gzipped (" + format(stats.compressedSize) + " bytes uncompressed)") readme = fs.readFileSync("./README.md", "utf8") kb = stats.compressedGzipSize / 1024 fs.writeFileSync("./README.md", readme.replace( /()(.+?)()/, "$1" + (kb % 1 ? kb.toFixed(2) : kb) + " KB$3" ) ) }) } mithril-1.1.6/bundler/minify.js000066400000000000000000000030131324223121200164400ustar00rootroot00000000000000"use strict" var http = require("https") var querystring = require("querystring") var fs = require("fs") module.exports = function(input, output, options, done) { function minify(input, output) { var code = fs.readFileSync(input, "utf8") var data = { output_format: "json", output_info: ["compiled_code", "warnings", "errors", "statistics"], compilation_level: options.advanced ? "ADVANCED_OPTIMIZATIONS" : "SIMPLE_OPTIMIZATIONS", warning_level: "default", output_file_name: "default.js", js_code: code, } var body = querystring.stringify(data) var response = "" var req = http.request({ method: "POST", hostname: "closure-compiler.appspot.com", path: "/compile", headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8", "Content-Length": body.length } }, function(res) { res.on("data", function(chunk) { response += chunk.toString() }) res.on("end", function() { try { var results = JSON.parse(response) } catch(e) { console.error(response); throw e; } if (results.errors) { for (var i = 0; i < results.errors.length; i++) console.log(results.errors[i]) } else { fs.writeFileSync(output, results.compiledCode, "utf8") console.log("done") if(typeof done === "function") done(results.statistics) } }) }) req.write(body) req.end() console.log("minifying...") } function run() { minify(input, output) } run() if (options && options.watch) fs.watchFile(input, run) } mithril-1.1.6/bundler/tests/000077500000000000000000000000001324223121200157545ustar00rootroot00000000000000mithril-1.1.6/bundler/tests/test-bundler.js000066400000000000000000000302571324223121200207310ustar00rootroot00000000000000"use strict" var o = require("../../ospec/ospec") var bundle = require("../bundle") var fs = require("fs") var ns = "bundler/tests/" function read(filepath) { try {return fs.readFileSync(ns + filepath, "utf8")} catch (e) {/* ignore */} } function write(filepath, data) { try {var exists = fs.statSync(ns + filepath).isFile()} catch (e) {/* ignore */} if (exists) throw new Error("Don't call `write('" + filepath + "')`. Cannot overwrite file") fs.writeFileSync(ns + filepath, data, "utf8") } function remove(filepath) { fs.unlinkSync(ns + filepath) } o.spec("bundler", function() { o("relative imports works", function() { write("a.js", 'var b = require("./b")') write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with semicolons", function() { write("a.js", 'var b = require("./b");') write("b.js", "module.exports = 1;") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b = 1;\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with let", function() { write("a.js", 'let b = require("./b")') write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nlet b = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with const", function() { write("a.js", 'const b = require("./b")') write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nconst b = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with assignment", function() { write("a.js", 'var a = {}\na.b = require("./b")') write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar a = {}\na.b = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports works with reassignment", function() { write("a.js", 'var b = {}\nb = require("./b")') write("b.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b = {}\nb = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict", function() { write("a.js", '"use strict"\nvar b = require("./b")') write("b.js", '"use strict"\nmodule.exports = 1') bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(';(function() {\n"use strict"\nvar b = 1\n}());') remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict using single quotes", function() { write("a.js", "'use strict'\nvar b = require(\"./b\")") write("b.js", "'use strict'\nmodule.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\n'use strict'\nvar b = 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("relative imports removes extra use strict using mixed quotes", function() { write("a.js", '"use strict"\nvar b = require("./b")') write("b.js", "'use strict'\nmodule.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(';(function() {\n"use strict"\nvar b = 1\n}());') remove("a.js") remove("b.js") remove("out.js") }) o("works w/ window", function() { write("a.js", 'window.a = 1\nvar b = require("./b")') write("b.js", "module.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nwindow.a = 1\nvar b = function() {return a}\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works without assignment", function() { write("a.js", 'require("./b")') write("b.js", "1 + 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\n1 + 1\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently", function() { write("a.js", 'var b = require("./b").toString()') write("b.js", "module.exports = []") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0.toString()\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently w/ multiline", function() { write("a.js", 'var b = require("./b")\n\t.toString()') write("b.js", "module.exports = []") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0\n\t.toString()\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if used w/ curry", function() { write("a.js", 'var b = require("./b")()') write("b.js", "module.exports = function() {}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = function() {}\nvar b = _0()\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if used w/ curry w/ multiline", function() { write("a.js", 'var b = require("./b")\n()') write("b.js", "module.exports = function() {}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = function() {}\nvar b = _0\n()\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if used fluently in one place and not in another", function() { write("a.js", 'var b = require("./b").toString()\nvar c = require("./c")') write("b.js", "module.exports = []") write("c.js", 'var b = require("./b")\nmodule.exports = function() {return b}') bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = []\nvar b = _0.toString()\nvar b0 = _0\nvar c = function() {return b0}\n}());") remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if used in sequence", function() { write("a.js", 'var b = require("./b"), c = require("./c")') write("b.js", "module.exports = 1") write("c.js", "var x\nmodule.exports = 2") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b = 1\nvar x\nvar c = 2\n}());") remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if assigned to property", function() { write("a.js", 'var x = {}\nx.b = require("./b")\nx.c = require("./c")') write("b.js", "var bb = 1\nmodule.exports = bb") write("c.js", "var cc = 2\nmodule.exports = cc") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar x = {}\nvar bb = 1\nx.b = bb\nvar cc = 2\nx.c = cc\n}());") remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if assigned to property using bracket notation", function() { write("a.js", 'var x = {}\nx["b"] = require("./b")\nx["c"] = require("./c")') write("b.js", "var bb = 1\nmodule.exports = bb") write("c.js", "var cc = 2\nmodule.exports = cc") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(';(function() {\nvar x = {}\nvar bb = 1\nx["b"] = bb\nvar cc = 2\nx["c"] = cc\n}());') remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if collision", function() { write("a.js", 'var b = require("./b")') write("b.js", "var b = 1\nmodule.exports = 2") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b0 = 1\nvar b = 2\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("works if multiple aliases", function() { write("a.js", 'var b = require("./b")\n') write("b.js", 'var b = require("./c")\nb.x = 1\nmodule.exports = b') write("c.js", "var b = {}\nmodule.exports = b") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b = {}\nb.x = 1\n}());") remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("works if multiple collision", function() { write("a.js", 'var b = require("./b")\nvar c = require("./c")\nvar d = require("./d")') write("b.js", "var a = 1\nmodule.exports = a") write("c.js", "var a = 2\nmodule.exports = a") write("d.js", "var a = 3\nmodule.exports = a") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar a = 1\nvar b = a\nvar a0 = 2\nvar c = a0\nvar a1 = 3\nvar d = a1\n}());") remove("a.js") remove("b.js") remove("c.js") remove("d.js") remove("out.js") }) o("works if included multiple times", function() { write("a.js", "module.exports = 123") write("b.js", 'var a = require("./a").toString()\nmodule.exports = a') write("c.js", 'var a = require("./a").toString()\nvar b = require("./b")') bundle(ns + "c.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = 123\nvar a = _0.toString()\nvar a0 = _0.toString()\nvar b = a0\n}());") remove("a.js") remove("b.js") remove("c.js") }) o("works if included multiple times reverse", function() { write("a.js", "module.exports = 123") write("b.js", 'var a = require("./a").toString()\nmodule.exports = a') write("c.js", 'var b = require("./b")\nvar a = require("./a").toString()') bundle(ns + "c.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar _0 = 123\nvar a0 = _0.toString()\nvar b = a0\nvar a = _0.toString()\n}());") remove("a.js") remove("b.js") remove("c.js") }) o("reuses binding if possible", function() { write("a.js", 'var b = require("./b")\nvar c = require("./c")') write("b.js", 'var d = require("./d")\nmodule.exports = function() {return d + 1}') write("c.js", 'var d = require("./d")\nmodule.exports = function() {return d + 2}') write("d.js", "module.exports = 1") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar d = 1\nvar b = function() {return d + 1}\nvar c = function() {return d + 2}\n}());") remove("a.js") remove("b.js") remove("c.js") remove("d.js") remove("out.js") }) o("disambiguates conflicts if imported collides with itself", function() { write("a.js", 'var b = require("./b")') write("b.js", "var b = 1\nmodule.exports = function() {return b}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b0 = 1\nvar b = function() {return b0}\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with something else", function() { write("a.js", 'var a = 1\nvar b = require("./b")') write("b.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar a = 1\nvar a0 = 2\nvar b = function() {return a0}\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with function declaration", function() { write("a.js", 'function a() {}\nvar b = require("./b")') write("b.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nfunction a() {}\nvar a0 = 2\nvar b = function() {return a0}\n}());") remove("a.js") remove("b.js") remove("out.js") }) o("disambiguates conflicts if imported collides with another module's private", function() { write("a.js", 'var b = require("./b")\nvar c = require("./c")') write("b.js", "var a = 1\nmodule.exports = function() {return a}") write("c.js", "var a = 2\nmodule.exports = function() {return a}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar a = 1\nvar b = function() {return a}\nvar a0 = 2\nvar c = function() {return a0}\n}());") remove("a.js") remove("b.js") remove("c.js") remove("out.js") }) o("does not mess up strings", function() { write("a.js", 'var b = require("./b")') write("b.js", 'var b = "b b b \\" b"\nmodule.exports = function() {return b}') bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(';(function() {\nvar b0 = "b b b \\\" b"\nvar b = function() {return b0}\n}());') remove("a.js") remove("b.js") remove("out.js") }) o("does not mess up properties", function() { write("a.js", 'var b = require("./b")') write("b.js", "var b = {b: 1}\nmodule.exports = function() {return b.b}") bundle(ns + "a.js", ns + "out.js") o(read("out.js")).equals(";(function() {\nvar b0 = {b: 1}\nvar b = function() {return b0.b}\n}());") remove("a.js") remove("b.js") remove("out.js") }) }) mithril-1.1.6/docs/000077500000000000000000000000001324223121200141075ustar00rootroot00000000000000mithril-1.1.6/docs/CNAME000066400000000000000000000000171324223121200146530ustar00rootroot00000000000000mithril.js.org mithril-1.1.6/docs/animation.md000066400000000000000000000105501324223121200164110ustar00rootroot00000000000000# Animations - [Technology choices](#technology-choices) - [Animation on element creation](#animation-on-element-creation) - [Animation on element removal](#animation-on-element-removal) - [Performance](#performance) --- ### Technology choices Animations are often used to make applications come alive. Nowadays, browsers have good support for CSS animations, and there are [various](https://greensock.com/gsap) [libraries](http://velocityjs.org/) that provide fast Javascript-based animations. There's also an upcoming [Web API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API) and a [polyfill](https://github.com/web-animations/web-animations-js) if you like living on the bleeding edge. Mithril does not provide any animation APIs per se, since these other options are more than sufficient to achieve rich, complex animations. Mithril does, however, offer hooks to make life easier in some specific cases where it's traditionally difficult to make animations work. --- ### Animation on element creation Animating an element via CSS when the element created couldn't be simpler. Just add an animation to a CSS class normally: ```css .fancy {animation:fade-in 0.5s;} @keyframes fade-in { from {opacity:0;} to {opacity:1;} } ``` ```javascript var FancyComponent = { view: function() { return m(".fancy", "Hello world") } } m.mount(document.body, FancyComponent) ``` --- ### Animation on element removal The problem with animating before removing an element is that we must wait until the animation is complete before we can actually remove the element. Fortunately, Mithril offers a [`onbeforeremove`](lifecycle-methods.md#onbeforeremove) hook that allows us to defer the removal of an element. Let's create an `exit` animation that fades `opacity` from 1 to 0. ```css .exit {animation:fade-out 0.5s;} @keyframes fade-out { from {opacity:1;} to {opacity:0;} } ``` Now let's create a contrived component that shows and hides the `FancyComponent` we created in the previous section: ```javascript var on = true var Toggler = { view: function() { return [ m("button", {onclick: function() {on = !on}}, "Toggle"), on ? m(FancyComponent) : null, ] } } ``` Next, let's modify `FancyComponent` so that it fades out when removed: ```javascript var FancyComponent = { onbeforeremove: function(vnode) { vnode.dom.classList.add("exit") return new Promise(function(resolve) { setTimeout(resolve, 500) }) }, view: function() { return m(".fancy", "Hello world") } } ``` `vnode.dom` points to the root DOM element of the component (`
`). We use the classList API here to add an `exit` class to `
`. Then we return a [Promise](promise.md) that resolves after half a second. When we return a promise from `onbeforeremove`, Mithril waits until the promise is resolved and only then it removes the element. In this case, it waits half a second, giving the exit animation the exact time it needs to complete. We can verify that both the enter and exit animations work by mounting the `Toggler` component: ```javascript m.mount(document.body, Toggler) ``` Note that the `onbeforeremove` hook only fires on the element that loses its `parentNode` when an element gets detached from the DOM. This behavior is by design and exists to prevent a potential jarring user experience where every conceivable exit animation on the page would run on a route change. If your exit animation is not running, make sure to attach the `onbeforeremove` handler as high up the tree as it makes sense to ensure that your animation code is called. --- ### Performance When creating animations, it's recommended that you only use the `opacity` and `transform` CSS rules, since these can be hardware-accelerated by modern browsers and yield better performance than animating `top`, `left`, `width`, and `height`. It's also recommended that you avoid the `box-shadow` rule and selectors like `:nth-child`, since these are also resource intensive options. If you want to animate a `box-shadow`, consider [putting the `box-shadow` rule on a pseudo element, and animate that element's opacity instead](http://tobiasahlin.com/blog/how-to-animate-box-shadow/). Other things that can be expensive include large or dynamically scaled images and overlapping elements with different `position` values (e.g. an absolute postioned element over a fixed element). mithril-1.1.6/docs/api.md000066400000000000000000000051441324223121200152060ustar00rootroot00000000000000# API ### Cheatsheet Here are examples for the most commonly used methods. If a method is not listed below, it's meant for advanced usage. #### m(selector, attrs, children) - [docs](hyperscript.md) ```javascript m("div.class#id", {title: "title"}, ["children"]) ``` --- #### m.mount(element, component) - [docs](mount.md) ```javascript var state = { count: 0, inc: function() {state.count++} } var Counter = { view: function() { return m("div", {onclick: state.inc}, state.count) } } m.mount(document.body, Counter) ``` --- #### m.route(root, defaultRoute, routes) - [docs](route.md) ```javascript var Home = { view: function() { return "Welcome" } } m.route(document.body, "/home", { "/home": Home, // defines `http://localhost/#!/home` }) ``` #### m.route.set(path) - [docs](route.md#mrouteset) ```javascript m.route.set("/home") ``` #### m.route.get() - [docs](route.md#mrouteget) ```javascript var currentRoute = m.route.get() ``` #### m.route.prefix(prefix) - [docs](route.md#mrouteprefix) Call this before `m.route()` ```javascript m.route.prefix("#!") ``` #### m.route.link() - [docs](route.md#mroutelink) ```javascript m("a[href='/Home']", {oncreate: m.route.link}, "Go to home page") ``` --- #### m.request(options) - [docs](request.md) ```javascript m.request({ method: "PUT", url: "/api/v1/users/:id", data: {id: 1, name: "test"} }) .then(function(result) { console.log(result) }) ``` --- #### m.jsonp(options) - [docs](jsonp.md) ```javascript m.jsonp({ url: "/api/v1/users/:id", data: {id: 1}, callbackKey: "callback", }) .then(function(result) { console.log(result) }) ``` --- #### m.parseQueryString(querystring) - [docs](parseQueryString.md) ```javascript var object = m.parseQueryString("a=1&b=2") // {a: "1", b: "2"} ``` --- #### m.buildQueryString(object) - [docs](buildQueryString.md) ```javascript var querystring = m.buildQueryString({a: "1", b: "2"}) // "a=1&b=2" ``` --- #### m.withAttr(attrName, callback) - [docs](withAttr.md) ```javascript var state = { value: "", setValue: function(v) {state.value = v} } var Component = { view: function() { return m("input", { oninput: m.withAttr("value", state.setValue), value: state.value, }) } } m.mount(document.body, Component) ``` --- #### m.trust(htmlString) - [docs](trust.md) ```javascript m.render(document.body, m.trust("

Hello

")) ``` --- #### m.redraw() - [docs](redraw.md) ```javascript var count = 0 function inc() { setInterval(function() { count++ m.redraw() }, 1000) } var Counter = { oninit: inc, view: function() { return m("div", count) } } m.mount(document.body, Counter) ``` mithril-1.1.6/docs/autoredraw.md000066400000000000000000000100441324223121200166050ustar00rootroot00000000000000# The auto-redraw system Mithril implements a virtual DOM diffing system for fast rendering, and in addition, it offers various mechanisms to gain granular control over the rendering of an application. When used idiomatically, Mithril employs an auto-redraw system that synchronizes the DOM whenever changes are made in the data layer. The auto-redraw system becomes enabled when you call `m.mount` or `m.route` (but it stays disabled if your app is bootstrapped solely via `m.render` calls). The auto-redraw system simply consists of triggering a re-render function behind the scenes after certain functions complete. ### After event handlers Mithril automatically redraws after DOM event handlers that are defined in a Mithril view: ```javascript var MyComponent = { view: function() { return m("div", {onclick: doSomething}) } } function doSomething() { // a redraw happens synchronously after this function runs } m.mount(document.body, MyComponent) ``` You can disable an auto-redraw for specific events by setting `e.redraw` to `false`. ```javascript var MyComponent = { view: function() { return m("div", {onclick: doSomething}) } } function doSomething(e) { e.redraw = false // no longer triggers a redraw when the div is clicked } m.mount(document.body, MyComponent) ``` ### After m.request Mithril automatically redraws after [`m.request`](request.md) completes: ```javascript m.request("/api/v1/users").then(function() { // a redraw happens after this function runs }) ``` You can disable an auto-redraw for a specific request by setting the `background` option to true: ```javascript m.request("/api/v1/users", {background: true}).then(function() { // does not trigger a redraw }) ``` ### After route changes Mithril automatically redraws after [`m.route.set()`](route.md#mrouteset) calls (or route changes via links that use [`m.route.link`](route.md#mroutelink) ```javascript var RoutedComponent = { view: function() { return [ // a redraw happens asynchronously after the route changes m("a", {href: "/", oncreate: m.route.link}), m("div", { onclick: function() { m.route.set("/") } }), ] } } m.route(document.body, "/", { "/": RoutedComponent, }) ``` --- ### When Mithril does not redraw Mithril does not redraw after `setTimeout`, `setInterval`, `requestAnimationFrame`, raw `Promise` resolutions and 3rd party library event handlers (e.g. Socket.io callbacks). In those cases, you must manually call [`m.redraw()`](redraw.md). Mithril also does not redraw after lifecycle methods. Parts of the UI may be redrawn after an `oninit` handler, but other parts of the UI may already have been redrawn when a given `oninit` handler fires. Handlers like `oncreate` and `onupdate` fire after the UI has been redrawn. If you need to explicitly trigger a redraw within a lifecycle method, you should call `m.redraw()`, which will trigger an asynchronous redraw. ```javascript var StableComponent = { oncreate: function(vnode) { vnode.state.height = vnode.dom.offsetHeight m.redraw() }, view: function() { return m("div", "This component is " + vnode.state.height + "px tall") } } ``` Mithril does not auto-redraw vnode trees that are rendered via `m.render`. This means redraws do not occur after event changes and `m.request` calls for templates that were rendered via `m.render`. Thus, if your architecture requires manual control over when rendering occurs (as can sometimes be the case when using libraries like Redux), you should use `m.render` instead of `m.mount`. Remember that `m.render` expects a vnode tree, and `m.mount` expects a component: ```javascript // wrap the component in a m() call for m.render m.render(document.body, m(MyComponent)) // don't wrap the component for m.mount m.mount(document.body, MyComponent) ``` Mithril may also avoid auto-redrawing if the frequency of requested redraws is higher than one animation frame (typically around 16ms). This means, for example, that when using fast-firing events like `onresize` or `onscroll`, Mithril will automatically throttle the number of redraws to avoid lag. mithril-1.1.6/docs/buildQueryString.md000066400000000000000000000023661324223121200177540ustar00rootroot00000000000000# buildQueryString(object) - [Description](#description) - [Signature](#signature) - [How it works](#how-it-works) --- ### Description Turns an object into a string of form `a=1&b=2` ```javascript var querystring = m.buildQueryString({a: "1", b: "2"}) // "a=1&b=2" ``` --- ### Signature `querystring = m.buildQueryString(object)` Argument | Type | Required | Description ------------ | ------------------------------------------ | -------- | --- `object` | `Object` | Yes | A key-value map to be converted into a string **returns** | `String` | | A string representing the input object [How to read signatures](signatures.md) --- ### How it works The `m.buildQueryString` creates a querystring from an object. It's useful for manipulating URLs ```javascript var querystring = m.buildQueryString({a: 1, b: 2}) // querystring is "a=1&b=2" ``` #### Deep data structures Deep data structures are serialized in a way that is understood by popular web application servers such as PHP, Rails and ExpressJS ```javascript var querystring = m.buildQueryString({a: ["hello", "world"]}) // querystring is "a[0]=hello&a[1]=world" ``` mithril-1.1.6/docs/change-log.md000066400000000000000000000576111324223121200164470ustar00rootroot00000000000000# Change log - [v1.1.6](#v116) - [v1.1.5](#v115) - [v1.1.4](#v114) - [v1.1.3](#v113) - [v1.1.2](#v112) - [v1.1.1](#v111) - [v1.1.0](#v110) - [v1.0.1](#v101) - [Migrating from v0.2.x](#migrating-from-v02x) - [Older docs](http://mithril.js.org/archive/v0.2.5/index.html) --- ### v1.1.6 #### Bug fixes - core: render() function can no longer prevent from changing `document.activeElement` in lifecycle hooks ([#1988](https://github.com/MithrilJS/mithril.js/pull/1988), [@purplecode](https://github.com/purplecode)) - core: don't call `onremove` on the children of components that return null from the view [#1921](https://github.com/MithrilJS/mithril.js/issues/1921) [@octavore](https://github.com/octavore) ([#1922](https://github.com/MithrilJS/mithril.js/pull/1922)) - hypertext: correct handling of shared attributes object passed to `m()`. Will copy attributes when it's necessary [#1941](https://github.com/MithrilJS/mithril.js/issues/1941) [@s-ilya](https://github.com/s-ilya) ([#1942](https://github.com/MithrilJS/mithril.js/pull/1942)) #### Ospec improvements - ospec v1.4.0 - Added support for async functions and promises in tests ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928), [@StephanHoyer](https://github.com/StephanHoyer)) - Error handling for async tests with `done` callbacks supports error as first argument ([#1928](https://github.com/MithrilJS/mithril.js/pull/1928)) - Error messages which include newline characters do not swallow the stack trace [#1495](https://github.com/MithrilJS/mithril.js/issues/1495) ([#1984](https://github.com/MithrilJS/mithril.js/pull/1984), [@RodericDay](https://github.com/RodericDay)) - ospec v2.0.0 (to be released) - Added support for custom reporters ([#2009](https://github.com/MithrilJS/mithril.js/pull/2020)) - Make Ospec more [Flems](https://flems.io)-friendly ([#2034](https://github.com/MithrilJS/mithril.js/pull/2034)) - Works either as a global or in CommonJS environments - the o.run() report is always printed asynchronously (it could be synchronous before if none of the tests were async). - Properly point to the assertion location of async errors [#2036](https://github.com/MithrilJS/mithril.js/issues/2036) - expose the default reporter as `o.report(results)` - Don't try to access the stack traces in IE9 --- ### v1.1.5 #### Bug fixes - API: If a user sets the Content-Type header within a request's options, that value will be the entire header value rather than being appended to the default value [#1919](https://github.com/MithrilJS/mithril.js/issues/1919) ([#1924](https://github.com/MithrilJS/mithril.js/pull/1924), [@tskillian](https://github.com/tskillian)) --- ### v1.1.4 #### Bug fixes - Fix IE bug where active element is null causing render function to throw error ([#1943](https://github.com/MithrilJS/mithril.js/pull/1943), [@JacksonJN](https://github.com/JacksonJN)) --- ### v1.1.3 #### Bug fixes - move out npm dependencies added by mistake --- ### v1.1.2 #### Bug fixes - core: Namespace fixes [#1819](https://github.com/MithrilJS/mithril.js/issues/1819), ([#1825](https://github.com/MithrilJS/mithril.js/pull/1825) [@SamuelTilly](https://github.com/SamuelTilly)), [#1820](https://github.com/MithrilJS/mithril.js/issues/1820) ([#1864](https://github.com/MithrilJS/mithril.js/pull/1864)), [#1872](https://github.com/MithrilJS/mithril.js/issues/1872) ([#1873](https://github.com/MithrilJS/mithril.js/pull/1873)) - core: Fix select option to allow empty string value [#1814](https://github.com/MithrilJS/mithril.js/issues/1814) ([#1828](https://github.com/MithrilJS/mithril.js/pull/1828) [@spacejack](https://github.com/spacejack)) - core: Reset e.redraw when it was set to `false` [#1850](https://github.com/MithrilJS/mithril.js/issues/1850) ([#1890](https://github.com/MithrilJS/mithril.js/pull/1890)) - core: differentiate between `{ value: "" }` and `{ value: 0 }` for form elements [#1595 comment](https://github.com/MithrilJS/mithril.js/pull/1595#issuecomment-304071453) ([#1862](https://github.com/MithrilJS/mithril.js/pull/1862)) - core: Don't reset the cursor of textareas in IE10 when setting an identical `value` [#1870](https://github.com/MithrilJS/mithril.js/issues/1870) ([#1871](https://github.com/MithrilJS/mithril.js/pull/1871)) - hypertext: Correct handling of `[value=""]` ([#1843](https://github.com/MithrilJS/mithril.js/issues/1843), [@CreaturesInUnitards](https://github.com/CreaturesInUnitards)) - router: Don't overwrite the options object when redirecting from `onmatch with m.route.set()` [#1857](https://github.com/MithrilJS/mithril.js/issues/1857) ([#1889](https://github.com/MithrilJS/mithril.js/pull/1889)) - stream: Move the "use strict" directive inside the IIFE [#1831](https://github.com/MithrilJS/mithril.js/issues/1831) ([#1893](https://github.com/MithrilJS/mithril.js/pull/1893)) #### Ospec improvements - Shell command: Ignore hidden directories and files ([#1855](https://github.com/MithrilJS/mithril.js/pull/1855) [@pdfernhout)](https://github.com/pdfernhout)) - Library: Add the possibility to name new test suites ([#1529](https://github.com/MithrilJS/mithril.js/pull/1529)) #### Docs / Repo maintenance Our thanks to [@0joshuaolson1](https://github.com/0joshuaolson1), [@ACXgit](https://github.com/ACXgit), [@cavemansspa](https://github.com/cavemansspa), [@CreaturesInUnitards](https://github.com/CreaturesInUnitards), [@dlepaux](https://github.com/dlepaux), [@isaaclyman](https://github.com/isaaclyman), [@kevinkace](https://github.com/kevinkace), [@micellius](https://github.com/micellius), [@spacejack](https://github.com/spacejack) and [@yurivish](https://github.com/yurivish) #### Other - Addition of a performance regression test suite ([#1789](https://github.com/MithrilJS/mithril.js/issues/1789)) --- ### v1.1.1 #### Bug fixes - hyperscript: Allow `0` as the second argument to `m()` - [#1752](https://github.com/MithrilJS/mithril.js/issues/1752) / [#1753](https://github.com/MithrilJS/mithril.js/pull/1753) ([@StephanHoyer](https://github.com/StephanHoyer)) - hyperscript: restore `attrs.class` handling to what it was in v1.0.1 - [#1764](https://github.com/MithrilJS/mithril.js/issues/1764) / [#1769](https://github.com/MithrilJS/mithril.js/pull/1769) - documentation improvements ([@JAForbes](https://github.com/JAForbes), [@smuemd](https://github.com/smuemd), [@hankeypancake](https://github.com/hankeypancake)) --- ### v1.1.0 #### News - support for ES6 class components - support for closure components - improvements in build and release automation #### Bug fixes - fix IE11 input[type] error - [#1610](https://github.com/MithrilJS/mithril.js/issues/1610) - apply [#1609](https://github.com/MithrilJS/mithril.js/issues/1609) to unkeyed children case - fix abort detection [#1612](https://github.com/MithrilJS/mithril.js/issues/1612) - fix input value focus issue when value is loosely equal to old value [#1593](https://github.com/MithrilJS/mithril.js/issues/1593) --- ### v1.0.1 #### News - performance improvements in IE [#1598](https://github.com/MithrilJS/mithril.js/pull/1598) #### Bug fixes - prevent infinite loop in non-existent default route - [#1579](https://github.com/MithrilJS/mithril.js/issues/1579) - call correct lifecycle methods on children of recycled keyed vnodes - [#1609](https://github.com/MithrilJS/mithril.js/issues/1609) --- ### Migrating from `v0.2.x` `v1.x` is largely API-compatible with `v0.2.x`, but there are some breaking changes. If you are migrating, consider using the [mithril-codemods](https://www.npmjs.com/package/mithril-codemods) tool to help automate the most straightforward migrations. - [`m.prop` removed](#mprop-removed) - [`m.component` removed](#mcomponent-removed) - [`config` function](#config-function) - [Changes in redraw behaviour](#changes-in-redraw-behaviour) - [No more redraw locks](#no-more-redraw-locks) - [Cancelling redraw from event handlers](#cancelling-redraw-from-event-handlers) - [Synchronous redraw removed](#synchronous-redraw-removed) - [`m.startComputation`/`m.endComputation` removed](#mstartcomputationmendcomputation-removed) - [Component `controller` function](#component-controller-function) - [Component arguments](#component-arguments) - [`view()` parameters](#view-parameters) - [Passing components to `m()`](#passing-components-to-m) - [Passing vnodes to `m.mount()` and `m.route()`](#passing-vnodes-to-mmount-and-mroute) - [`m.route.mode`](#mroutemode) - [`m.route` and anchor tags](#mroute-and-anchor-tags) - [Reading/writing the current route](#readingwriting-the-current-route) - [Accessing route params](#accessing-route-params) - [Building/Parsing query strings](#buildingparsing-query-strings) - [Preventing unmounting](#preventing-unmounting) - [Run code on component removal](#run-code-on-component-removal) - [`m.request`](#mrequest) - [`m.deferred` removed](#mdeferred-removed) - [`m.sync` removed](#msync-removed) - [`xlink` namespace required](#xlink-namespace-required) - [Nested arrays in views](#nested-arrays-in-views) - [`vnode` equality checks](#vnode-equality-checks) --- ## `m.prop` removed In `v1.x`, `m.prop()` is now a more powerful stream micro-library, but it's no longer part of core. You can read about how to use the optional Streams module in [the documentation](stream.md). ### `v0.2.x` ```javascript var m = require("mithril") var num = m.prop(1) ``` ### `v1.x` ```javascript var m = require("mithril") var prop = require("mithril/stream") var num = prop(1) var doubled = num.map(function(n) {return n * 2}) ``` --- ## `m.component` removed In `v0.2.x` components could be created using either `m(component)` or `m.component(component)`. `v1.x` only supports `m(component)`. ### `v0.2.x` ```javascript // These are equivalent m.component(component) m(component) ``` ### `v1.x` ```javascript m(component) ``` --- ## `config` function In `v0.2.x` mithril provided a single lifecycle method, `config`. `v1.x` provides much more fine-grained control over the lifecycle of a vnode. ### `v0.2.x` ```javascript m("div", { config : function(element, isInitialized) { // runs on each redraw // isInitialized is a boolean representing if the node has been added to the DOM } }) ``` ### `v1.x` More documentation on these new methods is available in [lifecycle-methods.md](lifecycle-methods.md). ```javascript m("div", { // Called before the DOM node is created oninit : function(vnode) { /*...*/ }, // Called after the DOM node is created oncreate : function(vnode) { /*...*/ }, // Called before the node is updated, return false to cancel onbeforeupdate : function(vnode, old) { /*...*/ }, // Called after the node is updated onupdate : function(vnode) { /*...*/ }, // Called before the node is removed, return a Promise that resolves when // ready for the node to be removed from the DOM onbeforeremove : function(vnode) { /*...*/ }, // Called before the node is removed, but after onbeforeremove calls done() onremove : function(vnode) { /*...*/ } }) ``` If available the DOM-Element of the vnode can be accessed at `vnode.dom`. --- ## Changes in redraw behaviour Mithril's rendering engine still operates on the basis of semi-automated global redraws, but some APIs and behaviours differ: ### No more redraw locks In v0.2.x, Mithril allowed 'redraw locks' which temporarily prevented blocked draw logic: by default, `m.request` would lock the draw loop on execution and unlock when all pending requests had resolved - the same behaviour could be invoked manually using `m.startComputation()` and `m.endComputation()`. The latter APIs and the associated behaviour has been removed in v1.x. Redraw locking can lead to buggy UIs: the concerns of one part of the application should not be allowed to prevent other parts of the view from updating to reflect change. ### Cancelling redraw from event handlers `m.mount()` and `m.route()` still automatically redraw after a DOM event handler runs. Cancelling these redraws from within your event handlers is now done by setting the `redraw` property on the passed-in event object to `false`. #### `v0.2.x` ```javascript m("div", { onclick : function(e) { m.redraw.strategy("none") } }) ``` #### `v1.x` ```javascript m("div", { onclick : function(e) { e.redraw = false } }) ``` ### Synchronous redraw removed In v0.2.x it was possible to force mithril to redraw immediately by passing a truthy value to `m.redraw()`. This behavior complicated usage of `m.redraw()` and caused some hard-to-reason about issues and has been removed. #### `v0.2.x` ```javascript m.redraw(true) // redraws immediately & synchronously ``` #### `v1.x` ```javascript m.redraw() // schedules a redraw on the next requestAnimationFrame tick ``` ### `m.startComputation`/`m.endComputation` removed They are considered anti-patterns and have a number of problematic edge cases, so they no longer exist in v1.x. --- ## Component `controller` function In `v1.x` there is no more `controller` property in components, use `oninit` instead. ### `v0.2.x` ```javascript m.mount(document.body, { controller : function() { var ctrl = this ctrl.fooga = 1 }, view : function(ctrl) { return m("p", ctrl.fooga) } }) ``` ### `v1.x` ```javascript m.mount(document.body, { oninit : function(vnode) { vnode.state.fooga = 1 }, view : function(vnode) { return m("p", vnode.state.fooga) } }) // OR m.mount(document.body, { oninit : function(vnode) { var state = this // this is bound to vnode.state by default state.fooga = 1 }, view : function(vnode) { var state = this // this is bound to vnode.state by default return m("p", state.fooga) } }) ``` --- ## Component arguments Arguments to a component in `v1.x` must be an object, simple values like `String`/`Number`/`Boolean` will be treated as text children. Arguments are accessed within the component by reading them from the `vnode.attrs` object. ### `v0.2.x` ```javascript var component = { controller : function(options) { // options.fooga === 1 }, view : function(ctrl, options) { // options.fooga == 1 } } m("div", m.component(component, { fooga : 1 })) ``` ### `v1.x` ```javascript var component = { oninit : function(vnode) { // vnode.attrs.fooga === 1 }, view : function(vnode) { // vnode.attrs.fooga == 1 } } m("div", m(component, { fooga : 1 })) ``` --- ## `view()` parameters In `v0.2.x` view functions are passed a reference to the `controller` instance and (optionally) any options passed to the component. In `v1.x` they are passed **only** the `vnode`, exactly like the `controller` function. ### `v0.2.x` ```javascript m.mount(document.body, { controller : function() {}, view : function(ctrl, options) { // ... } }) ``` ### `v1.x` ```javascript m.mount(document.body, { oninit : function(vnode) { // ... }, view : function(vnode) { // Use vnode.state instead of ctrl // Use vnode.attrs instead of options } }) ``` --- ## Passing components to `m()` In `v0.2.x` you could pass components as the second argument of `m()` w/o any wrapping required. To help with consistency in `v1.x` they must always be wrapped with a `m()` invocation. ### `v0.2.x` ```javascript m("div", component) ``` ### `v1.x` ```javascript m("div", m(component)) ``` --- ## Passing vnodes to `m.mount()` and `m.route()` In `v0.2.x`, `m.mount(element, component)` tolerated [vnodes](vnodes.md) as second arguments instead of [components](components.md) (even though it wasn't documented). Likewise, `m.route(element, defaultRoute, routes)` accepted vnodes as values in the `routes` object. In `v1.x`, components are required instead in both cases. ### `v0.2.x` ```javascript m.mount(element, m('i', 'hello')) m.mount(element, m(Component, attrs)) m.route(element, '/', { '/': m('b', 'bye') }) ``` ### `v1.x` ```javascript m.mount(element, {view: function () {return m('i', 'hello')}}) m.mount(element, {view: function () {return m(Component, attrs)}}) m.route(element, '/', { '/': {view: function () {return m('b', 'bye')}} }) ``` --- ## `m.route.mode` In `v0.2.x` the routing mode could be set by assigning a string of `"pathname"`, `"hash"`, or `"search"` to `m.route.mode`. In `v.1.x` it is replaced by `m.route.prefix(prefix)` where `prefix` can be `#`, `?`, or an empty string (for "pathname" mode). The new API also supports hashbang (`#!`), which is the default, and it supports non-root pathnames and arbitrary mode variations such as querybang (`?!`) ### `v0.2.x` ```javascript m.route.mode = "pathname" m.route.mode = "search" ``` ### `v1.x` ```javascript m.route.prefix("") m.route.prefix("?") ``` --- ## `m.route()` and anchor tags Handling clicks on anchor tags via the mithril router is similar to `v0.2.x` but uses a new lifecycle method and API. ### `v0.2.x` ```javascript // When clicked this link will load the "/path" route instead of navigating m("a", { href : "/path", config : m.route }) ``` ### `v1.x` ```javascript // When clicked this link will load the "/path" route instead of navigating m("a", { href : "/path", oncreate : m.route.link }) ``` --- ## Reading/writing the current route In `v0.2.x` all interaction w/ the current route happened via `m.route()`. In `v1.x` this has been broken out into two functions. ### `v0.2.x` ```javascript // Getting the current route m.route() // Setting a new route m.route("/other/route") ``` ### `v1.x` ```javascript // Getting the current route m.route.get() // Setting a new route m.route.set("/other/route") ``` --- ## Accessing route params In `v0.2.x` reading route params was entirely handled through `m.route.param()`. This API is still available in `v1.x`, and additionally any route params are passed as properties in the `attrs` object on the vnode. ### `v0.2.x` ```javascript m.route(document.body, "/booga", { "/:attr" : { controller : function() { m.route.param("attr") // "booga" }, view : function() { m.route.param("attr") // "booga" } } }) ``` ### `v1.x` ```javascript m.route(document.body, "/booga", { "/:attr" : { oninit : function(vnode) { vnode.attrs.attr // "booga" m.route.param("attr") // "booga" }, view : function(vnode) { vnode.attrs.attr // "booga" m.route.param("attr") // "booga" } } }) ``` --- ## Building/Parsing query strings `v0.2.x` used methods hanging off of `m.route`, `m.route.buildQueryString()` and `m.route.parseQueryString()`. In `v1.x` these have been broken out and attached to the root `m`. ### `v0.2.x` ```javascript var qs = m.route.buildQueryString({ a : 1 }); var obj = m.route.parseQueryString("a=1"); ``` ### `v1.x` ```javascript var qs = m.buildQueryString({ a : 1 }); var obj = m.parseQueryString("a=1"); ``` --- ## Preventing unmounting It is no longer possible to prevent unmounting via `onunload`'s `e.preventDefault()`. Instead you should explicitly call `m.route.set` when the expected conditions are met. ### `v0.2.x` ```javascript var Component = { controller: function() { this.onunload = function(e) { if (condition) e.preventDefault() } }, view: function() { return m("a[href=/]", {config: m.route}) } } ``` ### `v1.x` ```javascript var Component = { view: function() { return m("a", {onclick: function() {if (!condition) m.route.set("/")}}) } } ``` --- ## Run code on component removal Components no longer call `this.onunload` when they are being removed. They now use the standardized lifecycle hook `onremove`. ### `v0.2.x` ```javascript var Component = { controller: function() { this.onunload = function(e) { // ... } }, view: function() { // ... } } ``` ### `v1.x` ```javascript var Component = { onremove : function() { // ... } view: function() { // ... } } ``` --- ## m.request Promises returned by [m.request](request.md) are no longer `m.prop` getter-setters. In addition, `initialValue`, `unwrapSuccess` and `unwrapError` are no longer supported options. In addition, requests no longer have `m.startComputation`/`m.endComputation` semantics. Instead, redraws are always triggered when a request promise chain completes (unless `background:true` is set). ### `v0.2.x` ```javascript var data = m.request({ method: "GET", url: "https://api.github.com/", initialValue: [], }) setTimeout(function() { console.log(data()) }, 1000) ``` ### `v1.x` ```javascript var data = [] m.request({ method: "GET", url: "https://api.github.com/", }) .then(function (responseBody) { data = responseBody }) setTimeout(function() { console.log(data) // note: not a getter-setter }, 1000) ``` Additionally, if the `extract` option is passed to `m.request` the return value of the provided function will be used directly to resolve the request promise, and the `deserialize` callback is ignored. --- ## `m.deferred` removed `v0.2.x` used its own custom asynchronous contract object, exposed as `m.deferred`, which was used as the basis for `m.request`. `v1.x` uses Promises instead, and implements a [polyfill](promises.md) in non-supporting environments. In situations where you would have used `m.deferred`, you should use Promises instead. ### `v0.2.x` ```javascript var greetAsync = function() { var deferred = m.deferred() setTimeout(function() { deferred.resolve("hello") }, 1000) return deferred.promise } greetAsync() .then(function(value) {return value + " world"}) .then(function(value) {console.log(value)}) //logs "hello world" after 1 second ``` ### `v1.x` ```javascript var greetAsync = function() { return new Promise(function(resolve){ setTimeout(function() { resolve("hello") }, 1000) }) } greetAsync() .then(function(value) {return value + " world"}) .then(function(value) {console.log(value)}) //logs "hello world" after 1 second ``` --- ## `m.sync` removed Since `v1.x` uses standards-compliant Promises, `m.sync` is redundant. Use `Promise.all` instead. ### `v0.2.x` ```javascript m.sync([ m.request({ method: 'GET', url: 'https://api.github.com/users/lhorie' }), m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }), ]) .then(function (users) { console.log("Contributors:", users[0].name, "and", users[1].name) }) ``` ### `v1.x` ```javascript Promise.all([ m.request({ method: 'GET', url: 'https://api.github.com/users/lhorie' }), m.request({ method: 'GET', url: 'https://api.github.com/users/isiahmeadows' }), ]) .then(function (users) { console.log("Contributors:", users[0].name, "and", users[1].name) }) ``` --- ## `xlink` namespace required In `v0.2.x`, the `xlink` namespace was the only supported attribute namespace, and it was supported via special casing behavior. Now namespace parsing is fully supported, and namespaced attributes should explicitly declare their namespace. ### `v0.2.x` ```javascript m("svg", // the `href` attribute is namespaced automatically m("image[href='image.gif']") ) ``` ### `v1.x` ```javascript m("svg", // User-specified namespace on the `href` attribute m("image[xlink:href='image.gif']") ) ``` --- ## Nested arrays in views Arrays now represent [fragments](fragment.md), which are structurally significant in v1.x virtual DOM. Whereas nested arrays in v0.2.x would be flattened into one continuous list of virtual nodes for the purposes of diffing, v1.x preserves the array structure - the children of any given array are not considered siblings of those of adjacent arrays. --- ## `vnode` equality checks If a vnode is strictly equal to the vnode occupying its place in the last draw, v1.x will skip that part of the tree without checking for mutations or triggering any lifecycle methods in the subtree. The component documentation contains [more detail on this issue](components.md#avoid-creating-component-instances-outside-views). mithril-1.1.6/docs/code-of-conduct.md000066400000000000000000000063311324223121200174050ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [github@patcavit.com](mailto:github@patcavit.com?subject=Mithril Code of Conduct). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ mithril-1.1.6/docs/components.md000066400000000000000000000365571324223121200166360ustar00rootroot00000000000000# Components - [Structure](#structure) - [Lifecycle methods](#lifecycle-methods) - [Syntactic variants](#syntactic-variants) - [State](#state) - [Avoid anti-patterns](#avoid-anti-patterns) ### Structure Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. Any Javascript object that has a view method is a Mithril component. Components can be consumed via the [`m()`](hyperscript.md) utility: ```javascript var Example = { view: function() { return m("div", "Hello") } } m(Example) // equivalent HTML //
Hello
``` --- ### Passing data to components Data can be passed to component instances by passing an `attrs` object as the second parameter in the hyperscript function: ```javascript m(Example, {name: "Floyd"}) ``` This data can be accessed in the component's view or lifecycle methods via the `vnode.attrs`: ```javascript var Example = { view: function (vnode) { return m("div", "Hello, " + vnode.attrs.name) } } ``` NOTE: Lifecycle methods can also be provided via the `attrs` object, so you should avoid using the lifecycle method names for your own callbacks as they would also be invoked by Mithril. Use lifecycle methods in `attrs` only when you specifically wish to create lifecycle hooks. --- ### Lifecycle methods Components can have the same [lifecycle methods](lifecycle-methods.md) as virtual DOM nodes: `oninit`, `oncreate`, `onupdate`, `onbeforeremove`, `onremove` and `onbeforeupdate`. ```javascript var ComponentWithHooks = { oninit: function(vnode) { console.log("initialized") }, oncreate: function(vnode) { console.log("DOM created") }, onupdate: function(vnode) { console.log("DOM updated") }, onbeforeremove: function(vnode) { console.log("exit animation can start") return new Promise(function(resolve) { // call after animation completes resolve() }) }, onremove: function(vnode) { console.log("removing DOM element") }, onbeforeupdate: function(vnode, old) { return true }, view: function(vnode) { return "hello" } } ``` Like other types of virtual DOM nodes, components may have additional lifecycle methods defined when consumed as vnode types. ```javascript function initialize() { console.log("initialized as vnode") } m(ComponentWithHooks, {oninit: initialize}) ``` Lifecycle methods in vnodes do not override component methods, nor vice versa. Component lifecycle methods are always run after the vnode's corresponding method. Take care not to use lifecycle method names for your own callback function names in vnodes. To learn more about lifecycle methods, [see the lifecycle methods page](lifecycle-methods.md). --- ### Syntactic variants #### ES6 classes Components can also be written using ES6 class syntax: ```javascript class ES6ClassComponent { constructor(vnode) { // vnode.state is undefined at this point this.kind = "ES6 class" } view() { return m("div", `Hello from an ${this.kind}`) } oncreate() { console.log(`A ${this.kind} component was created`) } } ``` Component classes must define a `view()` method, detected via `.prototype.view`, to get the tree to render. They can be consumed in the same way regular components can. ```javascript // EXAMPLE: via m.render m.render(document.body, m(ES6ClassComponent)) // EXAMPLE: via m.mount m.mount(document.body, ES6ClassComponent) // EXAMPLE: via m.route m.route(document.body, "/", { "/": ES6ClassComponent }) // EXAMPLE: component composition class AnotherES6ClassComponent { view() { return m("main", [ m(ES6ClassComponent) ]) } } ``` #### Closure components Functionally minded developers may prefer using the "closure component" syntax: ```javascript function closureComponent(vnode) { // vnode.state is undefined at this point var kind = "closure component" return { view: function() { return m("div", "Hello from a " + kind) }, oncreate: function() { console.log("We've created a " + kind) } } } ``` The returned object must hold a `view` function, used to get the tree to render. They can be consumed in the same way regular components can. ```javascript // EXAMPLE: via m.render m.render(document.body, m(closureComponent)) // EXAMPLE: via m.mount m.mount(document.body, closuresComponent) // EXAMPLE: via m.route m.route(document.body, "/", { "/": closureComponent }) // EXAMPLE: component composition function anotherClosureComponent() { return { view: function() { return m("main", [ m(closureComponent) ]) } } } ``` #### Mixing component kinds Components can be freely mixed. A Class component can have closure or POJO components as children, etc... --- ### State Like all virtual DOM nodes, component vnodes can have state. Component state is useful for supporting object-oriented architectures, for encapsulation and for separation of concerns. The state of a component can be accessed three ways: as a blueprint at initialization, via `vnode.state` and via the `this` keyword in component methods. #### At initialization For POJO components, the component object is the prototype of each component instance, so any property defined on the component object will be accessible as a property of `vnode.state`. This allows simple state initialization. In the example below, `data` is a property of the `ComponentWithInitialState` component's state object. ```javascript var ComponentWithInitialState = { data: "Initial content", view: function(vnode) { return m("div", vnode.state.data) } } m(ComponentWithInitialState) // Equivalent HTML //
Initial content
``` For class components, the state is an instance of the class, set right after the constructor is called. For closure components, the state is the object returned by the closure, set right after the closure returns. The state object is mostly redundant for closure components (since variables defined in the closure scope can be used instead). #### Via vnode.state State can also be accessed via the `vnode.state` property, which is available to all lifecycle methods as well as the `view` method of a component. ```javascript var ComponentWithDynamicState = { oninit: function(vnode) { vnode.state.data = vnode.attrs.text }, view: function(vnode) { return m("div", vnode.state.data) } } m(ComponentWithDynamicState, {text: "Hello"}) // Equivalent HTML //
Hello
``` #### Via the this keyword State can also be accessed via the `this` keyword, which is available to all lifecycle methods as well as the `view` method of a component. ```javascript var ComponentUsingThis = { oninit: function(vnode) { this.data = vnode.attrs.text }, view: function(vnode) { return m("div", this.data) } } m(ComponentUsingThis, {text: "Hello"}) // Equivalent HTML //
Hello
``` Be aware that when using ES5 functions, the value of `this` in nested anonymous functions is not the component instance. There are two recommended ways to get around this Javascript limitation, use ES6 arrow functions, or if ES6 is not available, use `vnode.state`. --- ### Avoid anti-patterns Although Mithril is flexible, some code patterns are discouraged: #### Avoid fat components Generally speaking, a "fat" component is a component that has custom instance methods. In other words, you should avoid attaching functions to `vnode.state` or `this`. It's exceedingly rare to have logic that logically fits in a component instance method and that can't be reused by other components. It's relatively common that said logic might be needed by a different component down the road. It's easier to refactor code if that logic is placed in the data layer than if it's tied to a component state. Consider this fat component: ```javascript // views/Login.js // AVOID var Login = { username: "", password: "", setUsername: function(value) { this.username = value }, setPassword: function(value) { this.password = value }, canSubmit: function() { return this.username !== "" && this.password !== "" }, login: function() {/*...*/}, view: function() { return m(".login", [ m("input[type=text]", {oninput: m.withAttr("value", this.setUsername.bind(this)), value: this.username}), m("input[type=password]", {oninput: m.withAttr("value", this.setPassword.bind(this)), value: this.password}), m("button", {disabled: !this.canSubmit(), onclick: this.login}, "Login"), ]) } } ``` Normally, in the context of a larger application, a login component like the one above exists alongside components for user registration and password recovery. Imagine that we want to be able to prepopulate the email field when navigating from the login screen to the registration or password recovery screens (or vice versa), so that the user doesn't need to re-type their email if they happened to fill the wrong page (or maybe you want to bump the user to the registration form if a username is not found). Right away, we see that sharing the `username` and `password` fields from this component to another is difficult. This is because the fat component encapsulates its state, which by definition makes this state difficult to access from outside. It makes more sense to refactor this component and pull the state code out of the component and into the application's data layer. This can be as simple as creating a new module: ```javascript // models/Auth.js // PREFER var Auth = { username: "", password: "", setUsername: function(value) { Auth.username = value }, setPassword: function(value) { Auth.password = value }, canSubmit: function() { return Auth.username !== "" && Auth.password !== "" }, login: function() {/*...*/}, } module.exports = Auth ``` Then, we can clean up the component: ```javascript // views/Login.js // PREFER var Auth = require("../models/Auth") var Login = { view: function() { return m(".login", [ m("input[type=text]", {oninput: m.withAttr("value", Auth.setUsername), value: Auth.username}), m("input[type=password]", {oninput: m.withAttr("value", Auth.setPassword), value: Auth.password}), m("button", {disabled: !Auth.canSubmit(), onclick: Auth.login}, "Login"), ]) } } ``` This way, the `Auth` module is now the source of truth for auth-related state, and a `Register` component can easily access this data, and even reuse methods like `canSubmit`, if needed. In addition, if validation code is required (for example, for the email field), you only need to modify `setEmail`, and that change will do email validation for any component that modifies an email field. As a bonus, notice that we no longer need to use `.bind` to keep a reference to the state for the component's event handlers. #### Avoid restrictive interfaces Try to keep component interfaces generic - using `attrs` and `children` directly - unless the component requires special logic to operate on input. In the example below, the `button` configuration is severely limited: it does not support any events other than `onclick`, it's not styleable and it only accepts text as children (but not elements, fragments or trusted HTML). ```javascript // AVOID var RestrictiveComponent = { view: function(vnode) { return m("button", {onclick: vnode.attrs.onclick}, [ "Click to " + vnode.attrs.text ]) } } ``` If the required attributes are equivalent to generic DOM attributes, it's preferable to allow passing through parameters to a component's root node. ```javascript // PREFER var FlexibleComponent = { view: function(vnode) { return m("button", vnode.attrs, [ "Click to ", vnode.children ]) } } ``` #### Don't manipulate `children` If a component is opinionated in how it applies attributes or children, you should switch to using custom attributes. Often it's desirable to define multiple sets of children, for example, if a component has a configurable title and body. Avoid destructuring the `children` property for this purpose. ```javascript // AVOID var Header = { view: function(vnode) { return m(".section", [ m(".header", vnode.children[0]), m(".tagline", vnode.children[1]), ]) } } m(Header, [ m("h1", "My title"), m("h2", "Lorem ipsum"), ]) // awkward consumption use case m(Header, [ [ m("h1", "My title"), m("small", "A small note"), ], m("h2", "Lorem ipsum"), ]) ``` The component above breaks the assumption that children will be output in the same contiguous format as they are received. It's difficult to understand the component without reading its implementation. Instead, use attributes as named parameters and reserve `children` for uniform child content: ```javascript // PREFER var BetterHeader = { view: function(vnode) { return m(".section", [ m(".header", vnode.attrs.title), m(".tagline", vnode.attrs.tagline), ]) } } m(BetterHeader, { title: m("h1", "My title"), tagline: m("h2", "Lorem ipsum"), }) // clearer consumption use case m(BetterHeader, { title: [ m("h1", "My title"), m("small", "A small note"), ], tagline: m("h2", "Lorem ipsum"), }) ``` #### Define components statically, call them dynamically ##### Avoid creating component definitions inside views If you create a component from within a `view` method (either directly inline or by calling a function that does so), each redraw will have a different clone of the component. When diffing component vnodes, if the component referenced by the new vnode is not strictly equal to the one referenced by the old component, the two are assumed to be different components even if they ultimately run equivalent code. This means components created dynamically via a factory will always be re-created from scratch. For that reason you should avoid recreating components. Instead, consume components idiomatically. ```javascript // AVOID var ComponentFactory = function(greeting) { // creates a new component on every call return { view: function() { return m("div", greeting) } } } m.render(document.body, m(ComponentFactory("hello"))) // calling a second time recreates div from scratch rather than doing nothing m.render(document.body, m(ComponentFactory("hello"))) // PREFER var Component = { view: function(vnode) { return m("div", vnode.attrs.greeting) } } m.render(document.body, m(Component, {greeting: "hello"})) // calling a second time does not modify DOM m.render(document.body, m(Component, {greeting: "hello"})) ``` ##### Avoid creating component instances outside views Conversely, for similar reasons, if a component instance is created outside of a view, future redraws will perform an equality check on the node and skip it. Therefore component instances should always be created inside views: ```javascript // AVOID var Counter = { count: 0, view: function(vnode) { return m("div", m("p", "Count: " + vnode.state.count ), m("button", { onclick: function() { vnode.state.count++ } }, "Increase count") ) } } var counter = m(Counter) m.mount(document.body, { view: function(vnode) { return [ m("h1", "My app"), counter ] } }) ``` In the example above, clicking the counter component button will increase its state count, but its view will not be triggered because the vnode representing the component shares the same reference, and therefore the render process doesn't diff them. You should always call components in the view to ensure a new vnode is created: ```javascript // PREFER var Counter = { count: 0, view: function(vnode) { return m("div", m("p", "Count: " + vnode.state.count ), m("button", { onclick: function() { vnode.state.count++ } }, "Increase count") ) } } m.mount(document.body, { view: function(vnode) { return [ m("h1", "My app"), m(Counter) ] } }) ``` mithril-1.1.6/docs/credits.md000066400000000000000000000041401324223121200160650ustar00rootroot00000000000000# Credits Mithril was originally written by Leo Horie, but it is where it is today thanks to the hard work and great ideas of many people. Special thanks to: - Pat Cavit, who exposed most of the public API for Mithril 1.0, brought in test coverage and automated the publishing process - Isiah Meadows, who brought in linting, modernized the test suite and has been a strong voice in design discussions - Zoli Kahan, who replaced the original Promise implementation with one that actually worked properly - Alec Embke, who single-handedly wrote the JSON-P implementation - Barney Carroll, who suggested many great ideas and relentlessly pushed Mithril to the limit to uncover design issues prior to Mithril 1.0 - Dominic Gannaway, who offered insanely meticulous technical insight into rendering performance - Boris Letocha, whose search space reduction algorithm is the basis for Mithril's virtual DOM engine - Joel Richard, whose monomorphic virtual DOM structure is the basis for Mithril's vnode implementation - Simon Friis Vindum, whose open source work was an inspiration to many design decisions for Mithril 1.0 - Boris Kaul, for his awesome work on the benchmarking tools used to develop Mithril - Leon Sorokin, for writing a DOM instrumentation tool that helped improve performance in Mithril 1.0 - Jordan Walke, whose work on React was prior art to the implementation of keys in Mithril - Pierre-Yves Gérardy, who consistently makes high quality contributions - Gyandeep Singh, who contributed significant IE performance improvements Other people who also deserve recognition: - Arthur Clemens - creator of [Polythene](https://github.com/ArthurClemens/Polythene) and the [HTML-to-Mithril converter](http://arthurclemens.github.io/mithril-template-converter/index.html) - Stephan Hoyer - creator of [mithril-node-render](https://github.com/StephanHoyer/mithril-node-render), [mithril-query](https://github.com/StephanHoyer/mithril-query) and [mithril-source-hint](https://github.com/StephanHoyer/mithril-source-hint) - the countless people who have reported and fixed bugs, participated in discussions, and helped promote Mithril mithril-1.1.6/docs/css.md000066400000000000000000000101261324223121200152210ustar00rootroot00000000000000# CSS - [Vanilla CSS](#vanilla-css) - [Tachyons](#tachyons) - [CSS-in-JS](#css-in-js) --- ### Vanilla CSS For various reasons, CSS has a bad reputation and often developers reach for complex tools in an attempt to make styling more manageable. In this section, we'll take a step back and cover some tips on writing plain CSS: - **Avoid using the space operator** - The vast majority of CSS maintainability issues are due to CSS specificity issues. The space operator defines a descendant (e.g. `.a .b`) and at the same time, it increases the level of specificity for the CSS rules that apply to that selector, sometimes overriding styles unexpectedly. Instead, it's preferable to share a namespace prefix in all class names that belong to a logical group of elements: ```css /* AVOID */ .chat.container {/*...*/} .chat .item {/*...*/} .chat .avatar {/*...*/} .chat .text {/*...*/} /* PREFER */ .chat-container {/*...*/} .chat-item {/*...*/} .chat-avatar {/*...*/} .chat-text {/*...*/} ``` - **Use only single-class selectors** - This convention goes hand-in-hand with the previous one: avoiding high specificity selectors such as `#foo` or `div.bar` help decrease the likelyhood of specificity conflicts. ```css /* AVOID */ #home {} input.highlighted {} /* PREFER */ .home {} .input-highlighted {} ``` - **Develop naming conventions** - You can reduce naming collisions by defining keywords for certain types of UI elements. This is particularly effective when brand names are involved: ```css /* AVOID */ .twitter {} /* icon link in footer */ .facebook {} /* icon link in footer */ /* later... */ .modal.twitter {} /* tweet modal */ .modal.facebook {} /* share modal */ /* PREFER */ .link-twitter {} .link-facebook {} /* later... */ .modal-twitter {} .modal-facebook {} ``` --- ### Tachyons [Tachyons](https://github.com/tachyons-css/tachyons) is a CSS framework, but the concept behind it can easily be used without the library itself. The basic idea is that every class name must declare one and only one CSS rule. For example, `bw1` stands for `border-width:1px;`. To create a complex style, one simply combines class names representing each of the required CSS rules. For example, `.black.bg-dark-blue.br2` styles an element with blue background, black text and a 4px border-radius. Since each class is small and atomic, it's essentially impossible to run into CSS conflicts. As it turns out, the Tachyons convention fits extremely well with Mithril and JSX: ```jsx var Hero = ".black.bg-dark-blue.br2.pa3" m.mount(document.body, Hello) // equivalent to `m(".black.bg-dark.br2.pa3", "Hello")` ``` --- ### CSS in JS In plain CSS, all selectors live in the global scope and are prone to name collisions and specificity conflicts. CSS-in-JS aims to solve the issue of scoping in CSS, i.e. it groups related styles into non-global modules that are invisible to each other. CSS-in-JS is suitable for extremely large dev teams working on a single codebase, but it's not a good choice for most teams. Nowadays there are [a lot of CSS-in-JS libraries with various degrees of robustness](https://github.com/MicheleBertoli/css-in-js). The main problem with many of these libraries is that even though they require a non-trivial amount of transpiler tooling and configuration, they also require sacrificing code readability in order to work, e.g. `` vs `` (or `m("a.button.danger")` if we're using hyperscript). Often sacrifices also need to be made at time of debugging, when mapping rendered CSS class names back to their source. Often all you get in browser developer tools is a class like `button_fvp6zc2gdj35evhsl73ffzq_0 danger_fgdl0s2a5fmle5g56rbuax71_0` with useless source maps (or worse, entirely criptic class names). Another common issue is lack of support for less basic CSS features such as `@keyframes` and `@font-face`. If you are adamant about using a CSS-in-JS library, consider using [J2C](https://github.com/j2css/j2c), which works without configuration and implements `@keyframes` and `@font-face`. mithril-1.1.6/docs/es6.md000066400000000000000000000062671324223121200151410ustar00rootroot00000000000000# ES6 - [Setup](#setup) - [Using Babel with Webpack](#using-babel-with-webpack) --- Mithril is written in ES5, and is fully compatible with ES6 as well. ES6 is a recent update to Javascript that introduces new syntax sugar for various common cases. It's not yet fully supported by all major browsers and it's not a requirement for writing an application, but it may be pleasing to use depending on your team's preferences. In some limited environments, it's possible to use a significant subset of ES6 directly without extra tooling (for example, in internal applications that do not support IE). However, for the vast majority of use cases, a compiler toolchain like [Babel](https://babeljs.io) is required to compile ES6 features down to ES5. ### Setup The simplest way to setup an ES6 compilation toolchain is via [Babel](https://babeljs.io/). Babel requires NPM, which is automatically installed when you install [Node.js](https://nodejs.org/en/). Once NPM is installed, create a project folder and run this command: ```bash npm init -y ``` If you want to use Webpack and Babel together, [skip to the section below](#using-babel-with-webpack). To install Babel as a standalone tool, use this command: ```bash npm install babel-cli babel-preset-es2015 babel-plugin-transform-react-jsx --save-dev ``` Create a `.babelrc` file: ```json { "presets": ["es2015"], "plugins": [ ["transform-react-jsx", { "pragma": "m" }] ] } ``` To run Babel as a standalone tool, run this from the command line: ```bash babel src --out-dir bin --source-maps ``` #### Using Babel with Webpack If you're already using Webpack as a bundler, you can integrate Babel to Webpack by following these steps. ```bash npm install babel-core babel-loader babel-preset-es2015 babel-plugin-transform-react-jsx --save-dev ``` Create a `.babelrc` file: ```json { "presets": ["es2015"], "plugins": [ ["transform-react-jsx", { "pragma": "m" }] ] } ``` Next, create a file called `webpack.config.js` ```javascript const path = require('path') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, './bin'), filename: 'app.js', }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }] } } ``` This configuration assumes the source code file for the application entry point is in `src/index.js`, and this will output the bundle to `bin/app.js`. To run the bundler, setup an npm script. Open `package.json` and add this entry under `"scripts"`: ```json { "name": "my-project", "scripts": { "start": "webpack -d --watch" } } ``` You can now then run the bundler by running this from the command line: ```bash npm start ``` #### Production build To generate a minified file, open `package.json` and add a new npm script called `build`: ```json { "name": "my-project", "scripts": { "start": "webpack -d --watch", "build": "webpack -p" } } ``` You can use hooks in your production environment to run the production build script automatically. Here's an example for [Heroku](https://www.heroku.com/): ```json { "name": "my-project", "scripts": { "start": "webpack -d --watch", "build": "webpack -p", "heroku-postbuild": "webpack -p" } } ``` mithril-1.1.6/docs/examples.md000066400000000000000000000014371324223121200162540ustar00rootroot00000000000000# Examples Here are some examples of Mithril in action - [Animation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/animation/mosaic.html) - [DBMonster](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html) - [Markdown Editor](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/editor/index.html) - SVG: [Clock](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/clock.html), [Ring](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/ring.html), [Tiger](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/svg/tiger.html) - [ThreadItJS](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/threaditjs/index.html) - [TodoMVC](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/todomvc/index.html) mithril-1.1.6/docs/favicon.ico000066400000000000000000000353561324223121200162440ustar00rootroot0000000000000000 %6  % h6(0` $Kc cK,,||[KK[).>@.)373 3{67{B$ Dgd-&%2Bsx}=e"$h!" !rr0/ Ry)3+"b7!TI#"RU*rjevZQTO7!=ZNFB0 jO&,+W:JJ:6#rr#6*TT]&&n##AZ}I.$~@Eu>} 5PnL2-/rBL|-\K???ÏǏǏÏ???( @ PE""EPq--q))q4))4qSrrSBssB983 kk 3j{{jHG FHfe CR 10} (,K,4 ::#S.l**q<9=@ $\]# :@^^oj L; +Zw,NK ^: XBIB??????'ycy1#????(  Gd!!dGtUUtklv::v,}vu}2$xx#k]_th*5TT 0'9DE7fW-4AA%(0R\_Ia^3=xsesmithril-1.1.6/docs/favicon.png000066400000000000000000000032411324223121200162420ustar00rootroot00000000000000PNG  IHDR DgAMA a cHRMz&u0`:pQ<PLTEPtRNSIBXڦΝ NK ^:,wZ+;oj L辽=@ $\]#<9.l*q4 S}(ԯ10CRƠf̶eHGF{3k8sr)-PE")z&bKGDH pHYs чtIME 8 #WIDAT8uSiCRA)b[bek0sιw}D)COA(U @fVj(?<|ק NO$aTj\ɼ ()Me8s,gQLϡ2=)dI]Ӓ߶whDc#.X:8t.9==x4x}6?Q zC'귄:rzYyBp2B񄉥YնBcs8r{GXRDc,pG/nhvD̑WoQ b5U"^M 3__M.L;FZc?S&EUYy#LPI6`/3lWah"$V_Ќ9F)( X RR#|@bK i++K1%'`* bck5 ! wk3{` | Yes | A list of vnodes **returns** | `Vnode` | | A fragment [vnode](vnodes.md) [How to read signatures](signatures.md) --- ### How it works `m.fragment()` creates a [fragment vnode](vnodes.md) with attributes. It is meant for advanced use cases involving [keys](keys.md) or [lifecyle methods](lifecycle-methods.md). A fragment vnode represents a list of DOM elements. If you want a regular element vnode that represents only one DOM element, you should use [`m()`](hyperscript.md) instead. Normally you can use simple arrays instead to denote a list of nodes: ```javascript var groupVisible = true m("ul", [ m("li", "child 1"), m("li", "child 2"), groupVisible ? [ // a fragment containing two elements m("li", "child 3"), m("li", "child 4"), ] : null ]) ``` However, Javascript arrays cannot be keyed or hold lifecycle methods. One option would be to create a wrapper element to host the key or lifecycle method, but sometimes it is not desirable to have an extra element (for example in complex table structures). In those cases, a fragment vnode can be used instead. There are a few benefits that come from using `m.fragment` instead of handwriting a vnode object structure: m.fragment creates [monomorphic objects](vnodes.md#monomorphic-class), which have better performance characteristics than creating objects dynamically. In addition, using `m.fragment` makes your intentions clear to other developers, and it makes it less likely that you'll mistakenly set attributes on the vnode object itself rather than on its `attrs` map. mithril-1.1.6/docs/framework-comparison.md000066400000000000000000000564351324223121200206130ustar00rootroot00000000000000# Framework comparison - [Why not X?](#why-not-insert-favorite-framework-here) - [Why use Mithril?](#why-use-mithril) - [React](#react) - [Angular](#angular) - [Vue](#vue) If you're reading this page, you probably have used other frameworks to build applications, and you want to know if Mithril would help you solve your problems more effectively. --- ## Why not [insert favorite framework here]? The reality is that most modern frameworks are fast, well-suited to build complex applications, and maintainable if you know how to use them effectively. There are examples of highly complex applications in the wild using just about every popular framework: Udemy uses Angular, AirBnB uses React, Gitlab uses Vue, Guild Wars 2 uses Mithril (yes, inside the game!). Clearly, these are all production-quality frameworks. As a rule of thumb, if your team is already heavily invested in another framework/library/stack, it makes more sense to stick with it, unless your team agrees that there's a very strong reason to justify a costly rewrite. However, if you're starting something new, do consider giving Mithril a try, if nothing else, to see how much value Mithril adopters have been getting out of 8kb (gzipped) of code. Mithril is used by many well-known companies (e.g. Vimeo, Nike, Fitbit), and it powers large open-sourced platforms too (e.g. Lichess, Flarum). --- ## Why use Mithril? In one sentence: because **Mithril is pragmatic**. This [10 minute guide](index.md) is a good example: that's how long it takes to learn components, XHR and routing - and that's just about the right amount of knowledge needed to build useful applications. Mithril is all about getting meaningful work done efficiently. Doing file uploads? [The docs show you how](request.md#file-uploads). Authentication? [Documented too](route.md#authentication). Exit animations? [You got it](animation.md). No extra libraries, no magic. --- ## Comparisons ### React React is a view library maintained by Facebook. React and Mithril share a lot of similarities. If you already learned React, you already know almost all you need to build apps with Mithril. - They both use virtual DOM, lifecycle methods and key-based reconciliation - They both organize views via components - They both use Javascript as a flow control mechanism within views The most obvious difference between React and Mithril is in their scope. React is a view library, so a typical React-based application relies on third-party libraries for routing, XHR and state management. Using a library oriented approach allows developers to customize their stack to precisely match their needs. The not-so-nice way of saying that is that React-based architectures can vary wildly from project to project, and that those projects are that much more likely to cross the 1MB size line. Mithril has built-in modules for common necessities such as routing and XHR, and the [guide](simple-application.md) demonstrates idiomatic usage. This approach is preferable for teams that value consistency and ease of onboarding. #### Performance Both React and Mithril care strongly about rendering performance, but go about it in different ways. In the past React had two DOM rendering implementations (one using the DOM API, and one using `innerHTML`). Its upcoming fiber architecture introduces scheduling and prioritization of units of work. React also has a sophisticated build system that disables various checks and error messages for production deployments, and various browser-specific optimizations. In addition, there are also several performance-oriented libraries that leverage React's `shouldComponentUpdate` hook and immutable data structure libraries' fast object equality checking properties to reduce virtual DOM reconciliation times. Generally speaking, React's approach to performance is to engineer relatively complex solutions. Mithril follows the less-is-more school of thought. It has a substantially smaller, aggressively optimized codebase. The rationale is that a small codebase is easier to audit and optimize, and ultimately results in less code being run. Here's a comparison of library load times, i.e. the time it takes to parse and run the Javascript code for each framework, by adding a `console.time()` call on the first line and a `console.timeEnd()` call on the last of a script that is composed solely of framework code. For your reading convenience, here are best-of-20 results with logging code manually added to bundled scripts, running from the filesystem, in Chrome on a modest 2010 PC desktop: React | Mithril ------- | ------- 55.8 ms | 4.5 ms Library load times matter in applications that don't stay open for long periods of time (for example, anything in mobile) and cannot be improved via caching or other optimization techniques. Since this is a micro-benchmark, you are encouraged to replicate these tests yourself since hardware can heavily affect the numbers. Note that bundler frameworks like Webpack can move dependencies out before the timer calls to emulate static module resolution, so you should either copy the code from the compiled CDN files or open the output file from the bundler library, and manually add the high resolution timer calls `console.time` and `console.timeEnd` to the bundled script. Avoid using `new Date` and `performance.now`, as those mechanisms are not as statistically accurate. For your reading convenience, here's a version of that benchmark adapted to use CDNs on the web: the [benchmark for React is here](https://jsfiddle.net/0ovkv64u/), and the [benchmark for Mithril is here](https://jsfiddle.net/o7hxooqL/). Note that we're benchmarking all of Mithril rather than benchmarking only the rendering module (which would be equivalent in scope to React). Also note that this CDN-driven setup incurs some overheads due to fetching resources from disk cache (~2ms per resource). Due to those reasons, the numbers here are not entirely accurate, but they should be sufficient to observe that Mithril's initialization speed is noticeably better than React. Here's a slightly more meaningful benchmark: measuring the scripting time for creating 10,000 divs (and 10,000 text nodes). Again, here's the benchmark code for [React](https://jsfiddle.net/bfoeay4f/) and [Mithril](https://jsfiddle.net/fft0ht7n/). Their best results are shown below: React | Mithril ------- | ------- 99.7 ms | 42.8 ms What these numbers show is that not only does Mithril initializes significantly faster, it can process upwards of 20,000 virtual DOM nodes before React is ready to use. ##### Update performance Update performance can be even more important than first-render performance, since updates can happen many times while a Single Page Application is running. A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [React implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/react/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Sample results are shown below: React | Mithril ------- | ------- 12.1 ms | 6.4 ms ##### Development performance Another thing to keep in mind is that because React adds extra checks and helpful error messages in development mode, it is slower in development than the production version used for the benchmarks above. To illustrate, [here's the 10,000 node benchmark from above using the development version of React](https://jsfiddle.net/r1jfckrd/). ##### Drop-in replacements There are [several](https://preactjs.com/) [projects](https://github.com/Lucifier129/react-lite) [that](https://infernojs.org/) [claim](https://github.com/alibaba/rax) API parity with React (some via compatibility layer libraries), but they are not fully compatible (e.g. PropType support is usually stubbed out, synthetic events are sometimes not supported, and some APIs have different semantics). Note that these libraries typically also include features of their own that are not part of the official React API, which may become problematic down the road if one decides to switch back to React Fiber. Claims about small download size (compared to React) are accurate, but most of these libraries are slightly larger than Mithril's renderer module. Preact is the only exception. Be wary of aggressive performance claims, as benchmarks used by some of these projects are known to be out-of-date and flawed (in the sense that they can be - and are - exploited). Boris Kaul (author of some of the benchmarks) has [written in detail about how benchmarks are gamed](https://medium.com/@localvoid/how-to-win-in-web-framework-benchmarks-8bc31af76ce7). Another thing to keep in mind is that some benchmarks aggressively use advanced optimization features and thus demonstrate *potential* performance, i.e. performance that is possible given some caveats, but realistically unlikely unless you actively spend the time to go over your entire codebase identifying optimization candidates and evaluating the regression risks brought by the optimization caveats. In the spirit of demonstrating *typical* performance characteristics, the benchmarks presented in this comparison page are implemented in an apples-to-apples, naive, idiomatic way (i.e. the way you would normally write 99% of your code) and do not employ tricks or advanced optimizations to make one or other framework look artificially better. You are encouraged to contribute a PR if you feel any DbMonster implementation here could be written more idiomatically. #### Complexity Both React and Mithril have relatively small API surfaces compared to other frameworks, which help ease learning curve. However, whereas idiomatic Mithril can be written without loss of readability using plain ES5 and no other dependencies, idiomatic React relies heavily on complex tooling (e.g. Babel, JSX plugin, etc), and this level of complexity frequently extends to popular parts of its ecosystem, be it in the form of syntax extensions (e.g. non-standard object spread syntax in Redux), architectures (e.g. ones using immutable data libraries), or bells and whistles (e.g. hot module reloading). While complex toolchains are also possible with Mithril and other frameworks alike, it's *strongly* recommended that you follow the [KISS](https://en.wikipedia.org/wiki/KISS_principle) and [YAGNI](https://en.wikipedia.org/wiki/You_aren't_gonna_need_it) principles when using Mithril. #### Learning curve Both React and Mithril have relatively small learning curves. React's learning curve mostly involves understanding components and their lifecycle. The learning curve for Mithril components is nearly identical. There are obviously more APIs to learn in Mithril, since Mithril also includes routing and XHR, but the learning curve would be fairly similar to learning React, React Router and a XHR library like superagent or axios. Idiomatic React requires working knowledge of JSX and its caveats, and therefore there's also a small learning curve related to Babel. #### Documentation React documentation is clear and well written, and includes a good API reference, tutorials for getting started, as well as pages covering various advanced concepts. Unfortunately, since React is limited to being only a view library, its documentation does not explore how to use React idiomatically in the context of a real-life application. As a result, there are many popular state management libraries and thus architectures using React can differ drastically from company to company (or even between projects). Mithril documentation also includes [introductory](index.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. Mithril documentation also demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. --- ### Angular Angular is a web application framework maintained by Google. Angular and Mithril are fairly different, but they share a few similarities: - Both support componentization - Both have an array of tools for various aspects of web applications (e.g. routing, XHR) The most obvious difference between Angular and Mithril is in their complexity. This can be seen most easily in how views are implemented. Mithril views are plain Javascript, and flow control is done with Javascript built-in mechanisms such as ternary operators or `Array.prototype.map`. Angular, on the other hand, implements a directive system to extend HTML views so that it's possible to evaluate Javascript-like expressions within HTML attributes and interpolations. Angular actually ships with a parser and a compiler written in Javascript to achieve that. If that doesn't seem complex enough, there's actually two compilation modes (a default mode that generates Javascript functions dynamically for performance, and [a slower mode](https://docs.angularjs.org/api/ng/directive/ngCsp) for dealing with Content Security Policy restrictions). #### Performance Angular has made a lot of progress in terms of performance over the years. Angular 1 used a mechanism known as dirty checking which tended to get slow due to the need to constantly diff large `$scope` structures. Angular 2 uses a template change detection mechanism that is much more performant. However, even despite Angular's improvements, Mithril is often faster than Angular, due to the ease of auditing that Mithril's small codebase size affords. It's difficult to make a comparison of load times between Angular and Mithril for a couple of reasons. The first is that Angular 1 and 2 are in fact completely different codebases, and both versions are officially supported and maintained (and the vast majority of Angular codebases in the wild currently still use version 1). The second reason is that both Angular and Mithril are modular. In both cases, it's possible to remove a significant part of the framework that is not used in a given application. With that being said, the smallest known Angular 2 bundle is a [29kb hello world](https://www.lucidchart.com/techblog/2016/09/26/improving-angular-2-load-times/) compressed w/ the Brotli algorithm (it's 35kb using standard gzip), and with most of Angular's useful functionality removed. By comparison, a Mithril hello world - including the entire Mithril core - would not be over 8kb gzipped (a more optimized bundle could easily be half of that). Also, remember that frameworks like Angular and Mithril are designed for non-trivial application, so an application that managed to use all of Angular's API surface would need to download several hundred kb of framework code, rather than merely 29kb. ##### Update performance A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare an [Angular implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/angular/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below: Angular | Mithril ------- | ------- 11.5 ms | 6.4 ms #### Complexity Angular is superior to Mithril in the amount of tools it offers (in the form of various directives and services), but it is also far more complex. Compare [Angular's API surface](https://angular.io/docs/ts/latest/api/) with [Mithril's](api.md). You can make your own judgment on which API is more self-descriptive and more relevant to your needs. Angular 2 has a lot more concepts to understand: on the language level, Typescript is the recommended language, and on top of that there's also Angular-specific template syntax such as bindings, pipes, "safe navigator operator". You also need to learn about architectural concepts such as modules, components, services, directives, etc, and where it's appropriate to use what. #### Learning curve If we compare apples to apples, Angular 2 and Mithril have similar learning curves: in both, components are a central aspect of architecture, and both have reasonable routing and XHR tools. With that being said, Angular has a lot more concepts to learn than Mithril. It offers Angular-specific APIs for many things that often can be trivially implemented (e.g. pluralization is essentially a switch statement, "required" validation is simply an equality check, etc). Angular templates also have several layers of abstractions to emulate what Javascript does natively in Mithril - Angular's `ng-if`/`ngIf` is a *directive*, which uses a custom *parser* and *compiler* to evaluate an expression string and emulate lexical scoping... and so on. Mithril tends to be a lot more transparent, and therefore easier to reason about. #### Documentation Angular 2 documentation provides an extensive introductory tutorial, and another tutorial that implements an application. It also has various guides for advanced concepts, a cheatsheet and a style guide. Unfortunately, at the moment, the API reference leaves much to be desired. Several APIs are either undocumented or provide no context for what the API might be used for. Mithril documentation includes [introductory](index.md) [tutorials](simple-application.md), pages about advanced concepts, and an extensive API reference section, which includes input/output type information, examples for various common use cases and advice against misuse and anti-patterns. It also includes a cheatsheet for quick reference. Mithril documentation also demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. --- ### Vue Vue is a view library similar to Angular. Vue and Mithril have a lot of differences but they also share some similarities: - They both use virtual DOM and lifecycle methods - Both organize views via components Vue 2 uses a fork of Snabbdom as its virtual DOM system. In addition, Vue also provides tools for routing and state management as separate modules. Vue looks very similar to Angular and provides a similar directive system, HTML-based templates and logic flow directives. It differs from Angular in that it implements a monkeypatching reactive system that overwrites native methods in a component's data tree (whereas Angular 1 uses dirty checking and digest/apply cycles to achieve similar results). Similar to Angular 2, Vue compiles HTML templates into functions, but the compiled functions look more like Mithril or React views, rather than Angular's compiled rendering functions. Vue is significantly smaller than Angular when comparing apples to apples, but not as small as Mithril (Vue core is around 23kb gzipped, whereas the equivalent rendering module in Mithril is around 4kb gzipped). Both have similar performance characteristics, but benchmarks usually suggest Mithril is slightly faster. #### Performance Here's a comparison of library load times, i.e. the time it takes to parse and run the Javascript code for each framework, by adding a `console.time()` call on the first line and a `console.timeEnd()` call on the last of a script that is composed solely of framework code. For your reading convenience, here are best-of-20 results with logging code manually added to bundled scripts, running from the filesystem, in Chrome on a modest 2010 PC desktop: Vue | Mithril ------- | ------- 21.8 ms | 4.5 ms Library load times matter in applications that don't stay open for long periods of time (for example, anything in mobile) and cannot be improved via caching or other optimization techniques. ##### Update performance A useful tool to benchmark update performance is a tool developed by the Ember team called DbMonster. It updates a table as fast as it can and measures frames per second (FPS) and Javascript times (min, max and mean). The FPS count can be difficult to evaluate since it also includes browser repaint times and `setTimeout` clamping delay, so the most meaningful number to look at is the mean render time. You can compare a [Vue implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/vue/index.html) and a [Mithril implementation](http://cdn.rawgit.com/MithrilJS/mithril.js/master/examples/dbmonster/mithril/index.html). Both implementations are naive (i.e. no optimizations). Sample results are shown below: Vue | Mithril ------ | ------- 9.8 ms | 6.4 ms #### Complexity Vue is heavily inspired by Angular and has many things that Angular does (e.g. directives, filters, bi-directional bindings, `v-cloak`), but also has things inspired by React (e.g. components). As of Vue 2.0, it's also possible to write templates using hyperscript/JSX syntax (in addition to single-file components and the various webpack-based language transpilation plugins). Vue provides both bi-directional data binding and an optional Redux-like state management library, but unlike Angular, it provides no style guide. The many-ways-of-doing-one-thing approach can cause architectural fragmentation in long-lived projects. Mithril has far less concepts and typically organizes applications in terms of components and a data layer. All component creation styles in Mithril output the same vnode structure using native Javascript features only. The direct consequence of leaning on the language is less tooling and a simpler project setup. #### Documentation Both Vue and Mithril have good documentation. Both include a good API reference with examples, tutorials for getting started, as well as pages covering various advanced concepts. However, due to Vue's many-ways-to-do-one-thing approach, some things may not be adequately documented. For example, there's no documentation on hyperscript syntax or usage. Mithril documentation typically errs on the side of being overly thorough if a topic involves things outside of the scope of Mithril. For example, when a topic involves a 3rd party library, Mithril documentation walks through the installation process for the 3rd party library. Mithril documentation also often demonstrates simple, close-to-the-metal solutions to common use cases in real-life applications where it's appropriate to inform a developer that web standards may be now on par with larger established libraries. Mithril's tutorials also cover a lot more ground than Vue's: the [Vue tutorial](https://vuejs.org/v2/guide/#Getting-Started) finishes with a static list of foodstuff. [Mithril's 10 minute guide](index.md) covers the majority of its API and goes over key aspects of real-life applications, such as fetching data from a server and routing (and there's a [longer, more thorough tutorial](simple-application.md) if that's not enough). mithril-1.1.6/docs/generate.js000066400000000000000000000066321324223121200162460ustar00rootroot00000000000000"use strict" var fs = require("fs") var path = require("path") var marked = require("marked") var layout = fs.readFileSync("./docs/layout.html", "utf-8") var version = JSON.parse(fs.readFileSync("./package.json", "utf-8")).version try {fs.mkdirSync("./dist")} catch (e) {/* ignore */} try {fs.mkdirSync("./dist/archive")} catch (e) {/* ignore */} try {fs.mkdirSync("./dist/archive/v" + version)} catch (e) {/* ignore */} var guides = fs.readFileSync("docs/nav-guides.md", "utf-8") var methods = fs.readFileSync("docs/nav-methods.md", "utf-8") var index = fs.readFileSync("docs/index.md", "utf-8") fs.writeFileSync("README.md", index.replace(/(\]\()(.+?)\.md(\))/g, "$1http://mithril.js.org/$2.html$3"), "utf-8") generate("docs") function generate(pathname) { if (fs.lstatSync(pathname).isDirectory()) { fs.readdirSync(pathname).forEach(function(filename) { generate(pathname + "/" + filename) }) } else if (!pathname.match(/tutorials|archive|nav-/)) { if (pathname.match(/\.md$/)) { var outputFilename = pathname.replace(/\.md$/, ".html") var markdown = fs.readFileSync(pathname, "utf-8") var anchors = {} var fixed = markdown .replace(/`((?:\S| -> |, )+)(\|)(\S+)`/gim, function(match, a, b, c) { // fix pipes in code tags return "" + (a + b + c).replace(/\|/g, "|") + "" }) .replace(/(^# .+?(?:\r?\n){2,}?)(?:(-(?:.|\r|\n)+?)((?:\r?\n){2,})|)/m, function(match, title, nav) { // inject menu var file = path.basename(pathname) var link = new RegExp("([ \t]*)(- )(\\[.+?\\]\\(" + file + "\\))") var replace = function(match, space, li, link) { return space + li + "**" + link + "**" + (nav ? "\n" + nav.replace(/(^|\n)/g, "$1\t" + space) : "") } var modified = guides.match(link) ? guides.replace(link, replace) : methods.replace(link, replace) return title + modified + "\n\n" }) .replace(/(\]\([^\)]+)(\.md)/gim, function(match, path, extension) { return path + (path.match(/http/) ? extension : ".html") }) // fix links var markedHtml = marked(fixed) .replace(/(\W)Array<([^/<]+?)>/gim, "$1Array<$2>") // Fix type signatures containing Array<...> var title = fixed.match(/^#([^\n\r]+)/i) || [] var html = layout .replace(/Mithril\.js<\/title>/, "<title>" + title[1] + " - Mithril.js") .replace(/\[version\]/g, version) // update version .replace(/\[body\]/, markedHtml) .replace(/(.+?)<\/h.>/gim, function(match, n, id, text) { // fix anchors var anchor = text.toLowerCase().replace(/<(\/?)code>/g, "").replace(/.+?<\/a>/g, "").replace(/\.|\[|\]|"|\/|\(|\)/g, "").replace(/\s/g, "-"); if(anchor in anchors) { anchor += ++anchors[anchor] } else { anchors[anchor] = 0; } return `${text}`; }) fs.writeFileSync("./dist/archive/v" + version + "/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") fs.writeFileSync("./dist/" + outputFilename.replace(/^docs\//, ""), html, "utf-8") } else if (!pathname.match(/lint|generate/)) { var encoding = (/\.(ico|png)$/i).test(path.extname(pathname)) ? "binary" : "utf-8"; fs.writeFileSync("./dist/archive/v" + version + "/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, encoding), encoding) fs.writeFileSync("./dist/" + pathname.replace(/^docs\//, ""), fs.readFileSync(pathname, encoding), encoding) } } } mithril-1.1.6/docs/hyperscript.md000066400000000000000000000337001324223121200170100ustar00rootroot00000000000000# m(selector, attributes, children) - [Description](#description) - [Signature](#signature) - [How it works](#how-it-works) - [Flexibility](#flexibility) - [CSS selectors](#css-selectors) - [DOM attributes](#dom-attributes) - [Style attribute](#style-attribute) - [Events](#events) - [Properties](#properties) - [Components](#components) - [Lifecycle methods](#lifecycle-methods) - [Keys](#keys) - [SVG and MathML](#svg-and-mathml) - [Making templates dynamic](#making-templates-dynamic) - [Converting HTML](#converting-html) - [Avoid anti-patterns](#avoid-anti-patterns) --- ### Description Represents an HTML element in a Mithril view ```javascript m("div", {class: "foo"}, "hello") // represents
hello
``` You can also [use HTML syntax](https://babeljs.io/repl/#?code=%2F**%20%40jsx%20m%20*%2F%0A%3Ch1%3EMy%20first%20app%3C%2Fh1%3E) via a Babel plugin. ```markup /** jsx m */
hello
``` --- ### Signature `vnode = m(selector, attributes, children)` Argument | Type | Required | Description ------------ | ------------------------------------------ | -------- | --- `selector` | `String|Object` | Yes | A CSS selector or a [component](components.md) `attributes` | `Object` | No | HTML attributes or element properties `children` | `Array|String|Number|Boolean` | No | Child [vnodes](vnodes.md#structure). Can be written as [splat arguments](signatures.md#splats) **returns** | `Vnode` | | A [vnode](vnodes.md#structure) [How to read signatures](signatures.md) --- ### How it works Mithril provides a hyperscript function `m()`, which allows expressing any HTML structure using javascript syntax. It accepts a `selector` string (required), an `attributes` object (optional) and a `children` array (optional). ```javascript m("div", {id: "box"}, "hello") // equivalent HTML: //
hello
``` The `m()` function does not actually return a DOM element. Instead it returns a [virtual DOM node](vnodes.md), or *vnode*, which is a javascript object that represents the DOM element to be created. ```javascript // a vnode var vnode = {tag: "div", attrs: {id: "box"}, children: [ /*...*/ ]} ``` To transform a vnode into an actual DOM element, use the [`m.render()`](render.md) function: ```javascript m.render(document.body, m("br")) // puts a
in ``` Calling `m.render()` multiple times does **not** recreate the DOM tree from scratch each time. Instead, each call will only make a change to a DOM tree if it is absolutely necessary to reflect the virtual DOM tree passed into the call. This behavior is desirable because recreating the DOM from scratch is very expensive, and causes issues such as loss of input focus, among other things. By contrast, updating the DOM only where necessary is comparatively much faster and makes it easier to maintain complex UIs that handle multiple user stories. --- ### Flexibility The `m()` function is both *polymorphic* and *variadic*. In other words, it's very flexible in what it expects as input parameters: ```javascript // simple tag m("div") //
// attributes and children are optional m("a", {id: "b"}) // m("span", "hello") // hello // tag with child nodes m("ul", [ //
    m("li", "hello"), //
  • hello
  • m("li", "world"), //
  • world
  • ]) //
// array is optional m("ul", //
    m("li", "hello"), //
  • hello
  • m("li", "world") //
  • world
  • ) //
``` --- ### CSS selectors The first argument of `m()` can be any CSS selector that can describe an HTML element. It accepts any valid CSS combinations of `#` (id), `.` (class) and `[]` (attribute) syntax. ```javascript m("div#hello") //
m("section.container") //
m("input[type=text][placeholder=Name]") // m("a#exit.external[href='http://example.com']", "Leave") // Leave ``` If you omit the tag name, Mithril assumes a `div` tag. ```javascript m(".box.box-bordered") //
``` Typically, it's recommended that you use CSS selectors for static attributes (i.e. attributes whose value do not change), and pass an attributes object for dynamic attribute values. ```javascript var currentURL = "/" m("a.link[href=/]", { class: currentURL === "/" ? "selected" : "" }, "Home") // equivalent HTML: // Home ``` If there are class names in both first and second arguments of `m()`, they are merged together as you would expect. --- ### DOM attributes Mithril uses both the Javascript API and the DOM API (`setAttribute`) to resolve attributes. This means you can use both syntaxes to refer to attributes. For example, in the Javascript API, the `readonly` attribute is called `element.readOnly` (notice the uppercase). In Mithril, all of the following are supported: ```javascript m("input", {readonly: true}) // lowercase m("input", {readOnly: true}) // uppercase m("input[readonly]") m("input[readOnly]") ``` --- ### Style attribute Mithril supports both strings and objects as valid `style` values. In other words, all of the following are supported: ```javascript m("div", {style: "background:red;"}) m("div", {style: {background: "red"}}) m("div[style=background:red]") ``` Using a string as a `style` would overwrite all inline styles in the element if it is redrawn, and not only CSS rules whose values have changed. Mithril does not attempt to add units to number values. --- ### Events Mithril supports event handler binding for all DOM events, including events whose specs do not define an `on${event}` property, such as `touchstart` ```javascript function doSomething(e) { console.log(e) } m("div", {onclick: doSomething}) ``` --- ### Properties Mithril supports DOM functionality that is accessible via properties such as ``. ```javascript m.render(document.body, [ m("input[type=file]", {onchange: upload}) ]) function upload(e) { var file = e.target.files[0] } ``` The snippet above renders a file input. If a user picks a file, the `onchange` event is triggered, which calls the `upload` function. `e.target.files` is a list of `File` objects. Next, you need to create a [`FormData`](https://developer.mozilla.org/en/docs/Web/API/FormData) object to create a [multipart request](https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html), which is a specially formatted HTTP request that is able to send file data in the request body. ```javascript function upload(e) { var file = e.target.files[0] var data = new FormData() data.append("myfile", file) } ``` Next, you need to call `m.request` and set `options.method` to an HTTP method that uses body (e.g. `POST`, `PUT`, `PATCH`) and use the `FormData` object as `options.data`. ```javascript function upload(e) { var file = e.target.files[0] var data = new FormData() data.append("myfile", file) m.request({ method: "POST", url: "/api/v1/upload", data: data, }) } ``` Assuming the server is configured to accept multipart requests, the file information will be associated with the `myfile` key. #### Multiple file uploads It's possible to upload multiple files in one request. Doing so will make the batch upload atomic, i.e. no files will be processed if there's an error during the upload, so it's not possible to have only part of the files saved. If you want to save as many files as possible in the event of a network failure, you should consider uploading each file in a separate request instead. To upload multiple files, simply append them all to the `FormData` object. When using a file input, you can get a list of files by adding the `multiple` attribute to the input: ```javascript m.render(document.body, [ m("input[type=file][multiple]", {onchange: upload}) ]) function upload(e) { var files = e.target.files var data = new FormData() for (var i = 0; i < files.length; i++) { data.append("file" + i, files[i]) } m.request({ method: "POST", url: "/api/v1/upload", data: data, }) } ``` --- ### Monitoring progress Sometimes, if a request is inherently slow (e.g. a large file upload), it's desirable to display a progress indicator to the user to signal that the application is still working. `m.request()` exposes its underlying `XMLHttpRequest` object via the `options.config` parameter, which allows you to attach event listeners to the XMLHttpRequest object: ```javascript var progress = 0 m.mount(document.body, { view: function() { return [ m("input[type=file]", {onchange: upload}), progress + "% completed" ] } }) function upload(e) { var file = e.target.files[0] var data = new FormData() data.append("myfile", file) m.request({ method: "POST", url: "/api/v1/upload", data: data, config: function(xhr) { xhr.addEventListener("progress", function(e) { progress = e.loaded / e.total m.redraw() // tell Mithril that data changed and a re-render is needed }) } }) } ``` In the example above, a file input is rendered. If the user picks a file, an upload is initiated, and in the `config` callback, a `progress` event handler is registered. This event handler is fired whenever there's a progress update in the XMLHttpRequest. Because the XMLHttpRequest's progress event is not directly handled by Mithril's virtual DOM engine, `m.redraw()` must be called to signal to Mithril that data has changed and a redraw is required. --- ### Casting response to a type Depending on the overall application architecture, it may be desirable to transform the response data of a request to a specific class or type (for example, to uniformly parse date fields or to have helper methods). You can pass a constructor as the `options.type` parameter and Mithril will instantiate it for each object in the HTTP response. ```javascript function User(data) { this.name = data.firstName + " " + data.lastName } m.request({ method: "GET", url: "/api/v1/users", type: User }) .then(function(users) { console.log(users[0].name) // logs a name }) ``` In the example above, assuming `/api/v1/users` returns an array of objects, the `User` constructor will be instantiated (i.e. called as `new User(data)`) for each object in the array. If the response returned a single object, that object would be used as the `data` argument. --- ### Non-JSON responses Sometimes a server endpoint does not return a JSON response: for example, you may be requesting an HTML file, an SVG file, or a CSV file. By default Mithril attempts to parse a response as if it was JSON. To override that behavior, define a custom `options.deserialize` function: ```javascript m.request({ method: "GET", url: "/files/icon.svg", deserialize: function(value) {return value} }) .then(function(svg) { m.render(document.body, m.trust(svg)) }) ``` In the example above, the request retrieves an SVG file, does nothing to parse it (because `deserialize` merely returns the value as-is), and then renders the SVG string as trusted HTML. Of course, a `deserialize` function may be more elaborate: ```javascript m.request({ method: "GET", url: "/files/data.csv", deserialize: parseCSV }) .then(function(data) { console.log(data) }) function parseCSV(data) { // naive implementation for the sake of keeping example simple return data.split("\n").map(function(row) { return row.split(",") }) } ``` Ignoring the fact that the parseCSV function above doesn't handle a lot of cases that a proper CSV parser would, the code above logs an array of arrays. Custom headers may also be helpful in this regard. For example, if you're requesting an SVG, you probably want to set the content type accordingly. To override the default JSON request type, set `options.headers` to an object of key-value pairs corresponding to request header names and values. ```javascript m.request({ method: "GET", url: "/files/image.svg", headers: { "Content-Type": "image/svg+xml; charset=utf-8", "Accept": "image/svg, text/*" }, deserialize: function(value) {return value} }) ``` --- ### Retrieving response details By default Mithril attempts to parse a response as JSON and returns `xhr.responseText`. It may be useful to inspect a server response in more detail, this can be accomplished by passing a custom `options.extract` function: ```javascript m.request({ method: "GET", url: "/api/v1/users", extract: function(xhr) {return {status: xhr.status, body: xhr.responseText}} }) .then(function(response) { console.log(response.status, response.body) }) ``` The parameter to `options.extract` is the XMLHttpRequest object once its operation is completed, but before it has been passed to the returned promise chain, so the promise may still end up in an rejected state if processing throws an exception. --- ### Why JSON instead of HTML Many server-side frameworks provide a view engine that interpolates database data into a template before serving HTML (on page load or via AJAX) and then employ jQuery to handle user interactions. By contrast, Mithril is framework designed for thick client applications, which typically download templates and data separately and combine them in the browser via Javascript. Doing the templating heavy-lifting in the browser can bring benefits like reducing operational costs by freeing server resources. Separating templates from data also allow template code to be cached more effectively and enables better code reusability across different types of clients (e.g. desktop, mobile). Another benefit is that Mithril enables a [retained mode](https://en.wikipedia.org/wiki/Retained_mode) UI development paradigm, which greatly simplifies development and maintenance of complex user interactions. By default, `m.request` expects response data to be in JSON format. In a typical Mithril application, that JSON data is then usually consumed by a view. You should avoid trying to render server-generated dynamic HTML with Mithril. If you have an existing application that does use a server-side templating system, and you wish to re-architecture it, first decide whether the effort is feasible at all to begin with. Migrating from a thick server architecture to a thick client architecture is typically a somewhat large effort, and involves refactoring logic out of templates into logical data services (and the testing that goes with it). Data services may be organized in many different ways depending on the nature of the application. [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) architectures are popular with API providers, and [service oriented architectures](https://en.wikipedia.org/wiki/Service-oriented_architecture) are often required where there are lots of highly transactional workflows. --- ### Why XHR instead of fetch [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is a newer Web API for fetching resources from servers, similar to `XMLHttpRequest`. Mithril's `m.request` uses `XMLHttpRequest` instead of `fetch()` for a number of reasons: - `fetch` is not fully standardized yet, and may be subject to specification changes. - `XMLHttpRequest` calls can be aborted before they resolve (e.g. to avoid race conditions in for instant search UIs). - `XMLHttpRequest` provides hooks for progress listeners for long running requests (e.g. file uploads). - `XMLHttpRequest` is supported by all browsers, whereas `fetch()` is not supported by Internet Explorer, Safari and Android (non-Chromium). Currently, due to lack of browser support, `fetch()` typically requires a [polyfill](https://github.com/github/fetch), which is over 11kb uncompressed - nearly three times larger than Mithril's XHR module. Despite being much smaller, Mithril's XHR module supports many important and not-so-trivial-to-implement features like [URL interpolation](#dynamic-urls), querystring serialization and [JSON-P requests](jsonp.md), in addition to its ability to integrate seamlessly to Mithril's autoredrawing subsystem. The `fetch` polyfill does not support any of those, and requires extra libraries and boilerplates to achieve the same level of functionality. In addition, Mithril's XHR module is optimized for JSON-based endpoints and makes that most common case appropriately terse - i.e. `m.request(url)` - whereas `fetch` requires an additional explicit step to parse the response data as JSON: `fetch(url).then(function(response) {return response.json()})` The `fetch()` API does have a few technical advantages over `XMLHttpRequest` in a few uncommon cases: - it provides a streaming API (in the "video streaming" sense, not in the reactive programming sense), which enables better latency and memory consumption for very large responses (at the cost of code complexity). - it integrates to the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which provides an extra layer of control over how and when network requests happen. This API also allows access to push notifications and background synchronization features. In typical scenarios, streaming won't provide noticeable performance benefits because it's generally not advisable to download megabytes of data to begin with. Also, the memory gains from repeatedly reusing small buffers may be offset or nullified if they result in excessive browser repaints. For those reasons, choosing `fetch()` streaming instead of `m.request` is only recommended for extremely resource intensive applications. --- ### Avoid anti-patterns #### Promises are not the response data The `m.request` method returns a [Promise](promise.md), not the response data itself. It cannot return that data directly because an HTTP request may take a long time to complete (due to network latency), and if Javascript waited for it, it would freeze the application until the data was available. ```javascript // AVOID var users = m.request("/api/v1/users") console.log("list of users:", users) // `users` is NOT a list of users, it's a promise // PREFER m.request("/api/v1/users").then(function(users) { console.log("list of users:", users) }) ``` mithril-1.1.6/docs/route.md000066400000000000000000000656571324223121200156120ustar00rootroot00000000000000# route(root, defaultRoute, routes) - [Description](#description) - [Signature](#signature) - [Static members](#static-members) - [m.route.set](#mrouteset) - [m.route.get](#mrouteget) - [m.route.prefix](#mrouteprefix) - [m.route.link](#mroutelink) - [m.route.param](#mrouteparam) - [RouteResolver](#routeresolver) - [routeResolver.onmatch](#routeresolveronmatch) - [routeResolver.render](#routeresolverrender) - [How it works](#how-it-works) - [Typical usage](#typical-usage) - [Navigating to different routes](#navigating-to-different-routes) - [Routing parameters](#routing-parameters) - [Key parameter](#key-parameter) - [Variadic routes](#variadic-routes) - [History state](#history-state) - [Changing router prefix](#changing-router-prefix) - [Advanced component resolution](#advanced-component-resolution) - [Wrapping a layout component](#wrapping-a-layout-component) - [Authentication](#authentication) - [Preloading data](#preloading-data) - [Code splitting](#code-splitting) --- ### Description Navigate between "pages" within an application ```javascript var Home = { view: function() { return "Welcome" } } m.route(document.body, "/home", { "/home": Home, // defines `http://localhost/#!/home` }) ``` You can only have one `m.route` call per application. --- ### Signature `m.route(root, defaultRoute, routes)` Argument | Type | Required | Description ---------------------- | ---------------------------------------- | -------- | --- `root` | `Element` | Yes | A DOM element that will be the parent node to the subtree `defaultRoute` | `String` | Yes | The route to redirect to if the current URL does not match a route `routes` | `Object` | Yes | An object whose keys are route strings and values are either components or a [RouteResolver](#routeresolver) **returns** | | | Returns `undefined` [How to read signatures](signatures.md) #### Static members ##### m.route.set Redirects to a matching route, or to the default route if no matching routes can be found. `m.route.set(path, data, options)` Argument | Type | Required | Description ----------------- | --------- | -------- | --- `path` | `String` | Yes | The path to route to, without a prefix. The path may include slots for routing parameters `data` | `Object` | No | Routing parameters. If `path` has routing parameter slots, the properties of this object are interpolated into the path string `options.replace` | `Boolean` | No | Whether to create a new history entry or to replace the current one. Defaults to false `options.state` | `Object` | No | The `state` object to pass to the underlying `history.pushState` / `history.replaceState` call. This state object becomes available in the `history.state` property, and is merged into the [routing parameters](#routing-parameters) object. Note that this option only works when using the pushState API, but is ignored if the router falls back to hashchange mode (i.e. if the pushState API is not available) `options.title` | `String` | No | The `title` string to pass to the underlying `history.pushState` / `history.replaceState` call. **returns** | | | Returns `undefined` ##### m.route.get Returns the last fully resolved routing path, without the prefix. It may differ from the path displayed in the location bar while an asynchronous route is [pending resolution](#code-splitting). `path = m.route.get()` Argument | Type | Required | Description ----------------- | --------- | -------- | --- **returns** | String | | Returns the last fully resolved path ##### m.route.prefix Defines a router prefix. The router prefix is a fragment of the URL that dictates the underlying [strategy](#routing-strategies) used by the router. `m.route.prefix(prefix)` Argument | Type | Required | Description ----------------- | --------- | -------- | --- `prefix` | `String` | Yes | The prefix that controls the underlying [routing strategy](#routing-strategies) used by Mithril. **returns** | | | Returns `undefined` ##### m.route.link This function can be used as the `oncreate` (and `onupdate`) hook in a `m("a")` vnode: ```JS m("a[href=/]", {oncreate: m.route.link})`. ``` Using `m.route.link` as a `oncreate` hook causes the link to behave as a router link (i.e. it navigates to the route specified in `href`, instead of nagivating away from the current page to the URL specified in `href`. If the `href` attribute is not static, the `onupdate` hook must also be set: ```JS m("a", {href: someVariable, oncreate: m.route.link, onupdate: m.route.link})` ``` `m.route.link(vnode)` Argument | Type | Required | Description ----------------- | ----------- | -------- | --- `vnode` | `Vnode` | Yes | This method is meant to be used as or in conjunction with an `` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md) **returns** | | | Returns `undefined` ##### m.route.param Retrieves a route parameter from the last fully resolved route. A route parameter is a key-value pair. Route parameters may come from a few different places: - route interpolations (e.g. if a route is `/users/:id`, and it resolves to `/users/1`, the route parameter has a key `id` and value `"1"`) - router querystrings (e.g. if the path is `/users?page=1`, the route parameter has a key `page` and value `"1"`) - `history.state` (e.g. if history.state is `{foo: "bar"}`, the route parameter has key `foo` and value `"bar"`) `value = m.route.param(key)` Argument | Type | Required | Description ----------------- | --------------- | -------- | --- `key` | `String` | No | A route parameter name (e.g. `id` in route `/users/:id`, or `page` in path `/users/1?page=3`, or a key in `history.state`) **returns** | `String|Object` | | Returns a value for the specified key. If a key is not specified, it returns an object that contains all the interpolation keys Note that in the `onmatch` function of a RouteResolver, the new route hasn't yet been fully resolved, and `m.route.params()` will return the parameters of the previous route, if any. `onmatch` receives the parameters of the new route as an argument. #### RouteResolver A RouteResolver is an object that contains an `onmatch` method and/or a `render` method. Both methods are optional, but at least one must be present. A RouteResolver is not a component, and therefore it does NOT have lifecycle methods. As a rule of thumb, RouteResolvers should be in the same file as the `m.route` call, whereas component definitions should be in their own modules. `routeResolver = {onmatch, render}` ##### routeResolver.onmatch The `onmatch` hook is called when the router needs to find a component to render. It is called once per router path changes, but not on subsequent redraws while on the same path. It can be used to run logic before a component initializes (for example authentication logic, data preloading, redirection analytics tracking, etc) This method also allows you to asynchronously define what component will be rendered, making it suitable for code splitting and asynchronous module loading. To render a component asynchronously return a promise that resolves to a component. For more information on `onmatch`, see the [advanced component resolution](#advanced-component-resolution) section `routeResolver.onmatch(args, requestedPath)` Argument | Type | Description --------------- | ---------------------------------------- | --- `args` | `Object` | The [routing parameters](#routing-parameters) `requestedPath` | `String` | The router path requested by the last routing action, including interpolated routing parameter values, but without the prefix. When `onmatch` is called, the resolution for this path is not complete and `m.route.get()` still returns the previous path. **returns** | `Component|Promise|undefined` | Returns a component or a promise that resolves to a component If `onmatch` returns a component or a promise that resolves to a component, this component is used as the `vnode.tag` for the first argument in the RouteResolver's `render` method. Otherwise, `vnode.tag` is set to `"div"`. Similarly, if the `onmatch` method is omitted, `vnode.tag` is also `"div"`. If `onmatch` returns a promise that gets rejected, the router redirects back to `defaultRoute`. You may override this behavior by calling `.catch` on the promise chain before returning it. ##### routeResolver.render The `render` method is called on every redraw for a matching route. It is similar to the `view` method in components and it exists to simplify [component composition](#wrapping-a-layout-component). `vnode = routeResolve.render(vnode)` Argument | Type | Description ------------------- | -------------------- | ----------- `vnode` | `Object` | A [vnode](vnodes.md) whose attributes object contains routing parameters. If onmatch does not return a component or a promise that resolves to a component, the vnode's `tag` field defaults to `"div"` `vnode.attrs` | `Object` | A map of URL parameter values **returns** | `Array|Vnode` | The [vnodes](vnodes.md) to be rendered --- #### How it works Routing is a system that allows creating Single-Page-Applications (SPA), i.e. applications that can go from a "page" to another without causing a full browser refresh. It enables seamless navigability while preserving the ability to bookmark each page individually, and the ability to navigate the application via the browser's history mechanism. Routing without page refreshes is made partially possible by the [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method) API. Using this API, it's possible to programmatically change the URL displayed by the browser after a page has loaded, but it's the application developer's responsibility to ensure that navigating to any given URL from a cold state (e.g. a new tab) will render the appropriate markup. #### Routing strategies The routing strategy dictates how a library might actually implement routing. There are three general strategies that can be used to implement a SPA routing system, and each has different caveats: - Using the [fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier) (aka the hash) portion of the URL. A URL using this strategy typically looks like `http://localhost/#!/page1` - Using the querystring. A URL using this strategy typically looks like `http://localhost/?/page1` - Using the pathname. A URL using this strategy typically looks like `http://localhost/page1` Using the hash strategy is guaranteed to work in browsers that don't support `history.pushState` (namely, Internet Explorer 9), because it can fall back to using `onhashchange`. Use this strategy if you want to support IE9. The querystring strategy also technically works in IE9, but it falls back to reloading the page. Use this strategy if you want to support anchored links and you are not able to make the server-side necessary to support the pathname strategy. The pathname strategy produces the cleanest looking URLs, but does not work in IE9 *and* requires setting up the server to serve the single page application code from every URL that the application can route to. Use this strategy if you want cleaner-looking URLs and do not need to support IE9. Single page applications that use the hash strategy often use the convention of having an exclamation mark after the hash to indicate that they're using the hash as a routing mechanism and not for the purposes of linking to anchors. The `#!` string is known as a *hashbang*. The default strategy uses the hashbang. --- ### Typical usage Normally, you need to create a few [components](components.md) to map routes to: ```javascript var Home = { view: function() { return [ m(Menu), m("h1", "Home") ] } } var Page1 = { view: function() { return [ m(Menu), m("h1", "Page 1") ] } } ``` In the example above, there are two components: `Home` and `Page1`. Each contains a menu and some text. The menu is itself being defined as a component to avoid repetition: ```javascript var Menu = { view: function() { return m("nav", [ m("a[href=/]", {oncreate: m.route.link}, "Home"), m("a[href=/page1]", {oncreate: m.route.link}, "Page 1"), ]) } } ``` Now we can define routes and map our components to them: ```javascript m.route(document.body, "/", { "/": Home, "/page1": Page1, }) ``` Here we specify two routes: `/` and `/page1`, which render their respective components when the user navigates to each URL. By default, the SPA router prefix is `#!` --- ### Navigating to different routes In the example above, the `Menu` component has two links. You can specify that their `href` attribute is a route URL (rather than being a regular link that navigates away from the current page), by adding the hook `{oncreate: m.route.link}` You can also navigate programmatically, via `m.route.set(route)`. For example, `m.route.set("/page1")`. When navigating to routes, there's no need to explicitly specify the router prefix. In other words, don't add the hashbang `#!` in front of the route path when linking via `m.route.link` or redirecting. --- ### Routing parameters Sometimes we want to have a variable id or similar data appear in a route, but we don't want to explicitly specify a separate route for every possible id. In order to achieve that, Mithril supports parameterized routes: ```javascript var Edit = { view: function(vnode) { return [ m(Menu), m("h1", "Editing " + vnode.attrs.id) ] } } m.route(document.body, "/edit/1", { "/edit/:id": Edit, }) ``` In the example above, we defined a route `/edit/:id`. This creates a dynamic route that matches any URL that starts with `/edit/` and is followed by some data (e.g. `/edit/1`, `edit/234`, etc). The `id` value is then mapped as an attribute of the component's [vnode](vnodes.md) (`vnode.attrs.id`) It's possible to have multiple arguments in a route, for example `/edit/:projectID/:userID` would yield the properties `projectID` and `userID` on the component's vnode attributes object. #### Key parameter When a user navigates from a parameterized route to the same route with a different parameter (e.g. going from `/page/1` to `/page/2` given a route `/page/:id`, the component would not be recreated from scratch since both routes resolve to the same component, and thus result in a virtual dom in-place diff. This has the side-effect of triggering the `onupdate` hook, rather than `oninit`/`oncreate`. However, it's relatively common for a developer to want to synchronize the recreation of the component to the route change event. To achieve that, it's possible to combine route parameterization with the virtual dom [key reconciliation](keys.md) feature: ```javascript m.route(document.body, "/edit/1", { "/edit/:key": Edit, }) ``` This means that the [vnode](vnodes.md) that is created for the root component of the route has a route parameter object `key`. Route parameters become `attrs` in the vnode. Thus, when jumping from one page to another, the `key` changes and causes the component to be recreated from scratch (since the key tells the virtual dom engine that old and new components are different entities). You can take that idea further to create components that recreate themselves when reloaded: `m.route.set(m.route.get(), {key: Date.now()})` Or even use the [`history state`](#history-state) feature to achieve reloadable components without polluting the URL: `m.route.set(m.route.get(), null, {state: {key: Date.now()}})` #### Variadic routes It's also possible to have variadic routes, i.e. a route with an argument that contains URL pathnames that contain slashes: ```javascript m.route(document.body, "/edit/pictures/image.jpg", { "/files/:file...": Edit, }) ``` #### Handling 404s For isomorphic / universal javascript app, an url param and a variadic route combined is very usefull to display custom 404 error page. In a case of 404 Not Found error, the server send back the custom page to client. When Mithril is loaded, it will redirect client to the default route because it can't know that route. ```javascript m.route(document.body, "/", { "/": homeComponent, // [...] "/:404...": errorPageComponent }); ``` #### History state It's possible to take full advantage of the underlying `history.pushState` API to improve user's navigation experience. For example, an application could "remember" the state of a large form when the user leaves a page by navigating away, such that if the user pressed the back button in the browser, they'd have the form filled rather than a blank form. For example, you could create a form like this: ```javascript var state = { term: "", search: function() { // save the state for this route // this is equivalent to `history.replaceState({term: state.term}, null, location.href)` m.route.set(m.route.get(), null, {replace: true, state: {term: state.term}}) // navigate away location.href = "https://google.com/?q=" + state.term } } var Form = { oninit: function(vnode) { state.term = vnode.attrs.term || "" // populated from the `history.state` property if the user presses the back button }, view: function() { return m("form", [ m("input[placeholder='Search']", {oninput: m.withAttr("value", function(v) {state.term = v}), value: state.term}), m("button", {onclick: state.search}, "Search") ]) } } m.route(document.body, "/", { "/": Form, }) ``` This way, if the user searches and presses the back button to return to the application, the input will still be populated with the search term. This technique can improve the user experience of large forms and other apps where non-persisted state is laborious for a user to produce. --- ### Changing router prefix The router prefix is a fragment of the URL that dictates the underlying [strategy](#routing-strategies) used by the router. ```javascript // set to pathname strategy m.route.prefix("") // set to querystring strategy m.route.prefix("?") // set to hash without bang m.route.prefix("#") // set to pathname strategy on a non-root URL // e.g. if the app lives under `http://localhost/my-app` and something else lives under `http://localhost` m.route.prefix("/my-app") ``` --- ### Advanced component resolution Instead of mapping a component to a route, you can specify a RouteResolver object. A RouteResolver object contains a `onmatch()` and/or a `render()` method. Both methods are optional but at least one of them must be present. ```javascript m.route(document.body, "/", { "/": { onmatch: function(args, requestedPath) { return Home }, render: function(vnode) { return vnode // equivalent to m(Home) }, } }) ``` RouteResolvers are useful for implementing a variety of advanced routing use cases. --- #### Wrapping a layout component It's often desirable to wrap all or most of the routed components in a reusable shell (often called a "layout"). In order to do that, you first need to create a component that contains the common markup that will wrap around the various different components: ```javascript var Layout = { view: function(vnode) { return m(".layout", vnode.children) } } ``` In the example above, the layout merely consists of a `
` that contains the children passed to the component, but in a real life scenario it could be as complex as needed. One way to wrap the layout is to define an anonymous component in the routes map: ```javascript // example 1 m.route(document.body, "/", { "/": { view: function() { return m(Layout, m(Home)) }, }, "/form": { view: function() { return m(Layout, m(Form)) }, } }) ``` However, note that because the top level component is an anonymous component, jumping from the `/` route to the `/form` route (or vice-versa) will tear down the anonymous component and recreate the DOM from scratch. If the Layout component had [lifecycle methods](lifecycle-methods.md) defined, the `oninit` and `oncreate` hooks would fire on every route change. Depending on the application, this may or may not be desirable. If you would prefer to have the Layout component be diffed and maintained intact rather than recreated from scratch, you should instead use a RouteResolver as the root object: ```javascript // example 2 m.route(document.body, "/", { "/": { render: function() { return m(Layout, m(Home)) }, }, "/form": { render: function() { return m(Layout, m(Form)) }, } }) ``` Note that in this case, if the Layout component the `oninit` and `oncreate` lifecycle methods would only fire on the Layout component on the first route change (assuming all routes use the same layout). To clarify the difference between the two examples, example 1 is equivalent to this code: ```javascript // functionally equivalent to example 1 var Anon1 = { view: function() { return m(Layout, m(Home)) }, } var Anon2 = { view: function() { return m(Layout, m(Form)) }, } m.route(document.body, "/", { "/": { render: function() { return m(Anon1) } }, "/form": { render: function() { return m(Anon2) } }, }) ``` Since `Anon1` and `Anon2` are different components, their subtrees (including `Layout`) are recreated from scratch. This is also what happens when components are used directly without a RouteResolver. In example 2, since `Layout` is the top-level component in both routes, the DOM for the `Layout` component is diffed (i.e. left intact if it has no changes), and only the change from `Home` to `Form` triggers a recreation of that subsection of the DOM. --- #### Authentication The RouteResolver's `onmatch` hook can be used to run logic before the top level component in a route is initializated. The example below shows how to implement a login wall that prevents users from seeing the `/secret` page unless they login. ```javascript var isLoggedIn = false var Login = { view: function() { return m("form", [ m("button[type=button]", { onclick: function() { isLoggedIn = true m.route.set("/secret") } }, "Login") ]) } } m.route(document.body, "/secret", { "/secret": { onmatch: function() { if (!isLoggedIn) m.route.set("/login") else return Home } }, "/login": Login }) ``` When the application loads, `onmatch` is called and since `isLoggedIn` is false, the application redirects to `/login`. Once the user pressed the login button, `isLoggedIn` would be set to true, and the application would redirect to `/secret`. The `onmatch` hook would run once again, and since `isLoggedIn` is true this time, the application would render the `Home` component. For the sake of simplicity, in the example above, the user's logged in status is kept in a global variable, and that flag is merely toggled when the user clicks the login button. In a real life application, a user would obviously have to supply proper login credentials, and clicking the login button would trigger a request to a server to authenticate the user: ```javascript var Auth = { username: "", password: "", setUsername: function(value) { Auth.username = value }, setPassword: function(value) { Auth.password = value }, login: function() { m.request({ url: "/api/v1/auth", data: {username: Auth.username, password: Auth.password} }).then(function(data) { localStorage.setItem("auth-token": data.token) m.route.set("/secret") }) } } var Login = { view: function() { return m("form", [ m("input[type=text]", {oninput: m.withAttr("value", Auth.setUsername), value: Auth.username}), m("input[type=password]", {oninput: m.withAttr("value", Auth.setPassword), value: Auth.password}), m("button[type=button]", {onclick: Auth.login, "Login") ]) } } m.route(document.body, "/secret", { "/secret": { onmatch: function() { if (!localStorage.getItem("auth-token")) m.route.set("/login") else return Home } }, "/login": Login }) ``` --- #### Preloading data Typically, a component can load data upon initialization. Loading data this way renders the component twice (once upon routing, and once after the request completes). ```javascript var state = { users: [], loadUsers: function() { return m.request("/api/v1/users").then(function(users) { state.users = users }) } } m.route(document.body, "/user/list", { "/user/list": { oninit: state.loadUsers, view: function() { return state.users.length > 0 ? state.users.map(function(user) { return m("div", user.id) }) : "loading" } }, }) ``` In the example above, on the first render, the UI displays `"loading"` since `state.users` is an empty array before the request completes. Then, once data is available, the UI redraws and a list of user ids is shown. RouteResolvers can be used as a mechanism to preload data before rendering a component in order to avoid UI flickering and thus bypassing the need for a loading indicator: ```javascript var state = { users: [], loadUsers: function() { return m.request("/api/v1/users").then(function(users) { state.users = users }) } } m.route(document.body, "/user/list", { "/user/list": { onmatch: state.loadUsers, render: function() { return state.users.map(function(user) { return m("div", user.id) }) } }, }) ``` Above, `render` only runs after the request completes, making the ternary operator redundant. --- #### Code splitting In a large application, it may be desirable to download the code for each route on demand, rather than upfront. Dividing the codebase this way is known as code splitting or lazy loading. In Mithril, this can be accomplished by returning a promise from the `onmatch` hook: At its most basic form, one could do the following: ```javascript // Home.js module.export = { view: function() { return [ m(Menu), m("h1", "Home") ] } } ``` ```javascript // index.js function load(file) { return m.request({ method: "GET", url: file, extract: function(xhr) { return new Function("var module = {};" + xhr.responseText + ";return module.exports;") } }) } m.route(document.body, "/", { "/": { onmatch: function() { return load("Home.js") }, }, }) ``` However, realistically, in order for that to work on a production scale, it would be necessary to bundle all of the dependencies for the `Home.js` module into the file that is ultimately served by the server. Fortunately, there are a number of tools that facilitate the task of bundling modules for lazy loading. Here's an example using [webpack's code splitting system](https://webpack.github.io/docs/code-splitting.html): ```javascript m.route(document.body, "/", { "/": { onmatch: function() { // using Webpack async code splitting return new Promise(function(resolve) { require(['./Home.js'], resolve) }) }, }, }) ``` mithril-1.1.6/docs/signatures.md000066400000000000000000000061771324223121200166300ustar00rootroot00000000000000# How to read signatures Signature sections typically look like this: `vnode = m(selector, attributes, children)` Argument | Type | Required | Description ------------ | ------------------------------------ | -------- | --- `selector` | `String|Object` | Yes | A CSS selector or a component `attributes` | `Object` | No | HTML attributes or element properties `children` | `Array|String|Number|Boolean` | No | Child [vnodes](vnodes.md). Can be written as [splat arguments](signatures.md#splats) **returns** | `Vnode` | | A [vnode](vnodes.md) The signature line above the table indicates the general syntax of the method, showing the name of the method, the order of its arguments and a suggested variable name for its return value. The **Argument** column in the table indicates which part of the signature is explained by the respective table row. The `returns` row displays information about the return value of the method. The **Type** column indicates the expected type for the argument. A pipe (`|`) indicates that an argument is valid if it has any of the listed types. For example, `String|Object` indicates that `selector` can be a string OR an object. Angled brackets (`< >`) after an `Array` indicate the expected type for array items. For exampe, `Array` indicates that the argument must be an array and that all items in that array must be strings. Angled brackets after an `Object` indicate a map. For example, `Object` indicates that the argument must be an object, whose keys are strings and values are [components](components.md) Sometimes non-native types may appear to indicate that a specific object signature is required. For example, `Vnode` is an object that has a [virtual DOM node](vnodes.md) structure. The **Required** column indicates whether an argument is required or optional. If an argument is optional, you may set it to `null` or `undefined`, or omit it altogether, such that the next argument appears in its place. --- ### Optional arguments Function arguments surrounded by square brackets `[ ]` are optional. In the example below, `url` is an optional argument: `m.request([url,] options)` --- ### Splats A splat argument means that if the argument is an array, you can omit the square brackets and have a variable number of arguments in the method instead. In the example at the top, this means that `m("div", {id: "foo"}, ["a", "b", "c"])` can also be written as `m("div", {id: "foo"}, "a", "b", "c")`. Splats are useful in some compile-to-js languages such as Coffeescript, and also allow helpful shorthands for some common use cases. --- ### Function signatures Functions are denoted with an arrow (`->`). The left side of the arrow indicates the types of the input arguments and the right side indicates the type for the return value. For example, `parseFloat` has the signature `String -> Number`, i.e. it takes a string as input and returns a number as output. Functions with multiple arguments are denoted with parenthesis: `(String, Array) -> Number` mithril-1.1.6/docs/simple-application.md000066400000000000000000000605671324223121200202410ustar00rootroot00000000000000# Simple application Let's develop a simple application that covers some of the major aspects of Single Page Applications First let's create an entry point for the application. Create a file `index.html`: ```markup My Application ``` The `` line indicates this is an HTML 5 document. The first `charset` meta tag indicates the encoding of the document and the `viewport` meta tag dictates how mobile browsers should scale the page. The `title` tag contains the text to be displayed on the browser tab for this application, and the `script` tag indicates what is the path to the Javascript file that controls the application. We could create the entire application in a single Javascript file, but doing so would make it difficult to navigate the codebase later on. Instead, let's split the code into *modules*, and assemble these modules into a *bundle* `bin/app.js`. There are many ways to setup a bundler tool, but most are distributed via NPM. In fact, most modern Javascript libraries and tools are distributed that way, including Mithril. NPM stands for Node.js Package Manager. To download NPM, [install Node.js](https://nodejs.org/en/); NPM is installed automatically with it. Once you have Node.js and NPM installed, open the command line and run this command: ```bash npm init -y ``` If NPM is installed correctly, a file `package.json` will be created. This file will contain a skeleton project meta-description file. Feel free to edit the project and author information in this file. --- To install Mithril, follow the instructions in the [installation](installation.md) page. Once you have a project skeleton with Mithril installed, we are ready to create the application. Let's start by creating a module to store our state. Let's create a file called `src/models/User.js` ```javascript // src/models/User.js var User = { list: [] } module.exports = User ``` Now let's add code to load some data from a server. To communicate with a server, we can use Mithril's XHR utility, `m.request`. First, we include Mithril in the module: ```javascript // src/models/User.js var m = require("mithril") var User = { list: [] } module.exports = User ``` Next we create a function that will trigger an XHR call. Let's call it `loadList` ```javascript // src/models/User.js var m = require("mithril") var User = { list: [], loadList: function() { // TODO: make XHR call } } module.exports = User ``` Then we can add an `m.request` call to make an XHR request. For this tutorial, we'll make XHR calls to the [REM](http://rem-rest-api.herokuapp.com/) API, a mock REST API designed for rapid prototyping. This API returns a list of users from the `GET https://rem-rest-api.herokuapp.com/api/users` endpoint. Let's use `m.request` to make an XHR request and populate our data with the response of that endpoint. ```javascript // src/models/User.js var m = require("mithril") var User = { list: [], loadList: function() { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { User.list = result.data }) }, } module.exports = User ``` The `method` option is an [HTTP method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods). To retrieve data from the server without causing side-effects on the server, we need to use the `GET` method. The `url` is the address for the API endpoint. The `withCredentials: true` line indicates that we're using cookies (which is a requirement for the REM API). The `m.request` call returns a Promise that resolves to the data from the endpoint. By default, Mithril assumes a HTTP response body are in JSON format and automatically parses it into a Javascript object or array. The `.then` callback runs when the XHR request completes. In this case, the callback assigns the `result.data` array to `User.list`. Notice we also have a `return` statement in `loadList`. This is a general good practice when working with Promises, which allows us to register more callbacks to run after the completion of the XHR request. This simple model exposes two members: `User.list` (an array of user objects), and `User.loadList` (a method that populates `User.list` with server data). --- Now, let's create a view module so that we can display data from our User model module. Create a file called `src/views/UserList.js`. First, let's include Mithril and our model, since we'll need to use both: ```javascript // src/views/UserList.js var m = require("mithril") var User = require("../models/User") ``` Next, let's create a Mithril component. A component is simply an object that has a `view` method: ```javascript // src/views/UserList.js var m = require("mithril") var User = require("../models/User") module.exports = { view: function() { // TODO add code here } } ``` By default, Mithril views are described using [hyperscript](hyperscript.md). Hyperscript offers a terse syntax that can be indented more naturally than HTML for complex tags, and in addition, since its syntax is simply Javascript, it's possible to leverage a lot of Javascript tooling ecosystem: for example [Babel](es6.md), [JSX](jsx.md) (inline-HTML syntax extension), [eslint](http://eslint.org/) (linting), [uglifyjs](https://github.com/mishoo/UglifyJS2) (minification), [istanbul](https://github.com/gotwarlost/istanbul) (code coverage), [flow](https://flowtype.org/) (static type analysis), etc. Let's use Mithril hyperscript to create a list of items. Hyperscript is the most idiomatic way of writing Mithril views, but [JSX is another popular alternative that you could explore](jsx.md) once you're more comfortable with the basics: ```javascript var m = require("mithril") var User = require("../models/User") module.exports = { view: function() { return m(".user-list") } } ``` The `".user-list"` string is a CSS selector, and as you would expect, `.user-list` represents a class. When a tag is not specified, `div` is the default. So this view is equivalent to `
`. Now, let's reference the list of users from the model we created earlier (`User.list`) to dynamically loop through data: ```javascript // src/views/UserList.js var m = require("mithril") var User = require("../models/User") module.exports = { view: function() { return m(".user-list", User.list.map(function(user) { return m(".user-list-item", user.firstName + " " + user.lastName) })) } } ``` Since `User.list` is a Javascript array, and since hyperscript views are just Javascript, we can loop through the array using the `.map` method. This creates an array of vnodes that represents a list of `div`s, each containing the name of a user. The problem, of course, is that we never called the `User.loadList` function. Therefore, `User.list` is still an empty array, and thus this view would render a blank page. Since we want `User.loadList` to be called when we render this component, we can take advantage of component [lifecycle methods](lifecycle-methods.md): ```javascript // src/views/UserList.js var m = require("mithril") var User = require("../models/User") module.exports = { oninit: User.loadList, view: function() { return m(".user-list", User.list.map(function(user) { return m(".user-list-item", user.firstName + " " + user.lastName) })) } } ``` Notice that we added an `oninit` method to the component, which references `User.loadList`. This means that when the component initializes, User.loadList will be called, triggering an XHR request. When the server returns a response, `User.list` gets populated. Also notice we **didn't** do `oninit: User.loadList()` (with parentheses at the end). The difference is that `oninit: User.loadList()` calls the function once and immediately, but `oninit: User.loadList` only calls that function when the component renders. This is an important difference and a common pitfall for developers new to javascript: calling the function immediately means that the XHR request will fire as soon as the source code is evaluated, even if the component never renders. Also, if the component is ever recreated (through navigating back and forth through the application), the function won't be called again as expected. --- Let's render the view from the entry point file `src/index.js` we created earlier: ```javascript // src/index.js var m = require("mithril") var UserList = require("./views/UserList") m.mount(document.body, UserList) ``` The `m.mount` call renders the specified component (`UserList`) into a DOM element (`document.body`), erasing any DOM that was there previously. Opening the HTML file in a browser should now display a list of person names. --- Right now, the list looks rather plain because we have not defined any styles. There are many similar conventions and libraries that help organize application styles nowadays. Some, like [Bootstrap](http://getbootstrap.com/) dictate a specific set of HTML structures and semantically meaningful class names, which has the upside of providing low cognitive dissonance, but the downside of making customization more difficult. Others, like [Tachyons](http://tachyons.io/) provide a large number of self-describing, atomic class names at the cost of making the class names themselves non-semantic. "CSS-in-JS" is another type of CSS system that is growing in popularity, which basically consists of scoping CSS via transpilation tooling. CSS-in-JS libraries achieve maintainability by reducing the size of the problem space, but come at the cost of having high complexity. Regardless of what CSS convention/library you choose, a good rule of thumb is to avoid the cascading aspect of CSS. To keep this tutorial simple, we'll just use plain CSS with overly explicit class names, so that the styles themselves provide the atomicity of Tachyons, and class name collisions are made unlikely through the verbosity of the class names. Plain CSS can be sufficient for low-complexity projects (e.g. 3 to 6 man-months of initial implementation time and few project phases). To add styles, let's first create a file called `styles.css` and include it in the `index.html` file: ```markup My Application ``` Now we can style the `UserList` component: ```css .user-list {list-style:none;margin:0 0 10px;padding:0;} .user-list-item {background:#fafafa;border:1px solid #ddd;color:#333;display:block;margin:0 0 1px;padding:8px 15px;text-decoration:none;} .user-list-item:hover {text-decoration:underline;} ``` The CSS above is written using a convention of keeping all styles for a rule in a single line, in alphabetical order. This convention is designed to take maximum advantage of screen real estate, and makes it easier to scan the CSS selectors (since they are always on the left side) and their logical grouping, and it enforces predictable and uniform placement of CSS rules for each selector. Obviously you can use whatever spacing/indentation convention you prefer. The example above is just an illustration of a not-so-widespread convention that has strong rationales behind it, but deviate from the more widespread cosmetic-oriented spacing conventions. Reloading the browser window now should display some styled elements. --- Let's add routing to our application. Routing means binding a screen to a unique URL, to create the ability to go from one "page" to another. Mithril is designed for Single Page Applications, so these "pages" aren't necessarily different HTML files in the traditional sense of the word. Instead, routing in Single Page Applications retains the same HTML file throughout its lifetime, but changes the state of the application via Javascript. Client side routing has the benefit of avoiding flashes of blank screen between page transitions, and can reduce the amount of data being sent down from the server when used in conjunction with an web service oriented architecture (i.e. an application that downloads data as JSON instead of downloading pre-rendered chunks of verbose HTML). We can add routing by changing the `m.mount` call to a `m.route` call: ```javascript // src/index.js var m = require("mithril") var UserList = require("./views/UserList") m.route(document.body, "/list", { "/list": UserList }) ``` The `m.route` call specifies that the application will be rendered into `document.body`. The `"/list"` argument is the default route. That means the user will be redirected to that route if they land in a route that does not exist. The `{"/list": UserList}` object declares a map of existing routes, and what components each route resolves to. Refreshing the page in the browser should now append `#!/list` to the URL to indicate that routing is working. Since that route render UserList, we should still see the list of people on screen as before. The `#!` snippet is known as a hashbang, and it's a commonly used string for implementing client-side routing. It's possible to configure this string it via [`m.route.prefix`](route.md#mrouteprefix). Some configurations require supporting server-side changes, so we'll just continue using the hashbang for the rest of this tutorial. --- Let's add another route to our application for editing users. First let's create a module called `views/UserForm.js` ```javascript // src/views/UserForm.js module.exports = { view: function() { // TODO implement view } } ``` Then we can `require` this new module from `src/index.js` ```javascript // src/index.js var m = require("mithril") var UserList = require("./views/UserList") var UserForm = require("./views/UserForm") m.route(document.body, "/list", { "/list": UserList }) ``` And finally, we can create a route that references it: ```javascript // src/index.js var m = require("mithril") var UserList = require("./views/UserList") var UserForm = require("./views/UserForm") m.route(document.body, "/list", { "/list": UserList, "/edit/:id": UserForm, }) ``` Notice that the new route has a `:id` in it. This is a route parameter; you can think of it as a wild card; the route `/edit/1` would resolve to `UserForm` with an `id` of `"1"`. `/edit/2` would also resolve to `UserForm`, but with an `id` of `"2"`. And so on. Let's implement the `UserForm` component so that it can respond to those route parameters: ```javascript // src/views/UserForm.js var m = require("mithril") module.exports = { view: function() { return m("form", [ m("label.label", "First name"), m("input.input[type=text][placeholder=First name]"), m("label.label", "Last name"), m("input.input[placeholder=Last name]"), m("button.button[type=button]", "Save"), ]) } } ``` And let's add some styles to `styles.css`: ```css /* styles.css */ body,.input,.button {font:normal 16px Verdana;margin:0;} .user-list {list-style:none;margin:0 0 10px;padding:0;} .user-list-item {background:#fafafa;border:1px solid #ddd;color:#333;display:block;margin:0 0 1px;padding:8px 15px;text-decoration:none;} .user-list-item:hover {text-decoration:underline;} .label {display:block;margin:0 0 5px;} .input {border:1px solid #ddd;border-radius:3px;box-sizing:border-box;display:block;margin:0 0 10px;padding:10px 15px;width:100%;} .button {background:#eee;border:1px solid #ddd;border-radius:3px;color:#333;display:inline-block;margin:0 0 10px;padding:10px 15px;text-decoration:none;} .button:hover {background:#e8e8e8;} ``` Right now, this component does nothing to respond to user events. Let's add some code to our `User` model in `src/models/User.js`. This is how the code is right now: ```javascript // src/models/User.js var m = require("mithril") var User = { list: [], loadList: function() { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { User.list = result.data }) }, } module.exports = User ``` Let's add code to allow us to load a single user ```javascript // src/models/User.js var m = require("mithril") var User = { list: [], loadList: function() { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { User.list = result.data }) }, current: {}, load: function(id) { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users/" + id, withCredentials: true, }) .then(function(result) { User.current = result }) } } module.exports = User ``` Notice we added a `User.current` property, and a `User.load(id)` method which populates that property. We can now populate the `UserForm` view using this new method: ```javascript // src/views/UserForm.js var m = require("mithril") var User = require("../models/User") module.exports = { oninit: function(vnode) {User.load(vnode.attrs.id)}, view: function() { return m("form", [ m("label.label", "First name"), m("input.input[type=text][placeholder=First name]", {value: User.current.firstName}), m("label.label", "Last name"), m("input.input[placeholder=Last name]", {value: User.current.lastName}), m("button.button[type=button]", "Save"), ]) } } ``` Similar to the `UserList` component, `oninit` calls `User.load()`. Remember we had a route parameter called `:id` on the `"/edit/:id": UserForm` route? The route parameter becomes an attribute of the `UserForm` component's vnode, so routing to `/edit/1` would make `vnode.attrs.id` have a value of `"1"`. Now, let's modify the `UserList` view so that we can navigate from there to a `UserForm`: ```javascript // src/views/UserList.js var m = require("mithril") var User = require("../models/User") module.exports = { oninit: User.loadList, view: function() { return m(".user-list", User.list.map(function(user) { return m("a.user-list-item", {href: "/edit/" + user.id, oncreate: m.route.link}, user.firstName + " " + user.lastName) })) } } ``` Here we changed `.user-list-item` to `a.user-list-item`. We added an `href` that references the route we want, and finally we added `oncreate: m.route.link`. This makes the link behave like a routed link (as opposed to merely behaving like a regular link). What this means is that clicking the link would change the part of URL that comes after the hashbang `#!` (thus changing the route without unloading the current HTML page) If you refresh the page in the browser, you should now be able to click on a person and be taken to a form. You should also be able to press the back button in the browser to go back from the form to the list of people. --- The form itself still doesn't save when you press "Save". Let's make this form work: ```javascript // src/views/UserForm.js var m = require("mithril") var User = require("../models/User") module.exports = { oninit: function(vnode) {User.load(vnode.attrs.id)}, view: function() { return m("form", { onsubmit: function(e) { e.preventDefault() User.save() } }, [ m("label.label", "First name"), m("input.input[type=text][placeholder=First name]", { oninput: m.withAttr("value", function(value) {User.current.firstName = value}), value: User.current.firstName }), m("label.label", "Last name"), m("input.input[placeholder=Last name]", { oninput: m.withAttr("value", function(value) {User.current.lastName = value}), value: User.current.lastName }), m("button.button[type=submit]", "Save"), ]) } } ``` We added `oninput` events to both inputs, that set the `User.current.firstName` and `User.current.lastName` properties when a user types. In addition, we declared that a `User.save` method should be called when the "Save" button is pressed. Let's implement that method: ```javascript // src/models/User.js var m = require("mithril") var User = { list: [], loadList: function() { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users", withCredentials: true, }) .then(function(result) { User.list = result.data }) }, current: {}, load: function(id) { return m.request({ method: "GET", url: "https://rem-rest-api.herokuapp.com/api/users/" + id, withCredentials: true, }) .then(function(result) { User.current = result }) }, save: function() { return m.request({ method: "PUT", url: "https://rem-rest-api.herokuapp.com/api/users/" + User.current.id, data: User.current, withCredentials: true, }) } } module.exports = User ``` In the `save` method at the bottom, we used the `PUT` HTTP method to indicate that we are upserting data to the server. Now try editing the name of a user in the application. Once you save a change, you should be able to see the change reflected in the list of users. --- Currently, we're only able to navigate back to the user list via the browser back button. Ideally, we would like to have a menu - or more generically, a layout where we can put global UI elements Let's create a file `src/views/Layout.js`: ```javascript var m = require("mithril") module.exports = { view: function(vnode) { return m("main.layout", [ m("nav.menu", [ m("a[href='/list']", {oncreate: m.route.link}, "Users") ]), m("section", vnode.children) ]) } } ``` This component is fairly straightforward, it has a `