docs: update with latest fixes (#2116)

This commit is contained in:
Pat Cavit 2018-04-12 00:11:11 -07:00 committed by GitHub
parent b9f65c2fdd
commit 6fb77b7771
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 276 additions and 89 deletions

View file

@ -102,4 +102,4 @@ Note that the `onbeforeremove` hook only fires on the element that loses its `pa
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).
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 positioned element over a fixed element).

View file

@ -55,7 +55,7 @@ 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
reported by contacting the project team at [github@patcavit.com](mailto:github@patcavit.com?subject=Mithril%20Code%20of%20Conduct). 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.

View file

@ -61,6 +61,9 @@ var ComponentWithHooks = {
oncreate: function(vnode) {
console.log("DOM created")
},
onbeforeupdate: function(vnode, old) {
return true
},
onupdate: function(vnode) {
console.log("DOM updated")
},
@ -74,9 +77,6 @@ var ComponentWithHooks = {
onremove: function(vnode) {
console.log("removing DOM element")
},
onbeforeupdate: function(vnode, old) {
return true
},
view: function(vnode) {
return "hello"
}
@ -177,7 +177,7 @@ They can be consumed in the same way regular components can.
m.render(document.body, m(closureComponent))
// EXAMPLE: via m.mount
m.mount(document.body, closuresComponent)
m.mount(document.body, closureComponent)
// EXAMPLE: via m.route
m.route(document.body, "/", {

View file

@ -22,9 +22,11 @@ To send a pull request:
- fork the repo (button at the top right in GitHub)
- clone the forked repo to your computer (green button in GitHub)
- Switch to the `next` branch (run `git checkout next`)
- create a feature branch (run `git checkout -b the-feature-branch-name`)
- make your changes
- run the tests (run `npm t`)
- run the tests (run `npm test`)
- push your changes to your fork
- submit a pull request (go to the pull requests tab in GitHub, click the green button and select your feature branch)

View file

@ -87,7 +87,7 @@ Nowadays there are [a lot of CSS-in-JS libraries with various degrees of robustn
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. `<a class={classnames(styles.button, styles.danger)}></a>` vs `<a class="button danger"></a>` (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).
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 cryptic class names).
Another common issue is lack of support for less basic CSS features such as `@keyframes` and `@font-face`.

View file

@ -12,9 +12,6 @@ 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) {

View file

@ -225,7 +225,7 @@ var Splash = {
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`.
Now that we're going to have more than one screen, we use `m.route` instead of `m.mount`.
```javascript
m.route(root, "/splash", {

View file

@ -2,6 +2,8 @@
- [CDN](#cdn)
- [NPM](#npm)
- [Quick start with Webpack](#quick-start-with-webpack)
- [TypeScript](#typescript)
### CDN
@ -15,30 +17,57 @@ If you're new to Javascript or just want a very simple setup to get your feet we
### NPM
#### Quick start with Webpack
```bash
# 1) install
npm install mithril --save
npm install webpack --save
# 2) add this line into the scripts section in package.json
# "scripts": {
# "start": "webpack src/index.js bin/app.js --watch"
# }
# 3) create an `src/index.js` file
# 4) create an `index.html` file containing `<script src="bin/app.js"></script>`
# 5) run bundler
npm start
# 6) open `index.html` in the (default) browser
open index.html
$> npm install mithril --save
```
---
### Quick start with Webpack
1. Initialize the directory as an npm package
```bash
$> npm init --yes
```
2. install required tools
```bash
$> npm install mithril --save
$> npm install webpack webpack-cli --save-dev
```
3. Add a "start" entry to the scripts section in `package.json`.
```js
{
// ...
"scripts": {
"start": "webpack src/index.js --output bin/app.js -d --watch"
}
}
```
3. Create `src/index.js`
```js
import m from "mithril";
m.render(document.body, "hello world");
```
4. create `index.html`
```html
<!DOCTYPE html>
<body>
<script src="bin/app.js"></script>
</body>
```
5. run bundler
```bash
$> npm start
```
6. open `index.html` in a browser
#### Step by step
For production-level projects, the recommended way of installing Mithril is to use NPM.
@ -78,7 +107,7 @@ Most browser today do not natively support modularization systems (CommonJS or E
A popular way for creating a bundle is to setup an NPM script for [Webpack](https://webpack.js.org/). To install Webpack, run this from the command line:
```bash
npm install webpack --save-dev
npm install webpack webpack-cli --save-dev
```
Open the `package.json` that you created earlier, and add an entry to the `scripts` section:
@ -87,7 +116,7 @@ Open the `package.json` that you created earlier, and add an entry to the `scrip
{
"name": "my-project",
"scripts": {
"start": "webpack src/index.js bin/app.js -d --watch"
"start": "webpack src/index.js --output bin/app.js -d --watch"
}
}
```
@ -149,8 +178,8 @@ If you open bin/app.js, you'll notice that the Webpack bundle is not minified, s
{
"name": "my-project",
"scripts": {
"start": "webpack src/index.js bin/app.js -d --watch",
"build": "webpack src/index.js bin/app.js -p",
"start": "webpack src/index.js --output bin/app.js -d --watch",
"build": "webpack src/index.js --output bin/app.js -p",
}
}
```
@ -231,3 +260,15 @@ If you don't have the ability to run a bundler script due to company security po
// if a CommonJS environment is not detected, Mithril will be created in the global scope
m.render(document.body, "hello world")
```
---
### TypeScript
TypeScript type definitions are available from DefinitelyTyped. They can be installed with:
```bash
$> npm install @types/mithril --save-dev
```
For example usage, to file issues or to discuss TypeScript related topics visit: https://github.com/MithrilJS/mithril.d.ts

57
docs/integrating-libs.md Normal file
View file

@ -0,0 +1,57 @@
# Integrating with Other Libraries
Integration with third party libraries or vanilla javascript code can be achieved via [lifecycle methods](lifecycle-methods.md).
- [Usage](#usage)
### Usage
```javascript
var FullCalendar = {
oncreate: function (vnode) {
console.log('FullCalendar::oncreate')
$(vnode.dom).fullCalendar({
// put your initial options and callbacks here
})
Object.assign(vnode.attrs.parentState, {fullCalendarEl: vnode.dom})
},
// Consider that the lib will modify this parent element in the DOM (e.g. add dependent class attribute and values).
// As long as you return the same view results here, mithril will not
// overwrite the actual DOM because it's always comparing old and new VDOM
// before applying DOM updates.
view: function (vnode) {
return m('div')
},
onbeforeremove: function (vnode) {
// Run any destroy / cleanup methods here.
//E.g. $(vnode.state.fullCalendarEl).fullCalendar('destroy')
}
}
m.mount(document.body, {
view: function (vnode) {
return [
m('h1', 'Calendar'),
m(FullCalendar, {parentState: vnode.state}),
m('button', {onclick: prev}, 'Mithril Button -'),
m('button', {onclick: next}, 'Mithril Button +')
]
function next() {
$(vnode.state.fullCalendarEl).fullCalendar('next')
}
function prev() {
$(vnode.state.fullCalendarEl).full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qEkTRqhAOpynKuak13PKqDqvBGp0fRWvazrRpcBVeoAJkGgBOfBjoO1bJqykAZrmhaUrSx6AEdrE7CRat4er1ClJqdrQNqOroVwTHez7eriU7P10YNxF0cGPt4CRbvqB68Cepa8E1KkIu+36tua3aQZcVIQjxl4oYSZI4YgBHcYgtHpokWbMYQUoNNKIA)

View file

@ -98,7 +98,7 @@ npm install babel-core babel-loader babel-preset-es2015 babel-plugin-transform-r
Create a `.babelrc` file:
```
```json
{
"presets": ["es2015"],
"plugins": [
@ -121,7 +121,7 @@ module.exports = {
filename: 'app.js',
},
module: {
loaders: [{
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
@ -130,6 +130,8 @@ module.exports = {
}
```
For those familiar with Webpack already, please note that adding the Babel options to the `babel-loader` section of your `webpack.config.js` will throw an error, so you need to include them in the separate `.babelrc` file.
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"`:
@ -189,7 +191,7 @@ JSX is useful for teams where HTML is primarily written by someone without Javas
Hyperscript is the compiled representation of JSX. It's designed to be readable and can also be used as-is, instead of JSX (as is done in most of the documentation). Hyperscript tends to be terser than JSX for a couple of reasons:
- it does not require repeating the tag name in closing tags (e.g. `m("div")` vs `<div></div>`)
- static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `<div class="button"></div>`
- static attributes can be written using CSS selector syntax (i.e. `m("a.button")` vs `<a class="button"></a>`)
In addition, since hyperscript is plain Javascript, it's often more natural to indent than JSX:

View file

@ -180,7 +180,7 @@ m("div", [
#### Avoid passing model data directly to components if the model uses `key` as a data property
The `key` property may appear in your data model in a way that conflicts with Mithril's key logic. For example, a component may represent an entity whose `key` property is expected to change over time. This can lead to components receiving the wrong data, re-initialise, or change positions unexpectedly. If your data model uses the `key` property, make sure to wrap the data such that Mithril doesn't misinterpret it as a rendering instruction:
The `key` property may appear in your data model in a way that conflicts with Mithril's key logic. For example, a component may represent an entity whose `key` property is expected to change over time. This can lead to components receiving the wrong data, re-initialize, or change positions unexpectedly. If your data model uses the `key` property, make sure to wrap the data such that Mithril doesn't misinterpret it as a rendering instruction:
```javascript
// Data model

View file

@ -16,7 +16,7 @@
<a href="index.html">Guide</a>
<a href="api.html">API</a>
<a href="https://gitter.im/MithrilJS/mithril.js">Chat</a>
<a href="https://github.com/MithrilJS/mithril.js">Github</a>
<a href="https://github.com/MithrilJS/mithril.js">GitHub</a>
</nav>
</section>
</header>

5
docs/learning-mithril.md Normal file
View file

@ -0,0 +1,5 @@
# Learning Mithril
Links to Mithril learning content:
- [Mithril 0-60](https://scrimba.com/playlist/playlist-34)

View file

@ -35,12 +35,12 @@ m.mount(element, {view: function () {return m(Component, attrs)}})
### Signature
`m.mount(element, component)`
`m.mount(element, Component)`
Argument | Type | Required | Description
----------- | -------------------- | -------- | ---
`element` | `Element` | Yes | A DOM element that will be the parent node to the subtree
`component` | `Component|null` | Yes | The [component](components.md) to be rendered. `null` unmounts the tree and cleans up internal state.
`Component` | `Component|null` | Yes | The [component](components.md) to be rendered. `null` unmounts the tree and cleans up internal state.
**returns** | | | Returns nothing
[How to read signatures](signatures.md)
@ -49,7 +49,9 @@ Argument | Type | Required | Description
### How it works
Similar to [`m.render()`](render.md), the `m.mount()` method takes a component and mounts a corresponding DOM tree into `element`. If `element` already has a DOM tree mounted via a previous `m.mount()` call, the component is diffed against the previous vnode tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
`m.mount(element, Component)`, when called renders the component into the element and subscribe the `(element, Component)` pair to the redraw subsystem. That tree will be re-rendered when [manual](redraw.md) or [automatic](autoredraw.md) redraws are triggered.
On redraw, the new vDOM tree is compared (or "diffed") with the old one, and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
#### Replace a component
@ -73,7 +75,7 @@ In contrast, traversing a javascript data structure has a much more predictable
### Differences from m.render
A component rendered via `m.mount` automatically auto-redraws in response to view events, `m.redraw()` calls or `m.request()` calls. Vnodes rendered via `m.render()` do not.
A component rendered via `m.mount` [automatically redraws](autoredraw.md) in response to view events, `m.redraw()` calls or `m.request()` calls. Vnodes rendered via `m.render()` do not.
`m.mount()` is suitable for application developers integrating Mithril widgets into existing codebases where routing is handled by another library or framework, while still enjoying Mithril's auto-redrawing facilities.

View file

@ -9,6 +9,8 @@
- [Animation](animation.md)
- [Testing](testing.md)
- [Examples](examples.md)
- [Integrating with Other Libraries](integrating-libs.md)
- [Learning Mithril](learning-mithril.md)
- Key concepts
- [Vnodes](vnodes.md)
- [Components](components.md)

View file

@ -302,7 +302,7 @@ This example also illustrates another benefit of smaller functions: we reused th
### Why not callbacks
Callbacks are another mechanism for working with asynchrounous computations, and are indeed more adequate to use if an asynchronous computation may occur more than one time (for example, an `onscroll` event handler).
Callbacks are another mechanism for working with asynchronous computations, and are indeed more adequate to use if an asynchronous computation may occur more than one time (for example, an `onscroll` event handler).
However, for asynchronous computations that only occur once in response to an action, promises can be refactored more effectively, reducing code smells known as pyramids of doom (deeply nested series of callbacks with unmanaged state being used across several closure levels).

View file

@ -10,7 +10,7 @@
Updates the DOM after a change in the application data layer.
You DON'T need to call it if data is modified within the execution context of an event handler defined in a Mithril view, or after request completion when using `m.request`/`m.jsonp`.
You DON'T need to call it if data is modified within the execution context of an event handler defined in a Mithril view, or after request completion when using `m.request`/`m.jsonp`. The [autoredraw](autoredraw.md) system, which is built on top of `m.redraw()` will take care of it.
You DO need to call it in `setTimeout`/`setInterval`/`requestAnimationFrame` callbacks, or callbacks from 3rd party libraries.

View file

@ -2,6 +2,10 @@
**Note** These steps all assume that `MithrilJS/mithril.js` is a git remote named `mithriljs`, adjust accordingly if that doesn't match your setup.
- [Releasing a new Mithril version](#releasing-a-new-mithril-version)
- [Updating mithril.js.org](#updating-mithriljsorg)
- [Releasing a new ospec version](#releasing-a-new-ospec-version)
## Releasing a new Mithril version
### Prepare the release
@ -9,7 +13,7 @@
1. Ensure your local branch is up to date
```bash
$ git co next
$ git checkout next
$ git pull --rebase mithriljs next
```
@ -33,7 +37,7 @@ $ git push mithriljs next
5. Switch to `master` and make sure it's up to date
```bash
$ git co master
$ git checkout master
$ git pull --rebase mithriljs master
```
@ -70,7 +74,7 @@ This helps to ensure that the `version` field of `package.json` doesn't get out
12. Switch to `next` and make sure it's up to date
```bash
$ git co next
$ git checkout next
$ git pull --rebase mithriljs next
```
@ -99,12 +103,12 @@ Fixes to documentation can land whenever, updates to the site are published via
# These steps assume that MithrilJS/mithril.js is a git remote named "mithriljs"
# Ensure your next branch is up to date
$ git co next
$ git checkout next
$ git pull mithriljs next
# Splat the docs folder from next onto master
$ git co master
$ git co next -- ./docs
$ git checkout master
$ git checkout next -- ./docs
# Manually ensure that no new feature docs were added
@ -112,3 +116,61 @@ $ git push mithriljs
```
After the Travis build completes the updated docs should appear on https://mithril.js.org in a few minutes.
## Releasing a new ospec version
1. Ensure your local branch is up to date
```bash
$ git checkout next
$ git pull --rebase mithriljs next
```
2. Determine patch level of the change
3. Update `version` field in `ospec/package.json` to match new version being prepared for release
4. Commit changes to `next`
```
$ git add .
$ git commit -m "chore(ospec): ospec@<version>"
# Push to your branch
$ git push
# Push to MithrilJS/mithril.js
$ git push mithriljs next
```
### Merge from `next` to `master`
5. Switch to `master` and make sure it's up to date
```bash
$ git checkout master
$ git pull --rebase mithriljs master
```
6. merge `next` on top of it
```bash
$ git checkout next -- ./ospec
$ git add .
$ git commit -m "chore(ospec): ospec@<version>"
```
7. Ensure the tests are passing!
### Publish the release
8. Push the changes to `MithrilJS/mithril.js`
```bash
$ git push mithriljs master
```
9. Publish the changes to npm **from the `/ospec` folder**. That bit is important to ensure you don't accidentally ship a new Mithril release!
```bash
$ cd ./ospec
$ npm publish
```

View file

@ -36,7 +36,7 @@ Argument | Type | Required | Description
### How it works
The `m.render(element, vnodes)` method takes a virtual DOM tree (typically generated via the [`m()` hyperscript function](hyperscript.md), generates a DOM tree and mounts it on `element`. If `element` already has a DOM tree mounted via a previous `m.render()` call, `vnodes` is diffed against the previous `vnodes` tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
The `m.render(element, vnodes)` method takes a virtual DOM tree (typically generated via the [`m()` hyperscript function](hyperscript.md)), generates a DOM tree and mounts it on `element`. If `element` already has a DOM tree mounted via a previous `m.render()` call, `vnodes` is diffed against the previous `vnodes` tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.
`m.render` is synchronous.
@ -68,4 +68,4 @@ Another difference is that `m.render` method expects a [vnode](vnodes.md) (or a
The `m.render` module is similar in scope to view libraries like Knockout, React and Vue. It is approximately 500 lines of code (3kb min+gzip) and implements a virtual DOM diffing engine with a modern search space reduction algorithm and DOM recycling, which translate to top-of-class performance, both in terms of initial page load and re-rendering. It has no dependencies on other parts of Mithril and can be used as a standalone library.
Despite being incredibly small, the render module is fully functional and self-suficient. It supports everything you might expect: SVG, custom elements, and all valid attributes and events - without any weird case-sensitive edge cases or exceptions. Of course, it also fully supports [components](components.md) and [lifecycle methods](lifecycle-methods.md).
Despite being incredibly small, the render module is fully functional and self-sufficient. It supports everything you might expect: SVG, custom elements, and all valid attributes and events - without any weird case-sensitive edge cases or exceptions. Of course, it also fully supports [components](components.md) and [lifecycle methods](lifecycle-methods.md).

View file

@ -49,12 +49,13 @@ Argument | Type | Required | Descr
`options.user` | `String` | No | A username for HTTP authorization. Defaults to `undefined`.
`options.password` | `String` | No | A password for HTTP authorization. Defaults to `undefined`. This option is provided for `XMLHttpRequest` compatibility, but you should avoid using it because it sends the password in plain text over the network.
`options.withCredentials` | `Boolean` | No | Whether to send cookies to 3rd party domains. Defaults to `false`
`options.timeout` | `Number` | No | The amount of milliseconds a request can take before automatically being [terminated](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout). Defaults to `undefined`.
`options.config` | `xhr = Function(xhr)` | No | Exposes the underlying XMLHttpRequest object for low-level configuration. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function).
`options.headers` | `Object` | No | Headers to append to the request before sending it (applied right before `options.config`).
`options.type` | `any = Function(any)` | No | A constructor to be applied to each object in the response. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function).
`options.serialize` | `string = Function(any)` | No | A serialization method to be applied to `data`. Defaults to `JSON.stringify`, or if `options.data` is an instance of [`FormData`](https://developer.mozilla.org/en/docs/Web/API/FormData), defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function) (i.e. `function(value) {return value}`).
`options.deserialize` | `any = Function(string)` | No | A deserialization method to be applied to the `xhr.responseText`. Defaults to a small wrapper around `JSON.parse` that returns `null` for empty responses. If `extract` is defined, `deserialize` will be skipped.
`options.extract` | `any = Function(xhr, options)` | No | A hook to specify how the XMLHttpRequest response should be read. Useful for processing response data, reading headers and cookies. By default this is a function that returns `xhr.responseText`, which is in turn passed to `deserialize`. If a custom `extract` callback is provided, the `xhr` parameter is the XMLHttpRequest instance used for the request, and `options` is the object that was passed to the `m.request` call. Additionally, `deserialize` will be skipped and the value returned from the extract callback will not automatically be parsed as JSON.
`options.extract` | `any = Function(xhr, options)` | No | A hook to specify how the XMLHttpRequest response should be read. Useful for processing response data, reading headers and cookies. By default this is a function that returns `xhr.responseText`, which is in turn passed to `deserialize`. If a custom `extract` callback is provided, the `xhr` parameter is the XMLHttpRequest instance used for the request, and `options` is the object that was passed to the `m.request` call. Additionally, `deserialize` will be skipped and the value returned from the extract callback will be left as-is when the promise resolves. Furthermore, when an extract callback is provided, exceptions are *not* thrown when the server response status code indicates an error.
`options.useBody` | `Boolean` | No | Force the use of the HTTP body section for `data` in `GET` requests when set to `true`, or the use of querystring for other HTTP methods when set to `false`. Defaults to `false` for `GET` requests and `true` for other methods.
`options.background` | `Boolean` | No | If `false`, redraws mounted components upon completion of the request. If `true`, it does not. Defaults to `false`.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods
@ -81,6 +82,8 @@ A call to `m.request` returns a [promise](promise.md) and triggers a redraw upon
By default, `m.request` assumes the response is in JSON format and parses it into a Javascript object (or array).
If the HTTP response status code indicates an error, the returned Promise will be rejected. Supplying an extract callback will prevent the promise rejection.
---
### Typical usage
@ -329,7 +332,7 @@ function upload(e) {
url: "/api/v1/upload",
data: data,
config: function(xhr) {
xhr.addEventListener("progress", function(e) {
xhr.upload.addEventListener("progress", function(e) {
progress = e.loaded / e.total
m.redraw() // tell Mithril that data changed and a re-render is needed
@ -426,7 +429,7 @@ m.request({
### 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:
By default Mithril attempts to parse `xhr.responseText` as JSON and returns the parsed object. It may be useful to inspect a server response in more detail and process it manually. This can be accomplished by passing a custom `options.extract` function:
```javascript
m.request({

View file

@ -65,7 +65,7 @@ Argument | Type | Required | D
##### m.route.set
Redirects to a matching route, or to the default route if no matching routes can be found.
Redirects to a matching route, or to the default route if no matching routes can be found. Triggers an asynchronous redraw off all mount points.
`m.route.set(path, data, options)`
@ -104,23 +104,29 @@ Argument | Type | Required | Description
This function can be used as the `oncreate` (and `onupdate`) hook in a `m("a")` vnode:
```JS
m("a[href=/]", {oncreate: m.route.link})`.
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`.
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 navigating 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("a", {href: someVariable, oncreate: m.route.link, onupdate: m.route.link})
```
`m.route.link(vnode)`
`m.route.link` can also set the `options` passed to `m.route.set` when the link is clicked by calling the function in the lifecycle methods:
Argument | Type | Required | Description
----------------- | ----------- | -------- | ---
`vnode` | `Vnode` | Yes | This method is meant to be used as or in conjunction with an `<a>` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md)
**returns** | | | Returns `undefined`
```JS
m("a[href=/]", {oncreate: m.route.link({replace: true})})
```
`m.route.link(args)`
Argument | Type | Required | Description
----------------- | ---------------| -------- | ---
`args` | `Vnode|Object` | Yes | This method is meant to be used as or in conjunction with an `<a>` [vnode](vnodes.md)'s [`oncreate` and `onupdate` hooks](lifecycle-methods.md)
**returns** | `function` | | Returns the onclick handler function for the component
##### m.route.param
@ -317,13 +323,13 @@ It's also possible to have variadic routes, i.e. a route with an argument that c
```javascript
m.route(document.body, "/edit/pictures/image.jpg", {
"/files/:file...": Edit,
"/edit/: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.
For isomorphic / universal javascript app, an url param and a variadic route combined is very useful 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.
@ -508,7 +514,7 @@ In example 2, since `Layout` is the top-level component in both routes, 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.
The RouteResolver's `onmatch` hook can be used to run logic before the top level component in a route is initialized. 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
@ -568,7 +574,7 @@ var Login = {
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("button[type=button]", {onclick: Auth.login}, "Login")
])
}
}
@ -588,7 +594,7 @@ m.route(document.body, "/secret", {
#### 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).
Typically, a component can load data upon initialization. Loading data this way renders the component twice. The first render pass occurs upon routing, and the second fires after the request completes. Take care to note that `loadUsers()` returns a Promise, but any Promise returned by `oninit` is currently ignored. The second render pass comes from the [`background` option for `m.request`](request.md).
```javascript
var state = {

View file

@ -2,6 +2,8 @@
Let's develop a simple application that covers some of the major aspects of Single Page Applications
An interactive running example can be seen here [flems: Simple Application](https://flems.io/#0=N4IgzgpgNhDGAuEAmIBcICGAHLA6AVmCADQgBmAljEagNqgB2GAthGiAKqQBOAsgPZJoBIqVj8GiSewBuGbgAIuERQF4FwADoMFuhVAph4qBbQC6xbXv38MSADKHjCsgFcGCChIAUASg1W1nrcEPCu3DrMuCEAjq4QRt5aOkGprPAAFoImmiAA4gCiACq5limp1uFQOSAZ8PBYYKgA9M0hzAC0IUYd2BS4GSr8ANau2HjizM19za48YKWBFXoA7hSZAMIhQpIUGFBNCvDc8WXLAL6+S0G4mRAM3m4e8F4P3a5Q8P7Jy9bK3LgDEYFOp3p9cEgMPAMNdrJdrucytdYOEQpITMBEdcoLYkCYnp4fBQkN9YcFQuFItEIHEEvAkmS0qEsniFLlCiUSIyglUanUGk1Wu0unTelh+oNuCMxjhcJNpuLZvNmrkFABqBTEs6-XRrTbbe4vfaHY6nbnw8o3O4PAkvHxgr4BS3Lf5y1GGkEKB3mq6WrEMa5gDAyCD49yEh6k53ksIRBRRWLxRI-HXx5nZNkgAAKHE52p1vMz-MaLTaEE63XgYolQ1G4zl-CmMzmKjAKpA6qUPDd3DR8FwWu51kh0JMrpRvcN+d+eoyW2Qhr2BxMpog07hvrh2nOIERjBYbHQ-0cRhEJBA4kkhtk8i7KhP8E9Kd0EgoDHWY+7OLsD+nMgoEArGGzyvH4TrLCEsaRN4uS4C23AdEC8ClHeAJIbgzDYI84Z2g88FRqmXoUnGzAwZgcE8IhTgdOs5YocAGQhGQNTNMg6ztp28EDkgxAKBIsAhFCobxtE-CuIggJvsMiIKFxlDcEYAByB6dqqqoalxUAYEpB6bhUlx6bo5zbruxD7qw7D-AAYvw3BRIQ56XlI8A3oo1m2cwT7XK+77OLaoEyAwggQ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gUgL54TxA4m4KgeBHSgXhJWWAGW11UBlRxLAYYMzsnrPmY8x64SllfNWagAAHE87xABWWpT0qxCHENwKErwJkSGmfU-pwz9moCyCGRQwACUdCJbZUlEhUDuF+ofSlvStkcw0KC8FkLoWwpaTktpbS8XIvqVLDQdyHlPJeW8j5XykC3Nsr9LodgKBzFQB02pODSlgAoAAL3RQqnZRqQWGGFVCjBYr5DwslQs2pqKVkMDWXk7F0rwnlMqXkxJABSTZTiw46EOcc05YlzkAogPGjV9yVC5KVa84kqrvmWoQiSlZeqDXIt+bZAFQKOk2rBVpCFb4eUdHtTCuFcy2neuRe69FTafG+uZaykluFyVTNDaHIOOT6UqHlVGs5FyIAYsnZOupu4LDsykjQegOcDzsEqpkbgVBzxVHYMWQUsxzonIbFMddjEqAAAFvG4Cvb45op7N2cyATdO67AHLnDMOcIAA)
First let's create an entry point for the application. Create a file `index.html`:
```markup
@ -136,6 +138,7 @@ By default, Mithril views are described using [hyperscript](hyperscript.md). Hyp
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
// src/views/UserList.js
var m = require("mithril")
var User = require("../models/User")
@ -539,6 +542,7 @@ Currently, we're only able to navigate back to the user list via the browser bac
Let's create a file `src/views/Layout.js`:
```javascript
// src/views/Layout.js
var m = require("mithril")
module.exports = {

View file

@ -9,10 +9,10 @@
- [Stream.scanMerge](#streamscanmerge)
- [Stream.HALT](#streamhalt)
- [Stream["fantasy-land/of"]](#streamfantasy-landof)
- [Instance members](#static-members)
- [Instance members](#instance-members)
- [stream.map](#streammap)
- [stream.end](#streamend)
- [stream["fantasy-land/of"]](#streamfantasy-landof)
- [stream["fantasy-land/of"]](#streamfantasy-landof-1)
- [stream["fantasy-land/map"]](#streamfantasy-landmap)
- [stream["fantasy-land/ap"]](#streamfantasy-landap)
- [Basic usage](#basic-usage)
@ -159,7 +159,7 @@ A special value that can be returned to stream callbacks to halt execution of do
This method is functionally identical to `stream`. It exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section.
`stream = stream["fantasy-land/of"](value)`
`stream = Stream["fantasy-land/of"](value)`
Argument | Type | Required | Description
----------- | -------------------- | -------- | ---
@ -212,7 +212,7 @@ Creates a dependent stream whose value is set to the result of the callback func
This method exists to conform to [Fantasy Land's Applicative specification](https://github.com/fantasyland/fantasy-land). For more information, see the [What is Fantasy Land](#what-is-fantasy-land) section.
`dependentStream = stream()["fantasy-land/of"](callback)`
`dependentStream = stream()["fantasy-land/map"](callback)`
Argument | Type | Required | Description
------------ | -------------------- | -------- | ---
@ -384,7 +384,7 @@ var added = stream.combine(function(a, b) {
console.log(added()) // logs 12
```
A stream can depend on any number of streams and it's guaranteed to update atomically. For example, if a stream A has two dependent streams B and C, and a fourth stream D is dependent on both B and C, the stream D will only update once if the value of A changes. This guarantees that the callback for stream D is never called with unstable values such as when B has a new value but C has the old value. Atomicity also bring the performance benefits of not recomputing downstreams unnecessarily.
A stream can depend on any number of streams and it's guaranteed to update atomically. For example, if a stream A has two dependent streams B and C, and a fourth stream D is dependent on both B and C, the stream D will only update once if the value of A changes. This guarantees that the callback for stream D is never called with unstable values such as when B has a new value but C has the old value. Atomicity also brings the performance benefits of not recomputing downstreams unnecessarily.
You can prevent dependent streams from being updated by returning the special value `stream.HALT`

View file

@ -37,7 +37,7 @@ h2 a:visited,h3 a:visited,h4 a:visited,h5 a:visited {color:#000;text-decoration:
h2::before,h3::before,h4::before,h5::before {content:"#";position:absolute;left:-20px;visibility:hidden;}
h2:hover::before,h3:hover::before,h4:hover::before,h5:hover::before {visibility:visible;}
#signature + p code {padding:3px 10px;}
h1 + ul {margin:40px 0 0 -270px;padding:0;position:absolute;width:250px;}
h1 + ul {margin:40px 0 0 -270px;padding:0;position:absolute;width:250px;z-index:1;}
h1 + ul + hr {display:none;}
h1 + ul li {list-style:none;margin:0;padding:0;}
h1 + ul li:last-child {border-bottom:0;}

3
docs/support.md Normal file
View file

@ -0,0 +1,3 @@
## Getting Help
Mithril has an active & welcoming community on [Gitter](https://gitter.im/mithriljs/mithril.js), or feel free to ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/mithril.js) using the `mithril.js` tag.

View file

@ -58,7 +58,7 @@ Generally speaking, there are two ways to write tests: upfront and after the fac
Writing tests upfront requires specifications to be frozen. Upfront tests are a great way of codifying the rules that a yet-to-be-implemented API must obey. However, writing tests upfront may not be a suitable strategy if you don't have a reasonable idea of what your project will look like, if the scope of the API is not well known or if it's likely to change (e.g. based on previous history at the company).
Writing tests after the fact is a way to document the behavior of a system and avoid regressions. They are useful to ensure that obscure corner cases are not inadvertedly broken and that previously fixed bugs do not get re-introduced by unrelated changes.
Writing tests after the fact is a way to document the behavior of a system and avoid regressions. They are useful to ensure that obscure corner cases are not inadvertently broken and that previously fixed bugs do not get re-introduced by unrelated changes.
---
@ -74,7 +74,9 @@ var m = require("mithril")
module.exports = {
view: function() {
return m("div", "Hello world")
return m("div",
m("p", "Hello World")
)
}
}
```
@ -90,7 +92,7 @@ o.spec("MyComponent", function() {
o(vnode.tag).equals("div")
o(vnode.children.length).equals(1)
o(vnode.children[0].tag).equals("#")
o(vnode.children[0].tag).equals("p")
o(vnode.children[0].children).equals("Hello world")
})
})

View file

@ -11,7 +11,7 @@
### Description
Turns an HTML string into unescaped HTML. **Do not use `m.trust` on unsanitized user input.**
Turns an HTML or SVG string into unescaped HTML or SVG. **Do not use `m.trust` on unsanitized user input.**
Always try to use an [alternative method](#avoid-trusting-html) first, before considering using `m.trust`.
@ -23,7 +23,7 @@ Always try to use an [alternative method](#avoid-trusting-html) first, before co
Argument | Type | Required | Description
----------- | -------------------- | -------- | ---
`html` | `String` | Yes | A string containing HTML text
`html` | `String` | Yes | A string containing HTML or SVG text
**returns** | `Vnode` | | A trusted HTML [vnode](vnodes.md) that represents the input string
[How to read signatures](signatures.md)

View file

@ -21,11 +21,11 @@ It may seem wasteful to recreate vnodes so frequently, but as it turns out, mode
For that reason, Mithril uses a sophisticated and highly optimized virtual DOM diffing algorithm to minimize the amount of DOM updates. Mithril *also* generates carefully crafted vnode data structures that are compiled by Javascript engines for near-native data structure access performance. In addition, Mithril aggressively optimizes the function that creates vnodes as well.
The reason Mithril goes to such great lengths to support a rendering model that recreates the entire virtual DOM tree on every render is to provide [retained mode rendering](https://en.wikipedia.org/wiki/Retained_mode), a style of rendering that makes it drastically easier to manage UI complexity.
The reason Mithril goes to such great lengths to support a rendering model that recreates the entire virtual DOM tree on every render is to provide a declarative [immediate mode](https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)) API, a style of rendering that makes it drastically easier to manage UI complexity.
To illustrate why retained mode is so important, consider the DOM API and HTML. The DOM API is an [immediate mode](https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)) rendering system and requires writing out exact instructions to assemble a DOM tree procedurally. The imperative nature of the DOM API means you have many opportunities to micro-optimize your code, but it also means that you have more chances of introducing bugs and more chances to make code harder to understand.
To illustrate why immediate mode is so important, consider the DOM API and HTML. The DOM API is an imperative [retained mode](https://en.wikipedia.org/wiki/Retained_mode) API and requires 1. writing out exact instructions to assemble a DOM tree procedurally, and 2. writing out other instructions to update that tree. The imperative nature of the DOM API means you have many opportunities to micro-optimize your code, but it also means that you have more chances of introducing bugs and more chances to make code harder to understand.
In contrast, HTML is a retained mode rendering system. With HTML, you can write a DOM tree in a far more natural and readable way, without worrying about forgetting to append a child to a parent, running into stack overflows when rendering extremely deep trees, etc.
In contrast, HTML is closer to an immediate mode rendering system. With HTML, you can write a DOM tree in a far more natural and readable way, without worrying about forgetting to append a child to a parent, running into stack overflows when rendering extremely deep trees, etc.
Virtual DOM goes one step further than HTML by allowing you to write *dynamic* DOM trees without having to manually write multiple sets of DOM API calls to efficiently synchronize the UI to arbitrary data changes.
@ -74,7 +74,6 @@ Property | Type | Description
`dom` | `Element?` | Points to the element that corresponds to the vnode. This property is `undefined` in the `oninit` lifecycle method. In fragments and trusted HTML vnodes, `dom` points to the first element in the range.
`domSize` | `Number?` | This is only set in fragment and trusted HTML vnodes, and it's `undefined` in all other vnode types. It defines the number of DOM elements that the vnode represents (starting from the element referenced by the `dom` property).
`state` | `Object?` | An object that is persisted between redraws. It is provided by the core engine when needed. In POJO component vnodes, the `state` inherits prototypically from the component object/class. In class component vnodes it is an instance of the class. In closure components it is the object returned by the closure.
`_state` | `Object?` | For components, a reference to the original `vnode.state` object, used to lookup the `view` and hooks. This property is only used internally by Mithril, do not use or modify it.
`events` | `Object?` | An object that is persisted between redraws and that stores event handlers so that they can be removed using the DOM API. The `events` property is `undefined` if there are no event handlers defined. This property is only used internally by Mithril, do not use or modify it.
`instance` | `Object?` | For components, a storage location for the value returned by the `view`. This property is only used internally by Mithril, do not use or modify it.
`skip` | `Boolean` | This property is only used internally by Mithril when diffing keyed lists, do not use or modify it.
@ -89,7 +88,7 @@ The `tag` property of a vnode determines its type. There are five vnode types:
Vnode type | Example | Description
------------ | ------------------------------ | ---
Element | `{tag: "div"}` | Represents a DOM element.
Fragment | `{tag: "[", children: []}` | Represents a list of DOM elements whose parent DOM element may also contain other elements that are not in the fragment. When using the [`m()`](hyperscript.md) helper function, fragment vnodes can only be created by nesting arrays into the `children` parameter of `m()`. `m("[")` does not create a valid vnode.
Fragment | `{tag: "[", children: []}` | Represents a list of DOM elements whose parent DOM element may also contain other elements that are not in the fragment. When using the [`m()`](hyperscript.md) helper function, fragment vnodes can only be created by nesting arrays into the `children` parameter of `m()`. `m("[")` does not create a valid vnode.
Text | `{tag: "#", children: ""}` | Represents a DOM text node.
Trusted HTML | `{tag: "<", children: "<br>"}` | Represents a list of DOM elements from an HTML string.
Component | `{tag: ExampleComponent}` | If `tag` is a Javascript object with a `view` method, the vnode represents the DOM generated by rendering the component.