mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
339 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 14ceb382ef | |||
| 9846b2e997 | |||
| cfc2fb2ba2 | |||
| d57017b6ed | |||
| 5bf7a5c671 | |||
| 9b589af75a | |||
| 471fd49063 | |||
| 4fc3423682 | |||
| ffb3263c79 | |||
| e1acf66143 | |||
| 2a40907e35 | |||
| 1c0dd79955 | |||
| 9fad164c79 | |||
| 53a8841914 | |||
| 19f0863aa3 | |||
| 28f7b44f9e | |||
| fe46a6ccee | |||
| 3c23a7b246 | |||
| c52799de2c | |||
| 4edb90f44b | |||
| 0c1a7aabae | |||
| cfdce29ce7 | |||
| b344d73e07 | |||
| 4cd08d25c8 | |||
| f9861040c8 | |||
| 40d8090232 | |||
| 55be6437f1 | |||
| 6ff4dd74bf | |||
| 3628b49c37 | |||
| f289cb17ec | |||
| e6a3ede4a6 | |||
| 10cfe0b740 | |||
| a3d563ebb4 | |||
| 3b1247d476 | |||
| beb6c2bc82 | |||
| f0cd6f61cd | |||
| c950b385a0 | |||
| c172b31481 | |||
| 9b3a97e732 | |||
| 670c98916c | |||
| c59abef374 | |||
| bb4c2506c0 | |||
| 9843d16585 | |||
| 34e463ad0a | |||
| 2294c1967f | |||
| 4b53e48e91 | |||
| 70a70161e7 | |||
| e690991a6a | |||
| a621a14028 | |||
| 9754cc7521 | |||
| aa268937a7 | |||
| 3db6f0a643 | |||
| 635a7fc72c | |||
| 6cd5ec10f0 | |||
| 0a276fbf1d | |||
| d593131cc1 | |||
| 3c3dcb44a9 | |||
| 6ecd1d6ea2 | |||
| 1a931a2a08 | |||
| bf705fcd99 | |||
| bb46346767 | |||
| cd0762b436 | |||
| ca920a0091 | |||
| e5b1ba24d8 | |||
| eaf912bed7 | |||
| fd0fb5be00 | |||
| f9f730ab7b | |||
| b30b72fc36 | |||
| ab08e84bff | |||
| cd9cac1246 | |||
| f6369f9750 | |||
| f18c73e59f | |||
| 93d0a7dd46 | |||
| b1d022b583 | |||
| 5382e824b1 | |||
| 15a3f59744 | |||
| 4a90ec7ff0 | |||
| 9f9b6b174e | |||
| 545ceefc3d | |||
| 591508e769 | |||
| d9cbd23cd9 | |||
| f4cd111cc8 | |||
| ea015af741 | |||
| bfc7c81c0d | |||
| e24ff8f8aa | |||
| 9f1e64d399 | |||
| 8e1aa71436 | |||
| be2fc965b1 | |||
| 7245ccf8f9 | |||
| 1c8e1af86d | |||
| 60a6cca960 | |||
| ad55b42ccb | |||
| 50c0a4b126 | |||
| 2ca42e7470 | |||
| d381e85d94 | |||
| af7520d869 | |||
| 0095bfa61f | |||
| 1b12cf9b91 | |||
| dbfc7e4acd | |||
| e838e879c0 | |||
| ee63f6bb0f | |||
| 16bbb8bc9f | |||
| 4a5db0c283 | |||
| cc50a2e3bb | |||
| 1e2b204fdd | |||
| 4a889b7b6b | |||
| 34695883c2 | |||
| 3d2e2a1873 | |||
| af6aca83a2 | |||
| 8c8ffb6a6b | |||
| 63a8fcd7e2 | |||
| e6a5934162 | |||
| 5524c2e323 | |||
| 35c1de26b8 | |||
| d1cf6b1b8d | |||
| bfa2c681cd | |||
| 609c108607 | |||
| a56939f13a | |||
| 5ff501f8b8 | |||
| 60917bb102 | |||
| b201ef8162 | |||
| 9cacc78ad7 | |||
| 0d933b8570 | |||
| 72f6daa695 | |||
| 567d78a9ac | |||
| f013c57050 | |||
| b9fae87273 | |||
| 1f0457f69b | |||
| c481a73a76 | |||
| e64e415b3b | |||
| aa406b53e2 | |||
| 57027bd0fa | |||
| 671c662fee | |||
| 0ae70b1d63 | |||
| 2701a7d861 | |||
| 3ebe985c3c | |||
| 1c0d4b5832 | |||
| 2840794fa2 | |||
| 710f42d4e4 | |||
| 45a2b0122d | |||
| 4c41f62364 | |||
| c2ab9774fb | |||
| 22e48e3be0 | |||
| 1ff3c32fe4 | |||
| 9a3e1ed99e | |||
| 438e2fbc2e | |||
| b3db085745 | |||
| b948c59c6d | |||
| 6426fe98f9 | |||
| 4dd9de349e | |||
| e1bcea77b5 | |||
| 2a19aeb6a3 | |||
| b53a34b7d1 | |||
| f881640d3d | |||
| 54c3dd76e4 | |||
| 7b887447da | |||
| 438b21df3f | |||
| d1094f647a | |||
| 49baf0de6e | |||
| b14d069ee7 | |||
| e14a4fe338 | |||
| 1f9ec46236 | |||
| 1464a3631b | |||
| 7d3c374b78 | |||
| 1dd257f33c | |||
| 1206afe6be | |||
| 5842ed51b0 | |||
| d22219f084 | |||
| 0be1a54e03 | |||
| 32921ecc20 | |||
| 1c290c1172 | |||
| 2f9d7ea58f | |||
| fe23e76341 | |||
| 73023d4869 | |||
| ff51443b8e | |||
| f8e07f6d30 | |||
| 00da778753 | |||
| 187eb922c0 | |||
| 466c12a0e6 | |||
| 8dc3ec94bf | |||
| a554436d03 | |||
| 34b5049dee | |||
| 0eccfd08fe | |||
| 98b063fd70 | |||
| e9ba94ae55 | |||
| 4d72a4f240 | |||
| a08deb895d | |||
| 60cea14b01 | |||
| f60904b740 | |||
| 376f801541 | |||
| 26f14180e2 | |||
| bced9f3d04 | |||
| 94208d9cbb | |||
| 681983142d | |||
| a525b42537 | |||
| a4cc085b6d | |||
| 837dacf1cb | |||
| 7cdd1aa9a1 | |||
| 24c569e6d5 | |||
| 050694414c | |||
| 639908366a | |||
| 59f401303a | |||
| 649e20b956 | |||
| c2280ff1bb | |||
| 8a32d823cd | |||
| 13b31458da | |||
| 92b3ab32e2 | |||
| 4ca0a157e3 | |||
| 1dec8df715 | |||
| 8f29cfc996 | |||
| da275e74fd | |||
| 3d9f4e028c | |||
| 13577997bc | |||
| 671965026d | |||
| bc7fe9023d | |||
| c2c7997df3 | |||
| a1d7e6c987 | |||
| a1e982aba5 | |||
| 2ce027a0a6 | |||
| 61f21511a5 | |||
| 5682577870 | |||
| 25b633cc63 | |||
| f16b267931 | |||
| 30ec952588 | |||
| 46ba77d0cc | |||
| 042e376c2b | |||
| b9f1af2ad5 | |||
| 7df0fdcc0a | |||
| 73d743a1c3 | |||
| 8758dfcedf | |||
| 0a10bbc023 | |||
| 9c1d369e94 | |||
| 9556696fa8 | |||
| 04eb720619 | |||
| 8e098e8ed6 | |||
| c836cead58 | |||
| 361ecbe90b | |||
| ae8d7d3be2 | |||
| ed4f92211c | |||
| f8804d6501 | |||
| de7c680387 | |||
| 6dd7391cdc | |||
| dfa7d5932d | |||
| 53911de00a | |||
| 1760d0d336 | |||
| 0aba9748c9 | |||
| 8ee0973dab | |||
| e04c5b1c6b | |||
| f52a15d7f6 | |||
| 147f6fced7 | |||
| d928927da8 | |||
| 29cc94d567 | |||
| 7f33f9b68e | |||
| 80ffa37773 | |||
| 2f70a7a352 | |||
| f7f8c34e1c | |||
| edc7d2b635 | |||
| 7f0b236747 | |||
| b7860a95b0 | |||
| f7495dc897 | |||
| ba506be58d | |||
| 91896942dd | |||
| dfab8c7333 | |||
| bd29e4f761 | |||
| b9591cfecd | |||
| 51320204f9 | |||
| ec0bafaa8e | |||
| eb508b7660 | |||
| 7c8fc323e1 | |||
| ff2393f5df | |||
| ab2a98426e | |||
| 84b3cc42cf | |||
| d28b854e8d | |||
| 6c8c69affa | |||
| faec7d4ad9 | |||
| 5b9abb6785 | |||
| eb4ca0a8d5 | |||
| 641adc6e5c | |||
| 10ab97e3c6 | |||
| e060130655 | |||
| 4e982f5460 | |||
| d3197e9865 | |||
| 0da44033ac | |||
| 6350d9598d | |||
| 9df6c0aede | |||
| 896efca43f | |||
| efe82b6cd0 | |||
| eb910193d7 | |||
| 40e486a9eb | |||
| e56580efb2 | |||
| 46e05f1c96 | |||
| 4a748d2ea4 | |||
| 8f388e712e | |||
| 0a5b6aa0ec | |||
| fc1ea10243 | |||
| d52177560b | |||
| 1701d5aa86 | |||
| b08e876136 | |||
| 005b727328 | |||
| b44f274e37 | |||
| b6bd0f92a7 | |||
| 78108e8d2c | |||
| c405dadc1b | |||
| 2bd0719b9a | |||
| 9544034e6f | |||
| cf47f8459a | |||
| 8f7d06a5bd | |||
| d1708fc252 | |||
| f23a26426d | |||
| 40613e0a76 | |||
| aa11229641 | |||
| 754272b436 | |||
| d509373228 | |||
| 379cd2a90f | |||
| 4c2115d365 | |||
| 94b48cb389 | |||
| 3ecb772a56 | |||
| b14d264718 | |||
| 1a778922af | |||
| 79b97c6d24 | |||
| a8e919f382 | |||
| 20b33f50fa | |||
| 9170882010 | |||
| ae36cca2ef | |||
| f5ce05c81e | |||
| 2fbf4f2c22 | |||
| 8a4fd5015a | |||
| de04ed2339 | |||
| ae263730d9 | |||
| 85418043f4 | |||
| 4fb2733321 | |||
| d9d109c9a2 | |||
| 4ee39282ca | |||
| 3b3fd8a6c9 | |||
| 29111a5c10 | |||
| 4b30d0b412 | |||
| d07f396578 | |||
| 2c218c4463 | |||
| af83a8249e |
+10
-1
@@ -1,5 +1,6 @@
|
||||
/node_modules
|
||||
/dist
|
||||
|
||||
npm-debug.log
|
||||
|
||||
# misc
|
||||
@@ -14,4 +15,12 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
package-lock.json
|
||||
.vscode
|
||||
|
||||
#ide's
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
node_modules
|
||||
|
||||
# Extras temp file
|
||||
/tools/owl.js
|
||||
@@ -1,12 +1,9 @@
|
||||
|
||||
For copyright information, please see the COPYRIGHT file.
|
||||
|
||||
Odoo is published under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3
|
||||
OWL is published under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3
|
||||
(LGPLv3), as included below. Since the LGPL is a set of additional
|
||||
permissions on top of the GPL, the text of the GPL is included at the
|
||||
bottom as well.
|
||||
|
||||
Some external libraries and contributions bundled with Odoo may be published
|
||||
Some external libraries and contributions bundled with OWL may be published
|
||||
under other GPL-compatible licenses. For these, please refer to the relevant
|
||||
source files and/or license files, in the source code tree.
|
||||
|
||||
|
||||
@@ -1,124 +1,111 @@
|
||||
<h1 align="center">🦉 Odoo Web Lab 🦉</h1>
|
||||
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">Odoo Web Library</a> 🦉</h1>
|
||||
|
||||
_A web framework for structured, dynamic and maintainable applications_
|
||||
|
||||
## Project Overview
|
||||
|
||||
Odoo Web Lab (OWL) is a project to collect some useful, reusable, (hopefully)
|
||||
well designed building blocks for building web applications. However, since this is the basis for the Odoo web client, we will not hesitate
|
||||
to design the code here to better match the Odoo architecture/design principles.
|
||||
The Odoo Web Library (OWL) is a small (~16kb gzipped) UI framework intended to be the basis for
|
||||
the [Odoo](https://www.odoo.com/) Web Client, and hopefully many other Odoo
|
||||
related projects. OWL's main features are:
|
||||
|
||||
The most important element of this repository is certainly the component system.
|
||||
It is designed to be:
|
||||
- a _declarative component system_, (template based, with asynchronous rendering and a virtual dom)
|
||||
- a store implementation (for state management)
|
||||
- a small frontend router
|
||||
|
||||
1. **declarative:** the user interface should be described in term of the state
|
||||
of the application, not as a sequence of imperative steps.
|
||||
**Try it online!** An online playground is available at [https://odoo.github.io/owl/playground](https://odoo.github.io/owl/playground) to let you experiment with the OWL framework.
|
||||
|
||||
2. **composable:** each widget can seamlessly be created in a parent widget by
|
||||
a simple directive in its template.
|
||||
## Example
|
||||
|
||||
3. **asynchronous rendering:** the framework will transparently wait for each
|
||||
subwidgets to be ready before applying the rendering. It uses native promises
|
||||
under the hood.
|
||||
Here is a short example to illustrate interactive components:
|
||||
|
||||
4. **uses QWeb as a template system:** the templates are described in XML
|
||||
and follow the QWeb specification. This is a requirement for Odoo.
|
||||
```javascript
|
||||
import { Component, QWeb } from 'owl'
|
||||
import { xml } from 'owl/tags'
|
||||
|
||||
5. **with an imperative escape hatch:** if necessary, sub widgets can easily be
|
||||
manually created/destroyed.
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
Note: the code is written in typescript. This does not mean that the main web
|
||||
client will ever be converted to typescript (even though I would really like it).
|
||||
state = { value: 0 };
|
||||
|
||||
## Try it online
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
|
||||
You can experiment with the OWL project online: [https://odoo.github.io/owl/](https://odoo.github.io/owl/)
|
||||
class App extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span>Hello Owl</span>
|
||||
<Counter />
|
||||
</div>`;
|
||||
|
||||
## Installing/Building
|
||||
static components = { Counter };
|
||||
|
||||
Some npm scripts are available:
|
||||
}
|
||||
|
||||
| Command | Description |
|
||||
| ------------------ | --------------------------------------------------------- |
|
||||
| npm install | install every dependency required for this project |
|
||||
| npm run build | build a bundle of _owl_ in the _/dist/_ folder |
|
||||
| npm run build:es5 | build a bundle of _owl_ in the _/dist/_ folder (ES5 code) |
|
||||
| npm run minify | minify the prebuilt owl.js file |
|
||||
| npm run test | run all tests |
|
||||
| npm run test:watch | run all tests, and keep a watcher |
|
||||
const app = new App({ qweb: new QWeb() });
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
More interesting examples can be found on the
|
||||
[playground](https://odoo.github.io/owl/playground) application.
|
||||
|
||||
## OWL's Design Principles
|
||||
|
||||
OWL is designed to be used in highly dynamic applications where changing
|
||||
requirements are common and code needs to be maintained by large teams.
|
||||
|
||||
- **XML based**: templates are based on the XML format, which allows interesting
|
||||
applications. For example, they could be stored in a database and modified
|
||||
dynamically with `xpaths`.
|
||||
- **templates compilation in the browser**: this may not be a good fit for all
|
||||
applications, but if you need to generate dynamically user interfaces in the
|
||||
browser, this is very powerful. For example, a generic form view component
|
||||
could generate a specific form user interface for each various models, from a XML view.
|
||||
- **no toolchain required**: this is extremely useful for some applications, if,
|
||||
for various reasons (security/deployment/dynamic modules/specific assets tools),
|
||||
it is not ok to use standard web tools based on `npm`.
|
||||
|
||||
Owl is not designed to be fast nor small (even though it is quite good on those
|
||||
two topics). It is a no nonsense framework to build applications. There is only
|
||||
one way to define components (with classes).
|
||||
|
||||
If you are interested in a comparison with React or Vue, you will
|
||||
find some more information [here](doc/comparison.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
The complete documentation can be found [here](doc/readme.md). The most important sections are:
|
||||
|
||||
- [Quick Start](doc/quick_start.md)
|
||||
- [Tutorial](doc/tutorial.md)
|
||||
- [Component](doc/component.md)
|
||||
- [QWeb](doc/qweb.md)
|
||||
|
||||
# Examples
|
||||
Found an issue in the documentation? A broken link? Some outdated information?
|
||||
Submit a PR!
|
||||
|
||||
Here is a minimal Hello World example:
|
||||
## Installing/Building
|
||||
|
||||
```javascript
|
||||
class HelloWorld extends owl.core.Component {
|
||||
inlineTemplate = `<div>Hello <t t-esc="props.name"/></div>`;
|
||||
}
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
const env = {
|
||||
qweb: new owl.core.QWeb()
|
||||
};
|
||||
- [owl-0.21.0.js](https://github.com/odoo/owl/releases/download/v0.21.0/owl.js)
|
||||
- [owl-0.21.0.min.js](https://github.com/odoo/owl/releases/download/v0.21.0/owl.min.js)
|
||||
|
||||
const hello = new HelloWorld(env, { name: "World" });
|
||||
hello.mount(document.body);
|
||||
```
|
||||
Some npm scripts are available:
|
||||
|
||||
The next example show how interactive widgets can be created and how widget
|
||||
composition works:
|
||||
|
||||
```javascript
|
||||
class Counter extends owl.core.Component {
|
||||
inlineTemplate = `
|
||||
<div>
|
||||
<button t-on-click="increment(-1)">-</button>
|
||||
<span style="font-weight:bold">Value: <t t-esc="state.value"/></span>
|
||||
<button t-on-click="increment(1)">+</button>
|
||||
</div>`;
|
||||
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = {
|
||||
value: props.initialState || 0
|
||||
};
|
||||
}
|
||||
|
||||
increment(delta) {
|
||||
this.updateState({ value: this.state.value + delta });
|
||||
}
|
||||
}
|
||||
|
||||
class App extends owl.core.Component {
|
||||
inlineTemplate = `
|
||||
<div>
|
||||
<t t-widget="Counter" t-props="{initialState: 1}"/>
|
||||
<t t-widget="Counter" t-props="{initialState: 42}"/>
|
||||
</div>`;
|
||||
|
||||
widgets = { Counter };
|
||||
}
|
||||
|
||||
const env = {
|
||||
qweb: new owl.core.QWeb()
|
||||
};
|
||||
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
More interesting examples on how to work with this web framework can be found in the _examples/_ folder:
|
||||
|
||||
- [Todo Application](examples/readme.md#todo-app)
|
||||
- [Web Client](examples/readme.md#web-client-example)
|
||||
- [Benchmarks](examples/readme.md#benchmarks)
|
||||
| Command | Description |
|
||||
| --------------------- | ---------------------------------------------------------------------------- |
|
||||
| `npm install` | install every dependency required for this project |
|
||||
| `npm run build` | build a bundle of _owl_ in the _/dist/_ folder |
|
||||
| `npm run minify` | minify the prebuilt owl.js file |
|
||||
| `npm run test` | run all tests |
|
||||
| `npm run test:watch` | run all tests, and keep a watcher |
|
||||
| `npm run tools` | build tools applications, start a static server (see [here](doc/tooling.md)) |
|
||||
| `npm run tools:watch` | same as `tools`, but with a watcher to rebuild owl |
|
||||
|
||||
## License
|
||||
|
||||
OWL is [GPL licensed](./LICENSE).
|
||||
OWL is [LGPL licensed](./LICENSE).
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# 🦉 Animations 🦉
|
||||
|
||||
Animation is a complex topic. There are many different use cases, and many
|
||||
solutions and technologies. Owl only supports some basic use cases.
|
||||
|
||||
## Simple CSS effects
|
||||
|
||||
Sometimes, using pure CSS is enough. For these use cases, Owl is not really
|
||||
necessary: it just needs to render a DOM element with a specific class. For
|
||||
example:
|
||||
|
||||
```xml
|
||||
<a class="btn flash" t-on-click="doSomething">Click</a>
|
||||
```
|
||||
|
||||
with the following CSS:
|
||||
|
||||
```css
|
||||
btn {
|
||||
background-color: gray;
|
||||
}
|
||||
|
||||
.flash {
|
||||
transition: background 0.5s;
|
||||
}
|
||||
|
||||
.flash:active {
|
||||
background-color: #41454a;
|
||||
transition: background 0s;
|
||||
}
|
||||
```
|
||||
|
||||
will produce a nice flash effect whenever the user click (or activate with the
|
||||
keyboard) the button.
|
||||
|
||||
## CSS Transitions
|
||||
|
||||
A more complex situation occurs when we want to transition an element in or out
|
||||
of the page. For example, we may want a fade-in and fade-out effect.
|
||||
|
||||
The `t-transition` directive is here to help us. It works on html elements and
|
||||
on components, by adding and removing some css classes.
|
||||
|
||||
To perform useful transition effects, whenever an element appears or disappears,
|
||||
it is necessary to add/remove some css style or class at some precise moment in
|
||||
the lifetime of a node. Since this is not easy to do by hand, Owl `t-transition`
|
||||
directive is there to help.
|
||||
|
||||
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
||||
will happen:
|
||||
|
||||
At node insertion:
|
||||
|
||||
- the css classes `name-enter` and `name-enter-active` will be added directly
|
||||
when the node is inserted into the DOM,
|
||||
- on the next animation frame: the css class `name-enter` will be removed and the
|
||||
class `name-enter-to` will be added (so they can be used to trigger css
|
||||
transition effects),
|
||||
- the css class `name-enter-active` will be removed whenever a css transition
|
||||
ends.
|
||||
|
||||
At node destruction:
|
||||
|
||||
- the css classes `name-leave` and `name-leave-active` will be added before the
|
||||
node is removed to the DOM,
|
||||
- the css class `name-leave` will be removed on the next animation frame (so it
|
||||
can be used to trigger css transition effects),
|
||||
- the css class `name-leave-active` will be removed whenever a css transition
|
||||
ends. Only then will the element be removed from the DOM.
|
||||
|
||||
For example, a simple fade in/out effect can be done with this:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-if="state.flag" class="square" t-transition="fade">Hello</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
```css
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.5s;
|
||||
}
|
||||
.fade-enter,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
```
|
||||
|
||||
The `t-transition` directive can be applied on a node element or on a component.
|
||||
|
||||
Notes:
|
||||
|
||||
- more information on animations are available [here](animations.md).
|
||||
- Owl does not support more than one transition on a single node, so the
|
||||
`t-transition` expression must be a single value (i.e. no space allowed)
|
||||
@@ -0,0 +1,236 @@
|
||||
# Comparison with Vue/React
|
||||
|
||||
OWL, React and Vue have the same main feature: they allow developers to build
|
||||
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
||||
|
||||
In this page, we try to highlight some of these differences. Obviously, some
|
||||
effort was done to be fair. However, if you disagree with some of the points
|
||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||
|
||||
## Content
|
||||
|
||||
- [Size](#size)
|
||||
- [Class Based](#class-based)
|
||||
- [Tooling/Build Step](#toolingbuild-step)
|
||||
- [Templating](#templating)
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
- [Reactiveness](#reactiveness)
|
||||
- [State Management](#state-management)
|
||||
|
||||
## Size
|
||||
|
||||
OWL is intended to be small and to work at a slightly lower level of abstraction
|
||||
than React and Vue. Also, jQuery is not the same kind of framework, but it is interesting to compare.
|
||||
|
||||
| Framework | Size (minified, gzipped) |
|
||||
| ------------------------ | ------------------------ |
|
||||
| OWL | 16kb |
|
||||
| Vue + VueX | 30kb |
|
||||
| React + ReactDOM + Redux | 40kb |
|
||||
| jQuery | 30kb |
|
||||
|
||||
## Class Based
|
||||
|
||||
Both React and Vue moved away from defining components with classes. They prefer
|
||||
a more functional approach, in particular, with the new `hooks` mechanisms.
|
||||
|
||||
This has some advantages and disadvantages. But the end result is that React
|
||||
and Vue both offers multiple different ways of defining new components. In
|
||||
contrast, Owl has only one mechanism: class-based components. We believe that Owl
|
||||
components are fast enough for all our usecases, and making it as simple as
|
||||
possible for developers is more valuable (for us).
|
||||
|
||||
## Tooling/Build step
|
||||
|
||||
OWL is designed to be easy to use in a standalone way. For various reasons,
|
||||
Odoo does not want to rely on standard web tools (such as webpack), and OWL can
|
||||
be used by simply adding a script tag to a page.
|
||||
|
||||
```html
|
||||
<script src="owl.min.js" />
|
||||
```
|
||||
|
||||
In comparison, React encourages using JSX,
|
||||
which necessitate a build step, and most Vue applications uses single file
|
||||
components, which also necessitate a build step.
|
||||
|
||||
On the flipside, external tooling may make it harder to use in some case, but it
|
||||
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
||||
|
||||
## Templating
|
||||
|
||||
OWL uses its own QWeb engine, which compiles templates on the
|
||||
frontend, as they are needed. This is extremely convenient for our use case, in
|
||||
particular because templates are described in XML files, and can be modified by
|
||||
XPaths. Since Odoo is at its heart a modular application, this is an important
|
||||
feature for us.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<button t-on-click="increment">Click Me! [<t t-esc="state.value"/>]</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
Vue is actually kind of similar. Its template language is kind of close to QWeb,
|
||||
with the `v` replaced by the `t`. However, it is also more fully featured. For
|
||||
example, Vue templates have slots, or event modifiers. A large difference is that
|
||||
most Vue applications will need to be built ahead of time, to compile the templates
|
||||
into javascript functions. Note that Vue has a separate build which includes the
|
||||
template compiler.
|
||||
|
||||
In contrast, most React applications do not use a templating language, but write
|
||||
some JSX code, which is precompiled into plain JavaScript by a build step.
|
||||
|
||||
```jsx
|
||||
class Clock extends React.Component {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Hello, world!</h1>
|
||||
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This has the advantage of having the full power of Javascript, but is less
|
||||
structured than a template language. Note that the tooling is quite impressive:
|
||||
there is a syntax highlighter for jsx here on github!
|
||||
|
||||
## Asynchronous Rendering
|
||||
|
||||
This is actually a big difference between OWL and React/Vue: components in OWL
|
||||
are totally asynchronous. They have two asynchronous hooks in their lifecycle:
|
||||
|
||||
- `willStart` (before the component starts rendering)
|
||||
- `willUpdateProps` (before new props are set)
|
||||
|
||||
Both these methods can be implemented and return a promise. The rendering will
|
||||
then wait for these promises to be completed before patching the DOM. This is
|
||||
useful for some use cases: for example, a component may want to fetch an external
|
||||
library (a calendar component may need a specialized calendar rendering library),
|
||||
in its willStart hook.
|
||||
|
||||
```javascript
|
||||
class MyCalendarComponent extends owl.Component {
|
||||
...
|
||||
|
||||
willStart() {
|
||||
return utils.lazyLoad('static/libs/fullcalendar/fullcalendar.js');
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
This may be dangerous (to stop the rendering waiting for the network), but it is
|
||||
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
||||
|
||||
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
||||
more convoluted.
|
||||
|
||||
## Reactiveness
|
||||
|
||||
React has a simple model: whenever the state changes, it is
|
||||
replaced with a new state (via the setState method). Then, the DOM is patched.
|
||||
This is simple, efficient, and a little bit awkward to write.
|
||||
|
||||
Vue is a little bit different: it replace magically the properties in the state
|
||||
by getters/setters. With that, it can notify components whenever the state that
|
||||
they read was changed.
|
||||
|
||||
Owl is closer to vue: it also tracks magically the state properties, but it does
|
||||
only increment an internal counter whenever it changes. Note that it is done
|
||||
with a `Proxy`, which means that it is totally transparent to the developers.
|
||||
Adding new keys is supported. Once any part of the state has been changed, a
|
||||
rendering is scheduled in the next microtask tick (promise queue).
|
||||
|
||||
## State Management
|
||||
|
||||
Managing the state of an application is a tricky issue. Many solutions have
|
||||
been proposed these last few years. It also depends on the kind of application we
|
||||
are talking about. A small application may not need much more than a simple
|
||||
object to contain its state.
|
||||
|
||||
However, there are some common solutions for React and Vue: redux and vuex.
|
||||
Both of them are a centralized store that own the state, and they dictate how
|
||||
the state can be mutated.
|
||||
|
||||
**Redux**
|
||||
|
||||
In Redux, the state is mutated by reducers. Reducers are functions
|
||||
that modify the state by returning a different object:
|
||||
|
||||
```javascript
|
||||
...
|
||||
switch (action.type) {
|
||||
case ADD_TODO: {
|
||||
const { id, content } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
allIds: [...state.allIds, id],
|
||||
byIds: {
|
||||
...state.byIds,
|
||||
[id]: {
|
||||
content,
|
||||
completed: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This is a little bit awkward to write, but this allows the component system to
|
||||
check if a part of the state was changed. This is exactly what is done by the
|
||||
`connect` function: it create a _connected_ component, which is subscribed to
|
||||
the state and triggers a rerender if some part of the state was modified.
|
||||
|
||||
**VueX**
|
||||
|
||||
VueX is based on a different principle: the state is mutated through
|
||||
some special functions (the mutations), which modify the state in place:
|
||||
|
||||
```javascript
|
||||
function ({state}, payload) {
|
||||
const { id, content } = payload;
|
||||
const message = {id, content, completed: false};
|
||||
state.messages.push(message)
|
||||
}
|
||||
```
|
||||
|
||||
This is simpler, but there is a little bit more happening behind the scene:
|
||||
each key from the state is silently replaced by getters and setters, and VueX
|
||||
keeps track of who get data, and retrigger a render when it was changed.
|
||||
|
||||
**Owl**
|
||||
|
||||
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
||||
mutations), and like VueX, it keeps track of the state changes. However, it does
|
||||
not notify a component when the state changes. Instead, components need to connect
|
||||
to the store like in redux, by inheriting the `ConnectedComponent` class.
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter += val;
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: 0
|
||||
};
|
||||
const store = new owl.Store({ state, actions });
|
||||
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
increment() {
|
||||
this.env.store.dispatch("increment");
|
||||
}
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
```
|
||||
+1067
-56
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
# 🦉 Event Bus 🦉
|
||||
|
||||
It is sometimes useful to use a `Bus` to communicate informations between various
|
||||
parts of the code. Owl has a very simple bus class, which manages subscriptions,
|
||||
triggering events, and callbacks.
|
||||
|
||||
```js
|
||||
const bus = new owl.EventBus();
|
||||
|
||||
bus.on("some-event", null, function(...args) {
|
||||
console.log(...args);
|
||||
});
|
||||
|
||||
bus.trigger("some-event", 1, 2, 3);
|
||||
// [1,2,3] will be logged to the console
|
||||
```
|
||||
|
||||
Its API is:
|
||||
|
||||
| Method | Description |
|
||||
| -------------------------------- | --------------------------------- |
|
||||
| `on(eventType, owner, callback)` | add a listener |
|
||||
| `off(eventType, owner)` | remove all listeners for an owner |
|
||||
| `trigger(eventType, ...args)` | trigger an event |
|
||||
| `clear` | remove all subscriptions |
|
||||
|
||||
Note that the [`Store`](store.md) is an example of an `EventBus`.
|
||||
@@ -0,0 +1,50 @@
|
||||
# 🦉 Observer 🦉
|
||||
|
||||
Owl need to be able to react to state changes. For example, whenever the state
|
||||
of a component is changed, we need to rerender it. To help with that, we have
|
||||
an Observer class. Its job is to observe some object state, and react to any
|
||||
change. To do that, it recursively replace all keys of the observed state by
|
||||
getters and setters.
|
||||
|
||||
For example, this code will display `update` in the console:
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
observer.notifyCB = () => console.log("update");
|
||||
observer.observe(obj);
|
||||
|
||||
const obj = { a: { b: 1 } };
|
||||
obj.a.b = 2;
|
||||
```
|
||||
|
||||
## Technical Limitations
|
||||
|
||||
Since the observer uses getters and setters, it is actually unable to react to
|
||||
changes in three situations:
|
||||
|
||||
- adding a key to an object
|
||||
- deleting a key from an object
|
||||
- modifying an array by setting a new value at a given index
|
||||
|
||||
In those situations, we need a way to tell the observer that something happened.
|
||||
This can be done by using the `set` and `delete` (only for objects) static
|
||||
methods of the `Observer`.
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const obj = { a: 1 };
|
||||
observer.observe(obj);
|
||||
obj.b = 2; // won't notify the change
|
||||
owl.Observer.set(obj, "b", 2); // will notify the change
|
||||
|
||||
delete obj.b; // won't notify the change
|
||||
owl.Observer.delete(obj, "b"); // will notify the change
|
||||
```
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const arr = ["a"];
|
||||
observer.observe(arr);
|
||||
arr[0] = "b"; // won't notify the change
|
||||
owl.Observer.set(arr, 0, "b"); // will notify the change
|
||||
```
|
||||
+86
-46
@@ -1,61 +1,101 @@
|
||||
# Quick Start
|
||||
# 🦉 Quick Start 🦉
|
||||
|
||||
## Static Server
|
||||
|
||||
Let us assume that we have a static server running somewhere. We could then
|
||||
simply add an html page with a few extra files.
|
||||
|
||||
### HTML and CSS
|
||||
|
||||
In a file `index.html`:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>My OWL App</title>
|
||||
<link href="app.css" rel="stylesheet" />
|
||||
<script src="owl-X.Y.Z.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="main"></div>
|
||||
<script src="app.js" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
In `app.css`:
|
||||
|
||||
```css
|
||||
button {
|
||||
color: darkred;
|
||||
font-size: 30px;
|
||||
width: 220px;
|
||||
}
|
||||
```
|
||||
|
||||
Also, let's not forget to add a release of OWL (`owl-X.Y.Z.js`)
|
||||
|
||||
### XML
|
||||
|
||||
In `templates.xml`:
|
||||
|
||||
```xml
|
||||
<templates>
|
||||
<button t-name="clickcounter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>
|
||||
</templates>
|
||||
```
|
||||
|
||||
### JS
|
||||
|
||||
To build an application (or a sub-part of an application), we need two things:
|
||||
|
||||
- an environment
|
||||
- a root widget
|
||||
- an environment: it is the global context in which we are working. It needs to
|
||||
contain a QWeb instance (preloaded with templates), and anything else that we
|
||||
need. In practice, it could context some user session information, some
|
||||
configuration keys (for example, isMobile = true/false if we are in mobile mode).
|
||||
|
||||
Here are a few steps that may be useful to get started:
|
||||
- a description of the user interface: there should be a root component, which can
|
||||
have sub components
|
||||
|
||||
Here are a few steps that we may take to get started:
|
||||
|
||||
- get the templates
|
||||
- create a qweb engine, with the templates
|
||||
- create an environment
|
||||
- create an instance of the root widget
|
||||
- mount the root widget to a DOM element
|
||||
- create an instance of the root component
|
||||
- mount the root component to a DOM element
|
||||
|
||||
## Simple example
|
||||
|
||||
In a oversimplified example, here is what it could look like:
|
||||
Let us now add the javascript to make it work, in `app.js`:
|
||||
|
||||
```javascript
|
||||
const templates = await loadTemplates();
|
||||
class ClickCounter extends owl.Component {
|
||||
static template = "clickcounter";
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = { value: 0 };
|
||||
}
|
||||
|
||||
const qweb = new QWeb();
|
||||
qweb.loadTemplates(templates);
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
|
||||
const env = {
|
||||
qweb: qweb
|
||||
};
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const counter = new ClickCounter(env);
|
||||
const target = document.getElementById("main");
|
||||
await counter.mount(target);
|
||||
}
|
||||
|
||||
const root = new RootWidget(env, { initialState: 17 });
|
||||
|
||||
const target = document.getElementById("app");
|
||||
root.mount(target);
|
||||
```
|
||||
|
||||
## Managing state
|
||||
|
||||
The environment is propagated to each subchildren. So, it is convenient to use
|
||||
to give a reference to some global object. This is potentially very useful
|
||||
in a redux-like architecture:
|
||||
|
||||
```javascript
|
||||
...
|
||||
|
||||
const store = new Store();
|
||||
|
||||
const env = {
|
||||
qweb: qweb,
|
||||
store: store,
|
||||
};
|
||||
|
||||
const state = store.getState()
|
||||
const root = new RootWidget(env, state);
|
||||
|
||||
store.on('state_change', nextState => {
|
||||
root.updateProps(nextState);
|
||||
});
|
||||
|
||||
const target = document.getElementById('app');
|
||||
root.mount(target);
|
||||
start();
|
||||
```
|
||||
|
||||
+513
-18
@@ -1,35 +1,530 @@
|
||||
# QWeb
|
||||
# 🦉 QWeb 🦉
|
||||
|
||||
QWeb is a template specification. The QWeb class in this repository is:
|
||||
## Content
|
||||
|
||||
- an implementation of the QWeb specification
|
||||
- which outputs a virtual dom instead of a string
|
||||
- and extended with a few extra directives
|
||||
- [Overview](#overview)
|
||||
- [Directives](#directives)
|
||||
- [QWeb Engine](#qweb-engine)
|
||||
- [Reference](#reference)
|
||||
- [White Spaces](#white-spaces)
|
||||
- [Root Nodes](#root-nodes)
|
||||
- [Expression Evaluation](#expression-evaluation)
|
||||
- [Static html Nodes](#static-html-nodes)
|
||||
- [Outputting Data](#outputting-data)
|
||||
- [Setting Variables](#setting-variables)
|
||||
- [Conditionals](#conditionals)
|
||||
- [Dynamic Attributes](#dynamic-attributes)
|
||||
- [Loops](#loops)
|
||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||
- [Debugging](#debugging)
|
||||
|
||||
## QWeb Specification
|
||||
## Overview
|
||||
|
||||
add here a full description of what QWeb is supposed to be, with some examples
|
||||
[QWeb](https://www.odoo.com/documentation/12.0/reference/qweb.html) is the primary templating engine used by Odoo. It is based on the XML format, and used
|
||||
mostly to generate HTML. In OWL, QWeb templates are compiled into functions that
|
||||
generate a virtual dom representation of the HTML.
|
||||
|
||||
## QWeb Implementation
|
||||
Template directives are specified as XML attributes prefixed with `t-`, for instance `t-if` for conditionals, with elements and other attributes being rendered directly.
|
||||
|
||||
```javascript
|
||||
var qweb = new QWeb();
|
||||
qweb.addTemplate("sometemplate", '<div>hello <t t-esc="name"/></div>');
|
||||
To avoid element rendering, a placeholder element `<t>` is also available, which executes its directive but doesn’t generate any output in and of itself.
|
||||
|
||||
// result is a vnode which represent <div>hello world</div>
|
||||
result = qweb.render("sometemplate", { name: "world" });
|
||||
```xml
|
||||
<div>
|
||||
<span t-if="somecondition">Some string</span>
|
||||
<ul t-else="1">
|
||||
<li t-foreach="messages" t-as="message">
|
||||
<t t-esc="message">
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
```
|
||||
|
||||
## QWeb extensions
|
||||
The QWeb class in the OWL project is an implementation of that specification
|
||||
with a few interesting points:
|
||||
|
||||
- t-on directive
|
||||
- t-widget, t-props, t-key
|
||||
- t-ref
|
||||
- it compiles templates into functions that output a virtual DOM instead of a
|
||||
string. This is necessary for the component system.
|
||||
- it has a few extra directives: `t-component`, `t-on`, ...
|
||||
|
||||
## Note on white spaces
|
||||
## Directives
|
||||
|
||||
We present here a list of all standard QWeb directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------------ | ------------------------------------------------------------ |
|
||||
| `t-esc` | [Outputting safely a value](#outputting-data) |
|
||||
| `t-raw` | [Outputting value, without escaping](#outputting-data) |
|
||||
| `t-set`, `t-value` | [Setting variables](#setting-variables) |
|
||||
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
|
||||
| `t-foreach`, `t-as` | [Loops](#loops) |
|
||||
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
||||
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
||||
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
||||
| `t-name` | [Defining a template (not really a directive)](#qweb-engine) |
|
||||
|
||||
The component system in Owl requires additional directives, to express various
|
||||
needs. Here is a list of all Owl specific directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `t-component`, `t-props`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-mounted` | [Callback when a node or component is mounted](component.md#t-mounted-directive) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
|
||||
## QWeb Engine
|
||||
|
||||
This section is about the javascript code that implements the `QWeb` specification.
|
||||
Owl exports a `QWeb` class in `owl.QWeb`. To use it, it just needs to be
|
||||
instantiated:
|
||||
|
||||
```js
|
||||
const qweb = new owl.QWeb();
|
||||
```
|
||||
|
||||
It's API is quite simple:
|
||||
|
||||
- **`constructor(data)`**: constructor. Takes an optional string to add initial
|
||||
templates (see `addTemplates` for more information on format of the string).
|
||||
|
||||
```js
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
```
|
||||
|
||||
- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template.
|
||||
|
||||
```js
|
||||
qweb.addTemplate("mytemplate", "<div>hello</div>");
|
||||
```
|
||||
|
||||
If the optional `allowDuplicate` is set to `true`, then `QWeb` will simply return whenever a template is added for a second time. Otherwise, `QWeb` will crash.
|
||||
|
||||
- **`addTemplates(xmlStr)`**: add a list of templates (identified by `t-name`
|
||||
attribute).
|
||||
|
||||
```js
|
||||
const TEMPLATES = `
|
||||
<templates>
|
||||
<div t-name="App" class="main">main</div>
|
||||
<div t-name="OtherComponent">other component</div>
|
||||
</templates>`;
|
||||
qweb.addTemplates(TEMPLATES);
|
||||
```
|
||||
|
||||
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
||||
which is a virtual representation of the DOM (see [vdom doc](vdom.md)).
|
||||
|
||||
```js
|
||||
const vnode = qweb.render("App", component);
|
||||
```
|
||||
|
||||
- **`renderToString(name, context)`**: renders a template, but returns an html
|
||||
string.
|
||||
|
||||
```js
|
||||
const str = qweb.renderToString("someTemplate", somecontext);
|
||||
```
|
||||
|
||||
- **`registerTemplate(name, template)`**: static function to register an global
|
||||
QWeb template. This is useful for commonly used components accross the
|
||||
application, and for making a template available to an application without
|
||||
having a reference to the actual QWeb instance.
|
||||
|
||||
```js
|
||||
QWeb.registerTemplate("mytemplate", `<div>some template`);
|
||||
```
|
||||
|
||||
- **`registerComponent(name, Component)`**: static function to register an OWL Component
|
||||
to QWeb's global registry. Globally registered Components can be used in
|
||||
templates (see the `t-component` directive). This is useful for commonly used
|
||||
components accross the application.
|
||||
|
||||
```js
|
||||
class Dialog extends owl.Component { ... }
|
||||
QWeb.registerComponent("Dialog", Dialog);
|
||||
|
||||
...
|
||||
|
||||
class ParentComponent extends owl.Component { ... }
|
||||
qweb.addTemplate("ParentComponent", "<div><Dialog/></div>");
|
||||
```
|
||||
|
||||
In some way, a `QWeb` instance is the core of an Owl application. It is the only
|
||||
mandatory element of an [environment](component.md#environment). As such, it
|
||||
has an extra responsability: it can act as an event bus for internal communication
|
||||
between Owl classes. This is the reason why `QWeb` actually extends [EventBus](event_bus.md).
|
||||
|
||||
## Reference
|
||||
|
||||
We define in this section the specification of how `QWeb` templates should be
|
||||
rendered. Note that we only document here the standard QWeb specification. Owl
|
||||
specific extensions are documented in various other parts of the documentation.
|
||||
|
||||
### White Spaces
|
||||
|
||||
White spaces in a templates are handled in a special way:
|
||||
|
||||
- consecutive whitespaces are always condensed to a single whitespace
|
||||
- if a whitespace-only text node contains a linebreak, it is ignored
|
||||
- the previous rules do not apply if we are in a `<pre>` tag
|
||||
|
||||
### Root Nodes
|
||||
|
||||
For many reasons, Owl QWeb templates should have a single root node. More
|
||||
precisely, the result of a template rendering should have a single root node:
|
||||
|
||||
```xml
|
||||
<!–– not ok: two root nodes ––>
|
||||
<t>
|
||||
<div>foo</div>
|
||||
<div>bar</div>
|
||||
</t>
|
||||
|
||||
<!–– ok: result has one single root node ––>
|
||||
<t>
|
||||
<div t-if="someCondition">foo</div>
|
||||
<span t-else="1">bar</span>
|
||||
</t>
|
||||
```
|
||||
|
||||
Extra root nodes will actually be ignored (even though they will be rendered
|
||||
in memory).
|
||||
|
||||
Note: this does not apply to subtemplates (see the `t-call` directive). In that
|
||||
case, they will be inlined in the main template, and can actually have many
|
||||
root nodes.
|
||||
|
||||
### Expression Evaluation
|
||||
|
||||
QWeb expressions are strings that will be processed at compile time. Each variable in
|
||||
the javascript expression will be replaced by a lookup in the context (so, the
|
||||
component). For example, `a + b.c(d)` will be converted into:
|
||||
|
||||
```js
|
||||
context["a"] + context["b"].c(context["d"]);
|
||||
```
|
||||
|
||||
It is useful to explain the various rules that applies on these expressions:
|
||||
|
||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||
|
||||
```xml
|
||||
<div><p t-if="1 + 2 === 3">ok</p></div>
|
||||
```
|
||||
|
||||
is valid, but the following is not valid:
|
||||
|
||||
```xml
|
||||
<div><p t-if="console.log(1)">NOT valid</p></div>
|
||||
```
|
||||
|
||||
2. it can use anything in the rendering context (typically, the component):
|
||||
|
||||
```xml
|
||||
<p t-if="user.birthday === today()">Happy bithday!</p>
|
||||
```
|
||||
|
||||
is valid, and will read the `user` object from the context, and call the
|
||||
`today` function.
|
||||
|
||||
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
||||
`&` or `|`. This is useful to make sure that we still write valid XML.
|
||||
|
||||
| Word | will be replaced by |
|
||||
| ----- | ------------------- |
|
||||
| `and` | `&&` |
|
||||
| `or` | `\|\|` |
|
||||
| `gt` | `>` |
|
||||
| `gte` | `>=` |
|
||||
| `lt` | `<` |
|
||||
| `lte` | `<=` |
|
||||
|
||||
So, one can write this:
|
||||
|
||||
```xml
|
||||
<div><p t-if="10 + 2 gt 5">ok</p></div>
|
||||
```
|
||||
|
||||
### Static Html Nodes
|
||||
|
||||
Normal, regular html nodes are rendered into themselves:
|
||||
|
||||
```xml
|
||||
<div>hello</div> <!–– rendered as itself ––>
|
||||
```
|
||||
|
||||
### Outputting Data
|
||||
|
||||
The `t-esc` directive is necessary whenever you want to add a dynamic text
|
||||
expression in a template. The text is escaped to avoid security issues.
|
||||
|
||||
```xml
|
||||
<p><t t-esc="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `42` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p>42</p>
|
||||
```
|
||||
|
||||
The `t-raw` directive is almost the same as `t-esc`, but without the escaping.
|
||||
This is mostly useful to inject a raw html string somewhere. Obviously, this
|
||||
is unsafe to do in general, and should only be used for strings known to be safe.
|
||||
|
||||
```xml
|
||||
<p><t t-raw="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `<span>foo</span>` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p><span>foo</span></p>
|
||||
```
|
||||
|
||||
### Setting Variables
|
||||
|
||||
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
|
||||
|
||||
This is done via the `t-set` directive, which takes the name of the variable to create. The value to set can be provided in two ways:
|
||||
|
||||
1. a `t-value` attribute containing an expression, and the result of its
|
||||
evaluation will be set:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="2 + 1"/>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will print `3`. Note that the evaluation is done at rendering time, not at
|
||||
compilte time.
|
||||
|
||||
2. if there is no `t-value` attribute, the node’s body is saved and its value is
|
||||
set as the variable’s value:
|
||||
|
||||
```xml
|
||||
<t t-set="foo">
|
||||
<li>ok</li>
|
||||
</t>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will generate `<li>ok</li>` (the content is escaped as we used the `t-esc` directive)
|
||||
|
||||
The `t-set` directive acts like a regular variable in most programming language.
|
||||
It is lexically scoped (inner nodes are sub scopes), can be shadowed, ...
|
||||
|
||||
### Conditionals
|
||||
|
||||
The `t-if` directive is useful to conditionally render something. It evaluates
|
||||
the expression given as attribute value, and then acts accordingly.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<t t-if="condition">
|
||||
<p>ok</p>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
The element is rendered if the condition (evaluated with the current rendering
|
||||
context) is true:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p>ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
but if the condition is false it is removed from the result:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
</div>
|
||||
```
|
||||
|
||||
The conditional rendering applies to the bearer of the directive, which does not
|
||||
have to be `<t>`:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="condition">ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
will give the same results as the previous example.
|
||||
|
||||
Extra conditional branching directives `t-elif` and `t-else` are also available:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="user.birthday == today()">Happy bithday!</p>
|
||||
<p t-elif="user.login == 'root'">Welcome master!</p>
|
||||
<p t-else="">Welcome!</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Dynamic Attributes
|
||||
|
||||
One can use the `t-att-` directive to add dynamic attributes. Its main use is to
|
||||
evaluate an expression (at rendering time) and bind an attribute to its result:
|
||||
|
||||
For example, if we have `id` set to 32 in the rendering context,
|
||||
|
||||
```xml
|
||||
<div t-att-data-action-id="id"/> <!-- result: <div data-action-id="32"></div> -->
|
||||
```
|
||||
|
||||
If an expression evaluates to a falsy value, it will not be set at all:
|
||||
|
||||
```xml
|
||||
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
||||
```
|
||||
|
||||
There is another way to format a string attribute: the `t-attf-` directive. With
|
||||
it, you get string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
```
|
||||
|
||||
### Loops
|
||||
|
||||
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
||||
collection to iterate on, and a second parameter `t-as` providing the name to use
|
||||
for the current item of the iteration:
|
||||
|
||||
```xml
|
||||
<t t-foreach="[1, 2, 3]" t-as="i">
|
||||
<p><t t-esc="i"/></p>
|
||||
</t>
|
||||
```
|
||||
|
||||
will be rendered as:
|
||||
|
||||
```xml
|
||||
<p>1</p>
|
||||
<p>2</p>
|
||||
<p>3</p>
|
||||
```
|
||||
|
||||
Like conditions, `t-foreach` applies to the element bearing the directive’s attribute, and
|
||||
|
||||
```xml
|
||||
<p t-foreach="[1, 2, 3]" t-as="i">
|
||||
<t t-esc="i"/>
|
||||
</p>
|
||||
```
|
||||
|
||||
is equivalent to the previous example.
|
||||
|
||||
`t-foreach` can iterate on an array (the current item will be the current value)
|
||||
or an object (the current item will be the current key).
|
||||
|
||||
In addition to the name passed via t-as, `t-foreach` provides a few other
|
||||
variables for various data points (note: `$as` will be replaced by the name
|
||||
passed to `t-as`):
|
||||
|
||||
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
||||
integers, but for objects, it provides the value (where `$as` provides the key)
|
||||
- `$as_index`: the current iteration index (the first item of the iteration has index 0)
|
||||
- `$as_first`: whether the current item is the first of the iteration
|
||||
(equivalent to `$as_index == 0`)
|
||||
- `$as_last`: whether the current item is the last of the iteration
|
||||
(equivalent to `$as_index + 1 == $as_size`), requires the iteratee’s size be
|
||||
available
|
||||
|
||||
These extra variables provided and all new variables created into the `t-foreach`
|
||||
are only available in the scope of the `t-foreach`. If the variable exists outside
|
||||
the context of the `t-foreach`, the value is copied at the end of the foreach
|
||||
into the global context.
|
||||
|
||||
```xml
|
||||
<t t-set="existing_variable" t-value="False"/>
|
||||
<!-- existing_variable now False -->
|
||||
|
||||
<p t-foreach="Array(3)" t-as="i">
|
||||
<t t-set="existing_variable" t-value="True"/>
|
||||
<t t-set="new_variable" t-value="True"/>
|
||||
<!-- existing_variable and new_variable now True -->
|
||||
</p>
|
||||
|
||||
<!-- existing_variable always True -->
|
||||
<!-- new_variable undefined -->
|
||||
```
|
||||
|
||||
### Rendering Sub Templates
|
||||
|
||||
QWeb templates can be used for top level rendering, but they can also be used
|
||||
from within another template (to avoid duplication or give names to parts of
|
||||
templates), using the `t-call` directive:
|
||||
|
||||
```xml
|
||||
<div t-name="other-template">
|
||||
<p><t t-value="var"/></p>
|
||||
</div>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-set="var" t-value="owl"/>
|
||||
<t t-call="other-template"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
will be rendered as `<div><p>owl</p></div>`. This example shows that the sub
|
||||
template is rendered with the execution context of the parent. The sub template
|
||||
is actually inlined in the main template, but in a sub scope: variables defined
|
||||
in the sub template do not escape.
|
||||
|
||||
Sometimes, one might want to pass information to the sub template. In that case,
|
||||
the content of the body of the `t-call` directive is available as a special
|
||||
magic variable `0`:
|
||||
|
||||
```xml
|
||||
<t t-name="other-template">
|
||||
This template was called with content:
|
||||
<t t-raw="0"/>
|
||||
</t>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-call="other-template">
|
||||
<em>content</em>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
will result in :
|
||||
|
||||
```xml
|
||||
<div>
|
||||
This template was called with content:
|
||||
<em>content</em>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Debugging
|
||||
|
||||
The javascript QWeb implementation provides two useful debugging directives:
|
||||
|
||||
`t-debug` adds a debugger statement during template rendering:
|
||||
|
||||
```xml
|
||||
<t t-if="a_test">
|
||||
<t t-debug="">
|
||||
</t>
|
||||
```
|
||||
|
||||
will stop execution if the browser dev tools are open.
|
||||
|
||||
`t-log` takes an expression parameter, evaluates the expression during rendering and logs its result with console.log:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="42"/>
|
||||
<t t-log="foo"/>
|
||||
```
|
||||
|
||||
will print 42 to the console
|
||||
|
||||
+49
-13
@@ -1,17 +1,53 @@
|
||||
# Odoo Web Lab Documentation
|
||||
# 🦉 OWL Documentation 🦉
|
||||
|
||||
Currently, this repository contains:
|
||||
## Owl Content
|
||||
|
||||
- an implementation/extension of the QWeb template engine that outputs a virtual
|
||||
dom (using the snabbdom library)
|
||||
- a Component class, which uses the QWeb engine as its underlying rendering
|
||||
mechanism. The component class is designed to be declarative, with
|
||||
asynchronous rendering. Also, it uses snabbdom as the virtual dom library.
|
||||
- some utility functions/classes
|
||||
- a Store class and a connect function, to help manage the state of an application (like react-redux)
|
||||
Owl is a javascript library that contains some core classes and function to help
|
||||
build applications. Here is a complete representation of its content:
|
||||
|
||||
```
|
||||
owl
|
||||
Component
|
||||
QWeb
|
||||
core
|
||||
EventBus
|
||||
Observer
|
||||
router
|
||||
Link
|
||||
RouteComponent
|
||||
Router
|
||||
store
|
||||
Store
|
||||
ConnectedComponent
|
||||
tags
|
||||
xml
|
||||
utils
|
||||
debounce
|
||||
escape
|
||||
loadJS
|
||||
loadTemplates
|
||||
whenReady
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
- [Animations](animations.md)
|
||||
- [Component](component.md)
|
||||
- [Event Bus](event_bus.md)
|
||||
- [Observer](observer.md)
|
||||
- [QWeb](qweb.md)
|
||||
- [Router](router.md)
|
||||
- [Store](store.md)
|
||||
- [Tags](tags.md)
|
||||
- [Utils](utils.md)
|
||||
- [Virtual DOM](vdom.md)
|
||||
|
||||
## Learning Resources
|
||||
|
||||
- [Quick Start](quick_start.md)
|
||||
- [Tutorial](tutorial.md)
|
||||
- [Component](component.md)
|
||||
- [QWeb](qweb.md)
|
||||
- [State Management](state_management.md)
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
- [Comparison with React/Vue](comparison.md)
|
||||
- [Tooling](tooling.md)
|
||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
# 🦉 Router 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Route Definition](#route-definition)
|
||||
- [Router](#router)
|
||||
- [Navigation Guards](#navigation-guards)
|
||||
- [RouteComponent](#routecomponent)
|
||||
- [Link](#link)
|
||||
|
||||
## Overview
|
||||
|
||||
It is often useful to organize an application around urls. If the application is
|
||||
a single page application, then we need a way to manage those urls in the browser.
|
||||
This is why there are many different routers for different frameworks. A generic
|
||||
router can do the job just fine, but a specialized router for Owl can give a
|
||||
better developer experience.
|
||||
|
||||
The Owl router support the following features:
|
||||
|
||||
- `history` or `hash` mode
|
||||
- declarative routes
|
||||
- route redirection
|
||||
- navigation guards
|
||||
- parameterized routes
|
||||
- a `<Link/>` component
|
||||
- a `<RouteComponent/>` component
|
||||
|
||||
Note that it is still in early stage of developments, and there are probably
|
||||
still some issues.
|
||||
|
||||
## Example
|
||||
|
||||
To use the Owl router, there are some steps that needs to be done:
|
||||
|
||||
- declare some routes
|
||||
- create a router
|
||||
- add it to the environment
|
||||
|
||||
```js
|
||||
async function protectRoute({ env, to }) {
|
||||
if (!env.session.authUser) {
|
||||
env.session.setNextRoute(to.name);
|
||||
return { to: "SIGN_IN" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export const ROUTES = [
|
||||
{ name: "LANDING", path: "/", component: Landing },
|
||||
{ name: "TASK", path: "/tasks/{{id}}", component: Task },
|
||||
{ name: "SIGN_UP", path: "/signup", component: SignUp },
|
||||
{ name: "SIGN_IN", path: "/signin", component: SignIn },
|
||||
{ name: "ADMIN", path: "/admin", component: Admin, beforeRouteEnter: protectRoute },
|
||||
{ name: "ACCOUNT", path: "/account", component: Account, beforeRouteEnter: protectRoute },
|
||||
{ name: "UNKNOWN", path: "*", redirect: { to: "LANDING" } }
|
||||
];
|
||||
|
||||
function makeEnvironment() {
|
||||
...
|
||||
const env = { qweb };
|
||||
env.session = new Session(env);
|
||||
env.router = new owl.router.Router(env, ROUTES);
|
||||
await env.router.start();
|
||||
return env;
|
||||
}
|
||||
```
|
||||
|
||||
Notice that the router needs to be started. This is an asynchronous operation
|
||||
because it needs to apply the potential navigation guards on the current route
|
||||
(which may or may not mean that the application is redirected to another route).
|
||||
|
||||
## Reference
|
||||
|
||||
### Route definition
|
||||
|
||||
A route need to be defined as an object with the following keys:
|
||||
|
||||
- `name` (optional): a (unique) string useful to identify the current route. If not
|
||||
given, it will be assigned an automatic name,
|
||||
- `path`: a string describing the url. It can be static: `/admin` or dynamic: `/users/{{id}}`.
|
||||
It also can be `*`, to catch all remaining routes.
|
||||
- `component` (optional): an Owl component that will be used by the `t-routecomponent`
|
||||
directive if the route is active
|
||||
- `redirect` (optional): should be destination object (with optional keys `path`, `to` and `params`) if given, the application will be redirected to the destination whenever we match this route
|
||||
- `beforeRouteEnter`: defines a [navigation guard](#navigation-guards).
|
||||
|
||||
### `Router`
|
||||
|
||||
The `Router` constructor takes three arguments:
|
||||
|
||||
- `env`: a valid environment,
|
||||
- a list of routes,
|
||||
- an optional object (with the only key `mode` which can be `history` (default
|
||||
value) or `hash`).
|
||||
|
||||
```js
|
||||
const ROUTES = [...];
|
||||
const router = new owl.router.Router(env, ROUTES, {mode: 'history'});
|
||||
```
|
||||
|
||||
Note that the route are defined in a list, and the order matters: the router
|
||||
tries to find a match by going down the list.
|
||||
|
||||
The router needs to be added to the environment in the `router` sub key.
|
||||
|
||||
Once a router is created, it needs to be started. This is necessary to initialize
|
||||
its current state to the current URL (and also, to potentially apply any
|
||||
navigation guards and/or redirecting).
|
||||
|
||||
```js
|
||||
await router.start();
|
||||
```
|
||||
|
||||
Once started, the router will keep track of the current url and reflect its
|
||||
value in two keys:
|
||||
|
||||
- `router.currentRoute`
|
||||
- `router.currentParams`
|
||||
|
||||
The router also has a `navigate` method, useful to programmatically change the
|
||||
application to another state (and the url):
|
||||
|
||||
```js
|
||||
router.navigate({ to: "USER", params: { id: 51 } });
|
||||
```
|
||||
|
||||
### Navigation Guards
|
||||
|
||||
Navigation guards are very useful to be able to execute some business logic/
|
||||
perform some actions or redirect to other routes whenever the application is
|
||||
entering a new route. For example, the following guard checks if there is an
|
||||
authenticated user, and if it is not the case, redirect to the sign in route.
|
||||
|
||||
```js
|
||||
async function protectRoute({ env, to }) {
|
||||
if (!env.session.authUser) {
|
||||
env.session.setNextRoute(to.name);
|
||||
return { to: "SIGN_IN" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
A navigation guard is a function that returns a promise, which either resolves
|
||||
to `true` (the navigation is accepted), or to another destination object.
|
||||
|
||||
### `RouteComponent`
|
||||
|
||||
The `RouteComponent` component directs Owl to render the component associated
|
||||
to the currently active route (if any):
|
||||
|
||||
```xml
|
||||
<div t-name="App">
|
||||
<NavBar />
|
||||
<RouteComponent />
|
||||
</div>
|
||||
```
|
||||
|
||||
### `Link`
|
||||
|
||||
The `Link` component is a Owl component which render as a `<a>` tag with any
|
||||
content. It will compute the proper href from its props, and allow Owl to
|
||||
properly navigate to a given url if clicked on it.
|
||||
|
||||
```xml
|
||||
<Link to="'HOME'">Home</Link>
|
||||
```
|
||||
@@ -1,8 +0,0 @@
|
||||
# OWL: State Management
|
||||
|
||||
Managing the state in an application is not an easy task. Many different
|
||||
architectures/designs/systems/... have been created. We propose here to use
|
||||
the idea of a central store.
|
||||
|
||||
- Store
|
||||
- connect
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
# 🦉 Store 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Store](#store)
|
||||
- [Actions](#actions)
|
||||
- [Getters](#getters)
|
||||
- [Connecting a Component](#connecting-a-component)
|
||||
- [Semantics](#semantics)
|
||||
- [Good Practices](#good-practices)
|
||||
|
||||
## Overview
|
||||
|
||||
Managing the state in an application is not an easy task. In some cases, the
|
||||
state of an application can be part of the component tree, in a natural way.
|
||||
However, there are situations where some part of the state need to be displayed
|
||||
in various parts of the user interface, and then, it is not obvious which
|
||||
component should own which part of the state.
|
||||
|
||||
Owl's solution to this issue is a centralized store. It is a class that owns
|
||||
some state, and let the developer update it in a structured way, with `actions`.
|
||||
Owl components can then connect to the store, and will be updated if necessary.
|
||||
|
||||
Note: Owl store is inspired by React Redux and VueX.
|
||||
|
||||
## Example
|
||||
|
||||
Here is what a simple store looks like:
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
addTodo({ state }, message) {
|
||||
state.todos.push({
|
||||
id: state.nextId++,
|
||||
message,
|
||||
isCompleted: false
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
todos: [],
|
||||
nextId: 1
|
||||
};
|
||||
|
||||
const store = new owl.Store({ state, actions });
|
||||
store.on("update", () => console.log(store.state));
|
||||
|
||||
// updating the state
|
||||
store.dispatch("addTodo", "fix all bugs");
|
||||
```
|
||||
|
||||
This example shows how a store can be defined and used. Note that in most cases,
|
||||
actions will be dispatched by connected components.
|
||||
|
||||
## Reference
|
||||
|
||||
### `Store`
|
||||
|
||||
The store is a simple [`owl.EventBus`](event_bus.md) that triggers `update` events
|
||||
whenever its state is changed. Note that these events are triggered only after a
|
||||
microtask tick, so only one event will be triggered for any number of state changes in a
|
||||
call stack.
|
||||
|
||||
Also, it is important to mention that the state is observed (with an `owl.Observer`),
|
||||
which is the reason why it is able to know if it was changed. See the
|
||||
[Observer](observer.md)'s documentation for more details.
|
||||
|
||||
The `Store` class is quite small. It has two public methods:
|
||||
|
||||
- its constructor
|
||||
- `dispatch`
|
||||
|
||||
The constructor takes a configuration object with four (optional) keys:
|
||||
|
||||
- the initial state
|
||||
- the actions
|
||||
- the getters
|
||||
- the environment
|
||||
|
||||
```javascript
|
||||
const config = {
|
||||
state,
|
||||
actions,
|
||||
getters,
|
||||
env
|
||||
};
|
||||
const store = new Store(config);
|
||||
```
|
||||
|
||||
### Actions
|
||||
|
||||
Actions are used to coordinate state changes. It can be used for both synchronous
|
||||
and asynchronous logic.
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
async login({ state }, info) {
|
||||
state.loginState = "pending";
|
||||
try {
|
||||
const loginInfo = await doSomeRPC("/login/", info);
|
||||
state.loginState = loginInfo;
|
||||
} catch (e) {
|
||||
state.loginState = "error";
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Actions are called with the `dispatch` method on the store, and can receive an
|
||||
arbitrary number of arguments.
|
||||
|
||||
```js
|
||||
store.dispatch("login", someInfo);
|
||||
```
|
||||
|
||||
Note that anything returned by an action will also be returned by the `dispatch`
|
||||
call.
|
||||
|
||||
Also, it is important to be aware that we need to be careful with asynchronous
|
||||
logic. Each state change will potentially trigger a rerendering, so we need to
|
||||
make sure that we do not have a partial corrupted state. Here is an example that
|
||||
is likely not a good idea:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
async fetchSomeData({ state }, recordId) {
|
||||
state.recordId = recordId;
|
||||
const data = await doSomeRPC("/read/", recordId);
|
||||
state.recordData = data;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
In the previous example, there is a period of time in which the state has a
|
||||
`recordId` which does not correspond to the `recordData`. It is more likely that
|
||||
we want an atomic update: updating the `recordId` at the same time as the `recordData`
|
||||
values:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
async fetchSomeData({ state }, recordId) {
|
||||
const data = await doSomeRPC("/read/", recordId);
|
||||
state.recordId = recordId;
|
||||
state.recordData = data;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Getters
|
||||
|
||||
Usually, data contained in the store will be stored in a normalized way. For
|
||||
example,
|
||||
|
||||
```js
|
||||
{
|
||||
posts: [{id: 11, authorId: 4, content: 'Greetings'}],
|
||||
authors: [{id: 4, name: 'John'}]
|
||||
}
|
||||
```
|
||||
|
||||
However, the user interface will probably need some denormalized data like
|
||||
|
||||
```js
|
||||
{id: 11, author: {id: 4, name: 'John'}, content: 'Greetings'}
|
||||
```
|
||||
|
||||
This is what `getters` are for: they give a centralized way to process and
|
||||
transform the data contained in the store.
|
||||
|
||||
```js
|
||||
const getters = {
|
||||
getPost({ state }, id) {
|
||||
const post = state.posts.find(p => p.id === id);
|
||||
const author = state.authors.find(a => (a.id = post.id));
|
||||
return {
|
||||
id,
|
||||
author,
|
||||
content: post.content
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// somewhere else
|
||||
const post = store.getters.getPost(id);
|
||||
```
|
||||
|
||||
Getters take _at most_ one argument.
|
||||
|
||||
Note that getters are cached if they don't take any argument, or their argument
|
||||
is a string or a number.
|
||||
|
||||
### Connecting a Component
|
||||
|
||||
At some point, we need a way to access the state in the store from a component.
|
||||
By default, an Owl `Component` is not connected to any store. To do that, we
|
||||
need to create a component inheriting from `OwlComponent`:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter += val;
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: 0
|
||||
};
|
||||
const store = new owl.Store({ state, actions });
|
||||
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
increment() {
|
||||
this.env.store.dispatch("increment");
|
||||
}
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="props.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
The `ConnectedComponent` class can be configured with the following fields:
|
||||
|
||||
- `mapStoreToProps`: a function that extracts the `props` of the Component
|
||||
from the `state` of the `Store` and returns them as a dict.
|
||||
- `getStore`: a function that takes the `env` in arguments and returns an
|
||||
instance of `Store` to connect to (if not given, connects to `env.store`)
|
||||
- `hashFunction`: the function to use to detect changes in the state (if not
|
||||
given, generates a function that uses revision numbers, incremented at
|
||||
each state change)
|
||||
- `deep` (boolean): [only useful if no hashFunction is given] if `false`, only watch
|
||||
for top level state changes (`true` by default)
|
||||
|
||||
Note that the class `ConnectedComponent` has a `dispatch` method. This means
|
||||
that the previous example could be simplified like this:
|
||||
|
||||
```javascript
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="props.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
### Semantics
|
||||
|
||||
The `Store` and the `ConnectedComponent` try to be smart and to optimize as much
|
||||
as possible the rendering and update process. What is important to know is:
|
||||
|
||||
- components are always updated in the order of their creation (so, parent
|
||||
before children)
|
||||
- they are updated only if they are in the DOM
|
||||
- if a parent is asynchronous, the system will wait for it to complete its
|
||||
update before updating other components.
|
||||
- in general, updates are not coordinated. This is not a problem for synchronous
|
||||
components, but if there are many asynchronous components, this could lead to
|
||||
a situation where some part of the UI is updated and other parts of the UI is
|
||||
not updated.
|
||||
|
||||
### Good Practices
|
||||
|
||||
- avoid asynchronous components as much as possible. Asynchronous components
|
||||
lead to situations where parts of the UI is not updated immediately.
|
||||
- do not be afraid to connect many components, parent or children if needed. For
|
||||
example, a `MessageList` component could get a list of ids in its `mapStoreToProps` and a `Message` component could get the data of its own
|
||||
message
|
||||
- since the `mapStoreToProps` function is called for each connected component,
|
||||
for each state update, it is important to make sure that these functions are
|
||||
as fast as possible.
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# 🦉 Tags 🦉
|
||||
|
||||
Tags are very small helper to make it easy to write inline templates. There is
|
||||
only one currently available tag: `xml`, but we plan to add other tags later,
|
||||
such as a `css` tag, which will be used to write single file components.
|
||||
|
||||
## XML tag
|
||||
|
||||
Without tags, creating a standalone component would look like this:
|
||||
|
||||
```js
|
||||
import { Component } from 'owl'
|
||||
|
||||
const name = 'some-unique-name';
|
||||
const template = `
|
||||
<div>
|
||||
<span t-if="somecondition">text</span>
|
||||
<button t-on-click="someMethod">Click</button>
|
||||
</div>
|
||||
`;
|
||||
QWeb.registerTemplate(name, template);
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = name;
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
With tags, this process is slightly simplified. The name is uniquely generated,
|
||||
and the template is automatically registered:
|
||||
|
||||
```js
|
||||
import { Component } from 'owl'
|
||||
import { xml } from 'owl/tags'
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-if="somecondition">text</span>
|
||||
<button t-on-click="someMethod">Click</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
# 🦉 Tooling 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Development Mode](#development-mode)
|
||||
- [Playground](#playground)
|
||||
- [Benchmarks](#benchmarks)
|
||||
|
||||
## Overview
|
||||
|
||||
To help work with/improve/learn OWL, there are a few extras tools/settings.
|
||||
|
||||
- development mode: enable better error reporting for the developer
|
||||
- a playground application: a space to experiment and learn Owl.
|
||||
- a benchmarks application: allow comparison with a few common frameworks
|
||||
|
||||
The two applications are available in the `tools/` folder, and can be accessed
|
||||
by using a static http server. A simple python
|
||||
server is available in `server.py`. There is also a npm script to start it:
|
||||
`npm run tools` (and its version with a watcher: `npm run tools:watch`).
|
||||
|
||||
## Development Mode
|
||||
|
||||
By default, Owl is in _production_ mode, this means that it will try to do its
|
||||
job fast, and skip some expensive operations. However, in some cases, it is
|
||||
convenient to have better information on what is going on, this is the purpose
|
||||
of the dev mode.
|
||||
|
||||
Owl has a mode flag, in `owl.__info__.mode`. Its default value is `prod`, but
|
||||
it can be set to `dev`:
|
||||
|
||||
```js
|
||||
owl.__info__.mode = "dev";
|
||||
```
|
||||
|
||||
Note that templates compiled with the `prod` settings will not be recompiled.
|
||||
So, changing this setting is best done at startup.
|
||||
|
||||
An important job done by the `dev` mode is to validate props for each component
|
||||
creation and update. Also, extra props will cause an error.
|
||||
|
||||
## Playground
|
||||
|
||||
The playground is an important application designed to help learning and
|
||||
experimenting with Owl. The last published version of Owl can be tested [online](https://odoo.github.io/owl/playground/).
|
||||
|
||||
It is an application similar to `jsFiddle`, but specialized for Owl: there are
|
||||
three tabs (`js`, `css` and `xml`), and a simple button `Run` to execute that
|
||||
code in an iframe.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Note: This is more an internal tool, useful for people working on Owl.
|
||||
|
||||
The benchmarks application is a very small application, implemented in different
|
||||
frameworks, and in different versions of Owl. This is a simple internal tool,
|
||||
useful to compare various performance metrics on some tasks.
|
||||
@@ -1,3 +0,0 @@
|
||||
# Tutorial
|
||||
|
||||
todo...
|
||||
@@ -0,0 +1,63 @@
|
||||
# 🦉 Utils 🦉
|
||||
|
||||
Owl export a few useful utility functions, to help with common issues. Those
|
||||
functions are all available in the `owl.utils` namespace.
|
||||
|
||||
## Content
|
||||
|
||||
- [`whenReady`](#whenready): executing code when DOM is ready
|
||||
- [`loadJS`](#loadjs): loading script files
|
||||
- [`loadTemplates`](#loadtemplates): loading xml files
|
||||
- [`escape`](#escape): sanitizing strings
|
||||
- [`debounce`](#debounce): limiting rate of function calls
|
||||
|
||||
## `whenReady`
|
||||
|
||||
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
|
||||
not ready yet, resolved directly otherwise). If called with a callback as
|
||||
argument, it executes it as soon as the DOM ready (or directly).
|
||||
|
||||
```js
|
||||
Promise.all([loadTemplates(), owl.utils.whenReady()]).then(function([templates]) {
|
||||
const qweb = new owl.QWeb(templates);
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
owl.utils.whenReady(function() {
|
||||
const qweb = new owl.QWeb();
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
## `loadJS`
|
||||
|
||||
`loadJS` takes a url (string) for a javascript resource, and loads it. It returns
|
||||
a promise, so the caller can properly react when it is ready. Also, it is smart:
|
||||
it maintains a list of urls previously loaded (or currently being loaded), and
|
||||
prevent doing twice the work.
|
||||
|
||||
```js
|
||||
class MyComponent extends owl.Component {
|
||||
willStart() {
|
||||
return owl.utils.loadJS("/static/libs/someLib.js");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `loadTemplates`
|
||||
|
||||
```js
|
||||
async function makeEnv() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const qweb = new owl.QWeb(templates);
|
||||
return { qweb };
|
||||
}
|
||||
```
|
||||
|
||||
## `escape`
|
||||
|
||||
## `debounce`
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# 🦉 VDom 🦉
|
||||
|
||||
Owl is a declarative component system: we declare the structure of the component
|
||||
tree, and Owl will translate that to a list of imperative operations. This
|
||||
translation is done by a virtual dom. This is the low level layer of Owl, most
|
||||
developer will not need to call directly the virtual dom functions.
|
||||
|
||||
The main idea behind a virtual dom is to keep a in-memory representation of the
|
||||
DOM (called a virtual node), and whenever some change is needed, to regenerate
|
||||
a new representation, compute the difference between the old and the new, then
|
||||
apply the changes.
|
||||
|
||||
`vdom` exports two functions:
|
||||
|
||||
- `h`: create a new virtual node
|
||||
- `patch`: compare two virtual nodes, and apply the difference.
|
||||
|
||||
Note: Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
|
||||
@@ -1,45 +0,0 @@
|
||||
.main {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: 200px 1fr;
|
||||
}
|
||||
|
||||
.left-thing {
|
||||
background-color: gray;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.left-thing button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.left-thing .counter span {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.left-thing .counter button {
|
||||
width: 40px;
|
||||
}
|
||||
|
||||
.right-thing {
|
||||
padding: 20px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* Message widget */
|
||||
.message .author {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.message {
|
||||
width: 400px;
|
||||
background-color: lightblue;
|
||||
margin: 10px 5px;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Message } from "./message.js";
|
||||
import { messages } from "./data.js";
|
||||
|
||||
const template = `
|
||||
<div class="main">
|
||||
<div class="left-thing">
|
||||
<div class="counter">
|
||||
<button t-on-click="increment(-1)">-</button>
|
||||
<span style="font-weight:bold">Value: <t t-esc="state.messages.length"/></span>
|
||||
<button t-on-click="increment(1)">+</button>
|
||||
</div>
|
||||
<button t-on-click="setMessageCount(10)">10 messages</button>
|
||||
<button t-on-click="setMessageCount(20)">20 messages</button>
|
||||
<button t-on-click="setMessageCount(500)">500 messages</button>
|
||||
<button t-on-click="setMessageCount(1000)">1000 messages</button>
|
||||
<button t-on-click="setMessageCount(5000)">5000 messages</button>
|
||||
<button t-on-click="setMessageCount(15000)">15000 messages</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-att-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
export class App extends owl.Component {
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.inlineTemplate = template;
|
||||
this.widgets = { Message };
|
||||
this.state = {
|
||||
messages: messages.slice(0, 10)
|
||||
};
|
||||
}
|
||||
|
||||
setMessageCount(n) {
|
||||
this.state.messages = messages.slice(0, n);
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
const index = messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
}
|
||||
|
||||
increment(delta) {
|
||||
const n = this.state.messages.length + delta;
|
||||
this.setMessageCount(n);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
export class Counter extends owl.Component {
|
||||
inlineTemplate = `
|
||||
<div>
|
||||
<button t-on-click="increment(-1)">-</button>
|
||||
<span style="font-weight:bold">Value: <t t-esc="state.counter"/></span>
|
||||
<button t-on-click="increment(1)">+</button>
|
||||
</div>`;
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = {
|
||||
counter: props.initialState || 0
|
||||
};
|
||||
}
|
||||
|
||||
increment(delta) {
|
||||
this.state.counter += delta;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
export const messages = [];
|
||||
|
||||
const authors = ["Aaron", "David", "Vincent"];
|
||||
const content = [
|
||||
"Lorem ipsum dolor sit amet",
|
||||
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem",
|
||||
"Excepteur sint occaecat cupidatat non proident"
|
||||
];
|
||||
|
||||
function chooseRandomly(array) {
|
||||
const index = Math.floor(Math.random() * array.length);
|
||||
return array[index];
|
||||
}
|
||||
|
||||
for (let i = 1; i < 16000; i++) {
|
||||
messages.push({
|
||||
id: i,
|
||||
author: chooseRandomly(authors),
|
||||
msg: `${i}: ${chooseRandomly(content)}`,
|
||||
likes: 0
|
||||
});
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Odoo WebCore Benchmarks App</title>
|
||||
<link rel="icon" href="data:,">
|
||||
|
||||
<!-- Application JS/CSS -->
|
||||
<script src="/owl.js"></script>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
<script type="module" src="/main.js"></script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,13 +0,0 @@
|
||||
import { App } from "./app.js";
|
||||
|
||||
function createApp(el) {
|
||||
const env = {
|
||||
qweb: new owl.QWeb()
|
||||
};
|
||||
const app = new App(env, { initialState: 13 });
|
||||
app.mount(el);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
createApp(document.body);
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Counter } from "./counter.js";
|
||||
|
||||
export class Message extends owl.Component {
|
||||
inlineTemplate = `
|
||||
<div class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter" t-props="{initialState: props.id}"/>
|
||||
</div>`;
|
||||
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.widgets = { Counter };
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
# Examples
|
||||
|
||||
This project features three example to illustrate how to work with the web-core framework:
|
||||
|
||||
- _benchmarks_ is a small application to test large number of widgets,
|
||||
- _todoapp_ is the classical todo application (from the todomvc project),
|
||||
|
||||
## Benchmarks
|
||||
|
||||
This example is just a playground to experiment/showcase some features of the framework, with large number of widgets.
|
||||
|
||||
```
|
||||
npm run example:benchmarks:build # make a build in dist/examples/
|
||||
npm run example:benchmarks:dev # make a build in dist/examples/, and make a live server to access it
|
||||
```
|
||||
|
||||
The benchmarks application generates a large number of demo messages, and display them in a list, with a few buttons that can
|
||||
be used to alter the number of visible widgets.
|
||||
|
||||
Note that each message is itself a widget, with a sub widget. This
|
||||
example could be made faster (by not using subwidgets), but the point is to observe/measure the overhead of the Component class.
|
||||
|
||||
## Todo App
|
||||
|
||||
The Todo App is the classical todo application from _http://todomvc.com/_. It is a good mini application with non trivial data structures and interface updates.
|
||||
|
||||
```
|
||||
npm run example:todoapp:build # make a build in dist/examples/
|
||||
npm run example:todoapp:dev # make a build in dist/examples/, and make a live server to access it
|
||||
```
|
||||
|
||||
It is implemented with the Store class (as in redux/vuex).
|
||||
@@ -1,63 +0,0 @@
|
||||
import { TodoItem } from "./TodoItem.js";
|
||||
|
||||
const { Component, connect } = owl;
|
||||
|
||||
const ENTER_KEY = 13;
|
||||
|
||||
function mapStateToProps(state) {
|
||||
return { todos: state.todos };
|
||||
}
|
||||
|
||||
class TodoApp extends Component {
|
||||
template = "todoapp";
|
||||
widgets = { TodoItem };
|
||||
state = { filter: "all" };
|
||||
|
||||
get visibleTodos() {
|
||||
let todos = this.props.todos;
|
||||
if (this.state.filter === "active") {
|
||||
todos = todos.filter(t => !t.completed);
|
||||
}
|
||||
if (this.state.filter === "completed") {
|
||||
todos = todos.filter(t => t.completed);
|
||||
}
|
||||
return todos;
|
||||
}
|
||||
|
||||
get allChecked() {
|
||||
return this.props.todos.every(todo => todo.completed);
|
||||
}
|
||||
|
||||
get remaining() {
|
||||
return this.props.todos.filter(todo => !todo.completed).length;
|
||||
}
|
||||
|
||||
get remainingText() {
|
||||
const items = this.remaining < 2 ? "item" : "items";
|
||||
return ` ${items} left`;
|
||||
}
|
||||
|
||||
addTodo(ev) {
|
||||
if (ev.keyCode === ENTER_KEY) {
|
||||
const title = ev.target.value;
|
||||
if (title.trim()) {
|
||||
this.env.store.dispatch("addTodo", title);
|
||||
}
|
||||
ev.target.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
clearCompleted() {
|
||||
this.env.store.dispatch("clearCompleted");
|
||||
}
|
||||
|
||||
toggleAll() {
|
||||
this.env.store.dispatch("toggleAll", !this.allChecked);
|
||||
}
|
||||
|
||||
setFilter(filter) {
|
||||
this.state.filter = filter;
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps)(TodoApp);
|
||||
@@ -1,51 +0,0 @@
|
||||
const ENTER_KEY = 13;
|
||||
const ESC_KEY = 27;
|
||||
|
||||
export class TodoItem extends owl.Component {
|
||||
template = "todoitem";
|
||||
|
||||
state = { isEditing: false };
|
||||
|
||||
removeTodo() {
|
||||
this.env.store.dispatch("removeTodo", this.props.id);
|
||||
}
|
||||
|
||||
toggleTodo() {
|
||||
this.env.store.dispatch("toggleTodo", this.props.id);
|
||||
}
|
||||
|
||||
async editTodo() {
|
||||
this.state.isEditing = true;
|
||||
setTimeout(() => {
|
||||
this.refs.input.value = "";
|
||||
this.refs.input.focus();
|
||||
this.refs.input.value = this.props.title;
|
||||
});
|
||||
}
|
||||
|
||||
handleKeyup(ev) {
|
||||
if (ev.keyCode === ENTER_KEY) {
|
||||
this.updateTitle(ev.target.value);
|
||||
}
|
||||
if (ev.keyCode === ESC_KEY) {
|
||||
ev.target.value = this.props.title;
|
||||
this.state.isEditing = false;
|
||||
}
|
||||
}
|
||||
|
||||
handleBlur(ev) {
|
||||
this.updateTitle(ev.target.value);
|
||||
}
|
||||
updateTitle(title) {
|
||||
const value = title.trim();
|
||||
if (!value) {
|
||||
this.removeTodo(this.props.id);
|
||||
} else {
|
||||
this.env.store.dispatch("editTodo", {
|
||||
id: this.props.id,
|
||||
title: value
|
||||
});
|
||||
this.state.isEditing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
font-size: 100%;
|
||||
vertical-align: baseline;
|
||||
font-family: inherit;
|
||||
font-weight: inherit;
|
||||
color: inherit;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
body {
|
||||
font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
line-height: 1.4em;
|
||||
background: #f5f5f5;
|
||||
color: #4d4d4d;
|
||||
min-width: 230px;
|
||||
max-width: 550px;
|
||||
margin: 0 auto;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
:focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.todoapp {
|
||||
background: #fff;
|
||||
margin: 130px 0 40px 0;
|
||||
position: relative;
|
||||
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.todoapp input::-webkit-input-placeholder {
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
color: #e6e6e6;
|
||||
}
|
||||
|
||||
.todoapp input::-moz-placeholder {
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
color: #e6e6e6;
|
||||
}
|
||||
|
||||
.todoapp input::input-placeholder {
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
color: #e6e6e6;
|
||||
}
|
||||
|
||||
.todoapp h1 {
|
||||
position: absolute;
|
||||
top: -155px;
|
||||
width: 100%;
|
||||
font-size: 100px;
|
||||
font-weight: 100;
|
||||
text-align: center;
|
||||
color: rgba(175, 47, 47, 0.15);
|
||||
-webkit-text-rendering: optimizeLegibility;
|
||||
-moz-text-rendering: optimizeLegibility;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
.new-todo,
|
||||
.edit {
|
||||
position: relative;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
font-size: 24px;
|
||||
font-family: inherit;
|
||||
font-weight: inherit;
|
||||
line-height: 1.4em;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
padding: 6px;
|
||||
border: 1px solid #999;
|
||||
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
|
||||
box-sizing: border-box;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.new-todo {
|
||||
padding: 16px 16px 16px 60px;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.003);
|
||||
box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.main {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
border-top: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.toggle-all {
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
border: none; /* Mobile Safari */
|
||||
opacity: 0;
|
||||
position: absolute;
|
||||
right: 100%;
|
||||
bottom: 100%;
|
||||
}
|
||||
|
||||
.toggle-all + label {
|
||||
width: 60px;
|
||||
height: 34px;
|
||||
font-size: 0;
|
||||
position: absolute;
|
||||
top: -52px;
|
||||
left: -13px;
|
||||
-webkit-transform: rotate(90deg);
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.toggle-all + label:before {
|
||||
content: "❯";
|
||||
font-size: 22px;
|
||||
color: #e6e6e6;
|
||||
padding: 10px 27px 10px 27px;
|
||||
}
|
||||
|
||||
.toggle-all:checked + label:before {
|
||||
color: #737373;
|
||||
}
|
||||
|
||||
.todo-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.todo-list li {
|
||||
position: relative;
|
||||
font-size: 24px;
|
||||
border-bottom: 1px solid #ededed;
|
||||
}
|
||||
|
||||
.todo-list li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.todo-list li.editing {
|
||||
border-bottom: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.todo-list li.editing .edit {
|
||||
display: block;
|
||||
width: calc(100% - 43px);
|
||||
padding: 12px 16px;
|
||||
margin: 0 0 0 43px;
|
||||
}
|
||||
|
||||
.todo-list li.editing .view {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle {
|
||||
text-align: center;
|
||||
width: 40px;
|
||||
/* auto, since non-WebKit browsers doesn't support input styling */
|
||||
height: auto;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
margin: auto 0;
|
||||
border: none; /* Mobile Safari */
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.todo-list li .toggle + label {
|
||||
/*
|
||||
Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
|
||||
IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
|
||||
*/
|
||||
background-image: url("data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: center left;
|
||||
}
|
||||
|
||||
.todo-list li .toggle:checked + label {
|
||||
background-image: url("data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.todo-list li label {
|
||||
word-break: break-all;
|
||||
padding: 15px 15px 15px 60px;
|
||||
display: block;
|
||||
line-height: 1.2;
|
||||
transition: color 0.4s;
|
||||
}
|
||||
|
||||
.todo-list li.completed label {
|
||||
color: #d9d9d9;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.todo-list li .destroy {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 10px;
|
||||
bottom: 0;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
margin: auto 0;
|
||||
font-size: 30px;
|
||||
color: #cc9a9a;
|
||||
margin-bottom: 11px;
|
||||
transition: color 0.2s ease-out;
|
||||
}
|
||||
|
||||
.todo-list li .destroy:hover {
|
||||
color: #af5b5e;
|
||||
}
|
||||
|
||||
.todo-list li .destroy:after {
|
||||
content: "×";
|
||||
}
|
||||
|
||||
.todo-list li:hover .destroy {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.todo-list li .edit {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.todo-list li.editing:last-child {
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
color: #777;
|
||||
padding: 10px 15px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
border-top: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.footer:before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 50px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6,
|
||||
0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6,
|
||||
0 17px 2px -6px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.todo-count {
|
||||
float: left;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.todo-count strong {
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
.filters {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.filters li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.filters li a {
|
||||
color: inherit;
|
||||
margin: 3px;
|
||||
padding: 3px 7px;
|
||||
text-decoration: none;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.filters li a:hover {
|
||||
border-color: rgba(175, 47, 47, 0.1);
|
||||
}
|
||||
|
||||
.filters li a.selected {
|
||||
border-color: rgba(175, 47, 47, 0.2);
|
||||
}
|
||||
|
||||
.clear-completed,
|
||||
html .clear-completed:active {
|
||||
float: right;
|
||||
position: relative;
|
||||
line-height: 20px;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.clear-completed:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.info {
|
||||
margin: 65px auto 0;
|
||||
color: #bfbfbf;
|
||||
font-size: 10px;
|
||||
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.info p {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.info a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.info a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/*
|
||||
Hack to remove background from Mobile Safari.
|
||||
Can't use it globally since it destroys checkboxes in Firefox
|
||||
*/
|
||||
@media screen and (-webkit-min-device-pixel-ratio: 0) {
|
||||
.toggle-all,
|
||||
.todo-list li .toggle {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle {
|
||||
height: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 430px) {
|
||||
.footer {
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
.filters {
|
||||
bottom: 10px;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Odoo Demo App</title>
|
||||
<link rel="icon" href="data:,">
|
||||
|
||||
<!-- Application JS/CSS -->
|
||||
<script src="/owl.js"></script>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
<script type="module" src="/main.js"></script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
import TodoApp from "./TodoApp.js";
|
||||
import { makeStore } from "./store.js";
|
||||
|
||||
async function makeEnv() {
|
||||
const result = await fetch("templates.xml");
|
||||
if (!result.ok) {
|
||||
throw new Error("Error while fetching xml templates");
|
||||
}
|
||||
let templates = await result.text();
|
||||
templates = templates.replace(/<!--[\s\S]*?-->/g, "");
|
||||
const qweb = new owl.QWeb();
|
||||
qweb.loadTemplates(templates);
|
||||
return {
|
||||
qweb,
|
||||
store: makeStore()
|
||||
};
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async function() {
|
||||
const env = await makeEnv();
|
||||
const app = new TodoApp(env);
|
||||
|
||||
// for debugging purpose
|
||||
window.app = app;
|
||||
await app.mount(document.body);
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// ACTIONS
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const actions = {
|
||||
addTodo({ commit }, title) {
|
||||
commit("addTodo", title);
|
||||
},
|
||||
removeTodo({ commit }, id) {
|
||||
commit("removeTodo", id);
|
||||
},
|
||||
toggleTodo({ state, commit }, id) {
|
||||
const todo = state.todos.find(t => t.id === id);
|
||||
commit("editTodo", { id, completed: !todo.completed });
|
||||
},
|
||||
clearCompleted({ state, commit }) {
|
||||
state.todos
|
||||
.filter(todo => todo.completed)
|
||||
.forEach(todo => {
|
||||
commit("removeTodo", todo.id);
|
||||
});
|
||||
},
|
||||
toggleAll({ state, commit }, completed) {
|
||||
state.todos.forEach(todo => {
|
||||
commit("editTodo", { id: todo.id, completed });
|
||||
});
|
||||
},
|
||||
editTodo({ commit }, { id, title }) {
|
||||
commit("editTodo", { id, title });
|
||||
}
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// MUTATIONS
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const mutations = {
|
||||
addTodo({ state }, title) {
|
||||
const id = state.nextId++;
|
||||
const todo = { id, title, completed: false };
|
||||
state.todos.push(todo);
|
||||
},
|
||||
removeTodo({ state }, id) {
|
||||
const index = state.todos.findIndex(t => t.id === id);
|
||||
state.todos.splice(index, 1);
|
||||
},
|
||||
editTodo({ state }, { id, title, completed }) {
|
||||
const todo = state.todos.find(t => t.id === id);
|
||||
if (title !== undefined) {
|
||||
todo.title = title;
|
||||
}
|
||||
if (completed !== undefined) {
|
||||
todo.completed = completed;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// STORE
|
||||
//------------------------------------------------------------------------------
|
||||
const LOCALSTORAGE_KEY = "todos-odoo";
|
||||
|
||||
export function makeStore() {
|
||||
const todos = JSON.parse(
|
||||
window.localStorage.getItem(LOCALSTORAGE_KEY) || "[]"
|
||||
);
|
||||
const nextId = Math.max(0, ...todos.map(t => t.id || 0)) + 1;
|
||||
const state = { todos, nextId };
|
||||
const store = new owl.Store({ state, actions, mutations });
|
||||
store.on("update", null, () => {
|
||||
const state = JSON.stringify(store.state.todos);
|
||||
window.localStorage.setItem(LOCALSTORAGE_KEY, state);
|
||||
});
|
||||
return store;
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates id="template" xml:space="preserve">
|
||||
|
||||
<section t-name="todoapp" class="todoapp">
|
||||
<!-- header -->
|
||||
<header class="header">
|
||||
<h1>todos</h1>
|
||||
<input class="new-todo" autofocus="true" autocomplete="off" placeholder="What needs to be done?" t-on-keyup="addTodo"/>
|
||||
</header>
|
||||
<!-- main section -->
|
||||
<section class="main" t-if="props.todos.length">
|
||||
<input class="toggle-all" id="toggle-all" type="checkbox" t-att-checked="allChecked" t-on-click="toggleAll"/>
|
||||
<label for="toggle-all"></label>
|
||||
<ul class="todo-list">
|
||||
<t t-foreach="visibleTodos" t-as="todo">
|
||||
<t t-widget="TodoItem" t-key="todo.id" t-props="todo"/>
|
||||
</t>
|
||||
</ul>
|
||||
</section>
|
||||
<!-- footer -->
|
||||
<footer class="footer" t-if="props.todos.length">
|
||||
<span class="todo-count">
|
||||
<strong>
|
||||
<t t-esc="remaining"/>
|
||||
</strong>
|
||||
<t t-esc="remainingText"/>
|
||||
</span>
|
||||
<ul class="filters">
|
||||
<li>
|
||||
<a href="#/all" t-on-click="setFilter('all')" t-att-class="{selected: state.filter === 'all'}">All</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#/active" t-on-click="setFilter('active')" t-att-class="{selected: state.filter === 'active'}">Active</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#/completed" t-on-click="setFilter('completed')" t-att-class="{selected: state.filter === 'completed'}">Completed</a>
|
||||
</li>
|
||||
</ul>
|
||||
<button class="clear-completed" t-if="props.todos.length gt remaining" t-on-click="clearCompleted">
|
||||
Clear completed
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<li t-name="todoitem" class="todo" t-att-class="{completed: props.completed, editing: state.isEditing}">
|
||||
<div class="view">
|
||||
<input class="toggle" type="checkbox" t-on-change="toggleTodo" t-att-checked="props.completed"/>
|
||||
<label t-on-dblclick="editTodo">
|
||||
<t t-esc="props.title"/>
|
||||
</label>
|
||||
<button class="destroy" t-on-click="removeTodo"></button>
|
||||
</div>
|
||||
<input class="edit" t-ref="'input'" t-if="state.isEditing" t-att-value="props.title" t-on-keyup="handleKeyup" t-on-blur="handleBlur"/>
|
||||
</li>
|
||||
|
||||
</templates>
|
||||
@@ -1,9 +0,0 @@
|
||||
module.exports = {
|
||||
roots: ["<rootDir>/src", "<rootDir>/tests"],
|
||||
transform: {
|
||||
"^.+\\.ts?$": "ts-jest"
|
||||
},
|
||||
verbose: false,
|
||||
testRegex: "(/tests/.*(test|spec))\\.ts?$",
|
||||
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
|
||||
};
|
||||
@@ -1,64 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
||||
node_modules
|
||||
|
||||
# Vim
|
||||
*.swp
|
||||
|
||||
# Generated JavaScript
|
||||
/test/browserified.js
|
||||
/browserified.js
|
||||
/h.d.ts
|
||||
/h.js
|
||||
/h.js.map
|
||||
/hooks.d.ts
|
||||
/hooks.js
|
||||
/hooks.js.map
|
||||
/htmldomapi.d.ts
|
||||
/htmldomapi.js
|
||||
/htmldomapi.js.map
|
||||
/is.d.ts
|
||||
/is.js
|
||||
/is.js.map
|
||||
/snabbdom.bundle.d.ts
|
||||
/snabbdom.bundle.js
|
||||
/snabbdom.bundle.js.map
|
||||
/snabbdom.d.ts
|
||||
/snabbdom.js
|
||||
/snabbdom.js.map
|
||||
/thunk.d.ts
|
||||
/thunk.js
|
||||
/thunk.js.map
|
||||
/tovnode.d.ts
|
||||
/tovnode.js
|
||||
/tovnode.js.map
|
||||
/vnode.d.ts
|
||||
/vnode.js
|
||||
/vnode.js.map
|
||||
/modules
|
||||
/helpers
|
||||
/es
|
||||
@@ -1,33 +0,0 @@
|
||||
/test
|
||||
/perf
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
||||
node_modules
|
||||
|
||||
# Vim
|
||||
*.swp
|
||||
@@ -1,17 +0,0 @@
|
||||
sudo: false
|
||||
language: node_js
|
||||
node_js:
|
||||
- '6.10.1'
|
||||
script:
|
||||
- export IP_ADDR=$(ip addr | grep eth -A 4 | grep 'inet ' | awk '{ print $2 }' | sed 's/\/..//')
|
||||
- npm test
|
||||
addons:
|
||||
browserstack:
|
||||
username:
|
||||
secure: <TODO>
|
||||
access_key:
|
||||
secure: <TODO>
|
||||
env:
|
||||
global:
|
||||
- secure: <TODO>
|
||||
- secure: <TODO>
|
||||
@@ -1,22 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Simon Friis Vindum
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
@@ -1,758 +0,0 @@
|
||||
# Snabbdom
|
||||
|
||||
A virtual DOM library with focus on simplicity, modularity, powerful features
|
||||
and performance.
|
||||
|
||||
[](https://opensource.org/licenses/MIT) [](https://badge.fury.io/js/snabbdom) [](https://www.npmjs.com/package/snabbdom)
|
||||
|
||||
[](https://gitter.im/paldepind/snabbdom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Table of contents
|
||||
|
||||
* [Introduction](#introduction)
|
||||
* [Features](#features)
|
||||
* [Inline example](#inline-example)
|
||||
* [Examples](#examples)
|
||||
* [Core documentation](#core-documentation)
|
||||
* [Modules documentation](#modules-documentation)
|
||||
* [Helpers](#helpers)
|
||||
* [Virtual Node documentation](#virtual-node)
|
||||
* [Structuring applications](#structuring-applications)
|
||||
|
||||
## Why
|
||||
|
||||
Virtual DOM is awesome. It allows us to express our application's view
|
||||
as a function of its state. But existing solutions were way way too
|
||||
bloated, too slow, lacked features, had an API biased towards OOP
|
||||
and/or lacked features I needed.
|
||||
|
||||
## Introduction
|
||||
|
||||
Snabbdom consists of an extremely simple, performant and extensible
|
||||
core that is only ≈ 200 SLOC. It offers a modular architecture with
|
||||
rich functionality for extensions through custom modules. To keep the
|
||||
core simple, all non-essential functionality is delegated to modules.
|
||||
|
||||
You can mold Snabbdom into whatever you desire! Pick, choose and
|
||||
customize the functionality you want. Alternatively you can just use
|
||||
the default extensions and get a virtual DOM library with high
|
||||
performance, small size and all the features listed below.
|
||||
|
||||
## Features
|
||||
|
||||
* Core features
|
||||
* About 200 SLOC – you could easily read through the entire core and fully
|
||||
understand how it works.
|
||||
* Extendable through modules.
|
||||
* A rich set of hooks available, both per vnode and globally for modules,
|
||||
to hook into any part of the diff and patch process.
|
||||
* Splendid performance. Snabbdom is among the fastest virtual DOM libraries
|
||||
in the [Virtual DOM Benchmark](http://vdom-benchmark.github.io/vdom-benchmark/).
|
||||
* Patch function with a function signature equivalent to a reduce/scan
|
||||
function. Allows for easier integration with a FRP library.
|
||||
* Features in modules
|
||||
* `h` function for easily creating virtual DOM nodes.
|
||||
* [SVG _just works_ with the `h` helper](#svg).
|
||||
* Features for doing complex CSS animations.
|
||||
* Powerful event listener functionality.
|
||||
* [Thunks](#thunks) to optimize the diff and patch process even further.
|
||||
* Third party features
|
||||
* JSX support thanks to [snabbdom-pragma](https://github.com/Swizz/snabbdom-pragma).
|
||||
* Server-side HTML output provided by [snabbdom-to-html](https://github.com/acstll/snabbdom-to-html).
|
||||
* Compact virtual DOM creation with [snabbdom-helpers](https://github.com/krainboltgreene/snabbdom-helpers).
|
||||
* Template string support using [snabby](https://github.com/jamen/snabby).
|
||||
* Virtual DOM assertion with [snabbdom-looks-like](https://github.com/jvanbruegge/snabbdom-looks-like)
|
||||
|
||||
## Inline example
|
||||
|
||||
```javascript
|
||||
var snabbdom = require('snabbdom');
|
||||
var patch = snabbdom.init([ // Init patch function with chosen modules
|
||||
require('snabbdom/modules/class').default, // makes it easy to toggle classes
|
||||
require('snabbdom/modules/props').default, // for setting properties on DOM elements
|
||||
require('snabbdom/modules/style').default, // handles styling on elements with support for animations
|
||||
require('snabbdom/modules/eventlisteners').default, // attaches event listeners
|
||||
]);
|
||||
var h = require('snabbdom/h').default; // helper function for creating vnodes
|
||||
|
||||
var container = document.getElementById('container');
|
||||
|
||||
var vnode = h('div#container.two.classes', {on: {click: someFn}}, [
|
||||
h('span', {style: {fontWeight: 'bold'}}, 'This is bold'),
|
||||
' and this is just normal text',
|
||||
h('a', {props: {href: '/foo'}}, 'I\'ll take you places!')
|
||||
]);
|
||||
// Patch into empty DOM element – this modifies the DOM as a side effect
|
||||
patch(container, vnode);
|
||||
|
||||
var newVnode = h('div#container.two.classes', {on: {click: anotherEventHandler}}, [
|
||||
h('span', {style: {fontWeight: 'normal', fontStyle: 'italic'}}, 'This is now italic type'),
|
||||
' and this is still just normal text',
|
||||
h('a', {props: {href: '/bar'}}, 'I\'ll take you places!')
|
||||
]);
|
||||
// Second `patch` invocation
|
||||
patch(vnode, newVnode); // Snabbdom efficiently updates the old view to the new state
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
* [Animated reordering of elements](http://snabbdom.github.io/snabbdom/examples/reorder-animation/)
|
||||
* [Hero transitions](http://snabbdom.github.io/snabbdom/examples/hero/)
|
||||
* [SVG Carousel](http://snabbdom.github.io/snabbdom/examples/carousel-svg/)
|
||||
|
||||
## Core documentation
|
||||
|
||||
The core of Snabbdom provides only the most essential functionality.
|
||||
It is designed to be as simple as possible while still being fast and
|
||||
extendable.
|
||||
|
||||
### `snabbdom.init`
|
||||
|
||||
The core exposes only one single function `snabbdom.init`. This `init`
|
||||
takes a list of modules and returns a `patch` function that uses the
|
||||
specified set of modules.
|
||||
|
||||
```javascript
|
||||
var patch = snabbdom.init([
|
||||
require('snabbdom/modules/class').default,
|
||||
require('snabbdom/modules/style').default,
|
||||
]);
|
||||
```
|
||||
|
||||
### `patch`
|
||||
|
||||
The `patch` function returned by `init` takes two arguments. The first
|
||||
is a DOM element or a vnode representing the current view. The second
|
||||
is a vnode representing the new, updated view.
|
||||
|
||||
If a DOM element with a parent is passed, `newVnode` will be turned
|
||||
into a DOM node, and the passed element will be replaced by the
|
||||
created DOM node. If an old vnode is passed, Snabbdom will efficiently
|
||||
modify it to match the description in the new vnode.
|
||||
|
||||
Any old vnode passed must be the resulting vnode from a previous call
|
||||
to `patch`. This is necessary since Snabbdom stores information in the
|
||||
vnode. This makes it possible to implement a simpler and more
|
||||
performant architecture. This also avoids the creation of a new old
|
||||
vnode tree.
|
||||
|
||||
```javascript
|
||||
patch(oldVnode, newVnode);
|
||||
```
|
||||
|
||||
### `snabbdom/h`
|
||||
|
||||
It is recommended that you use `snabbdom/h` to create vnodes. `h` accepts a
|
||||
tag/selector as a string, an optional data object and an optional string or
|
||||
array of children.
|
||||
|
||||
```javascript
|
||||
var h = require('snabbdom/h').default;
|
||||
var vnode = h('div', {style: {color: '#000'}}, [
|
||||
h('h1', 'Headline'),
|
||||
h('p', 'A paragraph'),
|
||||
]);
|
||||
```
|
||||
|
||||
### `snabbdom/tovnode`
|
||||
|
||||
Converts a DOM node into a virtual node. Especially good for patching over an pre-existing,
|
||||
server-side generated content.
|
||||
|
||||
```javascript
|
||||
var snabbdom = require('snabbdom')
|
||||
var patch = snabbdom.init([ // Init patch function with chosen modules
|
||||
require('snabbdom/modules/class').default, // makes it easy to toggle classes
|
||||
require('snabbdom/modules/props').default, // for setting properties on DOM elements
|
||||
require('snabbdom/modules/style').default, // handles styling on elements with support for animations
|
||||
require('snabbdom/modules/eventlisteners').default, // attaches event listeners
|
||||
]);
|
||||
var h = require('snabbdom/h').default; // helper function for creating vnodes
|
||||
var toVNode = require('snabbdom/tovnode').default;
|
||||
|
||||
var newVNode = h('div', {style: {color: '#000'}}, [
|
||||
h('h1', 'Headline'),
|
||||
h('p', 'A paragraph'),
|
||||
]);
|
||||
|
||||
patch(toVNode(document.querySelector('.container')), newVNode)
|
||||
|
||||
```
|
||||
|
||||
### Hooks
|
||||
|
||||
Hooks are a way to hook into the lifecycle of DOM nodes. Snabbdom
|
||||
offers a rich selection of hooks. Hooks are used both by modules to
|
||||
extend Snabbdom, and in normal code for executing arbitrary code at
|
||||
desired points in the life of a virtual node.
|
||||
|
||||
#### Overview
|
||||
|
||||
| Name | Triggered when | Arguments to callback |
|
||||
| ----------- | -------------- | ----------------------- |
|
||||
| `pre` | the patch process begins | none |
|
||||
| `init` | a vnode has been added | `vnode` |
|
||||
| `create` | a DOM element has been created based on a vnode | `emptyVnode, vnode` |
|
||||
| `insert` | an element has been inserted into the DOM | `vnode` |
|
||||
| `prepatch` | an element is about to be patched | `oldVnode, vnode` |
|
||||
| `update` | an element is being updated | `oldVnode, vnode` |
|
||||
| `postpatch` | an element has been patched | `oldVnode, vnode` |
|
||||
| `destroy` | an element is directly or indirectly being removed | `vnode` |
|
||||
| `remove` | an element is directly being removed from the DOM | `vnode, removeCallback` |
|
||||
| `post` | the patch process is done | none |
|
||||
|
||||
The following hooks are available for modules: `pre`, `create`,
|
||||
`update`, `destroy`, `remove`, `post`.
|
||||
|
||||
The following hooks are available in the `hook` property of individual
|
||||
elements: `init`, `create`, `insert`, `prepatch`, `update`,
|
||||
`postpatch`, `destroy`, `remove`.
|
||||
|
||||
#### Usage
|
||||
|
||||
To use hooks, pass them as an object to `hook` field of the data
|
||||
object argument.
|
||||
|
||||
```javascript
|
||||
h('div.row', {
|
||||
key: movie.rank,
|
||||
hook: {
|
||||
insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight; }
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### The `init` hook
|
||||
|
||||
This hook is invoked during the patch process when a new virtual node
|
||||
has been found. The hook is called before Snabbdom has processed the
|
||||
node in any way. I.e., before it has created a DOM node based on the
|
||||
vnode.
|
||||
|
||||
#### The `insert` hook
|
||||
|
||||
This hook is invoked once the DOM element for a vnode has been
|
||||
inserted into the document _and_ the rest of the patch cycle is done.
|
||||
This means that you can do DOM measurements (like using
|
||||
[getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect)
|
||||
in this hook safely, knowing that no elements will be changed
|
||||
afterwards that could affect the position of the inserted elements.
|
||||
|
||||
#### The `remove` hook
|
||||
|
||||
Allows you to hook into the removal of an element. The hook is called
|
||||
once a vnode is to be removed from the DOM. The handling function
|
||||
receives both the vnode and a callback. You can control and delay the
|
||||
removal with the callback. The callback should be invoked once the
|
||||
hook is done doing its business, and the element will only be removed
|
||||
once all `remove` hooks have invoked their callback.
|
||||
|
||||
The hook is only triggered when an element is to be removed from its
|
||||
parent – not if it is the child of an element that is removed. For
|
||||
that, see the `destroy` hook.
|
||||
|
||||
#### The `destroy` hook
|
||||
|
||||
This hook is invoked on a virtual node when its DOM element is removed
|
||||
from the DOM or if its parent is being removed from the DOM.
|
||||
|
||||
To see the difference between this hook and the `remove` hook,
|
||||
consider an example.
|
||||
|
||||
```js
|
||||
var vnode1 = h('div', [h('div', [h('span', 'Hello')])]);
|
||||
var vnode2 = h('div', []);
|
||||
patch(container, vnode1);
|
||||
patch(vnode1, vnode2);
|
||||
```
|
||||
|
||||
Here `destroy` is triggered for both the inner `div` element _and_ the
|
||||
`span` element it contains. `remove`, on the other hand, is only
|
||||
triggered on the `div` element because it is the only element being
|
||||
detached from its parent.
|
||||
|
||||
You can, for instance, use `remove` to trigger an animation when an
|
||||
element is being removed and use the `destroy` hook to additionally
|
||||
animate the disappearance of the removed element's children.
|
||||
|
||||
### Creating modules
|
||||
|
||||
Modules works by registering global listeners for [hooks](#hooks). A module is simply a dictionary mapping hook names to functions.
|
||||
|
||||
```javascript
|
||||
var myModule = {
|
||||
create: function(oldVnode, vnode) {
|
||||
// invoked whenever a new virtual node is created
|
||||
},
|
||||
update: function(oldVnode, vnode) {
|
||||
// invoked whenever a virtual node is updated
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
With this mechanism you can easily augment the behaviour of Snabbdom.
|
||||
For demonstration, take a look at the implementations of the default
|
||||
modules.
|
||||
|
||||
## Modules documentation
|
||||
|
||||
This describes the core modules. All modules are optional.
|
||||
|
||||
### The class module
|
||||
|
||||
The class module provides an easy way to dynamically toggle classes on
|
||||
elements. It expects an object in the `class` data property. The
|
||||
object should map class names to booleans that indicates whether or
|
||||
not the class should stay or go on the vnode.
|
||||
|
||||
```javascript
|
||||
h('a', {class: {active: true, selected: false}}, 'Toggle');
|
||||
```
|
||||
|
||||
### The props module
|
||||
|
||||
Allows you to set properties on DOM elements.
|
||||
|
||||
```javascript
|
||||
h('a', {props: {href: '/foo'}}, 'Go to Foo');
|
||||
```
|
||||
|
||||
### The attributes module
|
||||
|
||||
Same as props, but set attributes instead of properties on DOM elements.
|
||||
|
||||
```javascript
|
||||
h('a', {attrs: {href: '/foo'}}, 'Go to Foo');
|
||||
```
|
||||
|
||||
Attributes are added and updated using `setAttribute`. In case of an
|
||||
attribute that had been previously added/set and is no longer present
|
||||
in the `attrs` object, it is removed from the DOM element's attribute
|
||||
list using `removeAttribute`.
|
||||
|
||||
In the case of boolean attributes (e.g. `disabled`, `hidden`,
|
||||
`selected` ...), the meaning doesn't depend on the attribute value
|
||||
(`true` or `false`) but depends instead on the presence/absence of the
|
||||
attribute itself in the DOM element. Those attributes are handled
|
||||
differently by the module: if a boolean attribute is set to a
|
||||
[falsy value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
|
||||
(`0`, `-0`, `null`, `false`,`NaN`, `undefined`, or the empty string
|
||||
(`""`)), then the attribute will be removed from the attribute list of
|
||||
the DOM element.
|
||||
|
||||
### The dataset module
|
||||
|
||||
Allows you to set custom data attributes (`data-*`) on DOM elements. These can then be accessed with the [HTMLElement.dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property.
|
||||
|
||||
```javascript
|
||||
h('button', {dataset: {action: 'reset'}}, 'Reset');
|
||||
```
|
||||
|
||||
### The style module
|
||||
|
||||
The style module is for making your HTML look slick and animate smoothly. At
|
||||
its core it allows you to set CSS properties on elements.
|
||||
|
||||
```javascript
|
||||
h('span', {
|
||||
style: {border: '1px solid #bada55', color: '#c0ffee', fontWeight: 'bold'}
|
||||
}, 'Say my name, and every colour illuminates');
|
||||
```
|
||||
|
||||
Note that the style module does not remove style attributes if they
|
||||
are removed as properties from the style object. To remove a style,
|
||||
you should instead set it to the empty string.
|
||||
|
||||
```javascript
|
||||
h('div', {
|
||||
style: {position: shouldFollow ? 'fixed' : ''}
|
||||
}, 'I, I follow, I follow you');
|
||||
```
|
||||
|
||||
#### Custom properties (CSS variables)
|
||||
|
||||
CSS custom properties (aka CSS variables) are supported, they must be prefixed
|
||||
with `--`
|
||||
|
||||
```javascript
|
||||
h('div', {
|
||||
style: {'--warnColor': 'yellow'}
|
||||
}, 'Warning');
|
||||
```
|
||||
|
||||
#### Delayed properties
|
||||
|
||||
You can specify properties as being delayed. Whenever these properties
|
||||
change, the change is not applied until after the next frame.
|
||||
|
||||
```javascript
|
||||
h('span', {
|
||||
style: {opacity: '0', transition: 'opacity 1s', delayed: {opacity: '1'}}
|
||||
}, 'Imma fade right in!');
|
||||
```
|
||||
|
||||
This makes it easy to declaratively animate the entry of elements.
|
||||
|
||||
#### Set properties on `remove`
|
||||
|
||||
Styles set in the `remove` property will take effect once the element
|
||||
is about to be removed from the DOM. The applied styles should be
|
||||
animated with CSS transitions. Only once all the styles are done
|
||||
animating will the element be removed from the DOM.
|
||||
|
||||
```javascript
|
||||
h('span', {
|
||||
style: {opacity: '1', transition: 'opacity 1s',
|
||||
remove: {opacity: '0'}}
|
||||
}, 'It\'s better to fade out than to burn away');
|
||||
```
|
||||
|
||||
This makes it easy to declaratively animate the removal of elements.
|
||||
|
||||
#### Set properties on `destroy`
|
||||
|
||||
```javascript
|
||||
h('span', {
|
||||
style: {opacity: '1', transition: 'opacity 1s',
|
||||
destroy: {opacity: '0'}}
|
||||
}, 'It\'s better to fade out than to burn away');
|
||||
```
|
||||
|
||||
### Eventlisteners module
|
||||
|
||||
The event listeners module gives powerful capabilities for attaching
|
||||
event listeners.
|
||||
|
||||
You can attach a function to an event on a vnode by supplying an
|
||||
object at `on` with a property corresponding to the name of the event
|
||||
you want to listen to. The function will be called when the event
|
||||
happens and will be passed the event object that belongs to it.
|
||||
|
||||
```javascript
|
||||
function clickHandler(ev) { console.log('got clicked'); }
|
||||
h('div', {on: {click: clickHandler}});
|
||||
```
|
||||
|
||||
Very often, however, you're not really interested in the event object
|
||||
itself. Often you have some data associated with the element that
|
||||
triggers an event and you want that data passed along instead.
|
||||
|
||||
Consider a counter application with three buttons, one to increment
|
||||
the counter by 1, one to increment the counter by 2 and one to
|
||||
increment the counter by 3. You don't really care exactly which button
|
||||
was pressed. Instead you're interested in what number was associated
|
||||
with the clicked button. The event listeners module allows one to
|
||||
express that by supplying an array at the named event property. The
|
||||
first element in the array should be a function that will be invoked
|
||||
with the value in the second element once the event occurs.
|
||||
|
||||
```javascript
|
||||
function clickHandler(number) { console.log('button ' + number + ' was clicked!'); }
|
||||
h('div', [
|
||||
h('a', {on: {click: [clickHandler, 1]}}),
|
||||
h('a', {on: {click: [clickHandler, 2]}}),
|
||||
h('a', {on: {click: [clickHandler, 3]}}),
|
||||
]);
|
||||
```
|
||||
|
||||
Each handler is called not only with the given arguments but also with the current event and vnode appended to the argument list. It also supports using multiple listeners per event by specifying an array of handlers:
|
||||
```javascript
|
||||
stopPropagation = function(ev) { ev.stopPropagation() }
|
||||
sendValue = function(func, ev, vnode) { func(vnode.elm.value) }
|
||||
|
||||
h('a', { on:{ click:[[sendValue, console.log], stopPropagation] } });
|
||||
```
|
||||
|
||||
Snabbdom allows swapping event handlers between renders. This happens without
|
||||
actually touching the event handlers attached to the DOM.
|
||||
|
||||
Note, however, that **you should be careful when sharing event
|
||||
handlers between vnodes**, because of the technique this module uses
|
||||
to avoid re-binding event handlers to the DOM. (And in general,
|
||||
sharing data between vnodes is not guaranteed to work, because modules
|
||||
are allowed to mutate the given data).
|
||||
|
||||
In particular, you should **not** do something like this:
|
||||
|
||||
```javascript
|
||||
// Does not work
|
||||
var sharedHandler = {
|
||||
change: function(e){ console.log('you chose: ' + e.target.value); }
|
||||
};
|
||||
h('div', [
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '0'},
|
||||
on: sharedHandler}),
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '1'},
|
||||
on: sharedHandler}),
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '2'},
|
||||
on: sharedHandler})
|
||||
]);
|
||||
```
|
||||
|
||||
For many such cases, you can use array-based handlers instead (described above).
|
||||
Alternatively, simply make sure each node is passed unique `on` values:
|
||||
|
||||
```javascript
|
||||
// Works
|
||||
var sharedHandler = function(e){ console.log('you chose: ' + e.target.value); };
|
||||
h('div', [
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '0'},
|
||||
on: {change: sharedHandler}}),
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '1'},
|
||||
on: {change: sharedHandler}}),
|
||||
h('input', {props: {type: 'radio', name: 'test', value: '2'},
|
||||
on: {change: sharedHandler}})
|
||||
]);
|
||||
```
|
||||
|
||||
## Helpers
|
||||
|
||||
### SVG
|
||||
|
||||
SVG just works when using the `h` function for creating virtual
|
||||
nodes. SVG elements are automatically created with the appropriate
|
||||
namespaces.
|
||||
|
||||
```javascript
|
||||
var vnode = h('div', [
|
||||
h('svg', {attrs: {width: 100, height: 100}}, [
|
||||
h('circle', {attrs: {cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow'}})
|
||||
])
|
||||
]);
|
||||
```
|
||||
|
||||
See also the [SVG example](./examples/svg) and the [SVG Carousel example](./examples/carousel-svg/).
|
||||
|
||||
#### Using Classes in SVG Elements
|
||||
|
||||
Certain browsers (like IE <=11) [do not support `classList` property in SVG elements](http://caniuse.com/#feat=classlist).
|
||||
Hence, the _class_ module (which uses `classList` property internally) will not work for these browsers.
|
||||
|
||||
The classes in selectors for SVG elements work fine from version 0.6.7.
|
||||
|
||||
You can add dynamic classes to SVG elements for these cases by using the _attributes_ module and an Array as shown below:
|
||||
|
||||
```js
|
||||
h('svg', [
|
||||
h('text.underline', { // 'underline' is a selector class, remain unchanged between renders.
|
||||
attrs: {
|
||||
// 'active' and 'red' are dynamic classes, they can change between renders
|
||||
// so we need to put them in the class attribute.
|
||||
// (Normally we'd use the classModule, but it doesn't work inside SVG)
|
||||
class: [isActive && "active", isColored && "red"].filter(Boolean).join(" ")
|
||||
}
|
||||
},
|
||||
'Hello World'
|
||||
)
|
||||
])
|
||||
```
|
||||
|
||||
### Thunks
|
||||
|
||||
The `thunk` function takes a selector, a key for identifying a thunk,
|
||||
a function that returns a vnode and a variable amount of state
|
||||
parameters. If invoked, the render function will receive the state
|
||||
arguments.
|
||||
|
||||
`thunk(selector, key, renderFn, [stateArguments])`
|
||||
|
||||
The `key` is optional. It should be supplied when the `selector` is
|
||||
not unique among the thunks siblings. This ensures that the thunk is
|
||||
always matched correctly when diffing.
|
||||
|
||||
Thunks are an optimization strategy that can be used when one is
|
||||
dealing with immutable data.
|
||||
|
||||
Consider a simple function for creating a virtual node based on a number.
|
||||
|
||||
```js
|
||||
function numberView(n) {
|
||||
return h('div', 'Number is: ' + n);
|
||||
}
|
||||
```
|
||||
|
||||
The view depends only on `n`. This means that if `n` is unchanged,
|
||||
then creating the virtual DOM node and patching it against the old
|
||||
vnode is wasteful. To avoid the overhead we can use the `thunk` helper
|
||||
function.
|
||||
|
||||
```js
|
||||
function render(state) {
|
||||
return thunk('num', numberView, [state.number]);
|
||||
}
|
||||
```
|
||||
|
||||
Instead of actually invoking the `numberView` function this will only
|
||||
place a dummy vnode in the virtual tree. When Snabbdom patches this
|
||||
dummy vnode against a previous vnode, it will compare the value of
|
||||
`n`. If `n` is unchanged it will simply reuse the old vnode. This
|
||||
avoids recreating the number view and the diff process altogether.
|
||||
|
||||
The view function here is only an example. In practice thunks are only
|
||||
relevant if you are rendering a complicated view that takes
|
||||
significant computational time to generate.
|
||||
|
||||
## Virtual Node
|
||||
**Properties**
|
||||
- [sel](#sel--string)
|
||||
- [data](#data--object)
|
||||
- [children](#children--array)
|
||||
- [text](#text--string)
|
||||
- [elm](#elm--element)
|
||||
- [key](#key--string--number)
|
||||
|
||||
#### sel : String
|
||||
|
||||
The `.sel` property of a virtual node is the CSS selector passed to
|
||||
[`h()`](#snabbdomh) during creation. For example: `h('div#container',
|
||||
{}, [...])` will create a a virtual node which has `div#container` as
|
||||
its `.sel` property.
|
||||
|
||||
#### data : Object
|
||||
|
||||
The `.data` property of a virtual node is the place to add information
|
||||
for [modules](#modules-documentation) to access and manipulate the
|
||||
real DOM element when it is created; Add styles, CSS classes,
|
||||
attributes, etc.
|
||||
|
||||
The data object is the (optional) second parameter to [`h()`](#snabbdomh)
|
||||
|
||||
For example `h('div', {props: {className: 'container'}}, [...])` will produce a virtual node with
|
||||
```js
|
||||
{
|
||||
"props": {
|
||||
className: "container"
|
||||
}
|
||||
}
|
||||
```
|
||||
as its `.data` object.
|
||||
|
||||
#### children : Array<vnode>
|
||||
|
||||
The `.children` property of a virtual node is the third (optional)
|
||||
parameter to [`h()`](#snabbdomh) during creation. `.children` is
|
||||
simply an Array of virtual nodes that should be added as children of
|
||||
the parent DOM node upon creation.
|
||||
|
||||
For example `h('div', {}, [ h('h1', {}, 'Hello, World') ])` will
|
||||
create a virtual node with
|
||||
|
||||
```js
|
||||
[
|
||||
{
|
||||
sel: 'h1',
|
||||
data: {},
|
||||
children: undefined,
|
||||
text: 'Hello, World',
|
||||
elm: Element,
|
||||
key: undefined,
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
as its `.children` property.
|
||||
|
||||
#### text : string
|
||||
|
||||
The `.text` property is created when a virtual node is created with
|
||||
only a single child that possesses text and only requires
|
||||
`document.createTextNode()` to be used.
|
||||
|
||||
For example: `h('h1', {}, 'Hello')` will create a virtual node with
|
||||
`Hello` as its `.text` property.
|
||||
|
||||
#### elm : Element
|
||||
|
||||
The `.elm` property of a virtual node is a pointer to the real DOM
|
||||
node created by snabbdom. This property is very useful to do
|
||||
calculations in [hooks](#hooks) as well as
|
||||
[modules](#modules-documentation).
|
||||
|
||||
#### key : string | number
|
||||
|
||||
The `.key` property is created when a key is provided inside of your
|
||||
[`.data`](#data--object) object. The `.key` property is used to keep
|
||||
pointers to DOM nodes that existed previously to avoid recreating them
|
||||
if it is unnecessary. This is very useful for things like list
|
||||
reordering. A key must be either a string or a number to allow for
|
||||
proper lookup as it is stored internally as a key/value pair inside of
|
||||
an object, where `.key` is the key and the value is the
|
||||
[`.elm`](#elm--element) property created.
|
||||
|
||||
For example: `h('div', {key: 1}, [])` will create a virtual node
|
||||
object with a `.key` property with the value of `1`.
|
||||
|
||||
|
||||
## Structuring applications
|
||||
|
||||
Snabbdom is a low-level virtual DOM library. It is unopinionated with
|
||||
regards to how you should structure your application.
|
||||
|
||||
Here are some approaches to building applications with Snabbdom.
|
||||
|
||||
* [functional-frontend-architecture](https://github.com/paldepind/functional-frontend-architecture) –
|
||||
a repository containing several example applications that
|
||||
demonstrates an architecture that uses Snabbdom.
|
||||
* [Cycle.js](https://cycle.js.org/) –
|
||||
"A functional and reactive JavaScript framework for cleaner code"
|
||||
uses Snabbdom
|
||||
* [Vue.js](http://vuejs.org/) use a fork of snabbdom.
|
||||
* [scheme-todomvc](https://github.com/amirouche/scheme-todomvc/) build
|
||||
redux-like architecture on top of snabbdom bindings.
|
||||
* [kaiju](https://github.com/AlexGalays/kaiju) -
|
||||
Stateful components and observables on top of snabbdom
|
||||
* [Tweed](https://tweedjs.github.io) –
|
||||
An Object Oriented approach to reactive interfaces.
|
||||
* [Cyclow](http://cyclow.js.org) -
|
||||
"A reactive frontend framework for JavaScript"
|
||||
uses Snabbdom
|
||||
* [Tung](https://github.com/Reon90/tung) –
|
||||
A JavaScript library for rendering html. Tung helps to divide html and JavaScript development.
|
||||
* [sprotty](https://github.com/theia-ide/sprotty) - "A web-based diagramming framework" uses Snabbdom.
|
||||
* [Mark Text](https://github.com/marktext/marktext) - "Realtime preview Markdown Editor" build on Snabbdom.
|
||||
* [puddles](https://github.com/flintinatux/puddles) -
|
||||
"Tiny vdom app framework. Pure Redux. No boilerplate." - Built with :heart: on Snabbdom.
|
||||
* [Backbone.VDOMView](https://github.com/jcbrand/backbone.vdomview) - A [Backbone](http://backbonejs.org/) View with VirtualDOM capability via Snabbdom.
|
||||
|
||||
Be sure to share it if you're building an application in another way
|
||||
using Snabbdom.
|
||||
|
||||
## Common errors
|
||||
|
||||
```
|
||||
Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node':
|
||||
The node before which the new node is to be inserted is not a child of this node.
|
||||
```
|
||||
The reason for this error is reusing of vnodes between patches (see code example), snabbdom stores actual dom nodes inside the virtual dom nodes passed to it as performance improvement, so reusing nodes between patches is not supported.
|
||||
```js
|
||||
var sharedNode = h('div', {}, 'Selected');
|
||||
var vnode1 = h('div', [
|
||||
h('div', {}, ['One']),
|
||||
h('div', {}, ['Two']),
|
||||
h('div', {}, [sharedNode]),
|
||||
]);
|
||||
var vnode2 = h('div', [
|
||||
h('div', {}, ['One']),
|
||||
h('div', {}, [sharedNode]),
|
||||
h('div', {}, ['Three']),
|
||||
]);
|
||||
patch(container, vnode1);
|
||||
patch(vnode1, vnode2);
|
||||
```
|
||||
You can fix this issue by creating a shallow copy of the object (here with object spread syntax):
|
||||
```js
|
||||
var vnode2 = h('div', [
|
||||
h('div', {}, ['One']),
|
||||
h('div', {}, [{ ...sharedNode }]),
|
||||
h('div', {}, ['Three']),
|
||||
]);
|
||||
```
|
||||
Another solution would be to wrap shared vnodes in a factory function:
|
||||
```js
|
||||
var sharedNode = () => h('div', {}, 'Selected');
|
||||
var vnode1 = h('div', [
|
||||
h('div', {}, ['One']),
|
||||
h('div', {}, ['Two']),
|
||||
h('div', {}, [sharedNode()]),
|
||||
]);
|
||||
```
|
||||
@@ -1,95 +0,0 @@
|
||||
module.exports = {
|
||||
// Latest mainstream
|
||||
BS_Chrome_Current: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'chrome',
|
||||
browser_version: 'latest',
|
||||
os: 'Windows',
|
||||
os_version: '10',
|
||||
},
|
||||
BS_Firefox_Current: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'firefox',
|
||||
browser_version: 'latest',
|
||||
os: 'Windows',
|
||||
os_version: '10',
|
||||
},
|
||||
BS_Safari_Current: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'safari',
|
||||
browser_version: 'latest',
|
||||
os: 'OS X',
|
||||
os_version: 'High Sierra',
|
||||
},
|
||||
BS_Android_8: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'Android',
|
||||
device: 'Google Pixel 2',
|
||||
os: 'Android',
|
||||
os_version: '8.0',
|
||||
real_mobile: true,
|
||||
},
|
||||
|
||||
// Older mainstream
|
||||
BS_Chrome_49: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'chrome',
|
||||
browser_version: '49',
|
||||
os: 'Windows',
|
||||
os_version: '10',
|
||||
},
|
||||
BS_Firefox_52: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'firefox',
|
||||
browser_version: '52',
|
||||
os: 'Windows',
|
||||
os_version: '10',
|
||||
},
|
||||
BS_Safari_9: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'safari',
|
||||
browser_version: '9.1',
|
||||
os: 'OS X',
|
||||
os_version: 'El Capitan',
|
||||
},
|
||||
|
||||
// Misc
|
||||
BS_Android_4_4: {
|
||||
base: 'BrowserStack',
|
||||
device_browser: 'ucbrowser',
|
||||
device: 'Google Nexus 5',
|
||||
os: 'Android',
|
||||
os_version: '4.4',
|
||||
real_mobile: true,
|
||||
},
|
||||
BS_iphone_10: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'Mobile Safari',
|
||||
browser_version: null,
|
||||
device: 'iPhone 7',
|
||||
real_mobile: true,
|
||||
os: 'ios',
|
||||
os_version: '10.3',
|
||||
},
|
||||
BS_MS_Edge: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'edge',
|
||||
browser_version: 'latest',
|
||||
os: 'Windows',
|
||||
os_version: '10',
|
||||
},
|
||||
BS_IE_11: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'ie',
|
||||
browser_version: '11.0',
|
||||
os: 'Windows',
|
||||
os_version: '7',
|
||||
},
|
||||
BS_IE_10: {
|
||||
base: 'BrowserStack',
|
||||
browser: 'ie',
|
||||
browser_version: '10.0',
|
||||
os: 'Windows',
|
||||
os_version: '7',
|
||||
},
|
||||
};
|
||||
Vendored
-83
@@ -1,83 +0,0 @@
|
||||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.h = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var vnode_1 = require("./vnode");
|
||||
var is = require("./is");
|
||||
function addNS(data, children, sel) {
|
||||
data.ns = 'http://www.w3.org/2000/svg';
|
||||
if (sel !== 'foreignObject' && children !== undefined) {
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
var childData = children[i].data;
|
||||
if (childData !== undefined) {
|
||||
addNS(childData, children[i].children, children[i].sel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function h(sel, b, c) {
|
||||
var data = {}, children, text, i;
|
||||
if (c !== undefined) {
|
||||
data = b;
|
||||
if (is.array(c)) {
|
||||
children = c;
|
||||
}
|
||||
else if (is.primitive(c)) {
|
||||
text = c;
|
||||
}
|
||||
else if (c && c.sel) {
|
||||
children = [c];
|
||||
}
|
||||
}
|
||||
else if (b !== undefined) {
|
||||
if (is.array(b)) {
|
||||
children = b;
|
||||
}
|
||||
else if (is.primitive(b)) {
|
||||
text = b;
|
||||
}
|
||||
else if (b && b.sel) {
|
||||
children = [b];
|
||||
}
|
||||
else {
|
||||
data = b;
|
||||
}
|
||||
}
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i]))
|
||||
children[i] = vnode_1.vnode(undefined, undefined, undefined, children[i]);
|
||||
}
|
||||
}
|
||||
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g' &&
|
||||
(sel.length === 3 || sel[3] === '.' || sel[3] === '#')) {
|
||||
addNS(data, children, sel);
|
||||
}
|
||||
return vnode_1.vnode(sel, data, children, text, undefined);
|
||||
}
|
||||
exports.h = h;
|
||||
;
|
||||
exports.default = h;
|
||||
|
||||
},{"./is":2,"./vnode":3}],2:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.array = Array.isArray;
|
||||
function primitive(s) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
}
|
||||
exports.primitive = primitive;
|
||||
|
||||
},{}],3:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function vnode(sel, data, children, text, elm) {
|
||||
var key = data === undefined ? undefined : data.key;
|
||||
return { sel: sel, data: data, children: children,
|
||||
text: text, elm: elm, key: key };
|
||||
}
|
||||
exports.vnode = vnode;
|
||||
exports.default = vnode;
|
||||
|
||||
},{}]},{},[1])(1)
|
||||
});
|
||||
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwiaC5qcyIsImlzLmpzIiwidm5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQzFEQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQ1BBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xudmFyIHZub2RlXzEgPSByZXF1aXJlKFwiLi92bm9kZVwiKTtcbnZhciBpcyA9IHJlcXVpcmUoXCIuL2lzXCIpO1xuZnVuY3Rpb24gYWRkTlMoZGF0YSwgY2hpbGRyZW4sIHNlbCkge1xuICAgIGRhdGEubnMgPSAnaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnO1xuICAgIGlmIChzZWwgIT09ICdmb3JlaWduT2JqZWN0JyAmJiBjaGlsZHJlbiAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgY2hpbGRyZW4ubGVuZ3RoOyArK2kpIHtcbiAgICAgICAgICAgIHZhciBjaGlsZERhdGEgPSBjaGlsZHJlbltpXS5kYXRhO1xuICAgICAgICAgICAgaWYgKGNoaWxkRGF0YSAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgYWRkTlMoY2hpbGREYXRhLCBjaGlsZHJlbltpXS5jaGlsZHJlbiwgY2hpbGRyZW5baV0uc2VsKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbn1cbmZ1bmN0aW9uIGgoc2VsLCBiLCBjKSB7XG4gICAgdmFyIGRhdGEgPSB7fSwgY2hpbGRyZW4sIHRleHQsIGk7XG4gICAgaWYgKGMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBkYXRhID0gYjtcbiAgICAgICAgaWYgKGlzLmFycmF5KGMpKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IGM7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaXMucHJpbWl0aXZlKGMpKSB7XG4gICAgICAgICAgICB0ZXh0ID0gYztcbiAgICAgICAgfVxuICAgICAgICBlbHNlIGlmIChjICYmIGMuc2VsKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IFtjXTtcbiAgICAgICAgfVxuICAgIH1cbiAgICBlbHNlIGlmIChiICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKGlzLmFycmF5KGIpKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IGI7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaXMucHJpbWl0aXZlKGIpKSB7XG4gICAgICAgICAgICB0ZXh0ID0gYjtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIGlmIChiICYmIGIuc2VsKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IFtiXTtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIGRhdGEgPSBiO1xuICAgICAgICB9XG4gICAgfVxuICAgIGlmIChpcy5hcnJheShjaGlsZHJlbikpIHtcbiAgICAgICAgZm9yIChpID0gMDsgaSA8IGNoaWxkcmVuLmxlbmd0aDsgKytpKSB7XG4gICAgICAgICAgICBpZiAoaXMucHJpbWl0aXZlKGNoaWxkcmVuW2ldKSlcbiAgICAgICAgICAgICAgICBjaGlsZHJlbltpXSA9IHZub2RlXzEudm5vZGUodW5kZWZpbmVkLCB1bmRlZmluZWQsIHVuZGVmaW5lZCwgY2hpbGRyZW5baV0pO1xuICAgICAgICB9XG4gICAgfVxuICAgIGlmIChzZWxbMF0gPT09ICdzJyAmJiBzZWxbMV0gPT09ICd2JyAmJiBzZWxbMl0gPT09ICdnJyAmJlxuICAgICAgICAoc2VsLmxlbmd0aCA9PT0gMyB8fCBzZWxbM10gPT09ICcuJyB8fCBzZWxbM10gPT09ICcjJykpIHtcbiAgICAgICAgYWRkTlMoZGF0YSwgY2hpbGRyZW4sIHNlbCk7XG4gICAgfVxuICAgIHJldHVybiB2bm9kZV8xLnZub2RlKHNlbCwgZGF0YSwgY2hpbGRyZW4sIHRleHQsIHVuZGVmaW5lZCk7XG59XG5leHBvcnRzLmggPSBoO1xuO1xuZXhwb3J0cy5kZWZhdWx0ID0gaDtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWguanMubWFwIiwiXCJ1c2Ugc3RyaWN0XCI7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoZXhwb3J0cywgXCJfX2VzTW9kdWxlXCIsIHsgdmFsdWU6IHRydWUgfSk7XG5leHBvcnRzLmFycmF5ID0gQXJyYXkuaXNBcnJheTtcbmZ1bmN0aW9uIHByaW1pdGl2ZShzKSB7XG4gICAgcmV0dXJuIHR5cGVvZiBzID09PSAnc3RyaW5nJyB8fCB0eXBlb2YgcyA9PT0gJ251bWJlcic7XG59XG5leHBvcnRzLnByaW1pdGl2ZSA9IHByaW1pdGl2ZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWlzLmpzLm1hcCIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xuZnVuY3Rpb24gdm5vZGUoc2VsLCBkYXRhLCBjaGlsZHJlbiwgdGV4dCwgZWxtKSB7XG4gICAgdmFyIGtleSA9IGRhdGEgPT09IHVuZGVmaW5lZCA/IHVuZGVmaW5lZCA6IGRhdGEua2V5O1xuICAgIHJldHVybiB7IHNlbDogc2VsLCBkYXRhOiBkYXRhLCBjaGlsZHJlbjogY2hpbGRyZW4sXG4gICAgICAgIHRleHQ6IHRleHQsIGVsbTogZWxtLCBrZXk6IGtleSB9O1xufVxuZXhwb3J0cy52bm9kZSA9IHZub2RlO1xuZXhwb3J0cy5kZWZhdWx0ID0gdm5vZGU7XG4vLyMgc291cmNlTWFwcGluZ1VSTD12bm9kZS5qcy5tYXAiXX0=
|
||||
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.h=e()}}(function(){return function e(r,n,i){function t(f,u){if(!n[f]){if(!r[f]){var d="function"==typeof require&&require;if(!u&&d)return d(f,!0);if(o)return o(f,!0);var a=new Error("Cannot find module '"+f+"'");throw a.code="MODULE_NOT_FOUND",a}var v=n[f]={exports:{}};r[f][0].call(v.exports,function(e){var n=r[f][1][e];return t(n?n:e)},v,v.exports,e,r,n,i)}return n[f].exports}for(var o="function"==typeof require&&require,f=0;f<i.length;f++)t(i[f]);return t}({1:[function(e,r,n){"use strict";function i(e,r,n){if(e.ns="http://www.w3.org/2000/svg","foreignObject"!==n&&void 0!==r)for(var t=0;t<r.length;++t){var o=r[t].data;void 0!==o&&i(o,r[t].children,r[t].sel)}}function t(e,r,n){var t,u,d,a={};if(void 0!==n?(a=r,f.array(n)?t=n:f.primitive(n)?u=n:n&&n.sel&&(t=[n])):void 0!==r&&(f.array(r)?t=r:f.primitive(r)?u=r:r&&r.sel?t=[r]:a=r),f.array(t))for(d=0;d<t.length;++d)f.primitive(t[d])&&(t[d]=o.vnode(void 0,void 0,void 0,t[d]));return"s"!==e[0]||"v"!==e[1]||"g"!==e[2]||3!==e.length&&"."!==e[3]&&"#"!==e[3]||i(a,t,e),o.vnode(e,a,t,u,void 0)}var o=e("./vnode"),f=e("./is");n.h=t,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=t},{"./is":2,"./vnode":3}],2:[function(e,r,n){"use strict";function i(e){return"string"==typeof e||"number"==typeof e}n.array=Array.isArray,n.primitive=i},{}],3:[function(e,r,n){"use strict";function i(e,r,n,i,t){var o=void 0===r?void 0:r.key;return{sel:e,data:r,children:n,text:i,elm:t,key:o}}n.vnode=i,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=h.min.js.map
|
||||
Vendored
-1
File diff suppressed because one or more lines are too long
-71
File diff suppressed because one or more lines are too long
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.snabbdom_attributes=e()}}(function(){return function e(t,r,n){function o(a,u){if(!r[a]){if(!t[a]){var d="function"==typeof require&&require;if(!u&&d)return d(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var f=r[a]={exports:{}};t[a][0].call(f.exports,function(e){var r=t[a][1][e];return o(r?r:e)},f,f.exports,e,t,r,n)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a<n.length;a++)o(n[a]);return o}({1:[function(e,t,r){"use strict";function n(e,t){var r,n,i,u,d=t.elm,l=e.data.attrs,f=t.data.attrs;if((l||f)&&l!==f){l=l||{},f=f||{};for(r in f)n=f[r],i=l[r],i!==n&&(!n&&a[r]?d.removeAttribute(r):(u=r.split(":"),u.length>1&&o.hasOwnProperty(u[0])?d.setAttributeNS(o[u[0]],r,n):d.setAttribute(r,n)));for(r in l)r in f||d.removeAttribute(r)}}for(var o={xlink:"http://www.w3.org/1999/xlink"},i=["allowfullscreen","async","autofocus","autoplay","checked","compact","controls","declare","default","defaultchecked","defaultmuted","defaultselected","defer","disabled","draggable","enabled","formnovalidate","hidden","indeterminate","inert","ismap","itemscope","loop","multiple","muted","nohref","noresize","noshade","novalidate","nowrap","open","pauseonexit","readonly","required","reversed","scoped","seamless","selected","sortable","spellcheck","translate","truespeed","typemustmatch","visible"],a=Object.create(null),u=0,d=i.length;u<d;u++)a[i[u]]=!0;r.attributesModule={create:n,update:n},Object.defineProperty(r,"__esModule",{value:!0}),r["default"]=r.attributesModule},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=snabbdom-attributes.min.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
-29
@@ -1,29 +0,0 @@
|
||||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_class = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function updateClass(oldVnode, vnode) {
|
||||
var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class, klass = vnode.data.class;
|
||||
if (!oldClass && !klass)
|
||||
return;
|
||||
if (oldClass === klass)
|
||||
return;
|
||||
oldClass = oldClass || {};
|
||||
klass = klass || {};
|
||||
for (name in oldClass) {
|
||||
if (!klass[name]) {
|
||||
elm.classList.remove(name);
|
||||
}
|
||||
}
|
||||
for (name in klass) {
|
||||
cur = klass[name];
|
||||
if (cur !== oldClass[name]) {
|
||||
elm.classList[cur ? 'add' : 'remove'](name);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.classModule = { create: updateClass, update: updateClass };
|
||||
exports.default = exports.classModule;
|
||||
|
||||
},{}]},{},[1])(1)
|
||||
});
|
||||
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwibW9kdWxlcy9jbGFzcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xuZnVuY3Rpb24gdXBkYXRlQ2xhc3Mob2xkVm5vZGUsIHZub2RlKSB7XG4gICAgdmFyIGN1ciwgbmFtZSwgZWxtID0gdm5vZGUuZWxtLCBvbGRDbGFzcyA9IG9sZFZub2RlLmRhdGEuY2xhc3MsIGtsYXNzID0gdm5vZGUuZGF0YS5jbGFzcztcbiAgICBpZiAoIW9sZENsYXNzICYmICFrbGFzcylcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGRDbGFzcyA9PT0ga2xhc3MpXG4gICAgICAgIHJldHVybjtcbiAgICBvbGRDbGFzcyA9IG9sZENsYXNzIHx8IHt9O1xuICAgIGtsYXNzID0ga2xhc3MgfHwge307XG4gICAgZm9yIChuYW1lIGluIG9sZENsYXNzKSB7XG4gICAgICAgIGlmICgha2xhc3NbbmFtZV0pIHtcbiAgICAgICAgICAgIGVsbS5jbGFzc0xpc3QucmVtb3ZlKG5hbWUpO1xuICAgICAgICB9XG4gICAgfVxuICAgIGZvciAobmFtZSBpbiBrbGFzcykge1xuICAgICAgICBjdXIgPSBrbGFzc1tuYW1lXTtcbiAgICAgICAgaWYgKGN1ciAhPT0gb2xkQ2xhc3NbbmFtZV0pIHtcbiAgICAgICAgICAgIGVsbS5jbGFzc0xpc3RbY3VyID8gJ2FkZCcgOiAncmVtb3ZlJ10obmFtZSk7XG4gICAgICAgIH1cbiAgICB9XG59XG5leHBvcnRzLmNsYXNzTW9kdWxlID0geyBjcmVhdGU6IHVwZGF0ZUNsYXNzLCB1cGRhdGU6IHVwZGF0ZUNsYXNzIH07XG5leHBvcnRzLmRlZmF1bHQgPSBleHBvcnRzLmNsYXNzTW9kdWxlO1xuLy8jIHNvdXJjZU1hcHBpbmdVUkw9Y2xhc3MuanMubWFwIl19
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.snabbdom_class=e()}}(function(){return function e(n,o,r){function t(i,u){if(!o[i]){if(!n[i]){var s="function"==typeof require&&require;if(!u&&s)return s(i,!0);if(f)return f(i,!0);var d=new Error("Cannot find module '"+i+"'");throw d.code="MODULE_NOT_FOUND",d}var a=o[i]={exports:{}};n[i][0].call(a.exports,function(e){var o=n[i][1][e];return t(o?o:e)},a,a.exports,e,n,o,r)}return o[i].exports}for(var f="function"==typeof require&&require,i=0;i<r.length;i++)t(r[i]);return t}({1:[function(e,n,o){"use strict";function r(e,n){var o,r,t=n.elm,f=e.data["class"],i=n.data["class"];if((f||i)&&f!==i){f=f||{},i=i||{};for(r in f)i[r]||t.classList.remove(r);for(r in i)o=i[r],o!==f[r]&&t.classList[o?"add":"remove"](r)}}o.classModule={create:r,update:r},Object.defineProperty(o,"__esModule",{value:!0}),o["default"]=o.classModule},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=snabbdom-class.min.js.map
|
||||
File diff suppressed because one or more lines are too long
-42
@@ -1,42 +0,0 @@
|
||||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_dataset = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var CAPS_REGEX = /[A-Z]/g;
|
||||
function updateDataset(oldVnode, vnode) {
|
||||
var elm = vnode.elm, oldDataset = oldVnode.data.dataset, dataset = vnode.data.dataset, key;
|
||||
if (!oldDataset && !dataset)
|
||||
return;
|
||||
if (oldDataset === dataset)
|
||||
return;
|
||||
oldDataset = oldDataset || {};
|
||||
dataset = dataset || {};
|
||||
var d = elm.dataset;
|
||||
for (key in oldDataset) {
|
||||
if (!dataset[key]) {
|
||||
if (d) {
|
||||
if (key in d) {
|
||||
delete d[key];
|
||||
}
|
||||
}
|
||||
else {
|
||||
elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (key in dataset) {
|
||||
if (oldDataset[key] !== dataset[key]) {
|
||||
if (d) {
|
||||
d[key] = dataset[key];
|
||||
}
|
||||
else {
|
||||
elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.datasetModule = { create: updateDataset, update: updateDataset };
|
||||
exports.default = exports.datasetModule;
|
||||
|
||||
},{}]},{},[1])(1)
|
||||
});
|
||||
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJtb2R1bGVzL2RhdGFzZXQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xudmFyIENBUFNfUkVHRVggPSAvW0EtWl0vZztcbmZ1bmN0aW9uIHVwZGF0ZURhdGFzZXQob2xkVm5vZGUsIHZub2RlKSB7XG4gICAgdmFyIGVsbSA9IHZub2RlLmVsbSwgb2xkRGF0YXNldCA9IG9sZFZub2RlLmRhdGEuZGF0YXNldCwgZGF0YXNldCA9IHZub2RlLmRhdGEuZGF0YXNldCwga2V5O1xuICAgIGlmICghb2xkRGF0YXNldCAmJiAhZGF0YXNldClcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGREYXRhc2V0ID09PSBkYXRhc2V0KVxuICAgICAgICByZXR1cm47XG4gICAgb2xkRGF0YXNldCA9IG9sZERhdGFzZXQgfHwge307XG4gICAgZGF0YXNldCA9IGRhdGFzZXQgfHwge307XG4gICAgdmFyIGQgPSBlbG0uZGF0YXNldDtcbiAgICBmb3IgKGtleSBpbiBvbGREYXRhc2V0KSB7XG4gICAgICAgIGlmICghZGF0YXNldFtrZXldKSB7XG4gICAgICAgICAgICBpZiAoZCkge1xuICAgICAgICAgICAgICAgIGlmIChrZXkgaW4gZCkge1xuICAgICAgICAgICAgICAgICAgICBkZWxldGUgZFtrZXldO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIGVsbS5yZW1vdmVBdHRyaWJ1dGUoJ2RhdGEtJyArIGtleS5yZXBsYWNlKENBUFNfUkVHRVgsICctJCYnKS50b0xvd2VyQ2FzZSgpKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbiAgICBmb3IgKGtleSBpbiBkYXRhc2V0KSB7XG4gICAgICAgIGlmIChvbGREYXRhc2V0W2tleV0gIT09IGRhdGFzZXRba2V5XSkge1xuICAgICAgICAgICAgaWYgKGQpIHtcbiAgICAgICAgICAgICAgICBkW2tleV0gPSBkYXRhc2V0W2tleV07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICBlbG0uc2V0QXR0cmlidXRlKCdkYXRhLScgKyBrZXkucmVwbGFjZShDQVBTX1JFR0VYLCAnLSQmJykudG9Mb3dlckNhc2UoKSwgZGF0YXNldFtrZXldKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbn1cbmV4cG9ydHMuZGF0YXNldE1vZHVsZSA9IHsgY3JlYXRlOiB1cGRhdGVEYXRhc2V0LCB1cGRhdGU6IHVwZGF0ZURhdGFzZXQgfTtcbmV4cG9ydHMuZGVmYXVsdCA9IGV4cG9ydHMuZGF0YXNldE1vZHVsZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWRhdGFzZXQuanMubWFwIl19
|
||||
-99
File diff suppressed because one or more lines are too long
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.snabbdom_eventlisteners=e()}}(function(){return function e(n,t,r){function o(f,u){if(!t[f]){if(!n[f]){var l="function"==typeof require&&require;if(!u&&l)return l(f,!0);if(i)return i(f,!0);var s=new Error("Cannot find module '"+f+"'");throw s.code="MODULE_NOT_FOUND",s}var d=t[f]={exports:{}};n[f][0].call(d.exports,function(e){var t=n[f][1][e];return o(t?t:e)},d,d.exports,e,n,t,r)}return t[f].exports}for(var i="function"==typeof require&&require,f=0;f<r.length;f++)o(r[f]);return o}({1:[function(e,n,t){"use strict";function r(e,n,t){if("function"==typeof e)e.call(n,t,n);else if("object"==typeof e)if("function"==typeof e[0])if(2===e.length)e[0].call(n,e[1],t,n);else{var o=e.slice(1);o.push(t),o.push(n),e[0].apply(n,o)}else for(var i=0;i<e.length;i++)r(e[i])}function o(e,n){var t=e.type,o=n.data.on;o&&o[t]&&r(o[t],n,e)}function i(){return function e(n){o(n,e.vnode)}}function f(e,n){var t,r=e.data.on,o=e.listener,f=e.elm,u=n&&n.data.on,l=n&&n.elm;if(r!==u){if(r&&o)if(u)for(t in r)u[t]||f.removeEventListener(t,o,!1);else for(t in r)f.removeEventListener(t,o,!1);if(u){var s=n.listener=e.listener||i();if(s.vnode=n,r)for(t in u)r[t]||l.addEventListener(t,s,!1);else for(t in u)l.addEventListener(t,s,!1)}}}t.eventListenersModule={create:f,update:f,destroy:f},Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=t.eventListenersModule},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=snabbdom-eventlisteners.min.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
-830
File diff suppressed because one or more lines are too long
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Vendored
-30
@@ -1,30 +0,0 @@
|
||||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_props = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function updateProps(oldVnode, vnode) {
|
||||
var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props, props = vnode.data.props;
|
||||
if (!oldProps && !props)
|
||||
return;
|
||||
if (oldProps === props)
|
||||
return;
|
||||
oldProps = oldProps || {};
|
||||
props = props || {};
|
||||
for (key in oldProps) {
|
||||
if (!props[key]) {
|
||||
delete elm[key];
|
||||
}
|
||||
}
|
||||
for (key in props) {
|
||||
cur = props[key];
|
||||
old = oldProps[key];
|
||||
if (old !== cur && (key !== 'value' || elm[key] !== cur)) {
|
||||
elm[key] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.propsModule = { create: updateProps, update: updateProps };
|
||||
exports.default = exports.propsModule;
|
||||
|
||||
},{}]},{},[1])(1)
|
||||
});
|
||||
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwibW9kdWxlcy9wcm9wcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbIihmdW5jdGlvbiBlKHQsbixyKXtmdW5jdGlvbiBzKG8sdSl7aWYoIW5bb10pe2lmKCF0W29dKXt2YXIgYT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2lmKCF1JiZhKXJldHVybiBhKG8sITApO2lmKGkpcmV0dXJuIGkobywhMCk7dmFyIGY9bmV3IEVycm9yKFwiQ2Fubm90IGZpbmQgbW9kdWxlICdcIitvK1wiJ1wiKTt0aHJvdyBmLmNvZGU9XCJNT0RVTEVfTk9UX0ZPVU5EXCIsZn12YXIgbD1uW29dPXtleHBvcnRzOnt9fTt0W29dWzBdLmNhbGwobC5leHBvcnRzLGZ1bmN0aW9uKGUpe3ZhciBuPXRbb11bMV1bZV07cmV0dXJuIHMobj9uOmUpfSxsLGwuZXhwb3J0cyxlLHQsbixyKX1yZXR1cm4gbltvXS5leHBvcnRzfXZhciBpPXR5cGVvZiByZXF1aXJlPT1cImZ1bmN0aW9uXCImJnJlcXVpcmU7Zm9yKHZhciBvPTA7bzxyLmxlbmd0aDtvKyspcyhyW29dKTtyZXR1cm4gc30pIiwiXCJ1c2Ugc3RyaWN0XCI7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoZXhwb3J0cywgXCJfX2VzTW9kdWxlXCIsIHsgdmFsdWU6IHRydWUgfSk7XG5mdW5jdGlvbiB1cGRhdGVQcm9wcyhvbGRWbm9kZSwgdm5vZGUpIHtcbiAgICB2YXIga2V5LCBjdXIsIG9sZCwgZWxtID0gdm5vZGUuZWxtLCBvbGRQcm9wcyA9IG9sZFZub2RlLmRhdGEucHJvcHMsIHByb3BzID0gdm5vZGUuZGF0YS5wcm9wcztcbiAgICBpZiAoIW9sZFByb3BzICYmICFwcm9wcylcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGRQcm9wcyA9PT0gcHJvcHMpXG4gICAgICAgIHJldHVybjtcbiAgICBvbGRQcm9wcyA9IG9sZFByb3BzIHx8IHt9O1xuICAgIHByb3BzID0gcHJvcHMgfHwge307XG4gICAgZm9yIChrZXkgaW4gb2xkUHJvcHMpIHtcbiAgICAgICAgaWYgKCFwcm9wc1trZXldKSB7XG4gICAgICAgICAgICBkZWxldGUgZWxtW2tleV07XG4gICAgICAgIH1cbiAgICB9XG4gICAgZm9yIChrZXkgaW4gcHJvcHMpIHtcbiAgICAgICAgY3VyID0gcHJvcHNba2V5XTtcbiAgICAgICAgb2xkID0gb2xkUHJvcHNba2V5XTtcbiAgICAgICAgaWYgKG9sZCAhPT0gY3VyICYmIChrZXkgIT09ICd2YWx1ZScgfHwgZWxtW2tleV0gIT09IGN1cikpIHtcbiAgICAgICAgICAgIGVsbVtrZXldID0gY3VyO1xuICAgICAgICB9XG4gICAgfVxufVxuZXhwb3J0cy5wcm9wc01vZHVsZSA9IHsgY3JlYXRlOiB1cGRhdGVQcm9wcywgdXBkYXRlOiB1cGRhdGVQcm9wcyB9O1xuZXhwb3J0cy5kZWZhdWx0ID0gZXhwb3J0cy5wcm9wc01vZHVsZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPXByb3BzLmpzLm1hcCJdfQ==
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;o="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,o.snabbdom_props=e()}}(function(){return function e(o,r,n){function t(i,u){if(!r[i]){if(!o[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(f)return f(i,!0);var p=new Error("Cannot find module '"+i+"'");throw p.code="MODULE_NOT_FOUND",p}var a=r[i]={exports:{}};o[i][0].call(a.exports,function(e){var r=o[i][1][e];return t(r?r:e)},a,a.exports,e,o,r,n)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<n.length;i++)t(n[i]);return t}({1:[function(e,o,r){"use strict";function n(e,o){var r,n,t,f=o.elm,i=e.data.props,u=o.data.props;if((i||u)&&i!==u){i=i||{},u=u||{};for(r in i)u[r]||delete f[r];for(r in u)n=u[r],t=i[r],t===n||"value"===r&&f[r]===n||(f[r]=n)}}r.propsModule={create:n,update:n},Object.defineProperty(r,"__esModule",{value:!0}),r["default"]=r.propsModule},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=snabbdom-props.min.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
-90
File diff suppressed because one or more lines are too long
-2
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.snabbdom_style=e()}}(function(){return function e(t,n,r){function o(f,d){if(!n[f]){if(!t[f]){var u="function"==typeof require&&require;if(!d&&u)return u(f,!0);if(i)return i(f,!0);var l=new Error("Cannot find module '"+f+"'");throw l.code="MODULE_NOT_FOUND",l}var a=n[f]={exports:{}};t[f][0].call(a.exports,function(e){var n=t[f][1][e];return o(n?n:e)},a,a.exports,e,t,n,r)}return n[f].exports}for(var i="function"==typeof require&&require,f=0;f<r.length;f++)o(r[f]);return o}({1:[function(e,t,n){"use strict";function r(e,t,n){u(function(){e[t]=n})}function o(e,t){var n,o,i=t.elm,f=e.data.style,d=t.data.style;if((f||d)&&f!==d){f=f||{},d=d||{};var u="delayed"in f;for(o in f)d[o]||("-"===o[0]&&"-"===o[1]?i.style.removeProperty(o):i.style[o]="");for(o in d)if(n=d[o],"delayed"===o)for(o in d.delayed)n=d.delayed[o],u&&n===f.delayed[o]||r(i.style,o,n);else"remove"!==o&&n!==f[o]&&("-"===o[0]&&"-"===o[1]?i.style.setProperty(o,n):i.style[o]=n)}}function i(e){var t,n,r=e.elm,o=e.data.style;if(o&&(t=o.destroy))for(n in t)r.style[n]=t[n]}function f(e,t){var n=e.data.style;if(!n||!n.remove)return void t();var r,o,i=e.elm,f=0,d=n.remove,u=0,l=[];for(r in d)l.push(r),i.style[r]=d[r];o=getComputedStyle(i);for(var a=o["transition-property"].split(", ");f<a.length;++f)l.indexOf(a[f])!==-1&&u++;i.addEventListener("transitionend",function(e){e.target===i&&--u,0===u&&t()})}var d="undefined"!=typeof window&&window.requestAnimationFrame||setTimeout,u=function(e){d(function(){d(e)})};n.styleModule={create:o,update:o,destroy:i,remove:f},Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=n.styleModule},{}]},{},[1])(1)});
|
||||
//# sourceMappingURL=snabbdom-style.min.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
-506
File diff suppressed because one or more lines are too long
Vendored
-2
File diff suppressed because one or more lines are too long
-1
File diff suppressed because one or more lines are too long
Vendored
-126
File diff suppressed because one or more lines are too long
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.tovnode=e()}}(function(){return function e(t,n,o){function r(u,d){if(!n[u]){if(!t[u]){var f="function"==typeof require&&require;if(!d&&f)return f(u,!0);if(i)return i(u,!0);var a=new Error("Cannot find module '"+u+"'");throw a.code="MODULE_NOT_FOUND",a}var l=n[u]={exports:{}};t[u][0].call(l.exports,function(e){var n=t[u][1][e];return r(n?n:e)},l,l.exports,e,t,n,o)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u<o.length;u++)r(o[u]);return r}({1:[function(e,t,n){"use strict";function o(e){return document.createElement(e)}function r(e,t){return document.createElementNS(e,t)}function i(e){return document.createTextNode(e)}function u(e){return document.createComment(e)}function d(e,t,n){e.insertBefore(t,n)}function f(e,t){e.removeChild(t)}function a(e,t){e.appendChild(t)}function l(e){return e.parentNode}function c(e){return e.nextSibling}function s(e){return e.tagName}function m(e,t){e.textContent=t}function v(e){return e.textContent}function p(e){return 1===e.nodeType}function x(e){return 3===e.nodeType}function h(e){return 8===e.nodeType}n.htmlDomApi={createElement:o,createElementNS:r,createTextNode:i,createComment:u,insertBefore:d,removeChild:f,appendChild:a,parentNode:l,nextSibling:c,tagName:s,setTextContent:m,getTextContent:v,isElement:p,isText:x,isComment:h},Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=n.htmlDomApi},{}],2:[function(e,t,n){"use strict";function o(e,t){var n,u=void 0!==t?t:i["default"];if(u.isElement(e)){var d,f=e.id?"#"+e.id:"",a=e.getAttribute("class"),l=a?"."+a.split(" ").join("."):"",c=u.tagName(e).toLowerCase()+f+l,s={},m=[],v=void 0,p=void 0,x=e.attributes,h=e.childNodes;for(v=0,p=x.length;v<p;v++)d=x[v].nodeName,"id"!==d&&"class"!==d&&(s[d]=x[v].nodeValue);for(v=0,p=h.length;v<p;v++)m.push(o(h[v]));return r["default"](c,{attrs:s},m,void 0,e)}return u.isText(e)?(n=u.getTextContent(e),r["default"](void 0,void 0,void 0,n,e)):u.isComment(e)?(n=u.getTextContent(e),r["default"]("!",void 0,void 0,n,void 0)):r["default"]("",{},[],void 0,void 0)}var r=e("./vnode"),i=e("./htmldomapi");n.toVNode=o,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=o},{"./htmldomapi":1,"./vnode":3}],3:[function(e,t,n){"use strict";function o(e,t,n,o,r){var i=void 0===t?void 0:t.key;return{sel:e,data:t,children:n,text:o,elm:r,key:i}}n.vnode=o,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=o},{}]},{},[2])(2)});
|
||||
//# sourceMappingURL=tovnode.min.js.map
|
||||
-1
File diff suppressed because one or more lines are too long
@@ -1,19 +0,0 @@
|
||||
This carousel example uses `style transform` and `transition` to rotate a group of SVG triangles.
|
||||
|
||||
Also, the color of each triangle changes when you hover or click/tap it.
|
||||
|
||||
I built the build.js using npm and browserify.
|
||||
|
||||
In my local copy of the snabbdom project root I did these preparations:
|
||||
```
|
||||
npm install --save-dev babelify
|
||||
npm install --save-dev babel-preset-es2015
|
||||
echo '{ "presets": ["es2015"] }' > .babelrc
|
||||
```
|
||||
|
||||
I then built like this:
|
||||
```
|
||||
browserify examples/carousel-svg/script.js -t babelify -o examples/carousel-svg/build.js
|
||||
```
|
||||
|
||||
-- *jk*
|
||||
@@ -1,566 +0,0 @@
|
||||
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function addNS(data, children) {
|
||||
data.ns = 'http://www.w3.org/2000/svg';
|
||||
if (children !== undefined) {
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
addNS(children[i].data, children[i].children);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function h(sel, b, c) {
|
||||
var data = {},
|
||||
children,
|
||||
text,
|
||||
i;
|
||||
if (arguments.length === 3) {
|
||||
data = b;
|
||||
if (is.array(c)) {
|
||||
children = c;
|
||||
} else if (is.primitive(c)) {
|
||||
text = c;
|
||||
}
|
||||
} else if (arguments.length === 2) {
|
||||
if (is.array(b)) {
|
||||
children = b;
|
||||
} else if (is.primitive(b)) {
|
||||
text = b;
|
||||
} else {
|
||||
data = b;
|
||||
}
|
||||
}
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
|
||||
}
|
||||
}
|
||||
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
|
||||
addNS(data, children);
|
||||
}
|
||||
return VNode(sel, data, children, text, undefined);
|
||||
};
|
||||
|
||||
},{"./is":2,"./vnode":7}],2:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
array: Array.isArray,
|
||||
primitive: function primitive(s) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
}
|
||||
};
|
||||
|
||||
},{}],3:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"];
|
||||
|
||||
var booleanAttrsDict = {};
|
||||
for (var i = 0, len = booleanAttrs.length; i < len; i++) {
|
||||
booleanAttrsDict[booleanAttrs[i]] = true;
|
||||
}
|
||||
|
||||
function updateAttrs(oldVnode, vnode) {
|
||||
var key,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldAttrs = oldVnode.data.attrs || {},
|
||||
attrs = vnode.data.attrs || {};
|
||||
|
||||
// update modified attributes, add new attributes
|
||||
for (key in attrs) {
|
||||
cur = attrs[key];
|
||||
old = oldAttrs[key];
|
||||
if (old !== cur) {
|
||||
// TODO: add support to namespaced attributes (setAttributeNS)
|
||||
if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur);
|
||||
}
|
||||
}
|
||||
//remove removed attributes
|
||||
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
|
||||
// the other option is to remove all attributes with value == undefined
|
||||
for (key in oldAttrs) {
|
||||
if (!(key in attrs)) {
|
||||
elm.removeAttribute(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateAttrs, update: updateAttrs };
|
||||
|
||||
},{}],4:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var is = require('../is');
|
||||
|
||||
function arrInvoker(arr) {
|
||||
return function () {
|
||||
// Special case when length is two, for performance
|
||||
arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1));
|
||||
};
|
||||
}
|
||||
|
||||
function fnInvoker(o) {
|
||||
return function (ev) {
|
||||
o.fn(ev);
|
||||
};
|
||||
}
|
||||
|
||||
function updateEventListeners(oldVnode, vnode) {
|
||||
var name,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldOn = oldVnode.data.on || {},
|
||||
on = vnode.data.on;
|
||||
if (!on) return;
|
||||
for (name in on) {
|
||||
cur = on[name];
|
||||
old = oldOn[name];
|
||||
if (old === undefined) {
|
||||
if (is.array(cur)) {
|
||||
elm.addEventListener(name, arrInvoker(cur));
|
||||
} else {
|
||||
cur = { fn: cur };
|
||||
on[name] = cur;
|
||||
elm.addEventListener(name, fnInvoker(cur));
|
||||
}
|
||||
} else if (is.array(old)) {
|
||||
// Deliberately modify old array since it's captured in closure created with `arrInvoker`
|
||||
old.length = cur.length;
|
||||
for (var i = 0; i < old.length; ++i) {
|
||||
old[i] = cur[i];
|
||||
}on[name] = old;
|
||||
} else {
|
||||
old.fn = cur;
|
||||
on[name] = old;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateEventListeners, update: updateEventListeners };
|
||||
|
||||
},{"../is":2}],5:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var raf = window && window.requestAnimationFrame || setTimeout;
|
||||
var nextFrame = function nextFrame(fn) {
|
||||
raf(function () {
|
||||
raf(fn);
|
||||
});
|
||||
};
|
||||
|
||||
function setNextFrame(obj, prop, val) {
|
||||
nextFrame(function () {
|
||||
obj[prop] = val;
|
||||
});
|
||||
}
|
||||
|
||||
function updateStyle(oldVnode, vnode) {
|
||||
var cur,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
oldStyle = oldVnode.data.style || {},
|
||||
style = vnode.data.style || {},
|
||||
oldHasDel = 'delayed' in oldStyle;
|
||||
for (name in oldStyle) {
|
||||
if (!style[name]) {
|
||||
elm.style[name] = '';
|
||||
}
|
||||
}
|
||||
for (name in style) {
|
||||
cur = style[name];
|
||||
if (name === 'delayed') {
|
||||
for (name in style.delayed) {
|
||||
cur = style.delayed[name];
|
||||
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
|
||||
setNextFrame(elm.style, name, cur);
|
||||
}
|
||||
}
|
||||
} else if (name !== 'remove' && cur !== oldStyle[name]) {
|
||||
elm.style[name] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyDestroyStyle(vnode) {
|
||||
var style,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
s = vnode.data.style;
|
||||
if (!s || !(style = s.destroy)) return;
|
||||
for (name in style) {
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
}
|
||||
|
||||
function applyRemoveStyle(vnode, rm) {
|
||||
var s = vnode.data.style;
|
||||
if (!s || !s.remove) {
|
||||
rm();
|
||||
return;
|
||||
}
|
||||
var name,
|
||||
elm = vnode.elm,
|
||||
idx,
|
||||
i = 0,
|
||||
maxDur = 0,
|
||||
compStyle,
|
||||
style = s.remove,
|
||||
amount = 0,
|
||||
applied = [];
|
||||
for (name in style) {
|
||||
applied.push(name);
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
compStyle = getComputedStyle(elm);
|
||||
var props = compStyle['transition-property'].split(', ');
|
||||
for (; i < props.length; ++i) {
|
||||
if (applied.indexOf(props[i]) !== -1) amount++;
|
||||
}
|
||||
elm.addEventListener('transitionend', function (ev) {
|
||||
if (ev.target === elm) --amount;
|
||||
if (amount === 0) rm();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
|
||||
|
||||
},{}],6:[function(require,module,exports){
|
||||
// jshint newcap: false
|
||||
/* global require, module, document, Element */
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function isUndef(s) {
|
||||
return s === undefined;
|
||||
}
|
||||
function isDef(s) {
|
||||
return s !== undefined;
|
||||
}
|
||||
|
||||
function emptyNodeAt(elm) {
|
||||
return VNode(elm.tagName, {}, [], undefined, elm);
|
||||
}
|
||||
|
||||
var emptyNode = VNode('', {}, [], undefined, undefined);
|
||||
|
||||
function sameVnode(vnode1, vnode2) {
|
||||
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
|
||||
}
|
||||
|
||||
function createKeyToOldIdx(children, beginIdx, endIdx) {
|
||||
var i,
|
||||
map = {},
|
||||
key;
|
||||
for (i = beginIdx; i <= endIdx; ++i) {
|
||||
key = children[i].key;
|
||||
if (isDef(key)) map[key] = i;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function createRmCb(childElm, listeners) {
|
||||
return function () {
|
||||
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
|
||||
};
|
||||
}
|
||||
|
||||
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
|
||||
|
||||
function init(modules) {
|
||||
var i,
|
||||
j,
|
||||
cbs = {};
|
||||
for (i = 0; i < hooks.length; ++i) {
|
||||
cbs[hooks[i]] = [];
|
||||
for (j = 0; j < modules.length; ++j) {
|
||||
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
|
||||
}
|
||||
}
|
||||
|
||||
function createElm(vnode, insertedVnodeQueue) {
|
||||
var i,
|
||||
data = vnode.data;
|
||||
if (isDef(data)) {
|
||||
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
|
||||
if (isDef(i = data.vnode)) vnode = i;
|
||||
}
|
||||
var elm,
|
||||
children = vnode.children,
|
||||
sel = vnode.sel;
|
||||
if (isDef(sel)) {
|
||||
// Parse selector
|
||||
var hashIdx = sel.indexOf('#');
|
||||
var dotIdx = sel.indexOf('.', hashIdx);
|
||||
var hash = hashIdx > 0 ? hashIdx : sel.length;
|
||||
var dot = dotIdx > 0 ? dotIdx : sel.length;
|
||||
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
||||
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
|
||||
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
|
||||
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
elm.appendChild(createElm(children[i], insertedVnodeQueue));
|
||||
}
|
||||
} else if (is.primitive(vnode.text)) {
|
||||
elm.appendChild(document.createTextNode(vnode.text));
|
||||
}
|
||||
for (i = 0; i < cbs.create.length; ++i) {
|
||||
cbs.create[i](emptyNode, vnode);
|
||||
}i = vnode.data.hook; // Reuse variable
|
||||
if (isDef(i)) {
|
||||
if (i.create) i.create(emptyNode, vnode);
|
||||
if (i.insert) insertedVnodeQueue.push(vnode);
|
||||
}
|
||||
} else {
|
||||
elm = vnode.elm = document.createTextNode(vnode.text);
|
||||
}
|
||||
return vnode.elm;
|
||||
}
|
||||
|
||||
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
|
||||
}
|
||||
}
|
||||
|
||||
function invokeDestroyHook(vnode) {
|
||||
var i = vnode.data,
|
||||
j;
|
||||
if (isDef(i)) {
|
||||
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
|
||||
for (i = 0; i < cbs.destroy.length; ++i) {
|
||||
cbs.destroy[i](vnode);
|
||||
}if (isDef(i = vnode.children)) {
|
||||
for (j = 0; j < vnode.children.length; ++j) {
|
||||
invokeDestroyHook(vnode.children[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
var i,
|
||||
listeners,
|
||||
rm,
|
||||
ch = vnodes[startIdx];
|
||||
if (isDef(ch)) {
|
||||
if (isDef(ch.sel)) {
|
||||
invokeDestroyHook(ch);
|
||||
listeners = cbs.remove.length + 1;
|
||||
rm = createRmCb(ch.elm, listeners);
|
||||
for (i = 0; i < cbs.remove.length; ++i) {
|
||||
cbs.remove[i](ch, rm);
|
||||
}if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
|
||||
i(ch, rm);
|
||||
} else {
|
||||
rm();
|
||||
}
|
||||
} else {
|
||||
// Text node
|
||||
parentElm.removeChild(ch.elm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
|
||||
var oldStartIdx = 0,
|
||||
newStartIdx = 0;
|
||||
var oldEndIdx = oldCh.length - 1;
|
||||
var oldStartVnode = oldCh[0];
|
||||
var oldEndVnode = oldCh[oldEndIdx];
|
||||
var newEndIdx = newCh.length - 1;
|
||||
var newStartVnode = newCh[0];
|
||||
var newEndVnode = newCh[newEndIdx];
|
||||
var oldKeyToIdx, idxInOld, elmToMove, before;
|
||||
|
||||
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
|
||||
if (isUndef(oldStartVnode)) {
|
||||
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
|
||||
} else if (isUndef(oldEndVnode)) {
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newStartVnode)) {
|
||||
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else if (sameVnode(oldEndVnode, newEndVnode)) {
|
||||
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newEndVnode)) {
|
||||
// Vnode moved right
|
||||
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldEndVnode, newStartVnode)) {
|
||||
// Vnode moved left
|
||||
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
|
||||
idxInOld = oldKeyToIdx[newStartVnode.key];
|
||||
if (isUndef(idxInOld)) {
|
||||
// New element
|
||||
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
elmToMove = oldCh[idxInOld];
|
||||
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
|
||||
oldCh[idxInOld] = undefined;
|
||||
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (oldStartIdx > oldEndIdx) {
|
||||
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
|
||||
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
|
||||
} else if (newStartIdx > newEndIdx) {
|
||||
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
|
||||
}
|
||||
}
|
||||
|
||||
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
|
||||
var i, hook;
|
||||
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
|
||||
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
|
||||
var elm = vnode.elm = oldVnode.elm,
|
||||
oldCh = oldVnode.children,
|
||||
ch = vnode.children;
|
||||
if (oldVnode === vnode) return;
|
||||
if (isDef(vnode.data)) {
|
||||
for (i = 0; i < cbs.update.length; ++i) {
|
||||
cbs.update[i](oldVnode, vnode);
|
||||
}i = vnode.data.hook;
|
||||
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
|
||||
}
|
||||
if (isUndef(vnode.text)) {
|
||||
if (isDef(oldCh) && isDef(ch)) {
|
||||
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
|
||||
} else if (isDef(ch)) {
|
||||
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
|
||||
} else if (isDef(oldCh)) {
|
||||
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
|
||||
}
|
||||
} else if (oldVnode.text !== vnode.text) {
|
||||
elm.textContent = vnode.text;
|
||||
}
|
||||
if (isDef(hook) && isDef(i = hook.postpatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
}
|
||||
|
||||
return function (oldVnode, vnode) {
|
||||
var i;
|
||||
var insertedVnodeQueue = [];
|
||||
for (i = 0; i < cbs.pre.length; ++i) {
|
||||
cbs.pre[i]();
|
||||
}if (oldVnode instanceof Element) {
|
||||
if (oldVnode.parentElement !== null) {
|
||||
createElm(vnode, insertedVnodeQueue);
|
||||
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
|
||||
} else {
|
||||
oldVnode = emptyNodeAt(oldVnode);
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
} else {
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
for (i = 0; i < insertedVnodeQueue.length; ++i) {
|
||||
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
|
||||
}
|
||||
for (i = 0; i < cbs.post.length; ++i) {
|
||||
cbs.post[i]();
|
||||
}return vnode;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { init: init };
|
||||
|
||||
},{"./is":2,"./vnode":7}],7:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
module.exports = function (sel, data, children, text, elm) {
|
||||
var key = data === undefined ? undefined : data.key;
|
||||
return { sel: sel, data: data, children: children,
|
||||
text: text, elm: elm, key: key };
|
||||
};
|
||||
|
||||
},{}],8:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([require('../../modules/attributes'), require('../../modules/style'), require('../../modules/eventlisteners')]);
|
||||
var h = require('../../h.js');
|
||||
|
||||
var vnode;
|
||||
|
||||
var data = {
|
||||
degRotation: 0
|
||||
};
|
||||
|
||||
function gRotation() {
|
||||
//console.log("gRotation: %s", data.degRotation);
|
||||
return "rotate(" + data.degRotation + "deg)";
|
||||
}
|
||||
|
||||
function triangleClick(id) {
|
||||
console.log("triangleClick: %s", id);
|
||||
render();
|
||||
}
|
||||
|
||||
function handleRotate(degs) {
|
||||
data.degRotation += degs;
|
||||
console.log("handleRotate: %s, %s", degs, data.degRotation);
|
||||
render();
|
||||
}
|
||||
|
||||
function handleReset(degs) {
|
||||
data.degRotation = degs;
|
||||
console.log("handleReset: %s", degs);
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
var hTriangle = function hTriangle(id, degRotation) {
|
||||
return h("polygon#" + id, {
|
||||
attrs: {
|
||||
points: "-50,-88 0,-175 50,-88",
|
||||
transform: "rotate(" + degRotation + ")",
|
||||
"stroke-width": 3
|
||||
},
|
||||
on: { click: [triangleClick, id] }
|
||||
});
|
||||
};
|
||||
|
||||
var view = function view(data) {
|
||||
return h("div.view", [h("h1", "Snabbdom SVG Carousel"), h("svg", { attrs: { width: 380, height: 380, viewBox: [-190, -190, 380, 380] } }, [h("g#carousel", { style: { "-webkit-transform": gRotation(), transform: gRotation() } }, [hTriangle("yellow", 0), hTriangle("green", 60), hTriangle("magenta", 120), hTriangle("red", 180), hTriangle("cyan", 240), hTriangle("blue", 300)])]), h("button", { on: { click: [handleRotate, 60] } }, "Rotate Clockwise"), h("button", { on: { click: [handleRotate, -60] } }, "Rotate Anticlockwise"), h("button", { on: { click: [handleReset, 0] } }, "Reset")]);
|
||||
};
|
||||
|
||||
window.addEventListener("DOMContentLoaded", function () {
|
||||
var container = document.getElementById("container");
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
|
||||
},{"../../h.js":1,"../../modules/attributes":3,"../../modules/eventlisteners":4,"../../modules/style":5,"../../snabbdom.js":6}]},{},[8]);
|
||||
@@ -1,74 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta charset="utf-8">
|
||||
<title>Carousel</title>
|
||||
<script type="text/javascript" src="build.js"></script>
|
||||
<style type="text/css">
|
||||
div.view {
|
||||
margin: 10px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 24px;
|
||||
color: #505000;
|
||||
}
|
||||
svg {
|
||||
display: block;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid gray;
|
||||
}
|
||||
g#carousel {
|
||||
-webkit-transition: -webkit-transform 1s ease;
|
||||
transition: transform 1s ease;
|
||||
}
|
||||
polygon {
|
||||
stroke: #808000;
|
||||
transition: fill 0.5s linear;
|
||||
}
|
||||
polygon#yellow {
|
||||
fill: rgba(255,255,0,0.4);
|
||||
}
|
||||
polygon#yellow:hover, polygon#yellow:active {
|
||||
fill: yellow;
|
||||
}
|
||||
polygon#green {
|
||||
fill: rgba(0,128,0,0.4);
|
||||
}
|
||||
polygon#green:hover, polygon#green:active {
|
||||
fill: green;
|
||||
}
|
||||
polygon#magenta {
|
||||
fill: rgba(255,0,255,0.4);
|
||||
}
|
||||
polygon#magenta:hover, polygon#magenta:active {
|
||||
fill: magenta;
|
||||
}
|
||||
polygon#red {
|
||||
fill: rgba(255,0,0,0.4);
|
||||
}
|
||||
polygon#red:hover, polygon#red:active {
|
||||
fill: red;
|
||||
}
|
||||
polygon#cyan {
|
||||
fill: rgba(0,255,255,0.4);
|
||||
}
|
||||
polygon#cyan:hover, polygon#cyan:active {
|
||||
fill: cyan;
|
||||
}
|
||||
polygon#blue {
|
||||
fill: rgba(0,0,255,0.4);
|
||||
}
|
||||
polygon#blue:hover, polygon#blue:active {
|
||||
fill: blue;
|
||||
}
|
||||
button {
|
||||
font-size: 15px;
|
||||
margin: 0 0.7em 0.7em 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,74 +0,0 @@
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([
|
||||
require('../../modules/attributes').default,
|
||||
require('../../modules/style').default,
|
||||
require('../../modules/eventlisteners').default
|
||||
]);
|
||||
var h = require('../../h.js').default;
|
||||
|
||||
var vnode;
|
||||
|
||||
var data = {
|
||||
degRotation: 0
|
||||
};
|
||||
|
||||
function gRotation() {
|
||||
//console.log("gRotation: %s", data.degRotation);
|
||||
return "rotate(" + data.degRotation + "deg)";
|
||||
}
|
||||
|
||||
function triangleClick(id) {
|
||||
console.log("triangleClick: %s", id);
|
||||
render();
|
||||
}
|
||||
|
||||
function handleRotate(degs) {
|
||||
data.degRotation += degs;
|
||||
console.log("handleRotate: %s, %s", degs, data.degRotation);
|
||||
render();
|
||||
}
|
||||
|
||||
function handleReset(degs) {
|
||||
data.degRotation = degs;
|
||||
console.log("handleReset: %s", degs);
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
const hTriangle = (id, degRotation) =>
|
||||
h("polygon#" + id, {
|
||||
attrs: {
|
||||
points: "-50,-88 0,-175 50,-88",
|
||||
transform: "rotate(" + degRotation + ")",
|
||||
"stroke-width": 3
|
||||
},
|
||||
on: {click: [triangleClick, id]}
|
||||
});
|
||||
|
||||
const view = (data) =>
|
||||
h("div.view", [
|
||||
h("h1", "Snabbdom SVG Carousel"),
|
||||
h("svg", {attrs: {width: 380, height: 380, viewBox: [-190, -190, 380, 380]}}, [
|
||||
h("g#carousel",
|
||||
{style: {"-webkit-transform": gRotation(), transform: gRotation()}}, [
|
||||
hTriangle("yellow", 0),
|
||||
hTriangle("green", 60),
|
||||
hTriangle("magenta", 120),
|
||||
hTriangle("red", 180),
|
||||
hTriangle("cyan", 240),
|
||||
hTriangle("blue", 300)
|
||||
])
|
||||
]),
|
||||
h("button", {on: {click: [handleRotate, 60]}}, "Rotate Clockwise"),
|
||||
h("button", {on: {click: [handleRotate, -60]}}, "Rotate Anticlockwise"),
|
||||
h("button", {on: {click: [handleReset, 0]}}, "Reset")
|
||||
]);
|
||||
|
||||
window.addEventListener("DOMContentLoaded", () => {
|
||||
var container = document.getElementById("container");
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
@@ -1,708 +0,0 @@
|
||||
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
/* jshint esnext: true */
|
||||
'use strict';
|
||||
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([require('../../modules/class'), require('../../modules/hero'), require('../../modules/style'), require('../../modules/eventlisteners')]);
|
||||
var h = require('../../h.js');
|
||||
|
||||
var vnode;
|
||||
|
||||
var data = {
|
||||
selected: undefined,
|
||||
movies: [{ rank: 1, title: 'This is an', desc: 'Lorem ipsum dolor sit amet, sed pede integer vitae bibendum, accumsan sit, vulputate aenean tempora ipsum. Lorem sed id et metus, eros posuere suspendisse nec nunc justo, fusce augue placerat nibh purus suspendisse. Aliquam aliquam, ut eget. Mollis a eget sed nibh tincidunt nec, mi integer, proin magna lacus iaculis tortor. Aliquam vel arcu arcu, vivamus a urna fames felis vel wisi, cursus tortor nec erat dignissim cras sem, mauris ac venenatis tellus elit.' }, { rank: 2, title: 'example of', desc: 'Consequuntur ipsum nulla, consequat curabitur in magnis risus. Taciti mattis bibendum tellus nibh, at dui neque eget, odio pede ut, sapien pede, ipsum ut. Sagittis dui, sodales sem, praesent ipsum conubia eget lorem lobortis wisi.' }, { rank: 3, title: 'Snabbdom', desc: 'Quam lorem aliquam fusce wisi, urna purus ipsum pharetra sed, at cras sodales enim vestibulum odio cras, luctus integer phasellus.' }, { rank: 4, title: 'doing hero transitions', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.' }, { rank: 5, title: 'using the', desc: 'Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.' }, { rank: 6, title: 'module for hero transitions', desc: 'Sapien laoreet, ligula elit tortor nulla pellentesque, maecenas enim turpis, quae duis venenatis vivamus ultricies, nunc imperdiet sollicitudin ipsum malesuada. Ut sem. Wisi fusce nullam nibh enim. Nisl hymenaeos id sed sed in. Proin leo et, pulvinar nunc pede laoreet.' }, { rank: 7, title: 'click on ar element in', desc: 'Accumsan quia, id nascetur dui et congue erat, id excepteur, primis ratione nec. At nulla et. Suspendisse lobortis, lobortis in tortor fringilla, duis adipiscing vestibulum voluptates sociosqu auctor.' }, { rank: 8, title: 'the list', desc: 'Ante tellus egestas vel hymenaeos, ut viverra nibh ut, ipsum nibh donec donec dolor. Eros ridiculus vel egestas convallis ipsum, commodo ut venenatis nullam porta iaculis, suspendisse ante proin leo, felis risus etiam.' }, { rank: 9, title: 'to witness', desc: 'Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst.' }, { rank: 10, title: 'the effect', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris' }]
|
||||
};
|
||||
|
||||
function select(m) {
|
||||
data.selected = m;
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
var fadeInOutStyle = {
|
||||
opacity: '0', delayed: { opacity: '1' }, remove: { opacity: '0' }
|
||||
};
|
||||
|
||||
var detailView = function detailView(movie) {
|
||||
return h('div.page', { style: fadeInOutStyle }, [h('div.header', [h('div.header-content.detail', {
|
||||
style: { opacity: '1', remove: { opacity: '0' } }
|
||||
}, [h('div.rank', [h('span.header-rank.hero', { hero: { id: 'rank' + movie.rank } }, movie.rank), h('div.rank-circle', {
|
||||
style: { transform: 'scale(0)',
|
||||
delayed: { transform: 'scale(1)' },
|
||||
destroy: { transform: 'scale(0)' } }
|
||||
})]), h('div.hero.header-title', { hero: { id: movie.title } }, movie.title), h('div.spacer'), h('div.close', {
|
||||
on: { click: [select, undefined] },
|
||||
style: { transform: 'scale(0)',
|
||||
delayed: { transform: 'scale(1)' },
|
||||
destroy: { transform: 'scale(0)' } }
|
||||
}, 'x')])]), h('div.page-content', [h('div.desc', {
|
||||
style: { opacity: '0', transform: 'translateX(3em)',
|
||||
delayed: { opacity: '1', transform: 'translate(0)' },
|
||||
remove: { opacity: '0', position: 'absolute', top: '0', left: '0',
|
||||
transform: 'translateX(3em)' }
|
||||
}
|
||||
}, [h('h2', 'Description:'), h('span', movie.desc)])])]);
|
||||
};
|
||||
|
||||
var overviewView = function overviewView(movies) {
|
||||
return h('div.page', { style: fadeInOutStyle }, [h('div.header', [h('div.header-content.overview', {
|
||||
style: fadeInOutStyle
|
||||
}, [h('div.header-title', {
|
||||
style: { transform: 'translateY(-2em)',
|
||||
delayed: { transform: 'translate(0)' },
|
||||
destroy: { transform: 'translateY(-2em)' } }
|
||||
}, 'Top 10 movies'), h('div.spacer')])]), h('div.page-content', [h('div.list', {
|
||||
style: { opacity: '0', delayed: { opacity: '1' },
|
||||
remove: { opacity: '0', position: 'absolute', top: '0', left: '0' } }
|
||||
}, movies.map(function (movie) {
|
||||
return h('div.row', {
|
||||
on: { click: [select, movie] }
|
||||
}, [h('div.hero.rank', [h('span.hero', { hero: { id: 'rank' + movie.rank } }, movie.rank)]), h('div.hero', { hero: { id: movie.title } }, movie.title)]);
|
||||
}))])]);
|
||||
};
|
||||
|
||||
var view = function view(data) {
|
||||
return h('div.page-container', [data.selected ? detailView(data.selected) : overviewView(data.movies)]);
|
||||
};
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
var container = document.getElementById('container');
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
|
||||
},{"../../h.js":2,"../../modules/class":4,"../../modules/eventlisteners":5,"../../modules/hero":6,"../../modules/style":7,"../../snabbdom.js":8}],2:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function addNS(data, children) {
|
||||
data.ns = 'http://www.w3.org/2000/svg';
|
||||
if (children !== undefined) {
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
addNS(children[i].data, children[i].children);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function h(sel, b, c) {
|
||||
var data = {},
|
||||
children,
|
||||
text,
|
||||
i;
|
||||
if (arguments.length === 3) {
|
||||
data = b;
|
||||
if (is.array(c)) {
|
||||
children = c;
|
||||
} else if (is.primitive(c)) {
|
||||
text = c;
|
||||
}
|
||||
} else if (arguments.length === 2) {
|
||||
if (is.array(b)) {
|
||||
children = b;
|
||||
} else if (is.primitive(b)) {
|
||||
text = b;
|
||||
} else {
|
||||
data = b;
|
||||
}
|
||||
}
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
|
||||
}
|
||||
}
|
||||
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
|
||||
addNS(data, children);
|
||||
}
|
||||
return VNode(sel, data, children, text, undefined);
|
||||
};
|
||||
|
||||
},{"./is":3,"./vnode":9}],3:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
array: Array.isArray,
|
||||
primitive: function primitive(s) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
}
|
||||
};
|
||||
|
||||
},{}],4:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
function updateClass(oldVnode, vnode) {
|
||||
var cur,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
oldClass = oldVnode.data['class'] || {},
|
||||
klass = vnode.data['class'] || {};
|
||||
for (name in klass) {
|
||||
cur = klass[name];
|
||||
if (cur !== oldClass[name]) {
|
||||
elm.classList[cur ? 'add' : 'remove'](name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateClass, update: updateClass };
|
||||
|
||||
},{}],5:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var is = require('../is');
|
||||
|
||||
function arrInvoker(arr) {
|
||||
return function () {
|
||||
// Special case when length is two, for performance
|
||||
arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1));
|
||||
};
|
||||
}
|
||||
|
||||
function fnInvoker(o) {
|
||||
return function (ev) {
|
||||
o.fn(ev);
|
||||
};
|
||||
}
|
||||
|
||||
function updateEventListeners(oldVnode, vnode) {
|
||||
var name,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldOn = oldVnode.data.on || {},
|
||||
on = vnode.data.on;
|
||||
if (!on) return;
|
||||
for (name in on) {
|
||||
cur = on[name];
|
||||
old = oldOn[name];
|
||||
if (old === undefined) {
|
||||
if (is.array(cur)) {
|
||||
elm.addEventListener(name, arrInvoker(cur));
|
||||
} else {
|
||||
cur = { fn: cur };
|
||||
on[name] = cur;
|
||||
elm.addEventListener(name, fnInvoker(cur));
|
||||
}
|
||||
} else if (is.array(old)) {
|
||||
// Deliberately modify old array since it's captured in closure created with `arrInvoker`
|
||||
old.length = cur.length;
|
||||
for (var i = 0; i < old.length; ++i) old[i] = cur[i];
|
||||
on[name] = old;
|
||||
} else {
|
||||
old.fn = cur;
|
||||
on[name] = old;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateEventListeners, update: updateEventListeners };
|
||||
|
||||
},{"../is":3}],6:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var raf = window && window.requestAnimationFrame || setTimeout;
|
||||
var nextFrame = function nextFrame(fn) {
|
||||
raf(function () {
|
||||
raf(fn);
|
||||
});
|
||||
};
|
||||
|
||||
function setNextFrame(obj, prop, val) {
|
||||
nextFrame(function () {
|
||||
obj[prop] = val;
|
||||
});
|
||||
}
|
||||
|
||||
function getTextNodeRect(textNode) {
|
||||
var rect;
|
||||
if (document.createRange) {
|
||||
var range = document.createRange();
|
||||
range.selectNodeContents(textNode);
|
||||
if (range.getBoundingClientRect) {
|
||||
rect = range.getBoundingClientRect();
|
||||
}
|
||||
}
|
||||
return rect;
|
||||
}
|
||||
|
||||
function calcTransformOrigin(isTextNode, textRect, boundingRect) {
|
||||
if (isTextNode) {
|
||||
if (textRect) {
|
||||
//calculate pixels to center of text from left edge of bounding box
|
||||
var relativeCenterX = textRect.left + textRect.width / 2 - boundingRect.left;
|
||||
var relativeCenterY = textRect.top + textRect.height / 2 - boundingRect.top;
|
||||
return relativeCenterX + 'px ' + relativeCenterY + 'px';
|
||||
}
|
||||
}
|
||||
return '0 0'; //top left
|
||||
}
|
||||
|
||||
function getTextDx(oldTextRect, newTextRect) {
|
||||
if (oldTextRect && newTextRect) {
|
||||
return oldTextRect.left + oldTextRect.width / 2 - (newTextRect.left + newTextRect.width / 2);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function getTextDy(oldTextRect, newTextRect) {
|
||||
if (oldTextRect && newTextRect) {
|
||||
return oldTextRect.top + oldTextRect.height / 2 - (newTextRect.top + newTextRect.height / 2);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function isTextElement(elm) {
|
||||
return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3;
|
||||
}
|
||||
|
||||
var removed, created;
|
||||
|
||||
function pre(oldVnode, vnode) {
|
||||
removed = {};
|
||||
created = [];
|
||||
}
|
||||
|
||||
function create(oldVnode, vnode) {
|
||||
var hero = vnode.data.hero;
|
||||
if (hero && hero.id) {
|
||||
created.push(hero.id);
|
||||
created.push(vnode);
|
||||
}
|
||||
}
|
||||
|
||||
function destroy(vnode) {
|
||||
var hero = vnode.data.hero;
|
||||
if (hero && hero.id) {
|
||||
var elm = vnode.elm;
|
||||
vnode.isTextNode = isTextElement(elm); //is this a text node?
|
||||
vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode
|
||||
vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node
|
||||
var computedStyle = window.getComputedStyle(elm, null); //get current styles (includes inherited properties)
|
||||
vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values
|
||||
removed[hero.id] = vnode;
|
||||
}
|
||||
}
|
||||
|
||||
function post() {
|
||||
var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect;
|
||||
for (i = 0; i < created.length; i += 2) {
|
||||
id = created[i];
|
||||
newElm = created[i + 1].elm;
|
||||
oldVnode = removed[id];
|
||||
if (oldVnode) {
|
||||
isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text?
|
||||
newStyle = newElm.style;
|
||||
newComputedStyle = window.getComputedStyle(newElm, null); //get full computed style for new element
|
||||
oldElm = oldVnode.elm;
|
||||
oldStyle = oldElm.style;
|
||||
//Overall element bounding boxes
|
||||
newRect = newElm.getBoundingClientRect();
|
||||
oldRect = oldVnode.boundingRect; //previously saved bounding rect
|
||||
//Text node bounding boxes & distances
|
||||
if (isTextNode) {
|
||||
newTextRect = getTextNodeRect(newElm.childNodes[0]);
|
||||
oldTextRect = oldVnode.textRect;
|
||||
dx = getTextDx(oldTextRect, newTextRect);
|
||||
dy = getTextDy(oldTextRect, newTextRect);
|
||||
} else {
|
||||
//Calculate distances between old & new positions
|
||||
dx = oldRect.left - newRect.left;
|
||||
dy = oldRect.top - newRect.top;
|
||||
}
|
||||
hRatio = newRect.height / Math.max(oldRect.height, 1);
|
||||
wRatio = isTextNode ? hRatio : newRect.width / Math.max(oldRect.width, 1); //text scales based on hRatio
|
||||
// Animate new element
|
||||
origTransform = newStyle.transform;
|
||||
origTransition = newStyle.transition;
|
||||
if (newComputedStyle.display === 'inline') //inline elements cannot be transformed
|
||||
newStyle.display = 'inline-block'; //this does not appear to have any negative side effects
|
||||
newStyle.transition = origTransition + 'transform 0s';
|
||||
newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect);
|
||||
newStyle.opacity = '0';
|
||||
newStyle.transform = origTransform + 'translate(' + dx + 'px, ' + dy + 'px) ' + 'scale(' + 1 / wRatio + ', ' + 1 / hRatio + ')';
|
||||
setNextFrame(newStyle, 'transition', origTransition);
|
||||
setNextFrame(newStyle, 'transform', origTransform);
|
||||
setNextFrame(newStyle, 'opacity', '1');
|
||||
// Animate old element
|
||||
for (var key in oldVnode.savedStyle) {
|
||||
//re-apply saved inherited properties
|
||||
if (parseInt(key) != key) {
|
||||
var ms = key.substring(0, 2) === 'ms';
|
||||
var moz = key.substring(0, 3) === 'moz';
|
||||
var webkit = key.substring(0, 6) === 'webkit';
|
||||
if (!ms && !moz && !webkit) //ignore prefixed style properties
|
||||
oldStyle[key] = oldVnode.savedStyle[key];
|
||||
}
|
||||
}
|
||||
oldStyle.position = 'absolute';
|
||||
oldStyle.top = oldRect.top + 'px'; //start at existing position
|
||||
oldStyle.left = oldRect.left + 'px';
|
||||
oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents
|
||||
oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents
|
||||
oldStyle.margin = 0; //Margin on hero element leads to incorrect positioning
|
||||
oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect);
|
||||
oldStyle.transform = '';
|
||||
oldStyle.opacity = '1';
|
||||
document.body.appendChild(oldElm);
|
||||
setNextFrame(oldStyle, 'transform', 'translate(' + -dx + 'px, ' + -dy + 'px) scale(' + wRatio + ', ' + hRatio + ')'); //scale must be on far right for translate to be correct
|
||||
setNextFrame(oldStyle, 'opacity', '0');
|
||||
oldElm.addEventListener('transitionend', function (ev) {
|
||||
if (ev.propertyName === 'transform') document.body.removeChild(ev.target);
|
||||
});
|
||||
}
|
||||
}
|
||||
removed = created = undefined;
|
||||
}
|
||||
|
||||
module.exports = { pre: pre, create: create, destroy: destroy, post: post };
|
||||
|
||||
},{}],7:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var raf = requestAnimationFrame || setTimeout;
|
||||
var nextFrame = function nextFrame(fn) {
|
||||
raf(function () {
|
||||
raf(fn);
|
||||
});
|
||||
};
|
||||
|
||||
function setNextFrame(obj, prop, val) {
|
||||
nextFrame(function () {
|
||||
obj[prop] = val;
|
||||
});
|
||||
}
|
||||
|
||||
function updateStyle(oldVnode, vnode) {
|
||||
var cur,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
oldStyle = oldVnode.data.style || {},
|
||||
style = vnode.data.style || {},
|
||||
oldHasDel = ('delayed' in oldStyle);
|
||||
for (name in style) {
|
||||
cur = style[name];
|
||||
if (name === 'delayed') {
|
||||
for (name in style.delayed) {
|
||||
cur = style.delayed[name];
|
||||
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
|
||||
setNextFrame(elm.style, name, cur);
|
||||
}
|
||||
}
|
||||
} else if (name !== 'remove' && cur !== oldStyle[name]) {
|
||||
elm.style[name] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyDestroyStyle(vnode) {
|
||||
var style,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
s = vnode.data.style;
|
||||
if (!s || !(style = s.destroy)) return;
|
||||
for (name in style) {
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
}
|
||||
|
||||
function applyRemoveStyle(vnode, rm) {
|
||||
var s = vnode.data.style;
|
||||
if (!s || !s.remove) {
|
||||
rm();
|
||||
return;
|
||||
}
|
||||
var name,
|
||||
elm = vnode.elm,
|
||||
idx,
|
||||
i = 0,
|
||||
maxDur = 0,
|
||||
compStyle,
|
||||
style = s.remove,
|
||||
amount = 0,
|
||||
applied = [];
|
||||
for (name in style) {
|
||||
applied.push(name);
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
compStyle = getComputedStyle(elm);
|
||||
var props = compStyle['transition-property'].split(', ');
|
||||
for (; i < props.length; ++i) {
|
||||
if (applied.indexOf(props[i]) !== -1) amount++;
|
||||
}
|
||||
elm.addEventListener('transitionend', function (ev) {
|
||||
if (ev.target === elm) --amount;
|
||||
if (amount === 0) rm();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
|
||||
|
||||
},{}],8:[function(require,module,exports){
|
||||
// jshint newcap: false
|
||||
/* global require, module, document, Element */
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function isUndef(s) {
|
||||
return s === undefined;
|
||||
}
|
||||
function isDef(s) {
|
||||
return s !== undefined;
|
||||
}
|
||||
|
||||
function emptyNodeAt(elm) {
|
||||
return VNode(elm.tagName, {}, [], undefined, elm);
|
||||
}
|
||||
|
||||
var emptyNode = VNode('', {}, [], undefined, undefined);
|
||||
|
||||
function sameVnode(vnode1, vnode2) {
|
||||
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
|
||||
}
|
||||
|
||||
function createKeyToOldIdx(children, beginIdx, endIdx) {
|
||||
var i,
|
||||
map = {},
|
||||
key;
|
||||
for (i = beginIdx; i <= endIdx; ++i) {
|
||||
key = children[i].key;
|
||||
if (isDef(key)) map[key] = i;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function createRmCb(childElm, listeners) {
|
||||
return function () {
|
||||
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
|
||||
};
|
||||
}
|
||||
|
||||
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
|
||||
|
||||
function init(modules) {
|
||||
var i,
|
||||
j,
|
||||
cbs = {};
|
||||
for (i = 0; i < hooks.length; ++i) {
|
||||
cbs[hooks[i]] = [];
|
||||
for (j = 0; j < modules.length; ++j) {
|
||||
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
|
||||
}
|
||||
}
|
||||
|
||||
function createElm(vnode, insertedVnodeQueue) {
|
||||
var i,
|
||||
data = vnode.data;
|
||||
if (isDef(data)) {
|
||||
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
|
||||
if (isDef(i = data.vnode)) vnode = i;
|
||||
}
|
||||
var elm,
|
||||
children = vnode.children,
|
||||
sel = vnode.sel;
|
||||
if (isDef(sel)) {
|
||||
// Parse selector
|
||||
var hashIdx = sel.indexOf('#');
|
||||
var dotIdx = sel.indexOf('.', hashIdx);
|
||||
var hash = hashIdx > 0 ? hashIdx : sel.length;
|
||||
var dot = dotIdx > 0 ? dotIdx : sel.length;
|
||||
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
||||
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
|
||||
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
|
||||
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
elm.appendChild(createElm(children[i], insertedVnodeQueue));
|
||||
}
|
||||
} else if (is.primitive(vnode.text)) {
|
||||
elm.appendChild(document.createTextNode(vnode.text));
|
||||
}
|
||||
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
|
||||
i = vnode.data.hook; // Reuse variable
|
||||
if (isDef(i)) {
|
||||
if (i.create) i.create(emptyNode, vnode);
|
||||
if (i.insert) insertedVnodeQueue.push(vnode);
|
||||
}
|
||||
} else {
|
||||
elm = vnode.elm = document.createTextNode(vnode.text);
|
||||
}
|
||||
return vnode.elm;
|
||||
}
|
||||
|
||||
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
|
||||
}
|
||||
}
|
||||
|
||||
function invokeDestroyHook(vnode) {
|
||||
var i = vnode.data,
|
||||
j;
|
||||
if (isDef(i)) {
|
||||
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
|
||||
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
|
||||
if (isDef(i = vnode.children)) {
|
||||
for (j = 0; j < vnode.children.length; ++j) {
|
||||
invokeDestroyHook(vnode.children[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
var i,
|
||||
listeners,
|
||||
rm,
|
||||
ch = vnodes[startIdx];
|
||||
if (isDef(ch)) {
|
||||
if (isDef(ch.sel)) {
|
||||
invokeDestroyHook(ch);
|
||||
listeners = cbs.remove.length + 1;
|
||||
rm = createRmCb(ch.elm, listeners);
|
||||
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
|
||||
if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
|
||||
i(ch, rm);
|
||||
} else {
|
||||
rm();
|
||||
}
|
||||
} else {
|
||||
// Text node
|
||||
parentElm.removeChild(ch.elm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
|
||||
var oldStartIdx = 0,
|
||||
newStartIdx = 0;
|
||||
var oldEndIdx = oldCh.length - 1;
|
||||
var oldStartVnode = oldCh[0];
|
||||
var oldEndVnode = oldCh[oldEndIdx];
|
||||
var newEndIdx = newCh.length - 1;
|
||||
var newStartVnode = newCh[0];
|
||||
var newEndVnode = newCh[newEndIdx];
|
||||
var oldKeyToIdx, idxInOld, elmToMove, before;
|
||||
|
||||
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
|
||||
if (isUndef(oldStartVnode)) {
|
||||
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
|
||||
} else if (isUndef(oldEndVnode)) {
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newStartVnode)) {
|
||||
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else if (sameVnode(oldEndVnode, newEndVnode)) {
|
||||
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newEndVnode)) {
|
||||
// Vnode moved right
|
||||
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldEndVnode, newStartVnode)) {
|
||||
// Vnode moved left
|
||||
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
|
||||
idxInOld = oldKeyToIdx[newStartVnode.key];
|
||||
if (isUndef(idxInOld)) {
|
||||
// New element
|
||||
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
elmToMove = oldCh[idxInOld];
|
||||
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
|
||||
oldCh[idxInOld] = undefined;
|
||||
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (oldStartIdx > oldEndIdx) {
|
||||
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
|
||||
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
|
||||
} else if (newStartIdx > newEndIdx) {
|
||||
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
|
||||
}
|
||||
}
|
||||
|
||||
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
|
||||
var i, hook;
|
||||
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
|
||||
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
|
||||
var elm = vnode.elm = oldVnode.elm,
|
||||
oldCh = oldVnode.children,
|
||||
ch = vnode.children;
|
||||
if (oldVnode === vnode) return;
|
||||
if (isDef(vnode.data)) {
|
||||
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
|
||||
i = vnode.data.hook;
|
||||
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
|
||||
}
|
||||
if (isUndef(vnode.text)) {
|
||||
if (isDef(oldCh) && isDef(ch)) {
|
||||
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
|
||||
} else if (isDef(ch)) {
|
||||
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
|
||||
} else if (isDef(oldCh)) {
|
||||
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
|
||||
}
|
||||
} else if (oldVnode.text !== vnode.text) {
|
||||
elm.textContent = vnode.text;
|
||||
}
|
||||
if (isDef(hook) && isDef(i = hook.postpatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
}
|
||||
|
||||
return function (oldVnode, vnode) {
|
||||
var i;
|
||||
var insertedVnodeQueue = [];
|
||||
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
|
||||
if (oldVnode instanceof Element) {
|
||||
if (oldVnode.parentElement !== null) {
|
||||
createElm(vnode, insertedVnodeQueue);
|
||||
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
|
||||
} else {
|
||||
oldVnode = emptyNodeAt(oldVnode);
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
} else {
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
for (i = 0; i < insertedVnodeQueue.length; ++i) {
|
||||
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
|
||||
}
|
||||
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
|
||||
return vnode;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { init: init };
|
||||
|
||||
},{"./is":3,"./vnode":9}],9:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
module.exports = function (sel, data, children, text, elm) {
|
||||
var key = data === undefined ? undefined : data.key;
|
||||
return { sel: sel, data: data, children: children,
|
||||
text: text, elm: elm, key: key };
|
||||
};
|
||||
|
||||
},{}]},{},[1]);
|
||||
@@ -1,166 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<title>Hero animation</title>
|
||||
<script type="text/javascript" src="build.js"></script>
|
||||
<style>
|
||||
{
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
body {
|
||||
background: #fff;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
.page-container {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
background: #fff;
|
||||
}
|
||||
@media (min-width: 28em),
|
||||
@media (min-height: 38em) {
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #aaaaaa;
|
||||
position: relative;
|
||||
}
|
||||
.page-container {
|
||||
box-shadow: 0 0 1em rgba(0, 0, 0, .5);
|
||||
width: 28em;
|
||||
min-height: 38em;
|
||||
height: 38em;
|
||||
}
|
||||
}
|
||||
.page {
|
||||
background: #fff;
|
||||
transition: opacity 0.4s ease-in-out,
|
||||
transform 0.4s ease-in-out;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
h2 {
|
||||
font-size: 1.1em;
|
||||
margin: .2em 0;
|
||||
}
|
||||
.header {
|
||||
height: 3.5em;
|
||||
background: #1293ea;
|
||||
overflow: hidden;
|
||||
}
|
||||
.header-content {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: .4em .8em;
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
position: absolute;
|
||||
transition: opacity 0.4s ease-in-out,
|
||||
transform 0.4s ease-in-out;
|
||||
}
|
||||
.header h1 {
|
||||
font-weight: normal;
|
||||
margin: 0;
|
||||
font-size: 1.5em;
|
||||
line-height: 1.8em;
|
||||
}
|
||||
.header-title {
|
||||
color: #fff;
|
||||
font-size: 1.5em;
|
||||
line-height: 1.8em;
|
||||
transition: transform 0.4s ease-in-out;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.header .rank {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 2.7em;
|
||||
height: 2.7em;
|
||||
margin-right: .5em;
|
||||
position: relative;
|
||||
}
|
||||
.header .rank-circle {
|
||||
position: absolute;
|
||||
background: #fff;
|
||||
width: 2.7em;
|
||||
height: 2.7em;
|
||||
border-radius: 1.35em;
|
||||
margin-right: .5em;
|
||||
transition: transform 0.4s ease-in-out;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
.header-rank {
|
||||
z-index: 2;
|
||||
color: #1293ea;
|
||||
font-size: 1.5em;
|
||||
}
|
||||
.header .close {
|
||||
line-height: 1.8em;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
width: 1.8em;
|
||||
height: 1.8em;
|
||||
border-radius: .9em;
|
||||
background: rgba(0, 0, 0, .5);
|
||||
transition: transform 0.4s ease-in-out;
|
||||
}
|
||||
.hero {
|
||||
transition: transform 0.4s ease-in-out,
|
||||
opacity 0.4s ease-in-out;
|
||||
}
|
||||
.page-content {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: calc(100% - 3.5em);
|
||||
}
|
||||
.list {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
transition: transform 0.4s ease-in-out,
|
||||
opacity 0.4s ease-in-out;
|
||||
}
|
||||
.desc {
|
||||
position: absolute;
|
||||
transition: transform 0.4s ease-in-out,
|
||||
opacity 0.4s ease-in-out;
|
||||
padding: 1em;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.row {
|
||||
cursor: pointer;
|
||||
box-sizing: border-box;
|
||||
padding: 1em;
|
||||
}
|
||||
.row:not(:first-child) {
|
||||
border-top: 1px solid #eeeeee;
|
||||
}
|
||||
.row div {
|
||||
display: inline-block;
|
||||
}
|
||||
.row > div:nth-child(1) {
|
||||
text-align: center;
|
||||
margin-right: 1em;
|
||||
width: 1em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,120 +0,0 @@
|
||||
/* jshint esnext: true */
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([
|
||||
require('../../modules/class').default,
|
||||
require('../../modules/hero').default,
|
||||
require('../../modules/style').default,
|
||||
require('../../modules/eventlisteners').default,
|
||||
]);
|
||||
var h = require('../../h.js').default;
|
||||
|
||||
var vnode;
|
||||
|
||||
var data = {
|
||||
selected: undefined,
|
||||
movies: [
|
||||
{rank: 1, title: 'This is an', desc: 'Lorem ipsum dolor sit amet, sed pede integer vitae bibendum, accumsan sit, vulputate aenean tempora ipsum. Lorem sed id et metus, eros posuere suspendisse nec nunc justo, fusce augue placerat nibh purus suspendisse. Aliquam aliquam, ut eget. Mollis a eget sed nibh tincidunt nec, mi integer, proin magna lacus iaculis tortor. Aliquam vel arcu arcu, vivamus a urna fames felis vel wisi, cursus tortor nec erat dignissim cras sem, mauris ac venenatis tellus elit.'},
|
||||
{rank: 2, title: 'example of', desc: 'Consequuntur ipsum nulla, consequat curabitur in magnis risus. Taciti mattis bibendum tellus nibh, at dui neque eget, odio pede ut, sapien pede, ipsum ut. Sagittis dui, sodales sem, praesent ipsum conubia eget lorem lobortis wisi.'},
|
||||
{rank: 3, title: 'Snabbdom', desc: 'Quam lorem aliquam fusce wisi, urna purus ipsum pharetra sed, at cras sodales enim vestibulum odio cras, luctus integer phasellus.'},
|
||||
{rank: 4, title: 'doing hero transitions', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.'},
|
||||
{rank: 5, title: 'using the', desc: 'Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.'},
|
||||
{rank: 6, title: 'module for hero transitions', desc: 'Sapien laoreet, ligula elit tortor nulla pellentesque, maecenas enim turpis, quae duis venenatis vivamus ultricies, nunc imperdiet sollicitudin ipsum malesuada. Ut sem. Wisi fusce nullam nibh enim. Nisl hymenaeos id sed sed in. Proin leo et, pulvinar nunc pede laoreet.'},
|
||||
{rank: 7, title: 'click on ar element in', desc: 'Accumsan quia, id nascetur dui et congue erat, id excepteur, primis ratione nec. At nulla et. Suspendisse lobortis, lobortis in tortor fringilla, duis adipiscing vestibulum voluptates sociosqu auctor.'},
|
||||
{rank: 8, title: 'the list', desc: 'Ante tellus egestas vel hymenaeos, ut viverra nibh ut, ipsum nibh donec donec dolor. Eros ridiculus vel egestas convallis ipsum, commodo ut venenatis nullam porta iaculis, suspendisse ante proin leo, felis risus etiam.'},
|
||||
{rank: 9, title: 'to witness', desc: 'Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst.'},
|
||||
{rank: 10, title: 'the effect', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris'},
|
||||
]
|
||||
};
|
||||
|
||||
function select(m) {
|
||||
data.selected = m;
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
const fadeInOutStyle = {
|
||||
opacity: '0', delayed: {opacity: '1'}, remove: {opacity: '0'}
|
||||
};
|
||||
|
||||
const detailView = (movie) =>
|
||||
h('div.page', {style: fadeInOutStyle}, [
|
||||
h('div.header', [
|
||||
h('div.header-content.detail', {
|
||||
style: {opacity: '1', remove: {opacity: '0'}},
|
||||
}, [
|
||||
h('div.rank', [
|
||||
h('span.header-rank.hero', {hero: {id: 'rank'+movie.rank}}, movie.rank),
|
||||
h('div.rank-circle', {
|
||||
style: {transform: 'scale(0)',
|
||||
delayed: {transform: 'scale(1)'},
|
||||
destroy: {transform: 'scale(0)'}},
|
||||
}),
|
||||
]),
|
||||
h('div.hero.header-title', {hero: {id: movie.title}}, movie.title),
|
||||
h('div.spacer'),
|
||||
h('div.close', {
|
||||
on: {click: [select, undefined]},
|
||||
style: {transform: 'scale(0)',
|
||||
delayed: {transform: 'scale(1)'},
|
||||
destroy: {transform: 'scale(0)'}},
|
||||
}, 'x'),
|
||||
]),
|
||||
]),
|
||||
h('div.page-content', [
|
||||
h('div.desc', {
|
||||
style: {opacity: '0', transform: 'translateX(3em)',
|
||||
delayed: {opacity: '1', transform: 'translate(0)'},
|
||||
remove: {opacity: '0', position: 'absolute', top: '0', left: '0',
|
||||
transform: 'translateX(3em)'}
|
||||
}
|
||||
}, [
|
||||
h('h2', 'Description:'),
|
||||
h('span', movie.desc),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
|
||||
const overviewView = (movies) =>
|
||||
h('div.page', {style: fadeInOutStyle}, [
|
||||
h('div.header', [
|
||||
h('div.header-content.overview', {
|
||||
style: fadeInOutStyle,
|
||||
}, [
|
||||
h('div.header-title', {
|
||||
style: {transform: 'translateY(-2em)',
|
||||
delayed: {transform: 'translate(0)'},
|
||||
destroy: {transform: 'translateY(-2em)'}}
|
||||
}, 'Top 10 movies'),
|
||||
h('div.spacer'),
|
||||
]),
|
||||
]),
|
||||
h('div.page-content', [
|
||||
h('div.list', {
|
||||
style: {opacity: '0', delayed: {opacity: '1'},
|
||||
remove: {opacity: '0', position: 'absolute', top: '0', left: '0'}}
|
||||
}, movies.map((movie) =>
|
||||
h('div.row', {
|
||||
on: {click: [select, movie]},
|
||||
}, [
|
||||
h('div.hero.rank', [
|
||||
h('span.hero', {hero: {id: 'rank'+movie.rank}}, movie.rank)
|
||||
]),
|
||||
h('div.hero', {hero: {id: movie.title}}, movie.title)
|
||||
])
|
||||
)),
|
||||
]),
|
||||
]);
|
||||
|
||||
const view = (data) =>
|
||||
h('div.page-container', [
|
||||
data.selected ? detailView(data.selected) : overviewView(data.movies),
|
||||
]);
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
var container = document.getElementById('container');
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
@@ -1,523 +0,0 @@
|
||||
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([require('../../modules/class'), require('../../modules/props'), require('../../modules/style'), require('../../modules/eventlisteners')]);
|
||||
var h = require('../../h.js');
|
||||
|
||||
var vnode;
|
||||
|
||||
var nextKey = 11;
|
||||
var margin = 8;
|
||||
var sortBy = 'rank';
|
||||
var totalHeight = 0;
|
||||
var originalData = [{ rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0 }, { rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0 }, { rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0 }, { rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0 }, { rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0 }, { rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0 }, { rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0 }, { rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0 }, { rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0 }, { rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0 }];
|
||||
var data = [originalData[0], originalData[1], originalData[2], originalData[3], originalData[4], originalData[5], originalData[6], originalData[7], originalData[8], originalData[9]];
|
||||
|
||||
function changeSort(prop) {
|
||||
sortBy = prop;
|
||||
data.sort(function (a, b) {
|
||||
if (a[prop] > b[prop]) {
|
||||
return 1;
|
||||
}
|
||||
if (a[prop] < b[prop]) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
function add() {
|
||||
var n = originalData[Math.floor(Math.random() * 10)];
|
||||
data = [{ rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0 }].concat(data);
|
||||
render();
|
||||
render();
|
||||
}
|
||||
|
||||
function remove(movie) {
|
||||
data = data.filter(function (m) {
|
||||
return m !== movie;
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
function movieView(movie) {
|
||||
return h('div.row', {
|
||||
key: movie.rank,
|
||||
style: { opacity: '0', transform: 'translate(-200px)',
|
||||
delayed: { transform: 'translateY(' + movie.offset + 'px)', opacity: '1' },
|
||||
remove: { opacity: '0', transform: 'translateY(' + movie.offset + 'px) translateX(200px)' } },
|
||||
hook: { insert: function insert(vnode) {
|
||||
movie.elmHeight = vnode.elm.offsetHeight;
|
||||
} } }, [h('div', { style: { fontWeight: 'bold' } }, movie.rank), h('div', movie.title), h('div', movie.desc), h('div.btn.rm-btn', { on: { click: [remove, movie] } }, 'x')]);
|
||||
}
|
||||
|
||||
function render() {
|
||||
data = data.reduce(function (acc, m) {
|
||||
var last = acc[acc.length - 1];
|
||||
m.offset = last ? last.offset + last.elmHeight + margin : margin;
|
||||
return acc.concat(m);
|
||||
}, []);
|
||||
totalHeight = data[data.length - 1].offset + data[data.length - 1].elmHeight;
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
function view(data) {
|
||||
return h('div', [h('h1', 'Top 10 movies'), h('div', [h('a.btn.add', { on: { click: add } }, 'Add'), 'Sort by: ', h('span.btn-group', [h('a.btn.rank', { 'class': { active: sortBy === 'rank' }, on: { click: [changeSort, 'rank'] } }, 'Rank'), h('a.btn.title', { 'class': { active: sortBy === 'title' }, on: { click: [changeSort, 'title'] } }, 'Title'), h('a.btn.desc', { 'class': { active: sortBy === 'desc' }, on: { click: [changeSort, 'desc'] } }, 'Description')])]), h('div.list', { style: { height: totalHeight + 'px' } }, data.map(movieView))]);
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
var container = document.getElementById('container');
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
|
||||
},{"../../h.js":2,"../../modules/class":4,"../../modules/eventlisteners":5,"../../modules/props":6,"../../modules/style":7,"../../snabbdom.js":8}],2:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
module.exports = function h(sel, b, c) {
|
||||
var data = {},
|
||||
children,
|
||||
text,
|
||||
i;
|
||||
if (arguments.length === 3) {
|
||||
data = b;
|
||||
if (is.array(c)) {
|
||||
children = c;
|
||||
} else if (is.primitive(c)) {
|
||||
text = c;
|
||||
}
|
||||
} else if (arguments.length === 2) {
|
||||
if (is.array(b)) {
|
||||
children = b;
|
||||
} else if (is.primitive(b)) {
|
||||
text = b;
|
||||
} else {
|
||||
data = b;
|
||||
}
|
||||
}
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
|
||||
}
|
||||
}
|
||||
return VNode(sel, data, children, text, undefined);
|
||||
};
|
||||
|
||||
},{"./is":3,"./vnode":9}],3:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
array: Array.isArray,
|
||||
primitive: function primitive(s) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
} };
|
||||
|
||||
},{}],4:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
function updateClass(oldVnode, vnode) {
|
||||
var cur,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
oldClass = oldVnode.data['class'] || {},
|
||||
klass = vnode.data['class'] || {};
|
||||
for (name in klass) {
|
||||
cur = klass[name];
|
||||
if (cur !== oldClass[name]) {
|
||||
elm.classList[cur ? 'add' : 'remove'](name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateClass, update: updateClass };
|
||||
|
||||
},{}],5:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var is = require('../is');
|
||||
|
||||
function arrInvoker(arr) {
|
||||
return function () {
|
||||
arr[0](arr[1]);
|
||||
};
|
||||
}
|
||||
|
||||
function updateEventListeners(oldVnode, vnode) {
|
||||
var name,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldOn = oldVnode.data.on || {},
|
||||
on = vnode.data.on;
|
||||
if (!on) return;
|
||||
for (name in on) {
|
||||
cur = on[name];
|
||||
old = oldOn[name];
|
||||
if (old === undefined) {
|
||||
elm.addEventListener(name, is.array(cur) ? arrInvoker(cur) : cur);
|
||||
} else if (is.array(old)) {
|
||||
old[0] = cur[0]; // Deliberately modify old array since it's
|
||||
old[1] = cur[1]; // captured in closure created with `arrInvoker`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateEventListeners, update: updateEventListeners };
|
||||
|
||||
},{"../is":3}],6:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
function updateProps(oldVnode, vnode) {
|
||||
var key,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldProps = oldVnode.data.props || {},
|
||||
props = vnode.data.props || {};
|
||||
for (key in props) {
|
||||
cur = props[key];
|
||||
old = oldProps[key];
|
||||
if (old !== cur) {
|
||||
elm[key] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateProps, update: updateProps };
|
||||
|
||||
},{}],7:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var raf = requestAnimationFrame || setTimeout;
|
||||
var nextFrame = function nextFrame(fn) {
|
||||
raf(function () {
|
||||
raf(fn);
|
||||
});
|
||||
};
|
||||
|
||||
function setNextFrame(obj, prop, val) {
|
||||
nextFrame(function () {
|
||||
obj[prop] = val;
|
||||
});
|
||||
}
|
||||
|
||||
function updateStyle(oldVnode, vnode) {
|
||||
var cur,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
oldStyle = oldVnode.data.style || {},
|
||||
style = vnode.data.style || {},
|
||||
oldHasDel = ('delayed' in oldStyle);
|
||||
for (name in style) {
|
||||
cur = style[name];
|
||||
if (name === 'delayed') {
|
||||
for (name in style.delayed) {
|
||||
cur = style.delayed[name];
|
||||
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
|
||||
setNextFrame(elm.style, name, cur);
|
||||
}
|
||||
}
|
||||
} else if (name !== 'remove' && cur !== oldStyle[name]) {
|
||||
elm.style[name] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyDestroyStyle(vnode) {
|
||||
var style,
|
||||
name,
|
||||
elm = vnode.elm,
|
||||
s = vnode.data.style;
|
||||
if (!s || !(style = s.destroy)) return;
|
||||
for (name in style) {
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
}
|
||||
|
||||
function applyRemoveStyle(vnode, rm) {
|
||||
var s = vnode.data.style;
|
||||
if (!s || !s.remove) {
|
||||
rm();
|
||||
return;
|
||||
}
|
||||
var name,
|
||||
elm = vnode.elm,
|
||||
idx,
|
||||
i = 0,
|
||||
maxDur = 0,
|
||||
compStyle,
|
||||
style = s.remove,
|
||||
amount = 0;
|
||||
var applied = [];
|
||||
for (name in style) {
|
||||
applied.push(name);
|
||||
elm.style[name] = style[name];
|
||||
}
|
||||
compStyle = getComputedStyle(elm);
|
||||
var props = compStyle['transition-property'].split(', ');
|
||||
for (; i < props.length; ++i) {
|
||||
if (applied.indexOf(props[i]) !== -1) amount++;
|
||||
}
|
||||
elm.addEventListener('transitionend', function (ev) {
|
||||
if (ev.target === elm) --amount;
|
||||
if (amount === 0) rm();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
|
||||
|
||||
},{}],8:[function(require,module,exports){
|
||||
// jshint newcap: false
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function isUndef(s) {
|
||||
return s === undefined;
|
||||
}
|
||||
|
||||
function emptyNodeAt(elm) {
|
||||
return VNode(elm.tagName, {}, [], undefined, elm);
|
||||
}
|
||||
|
||||
var emptyNode = VNode('', {}, [], undefined, undefined);
|
||||
|
||||
var insertedVnodeQueue;
|
||||
|
||||
function sameVnode(vnode1, vnode2) {
|
||||
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
|
||||
}
|
||||
|
||||
function createKeyToOldIdx(children, beginIdx, endIdx) {
|
||||
var i,
|
||||
map = {},
|
||||
key;
|
||||
for (i = beginIdx; i <= endIdx; ++i) {
|
||||
key = children[i].key;
|
||||
if (!isUndef(key)) map[key] = i;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function createRmCb(parentElm, childElm, listeners) {
|
||||
return function () {
|
||||
if (--listeners === 0) parentElm.removeChild(childElm);
|
||||
};
|
||||
}
|
||||
|
||||
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
|
||||
|
||||
function init(modules) {
|
||||
var i,
|
||||
j,
|
||||
cbs = {};
|
||||
for (i = 0; i < hooks.length; ++i) {
|
||||
cbs[hooks[i]] = [];
|
||||
for (j = 0; j < modules.length; ++j) {
|
||||
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
|
||||
}
|
||||
}
|
||||
|
||||
function createElm(vnode) {
|
||||
var i;
|
||||
if (!isUndef(i = vnode.data) && !isUndef(i = i.hook) && !isUndef(i = i.init)) {
|
||||
i(vnode);
|
||||
}
|
||||
if (!isUndef(i = vnode.data) && !isUndef(i = i.vnode)) vnode = i;
|
||||
var elm,
|
||||
children = vnode.children,
|
||||
sel = vnode.sel;
|
||||
if (!isUndef(sel)) {
|
||||
// Parse selector
|
||||
var hashIdx = sel.indexOf('#');
|
||||
var dotIdx = sel.indexOf('.', hashIdx);
|
||||
var hash = hashIdx > 0 ? hashIdx : sel.length;
|
||||
var dot = dotIdx > 0 ? dotIdx : sel.length;
|
||||
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
||||
elm = vnode.elm = document.createElement(tag);
|
||||
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
|
||||
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
elm.appendChild(createElm(children[i]));
|
||||
}
|
||||
} else if (is.primitive(vnode.text)) {
|
||||
elm.appendChild(document.createTextNode(vnode.text));
|
||||
}
|
||||
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
|
||||
i = vnode.data.hook; // Reuse variable
|
||||
if (!isUndef(i)) {
|
||||
if (i.create) i.create(vnode);
|
||||
if (i.insert) insertedVnodeQueue.push(vnode);
|
||||
}
|
||||
} else {
|
||||
elm = vnode.elm = document.createTextNode(vnode.text);
|
||||
}
|
||||
return elm;
|
||||
}
|
||||
|
||||
function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
|
||||
if (isUndef(before)) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
parentElm.appendChild(createElm(vnodes[startIdx]));
|
||||
}
|
||||
} else {
|
||||
var elm = before.elm;
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
parentElm.insertBefore(createElm(vnodes[startIdx]), elm);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function invokeDestroyHook(vnode) {
|
||||
var i = vnode.data.hook,
|
||||
j;
|
||||
if (!isUndef(i) && !isUndef(j = i.destroy)) j(vnode);
|
||||
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
|
||||
if (!isUndef(vnode.children)) {
|
||||
for (j = 0; j < vnode.children.length; ++j) {
|
||||
invokeDestroyHook(vnode.children[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
var i,
|
||||
listeners,
|
||||
rm,
|
||||
ch = vnodes[startIdx];
|
||||
if (!isUndef(ch)) {
|
||||
listeners = cbs.remove.length + 1;
|
||||
rm = createRmCb(parentElm, ch.elm, listeners);
|
||||
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
|
||||
invokeDestroyHook(ch);
|
||||
if (ch.data.hook && ch.data.hook.remove) {
|
||||
ch.data.hook.remove(ch, rm);
|
||||
} else {
|
||||
rm();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateChildren(parentElm, oldCh, newCh) {
|
||||
var oldStartIdx = 0,
|
||||
newStartIdx = 0;
|
||||
var oldEndIdx = oldCh.length - 1;
|
||||
var oldStartVnode = oldCh[0];
|
||||
var oldEndVnode = oldCh[oldEndIdx];
|
||||
var newEndIdx = newCh.length - 1;
|
||||
var newStartVnode = newCh[0];
|
||||
var newEndVnode = newCh[newEndIdx];
|
||||
var oldKeyToIdx, idxInOld, elmToMove;
|
||||
|
||||
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
|
||||
if (isUndef(oldStartVnode)) {
|
||||
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
|
||||
} else if (isUndef(oldEndVnode)) {
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newStartVnode)) {
|
||||
patchVnode(oldStartVnode, newStartVnode);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else if (sameVnode(oldEndVnode, newEndVnode)) {
|
||||
patchVnode(oldEndVnode, newEndVnode);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newEndVnode)) {
|
||||
// Vnode moved right
|
||||
patchVnode(oldStartVnode, newEndVnode);
|
||||
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldEndVnode, newStartVnode)) {
|
||||
// Vnode moved left
|
||||
patchVnode(oldEndVnode, newStartVnode);
|
||||
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
|
||||
idxInOld = oldKeyToIdx[newStartVnode.key];
|
||||
if (isUndef(idxInOld)) {
|
||||
// New element
|
||||
parentElm.insertBefore(createElm(newStartVnode), oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
elmToMove = oldCh[idxInOld];
|
||||
patchVnode(elmToMove, newStartVnode);
|
||||
oldCh[idxInOld] = undefined;
|
||||
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (oldStartIdx > oldEndIdx) addVnodes(parentElm, oldStartVnode, newCh, newStartIdx, newEndIdx);else if (newStartIdx > newEndIdx) removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
|
||||
}
|
||||
|
||||
function patchVnode(oldVnode, vnode) {
|
||||
var i;
|
||||
if (!isUndef(i = vnode.data) && !isUndef(i = i.hook) && !isUndef(i = i.patch)) {
|
||||
i = i(oldVnode, vnode);
|
||||
}
|
||||
if (!isUndef(i = oldVnode.data) && !isUndef(i = i.vnode)) oldVnode = i;
|
||||
if (!isUndef(i = vnode.data) && !isUndef(i = i.vnode)) vnode = i;
|
||||
var elm = vnode.elm = oldVnode.elm,
|
||||
oldCh = oldVnode.children,
|
||||
ch = vnode.children;
|
||||
if (oldVnode === vnode) return;
|
||||
if (!isUndef(vnode.data)) {
|
||||
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
|
||||
i = vnode.data.hook;
|
||||
if (!isUndef(i) && !isUndef(i = i.update)) i(vnode);
|
||||
}
|
||||
if (isUndef(vnode.text)) {
|
||||
if (!isUndef(oldCh) && !isUndef(ch)) {
|
||||
if (oldCh !== ch) updateChildren(elm, oldCh, ch);
|
||||
} else if (!isUndef(ch)) {
|
||||
addVnodes(elm, undefined, ch, 0, ch.length - 1);
|
||||
} else if (!isUndef(oldCh)) {
|
||||
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
|
||||
}
|
||||
} else if (oldVnode.text !== vnode.text) {
|
||||
elm.childNodes[0].nodeValue = vnode.text;
|
||||
}
|
||||
return vnode;
|
||||
}
|
||||
|
||||
return function (oldVnode, vnode) {
|
||||
var i;
|
||||
insertedVnodeQueue = [];
|
||||
if (oldVnode instanceof Element) {
|
||||
oldVnode = emptyNodeAt(oldVnode);
|
||||
}
|
||||
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
|
||||
patchVnode(oldVnode, vnode);
|
||||
for (i = 0; i < insertedVnodeQueue.length; ++i) {
|
||||
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
|
||||
}
|
||||
insertedVnodeQueue = undefined;
|
||||
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
|
||||
return vnode;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { init: init };
|
||||
|
||||
},{"./is":3,"./vnode":9}],9:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
module.exports = function (sel, data, children, text, elm) {
|
||||
var key = data === undefined ? undefined : data.key;
|
||||
return { sel: sel, data: data, children: children,
|
||||
text: text, elm: elm, key: key };
|
||||
};
|
||||
|
||||
},{}]},{},[1]);
|
||||
@@ -1,84 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Reorder animation</title>
|
||||
<script type="text/javascript" src="build.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: #fafafa;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
h1 {
|
||||
font-weight: normal;
|
||||
}
|
||||
.btn {
|
||||
display: inline-block;
|
||||
cursor: pointer;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
|
||||
padding: .5em .8em;
|
||||
transition: box-shadow .05s ease-in-out;
|
||||
-webkit-transition: box-shadow .05s ease-in-out;
|
||||
}
|
||||
.btn:hover {
|
||||
box-shadow: 0 0 2px rgba(0, 0, 0, .2);
|
||||
}
|
||||
.btn:active, .active, .active:hover {
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2),
|
||||
inset 0 0 4px rgba(0, 0, 0, .1);
|
||||
}
|
||||
.add {
|
||||
float: right;
|
||||
}
|
||||
#container {
|
||||
max-width: 42em;
|
||||
margin: 0 auto 2em auto;
|
||||
}
|
||||
.list {
|
||||
position: relative;
|
||||
}
|
||||
.row {
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
left: 0px;
|
||||
margin: .5em 0;
|
||||
padding: 1em;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
|
||||
transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
|
||||
-webkit-transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
|
||||
}
|
||||
.row div {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.row > div:nth-child(1) {
|
||||
width: 5%;
|
||||
}
|
||||
.row > div:nth-child(2) {
|
||||
width: 30%;
|
||||
}
|
||||
.row > div:nth-child(3) {
|
||||
width: 65%;
|
||||
}
|
||||
.rm-btn {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
color: #C25151;
|
||||
width: 1.4em;
|
||||
height: 1.4em;
|
||||
text-align: center;
|
||||
line-height: 1.4em;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,112 +0,0 @@
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([
|
||||
require('../../modules/class').default,
|
||||
require('../../modules/props').default,
|
||||
require('../../modules/style').default,
|
||||
require('../../modules/eventlisteners').default,
|
||||
]);
|
||||
var h = require('../../h.js').default;
|
||||
|
||||
var vnode;
|
||||
|
||||
var nextKey = 11;
|
||||
var margin = 8;
|
||||
var sortBy = 'rank';
|
||||
var totalHeight = 0;
|
||||
var originalData = [
|
||||
{rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0},
|
||||
{rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0},
|
||||
{rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0},
|
||||
{rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0},
|
||||
{rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0},
|
||||
{rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0},
|
||||
{rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0},
|
||||
{rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0},
|
||||
{rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0},
|
||||
{rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0},
|
||||
];
|
||||
var data = [
|
||||
originalData[0],
|
||||
originalData[1],
|
||||
originalData[2],
|
||||
originalData[3],
|
||||
originalData[4],
|
||||
originalData[5],
|
||||
originalData[6],
|
||||
originalData[7],
|
||||
originalData[8],
|
||||
originalData[9],
|
||||
];
|
||||
|
||||
function changeSort(prop) {
|
||||
sortBy = prop;
|
||||
data.sort((a, b) => {
|
||||
if (a[prop] > b[prop]) {
|
||||
return 1;
|
||||
}
|
||||
if (a[prop] < b[prop]) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
function add() {
|
||||
var n = originalData[Math.floor(Math.random() * 10)];
|
||||
data = [{rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0}].concat(data);
|
||||
render();
|
||||
render();
|
||||
}
|
||||
|
||||
function remove(movie) {
|
||||
data = data.filter((m) => { return m !== movie; });
|
||||
render();
|
||||
}
|
||||
|
||||
function movieView(movie) {
|
||||
return h('div.row', {
|
||||
key: movie.rank,
|
||||
style: {opacity: '0', transform: 'translate(-200px)',
|
||||
delayed: {transform: `translateY(${movie.offset}px)`, opacity: '1'},
|
||||
remove: {opacity: '0', transform: `translateY(${movie.offset}px) translateX(200px)`}},
|
||||
hook: {insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight; }},
|
||||
}, [
|
||||
h('div', {style: {fontWeight: 'bold'}}, movie.rank),
|
||||
h('div', movie.title),
|
||||
h('div', movie.desc),
|
||||
h('div.btn.rm-btn', {on: {click: [remove, movie]}}, 'x'),
|
||||
]);
|
||||
}
|
||||
|
||||
function render() {
|
||||
data = data.reduce((acc, m) => {
|
||||
var last = acc[acc.length - 1];
|
||||
m.offset = last ? last.offset + last.elmHeight + margin : margin;
|
||||
return acc.concat(m);
|
||||
}, []);
|
||||
totalHeight = data[data.length - 1].offset + data[data.length - 1].elmHeight;
|
||||
vnode = patch(vnode, view(data));
|
||||
}
|
||||
|
||||
function view(data) {
|
||||
return h('div', [
|
||||
h('h1', 'Top 10 movies'),
|
||||
h('div', [
|
||||
h('a.btn.add', {on: {click: add}}, 'Add'),
|
||||
'Sort by: ',
|
||||
h('span.btn-group', [
|
||||
h('a.btn.rank', {class: {active: sortBy === 'rank'}, on: {click: [changeSort, 'rank']}}, 'Rank'),
|
||||
h('a.btn.title', {class: {active: sortBy === 'title'}, on: {click: [changeSort, 'title']}}, 'Title'),
|
||||
h('a.btn.desc', {class: {active: sortBy === 'desc'}, on: {click: [changeSort, 'desc']}}, 'Description'),
|
||||
]),
|
||||
]),
|
||||
h('div.list', {style: {height: totalHeight+'px'}}, data.map(movieView)),
|
||||
]);
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
var container = document.getElementById('container');
|
||||
vnode = patch(container, view(data));
|
||||
render();
|
||||
});
|
||||
@@ -1,376 +0,0 @@
|
||||
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([require('../../modules/attributes')]);
|
||||
var h = require('../../h.js');
|
||||
|
||||
var vnode;
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
var container = document.getElementById('container');
|
||||
var vnode = h('div', [h('svg', { attrs: { width: 100, height: 100 } }, [h('circle', { attrs: { cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow' } })])]);
|
||||
vnode = patch(container, vnode);
|
||||
});
|
||||
|
||||
},{"../../h.js":2,"../../modules/attributes":4,"../../snabbdom.js":5}],2:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function addNS(data, children) {
|
||||
data.ns = 'http://www.w3.org/2000/svg';
|
||||
if (children !== undefined) {
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
addNS(children[i].data, children[i].children);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function h(sel, b, c) {
|
||||
var data = {},
|
||||
children,
|
||||
text,
|
||||
i;
|
||||
if (arguments.length === 3) {
|
||||
data = b;
|
||||
if (is.array(c)) {
|
||||
children = c;
|
||||
} else if (is.primitive(c)) {
|
||||
text = c;
|
||||
}
|
||||
} else if (arguments.length === 2) {
|
||||
if (is.array(b)) {
|
||||
children = b;
|
||||
} else if (is.primitive(b)) {
|
||||
text = b;
|
||||
} else {
|
||||
data = b;
|
||||
}
|
||||
}
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
|
||||
}
|
||||
}
|
||||
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
|
||||
addNS(data, children);
|
||||
}
|
||||
return VNode(sel, data, children, text, undefined);
|
||||
};
|
||||
|
||||
},{"./is":3,"./vnode":6}],3:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
array: Array.isArray,
|
||||
primitive: function primitive(s) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
} };
|
||||
|
||||
},{}],4:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"];
|
||||
|
||||
var booleanAttrsDict = {};
|
||||
for (var i = 0, len = booleanAttrs.length; i < len; i++) {
|
||||
booleanAttrsDict[booleanAttrs[i]] = true;
|
||||
}
|
||||
|
||||
function updateAttrs(oldVnode, vnode) {
|
||||
var key,
|
||||
cur,
|
||||
old,
|
||||
elm = vnode.elm,
|
||||
oldAttrs = oldVnode.data.attrs || {},
|
||||
attrs = vnode.data.attrs || {};
|
||||
|
||||
// update modified attributes, add new attributes
|
||||
for (key in attrs) {
|
||||
cur = attrs[key];
|
||||
old = oldAttrs[key];
|
||||
if (old !== cur) {
|
||||
// TODO: add support to namespaced attributes (setAttributeNS)
|
||||
if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur);
|
||||
}
|
||||
}
|
||||
//remove removed attributes
|
||||
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
|
||||
// the other option is to remove all attributes with value == undefined
|
||||
for (key in oldAttrs) {
|
||||
if (!(key in attrs)) {
|
||||
elm.removeAttribute(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { create: updateAttrs, update: updateAttrs };
|
||||
|
||||
},{}],5:[function(require,module,exports){
|
||||
// jshint newcap: false
|
||||
/* global require, module, document, Element */
|
||||
'use strict';
|
||||
|
||||
var VNode = require('./vnode');
|
||||
var is = require('./is');
|
||||
|
||||
function isUndef(s) {
|
||||
return s === undefined;
|
||||
}
|
||||
function isDef(s) {
|
||||
return s !== undefined;
|
||||
}
|
||||
|
||||
function emptyNodeAt(elm) {
|
||||
return VNode(elm.tagName, {}, [], undefined, elm);
|
||||
}
|
||||
|
||||
var emptyNode = VNode('', {}, [], undefined, undefined);
|
||||
|
||||
function sameVnode(vnode1, vnode2) {
|
||||
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
|
||||
}
|
||||
|
||||
function createKeyToOldIdx(children, beginIdx, endIdx) {
|
||||
var i,
|
||||
map = {},
|
||||
key;
|
||||
for (i = beginIdx; i <= endIdx; ++i) {
|
||||
key = children[i].key;
|
||||
if (isDef(key)) map[key] = i;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function createRmCb(childElm, listeners) {
|
||||
return function () {
|
||||
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
|
||||
};
|
||||
}
|
||||
|
||||
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
|
||||
|
||||
function init(modules) {
|
||||
var i,
|
||||
j,
|
||||
cbs = {};
|
||||
for (i = 0; i < hooks.length; ++i) {
|
||||
cbs[hooks[i]] = [];
|
||||
for (j = 0; j < modules.length; ++j) {
|
||||
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
|
||||
}
|
||||
}
|
||||
|
||||
function createElm(vnode, insertedVnodeQueue) {
|
||||
var i,
|
||||
data = vnode.data;
|
||||
if (isDef(data)) {
|
||||
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
|
||||
if (isDef(i = data.vnode)) vnode = i;
|
||||
}
|
||||
var elm,
|
||||
children = vnode.children,
|
||||
sel = vnode.sel;
|
||||
if (isDef(sel)) {
|
||||
// Parse selector
|
||||
var hashIdx = sel.indexOf('#');
|
||||
var dotIdx = sel.indexOf('.', hashIdx);
|
||||
var hash = hashIdx > 0 ? hashIdx : sel.length;
|
||||
var dot = dotIdx > 0 ? dotIdx : sel.length;
|
||||
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
||||
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
|
||||
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
|
||||
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
|
||||
if (is.array(children)) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
elm.appendChild(createElm(children[i], insertedVnodeQueue));
|
||||
}
|
||||
} else if (is.primitive(vnode.text)) {
|
||||
elm.appendChild(document.createTextNode(vnode.text));
|
||||
}
|
||||
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
|
||||
i = vnode.data.hook; // Reuse variable
|
||||
if (isDef(i)) {
|
||||
if (i.create) i.create(emptyNode, vnode);
|
||||
if (i.insert) insertedVnodeQueue.push(vnode);
|
||||
}
|
||||
} else {
|
||||
elm = vnode.elm = document.createTextNode(vnode.text);
|
||||
}
|
||||
return vnode.elm;
|
||||
}
|
||||
|
||||
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
|
||||
}
|
||||
}
|
||||
|
||||
function invokeDestroyHook(vnode) {
|
||||
var i = vnode.data,
|
||||
j;
|
||||
if (isDef(i)) {
|
||||
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
|
||||
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
|
||||
if (isDef(i = vnode.children)) {
|
||||
for (j = 0; j < vnode.children.length; ++j) {
|
||||
invokeDestroyHook(vnode.children[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
|
||||
for (; startIdx <= endIdx; ++startIdx) {
|
||||
var i,
|
||||
listeners,
|
||||
rm,
|
||||
ch = vnodes[startIdx];
|
||||
if (isDef(ch)) {
|
||||
if (isDef(ch.sel)) {
|
||||
invokeDestroyHook(ch);
|
||||
listeners = cbs.remove.length + 1;
|
||||
rm = createRmCb(ch.elm, listeners);
|
||||
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
|
||||
if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
|
||||
i(ch, rm);
|
||||
} else {
|
||||
rm();
|
||||
}
|
||||
} else {
|
||||
// Text node
|
||||
parentElm.removeChild(ch.elm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
|
||||
var oldStartIdx = 0,
|
||||
newStartIdx = 0;
|
||||
var oldEndIdx = oldCh.length - 1;
|
||||
var oldStartVnode = oldCh[0];
|
||||
var oldEndVnode = oldCh[oldEndIdx];
|
||||
var newEndIdx = newCh.length - 1;
|
||||
var newStartVnode = newCh[0];
|
||||
var newEndVnode = newCh[newEndIdx];
|
||||
var oldKeyToIdx, idxInOld, elmToMove, before;
|
||||
|
||||
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
|
||||
if (isUndef(oldStartVnode)) {
|
||||
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
|
||||
} else if (isUndef(oldEndVnode)) {
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newStartVnode)) {
|
||||
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else if (sameVnode(oldEndVnode, newEndVnode)) {
|
||||
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldStartVnode, newEndVnode)) {
|
||||
// Vnode moved right
|
||||
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
|
||||
oldStartVnode = oldCh[++oldStartIdx];
|
||||
newEndVnode = newCh[--newEndIdx];
|
||||
} else if (sameVnode(oldEndVnode, newStartVnode)) {
|
||||
// Vnode moved left
|
||||
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
|
||||
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
|
||||
oldEndVnode = oldCh[--oldEndIdx];
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
|
||||
idxInOld = oldKeyToIdx[newStartVnode.key];
|
||||
if (isUndef(idxInOld)) {
|
||||
// New element
|
||||
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
} else {
|
||||
elmToMove = oldCh[idxInOld];
|
||||
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
|
||||
oldCh[idxInOld] = undefined;
|
||||
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
|
||||
newStartVnode = newCh[++newStartIdx];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (oldStartIdx > oldEndIdx) {
|
||||
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
|
||||
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
|
||||
} else if (newStartIdx > newEndIdx) {
|
||||
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
|
||||
}
|
||||
}
|
||||
|
||||
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
|
||||
var i, hook;
|
||||
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
|
||||
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
|
||||
var elm = vnode.elm = oldVnode.elm,
|
||||
oldCh = oldVnode.children,
|
||||
ch = vnode.children;
|
||||
if (oldVnode === vnode) return;
|
||||
if (isDef(vnode.data)) {
|
||||
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
|
||||
i = vnode.data.hook;
|
||||
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
|
||||
}
|
||||
if (isUndef(vnode.text)) {
|
||||
if (isDef(oldCh) && isDef(ch)) {
|
||||
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
|
||||
} else if (isDef(ch)) {
|
||||
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
|
||||
} else if (isDef(oldCh)) {
|
||||
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
|
||||
}
|
||||
} else if (oldVnode.text !== vnode.text) {
|
||||
elm.textContent = vnode.text;
|
||||
}
|
||||
if (isDef(hook) && isDef(i = hook.postpatch)) {
|
||||
i(oldVnode, vnode);
|
||||
}
|
||||
}
|
||||
|
||||
return function (oldVnode, vnode) {
|
||||
var i;
|
||||
var insertedVnodeQueue = [];
|
||||
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
|
||||
if (oldVnode instanceof Element) {
|
||||
if (oldVnode.parentElement !== null) {
|
||||
createElm(vnode, insertedVnodeQueue);
|
||||
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
|
||||
} else {
|
||||
oldVnode = emptyNodeAt(oldVnode);
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
} else {
|
||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
||||
}
|
||||
for (i = 0; i < insertedVnodeQueue.length; ++i) {
|
||||
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
|
||||
}
|
||||
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
|
||||
return vnode;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { init: init };
|
||||
|
||||
},{"./is":3,"./vnode":6}],6:[function(require,module,exports){
|
||||
"use strict";
|
||||
|
||||
module.exports = function (sel, data, children, text, elm) {
|
||||
var key = data === undefined ? undefined : data.key;
|
||||
return { sel: sel, data: data, children: children,
|
||||
text: text, elm: elm, key: key };
|
||||
};
|
||||
|
||||
},{}]},{},[1]);
|
||||
@@ -1,84 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>SVG</title>
|
||||
<script type="text/javascript" src="build.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: #fafafa;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
h1 {
|
||||
font-weight: normal;
|
||||
}
|
||||
.btn {
|
||||
display: inline-block;
|
||||
cursor: pointer;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
|
||||
padding: .5em .8em;
|
||||
transition: box-shadow .05s ease-in-out;
|
||||
-webkit-transition: box-shadow .05s ease-in-out;
|
||||
}
|
||||
.btn:hover {
|
||||
box-shadow: 0 0 2px rgba(0, 0, 0, .2);
|
||||
}
|
||||
.btn:active, .active, .active:hover {
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2),
|
||||
inset 0 0 4px rgba(0, 0, 0, .1);
|
||||
}
|
||||
.add {
|
||||
float: right;
|
||||
}
|
||||
#container {
|
||||
max-width: 42em;
|
||||
margin: 0 auto 2em auto;
|
||||
}
|
||||
.list {
|
||||
position: relative;
|
||||
}
|
||||
.row {
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
left: 0px;
|
||||
margin: .5em 0;
|
||||
padding: 1em;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
|
||||
transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
|
||||
-webkit-transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
|
||||
}
|
||||
.row div {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.row > div:nth-child(1) {
|
||||
width: 5%;
|
||||
}
|
||||
.row > div:nth-child(2) {
|
||||
width: 30%;
|
||||
}
|
||||
.row > div:nth-child(3) {
|
||||
width: 65%;
|
||||
}
|
||||
.rm-btn {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
color: #C25151;
|
||||
width: 1.4em;
|
||||
height: 1.4em;
|
||||
text-align: center;
|
||||
line-height: 1.4em;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,17 +0,0 @@
|
||||
var snabbdom = require('../../snabbdom.js');
|
||||
var patch = snabbdom.init([
|
||||
require('../../modules/attributes').default,
|
||||
]);
|
||||
var h = require('../../h.js').default;
|
||||
|
||||
var vnode;
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
var container = document.getElementById('container');
|
||||
var vnode = h('div', [
|
||||
h('svg', {attrs: {width: 100, height: 100}}, [
|
||||
h('circle', {attrs: {cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow'}})
|
||||
])
|
||||
]);
|
||||
vnode = patch(container, vnode);
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
var gulp = require('gulp')
|
||||
var clean = require('gulp-clean')
|
||||
var uglify = require('gulp-uglify')
|
||||
var rename = require('gulp-rename')
|
||||
var sourcemaps = require('gulp-sourcemaps')
|
||||
var browserify = require('browserify')
|
||||
var fs = require('fs')
|
||||
|
||||
function standalone(name, entry, exportName) {
|
||||
return browserify(entry, { debug: true, standalone: exportName || name })
|
||||
.bundle()
|
||||
.pipe(fs.createWriteStream('./dist/'+ name.replace(/_/g, '-') +'.js'))
|
||||
}
|
||||
|
||||
gulp.task('bundle:snabbdom', function() {
|
||||
return standalone('snabbdom_patch', './snabbdom.bundle.js', 'snabbdom')
|
||||
})
|
||||
|
||||
gulp.task('bundle:snabbdom:init', function() {
|
||||
return standalone('snabbdom', './snabbdom.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:snabbdom:h', function() {
|
||||
return standalone('h', './h.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:snabbdom:tovnode', function() {
|
||||
return standalone('tovnode', './tovnode.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:class', function() {
|
||||
return standalone('snabbdom_class', './modules/class.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:dataset', function() {
|
||||
return standalone('snabbdom_dataset', './modules/dataset.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:props', function() {
|
||||
return standalone('snabbdom_props', './modules/props.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:attributes', function() {
|
||||
return standalone('snabbdom_attributes', './modules/attributes.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:style', function() {
|
||||
return standalone('snabbdom_style', './modules/style.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle:module:eventlisteners', function() {
|
||||
return standalone('snabbdom_eventlisteners', './modules/eventlisteners.js')
|
||||
})
|
||||
|
||||
gulp.task('bundle', [
|
||||
'bundle:snabbdom',
|
||||
'bundle:snabbdom:init',
|
||||
'bundle:snabbdom:h',
|
||||
'bundle:snabbdom:tovnode',
|
||||
'bundle:module:attributes',
|
||||
'bundle:module:class',
|
||||
'bundle:module:dataset',
|
||||
'bundle:module:props',
|
||||
'bundle:module:style',
|
||||
'bundle:module:eventlisteners'
|
||||
])
|
||||
|
||||
gulp.task('compress', ['bundle'], function() {
|
||||
return gulp.src(['dist/*.js', '!dist/*.min.js'])
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(uglify())
|
||||
.pipe(rename({ suffix: '.min' }))
|
||||
.pipe(sourcemaps.write('.'))
|
||||
.pipe(gulp.dest('dist'))
|
||||
})
|
||||
|
||||
gulp.task('clean', function() {
|
||||
return gulp.src('dist/*.*', {read: false})
|
||||
.pipe(clean())
|
||||
})
|
||||
|
||||
gulp.task('default', ['bundle'])
|
||||
@@ -1,66 +0,0 @@
|
||||
const ci = !!process.env.CI;
|
||||
const watch = !!process.env.WATCH;
|
||||
const live = !!process.env.LIVE;
|
||||
|
||||
const identifier = process.env.BROWSERSTACK_LOCAL_IDENTIFIER;
|
||||
const ip = process.env.IP_ADDR;
|
||||
|
||||
const browserstack = require('./browserstack-karma.js');
|
||||
|
||||
const browsers = ci
|
||||
? Object.keys(browserstack)
|
||||
: live
|
||||
? undefined
|
||||
: watch
|
||||
? ['Chrome']
|
||||
: ['Chrome', 'Firefox'];
|
||||
|
||||
module.exports = function(config) {
|
||||
config.set({
|
||||
basePath: '.',
|
||||
frameworks: ['mocha', 'karma-typescript'],
|
||||
// list of files / patterns to load in the browser
|
||||
files: [{pattern: 'src/**/*.ts'}, {pattern: 'test/**/*'}],
|
||||
plugins: [
|
||||
'karma-mocha',
|
||||
'karma-chrome-launcher',
|
||||
'karma-firefox-launcher',
|
||||
'karma-browserstack-launcher',
|
||||
'karma-typescript',
|
||||
],
|
||||
hostname: ci ? ip : 'localhost',
|
||||
preprocessors: {
|
||||
'src/**/*.ts': ['karma-typescript'],
|
||||
'test/**/*.js': ['karma-typescript'],
|
||||
},
|
||||
browserStack: {
|
||||
name: 'Snabbdom',
|
||||
startTunnel: false,
|
||||
retryLimit: 3,
|
||||
tunnelIdentifier: identifier,
|
||||
},
|
||||
browserNoActivityTimeout: 1000000,
|
||||
customLaunchers: browserstack,
|
||||
karmaTypescriptConfig: {
|
||||
coverageOptions: {
|
||||
exclude: /test\//,
|
||||
},
|
||||
compilerOptions: {
|
||||
allowJs: true,
|
||||
declaration: false
|
||||
},
|
||||
tsconfig: './tsconfig.json',
|
||||
include: {
|
||||
mode: 'merge',
|
||||
values: ['test/**/*'],
|
||||
},
|
||||
},
|
||||
reporters: ['dots', 'karma-typescript', 'BrowserStack'],
|
||||
port: 9876,
|
||||
colors: true,
|
||||
autoWatch: true,
|
||||
browsers: browsers,
|
||||
singleRun: !watch && !live,
|
||||
concurrency: ci ? 1 : Infinity,
|
||||
});
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"name": "snabbdom",
|
||||
"version": "0.7.3",
|
||||
"description": "A virtual DOM library with focus on simplicity, modularity, powerful features and performance.",
|
||||
"main": "snabbdom.js",
|
||||
"module": "es/snabbdom.js",
|
||||
"typings": "snabbdom.d.ts",
|
||||
"directories": {
|
||||
"example": "examples",
|
||||
"test": "test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"benchmark": "^2.1.4",
|
||||
"browserify": "^14.4.0",
|
||||
"fake-raf": "1.0.1",
|
||||
"gulp": "^3.9.1",
|
||||
"gulp-clean": "^0.3.2",
|
||||
"gulp-rename": "^1.2.2",
|
||||
"gulp-sourcemaps": "^2.6.0",
|
||||
"gulp-uglify": "^3.0.0",
|
||||
"karma": "^3.0.0",
|
||||
"karma-browserstack-launcher": "^1.3.0",
|
||||
"karma-chrome-launcher": "^2.2.0",
|
||||
"karma-firefox-launcher": "^1.1.0",
|
||||
"karma-mocha": "^1.3.0",
|
||||
"karma-typescript": "^3.0.13",
|
||||
"knuth-shuffle": "^1.0.1",
|
||||
"mocha": "^5.2.0",
|
||||
"typescript": "^3.0.3",
|
||||
"xyz": "2.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"pretest": "npm run compile",
|
||||
"test": "testem",
|
||||
"compile": "npm run compile-es && npm run compile-commonjs",
|
||||
"compile-es": "tsc --outDir es --module es6 --moduleResolution node",
|
||||
"compile-commonjs": "tsc --outDir ./",
|
||||
"prepublish": "npm run compile",
|
||||
"release-major": "xyz --repo git@github.com:paldepind/snabbdom.git --increment major",
|
||||
"release-minor": "xyz --repo git@github.com:paldepind/snabbdom.git --increment minor",
|
||||
"release-patch": "xyz --repo git@github.com:paldepind/snabbdom.git --increment patch"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/paldepind/snabbdom.git"
|
||||
},
|
||||
"keywords": [
|
||||
"virtual",
|
||||
"dom",
|
||||
"light",
|
||||
"kiss",
|
||||
"performance"
|
||||
],
|
||||
"author": "Simon Friis Vindum",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/paldepind/snabbdom/issues"
|
||||
},
|
||||
"homepage": "https://github.com/paldepind/snabbdom#readme"
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
var Benchmark = require('benchmark');
|
||||
var a = require('../snabbdom.js');
|
||||
var b = require('../oldsnabbdom.js');
|
||||
|
||||
global.a = a;
|
||||
global.b = b;
|
||||
|
||||
var suite = new Benchmark.Suite();
|
||||
|
||||
a.spanNum = function spanNum(n) {
|
||||
return a.h('span', {key: n}, n.toString());
|
||||
};
|
||||
|
||||
b.spanNum = function spanNum(n) {
|
||||
return b.h('span', {key: n}, n.toString());
|
||||
};
|
||||
|
||||
var elms = global.elms = 10;
|
||||
var arr = global.arr = [];
|
||||
for (var n = 0; n < elms; ++n) { arr[n] = n; }
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
var elm = global.elm = document.getElementById('container');
|
||||
// add tests
|
||||
suite.add('a/ insert first', {
|
||||
setup: function() {
|
||||
var vnode1 = a.h('div', arr.map(a.spanNum));
|
||||
var vnode2 = a.h('div', ['new'].concat(arr).map(a.spanNum));
|
||||
},
|
||||
fn: function() {
|
||||
var emptyNode = a.emptyNodeAt(elm);
|
||||
a.patch(emptyNode, vnode1);
|
||||
a.patch(vnode1, vnode2);
|
||||
a.patch(vnode2, a.emptyNode);
|
||||
},
|
||||
})
|
||||
.add('b/ insert first', {
|
||||
setup: function() {
|
||||
var vnode1 = b.h('div', arr.map(b.spanNum));
|
||||
var vnode2 = b.h('div', ['new'].concat(arr).map(b.spanNum));
|
||||
},
|
||||
fn: function() {
|
||||
var emptyNode = b.emptyNodeAt(elm);
|
||||
b.patch(emptyNode, vnode1);
|
||||
b.patch(vnode1, vnode2);
|
||||
b.patch(vnode2, b.emptyNode);
|
||||
},
|
||||
})
|
||||
// add listeners
|
||||
.on('cycle', function(event) {
|
||||
console.log(String(event.target));
|
||||
})
|
||||
.on('complete', function() {
|
||||
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
|
||||
})
|
||||
// run async
|
||||
.run({async: true});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Snabbdom benchmarks</title>
|
||||
<script type="text/javascript" src="build.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<p>See console</p>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,50 +0,0 @@
|
||||
import {vnode, VNode, VNodeData} from './vnode';
|
||||
export type VNodes = Array<VNode>;
|
||||
export type VNodeChildElement = VNode | string | number | undefined | null;
|
||||
export type ArrayOrElement<T> = T | T[];
|
||||
export type VNodeChildren = ArrayOrElement<VNodeChildElement>
|
||||
import * as is from './is';
|
||||
|
||||
function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
|
||||
data.ns = 'http://www.w3.org/2000/svg';
|
||||
if (sel !== 'foreignObject' && children !== undefined) {
|
||||
for (let i = 0; i < children.length; ++i) {
|
||||
let childData = children[i].data;
|
||||
if (childData !== undefined) {
|
||||
addNS(childData, (children[i] as VNode).children as VNodes, children[i].sel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function h(sel: string): VNode;
|
||||
export function h(sel: string, data: VNodeData): VNode;
|
||||
export function h(sel: string, children: VNodeChildren): VNode;
|
||||
export function h(sel: string, data: VNodeData, children: VNodeChildren): VNode;
|
||||
export function h(sel: any, b?: any, c?: any): VNode {
|
||||
var data: VNodeData = {}, children: any, text: any, i: number;
|
||||
if (c !== undefined) {
|
||||
data = b;
|
||||
if (is.array(c)) { children = c; }
|
||||
else if (is.primitive(c)) { text = c; }
|
||||
else if (c && c.sel) { children = [c]; }
|
||||
} else if (b !== undefined) {
|
||||
if (is.array(b)) { children = b; }
|
||||
else if (is.primitive(b)) { text = b; }
|
||||
else if (b && b.sel) { children = [b]; }
|
||||
else { data = b; }
|
||||
}
|
||||
if (children !== undefined) {
|
||||
for (i = 0; i < children.length; ++i) {
|
||||
if (is.primitive(children[i])) children[i] = vnode(undefined, undefined, undefined, children[i], undefined);
|
||||
}
|
||||
}
|
||||
if (
|
||||
sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g' &&
|
||||
(sel.length === 3 || sel[3] === '.' || sel[3] === '#')
|
||||
) {
|
||||
addNS(data, children, sel);
|
||||
}
|
||||
return vnode(sel, data, children, text, undefined);
|
||||
};
|
||||
export default h;
|
||||
@@ -1,64 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
|
||||
export interface AttachData {
|
||||
[key: string]: any
|
||||
[i: number]: any
|
||||
placeholder?: any
|
||||
real?: Node
|
||||
}
|
||||
|
||||
interface VNodeDataWithAttach extends VNodeData {
|
||||
attachData: AttachData
|
||||
}
|
||||
|
||||
interface VNodeWithAttachData extends VNode {
|
||||
data: VNodeDataWithAttach
|
||||
}
|
||||
|
||||
function pre(vnode: VNodeWithAttachData, newVnode: VNodeWithAttachData): void {
|
||||
const attachData = vnode.data.attachData;
|
||||
// Copy created placeholder and real element from old vnode
|
||||
newVnode.data.attachData.placeholder = attachData.placeholder;
|
||||
newVnode.data.attachData.real = attachData.real;
|
||||
// Mount real element in vnode so the patch process operates on it
|
||||
vnode.elm = vnode.data.attachData.real;
|
||||
}
|
||||
|
||||
function post(_: any, vnode: VNodeWithAttachData): void {
|
||||
// Mount dummy placeholder in vnode so potential reorders use it
|
||||
vnode.elm = vnode.data.attachData.placeholder;
|
||||
}
|
||||
|
||||
function destroy(vnode: VNodeWithAttachData): void {
|
||||
// Remove placeholder
|
||||
if (vnode.elm !== undefined) {
|
||||
(vnode.elm.parentNode as HTMLElement).removeChild(vnode.elm);
|
||||
}
|
||||
// Remove real element from where it was inserted
|
||||
vnode.elm = vnode.data.attachData.real;
|
||||
}
|
||||
|
||||
function create(_: any, vnode: VNodeWithAttachData): void {
|
||||
const real = vnode.elm, attachData = vnode.data.attachData;
|
||||
const placeholder = document.createElement('span');
|
||||
// Replace actual element with dummy placeholder
|
||||
// Snabbdom will then insert placeholder instead
|
||||
vnode.elm = placeholder;
|
||||
attachData.target.appendChild(real);
|
||||
attachData.real = real;
|
||||
attachData.placeholder = placeholder;
|
||||
}
|
||||
|
||||
export function attachTo(target: Element, vnode: VNode): VNode {
|
||||
if (vnode.data === undefined) vnode.data = {};
|
||||
if (vnode.data.hook === undefined) vnode.data.hook = {};
|
||||
const data = vnode.data;
|
||||
const hook = vnode.data.hook;
|
||||
data.attachData = {target: target, placeholder: undefined, real: undefined};
|
||||
hook.create = create;
|
||||
hook.prepatch = pre;
|
||||
hook.postpatch = post;
|
||||
hook.destroy = destroy;
|
||||
return vnode;
|
||||
};
|
||||
export default attachTo;
|
||||
@@ -1,25 +0,0 @@
|
||||
import {VNode} from './vnode';
|
||||
|
||||
export type PreHook = () => any;
|
||||
export type InitHook = (vNode: VNode) => any;
|
||||
export type CreateHook = (emptyVNode: VNode, vNode: VNode) => any;
|
||||
export type InsertHook = (vNode: VNode) => any;
|
||||
export type PrePatchHook = (oldVNode: VNode, vNode: VNode) => any;
|
||||
export type UpdateHook = (oldVNode: VNode, vNode: VNode) => any;
|
||||
export type PostPatchHook = (oldVNode: VNode, vNode: VNode) => any;
|
||||
export type DestroyHook = (vNode: VNode) => any;
|
||||
export type RemoveHook = (vNode: VNode, removeCallback: () => void) => any;
|
||||
export type PostHook = () => any;
|
||||
|
||||
export interface Hooks {
|
||||
pre?: PreHook;
|
||||
init?: InitHook;
|
||||
create?: CreateHook;
|
||||
insert?: InsertHook;
|
||||
prepatch?: PrePatchHook;
|
||||
update?: UpdateHook;
|
||||
postpatch?: PostPatchHook;
|
||||
destroy?: DestroyHook;
|
||||
remove?: RemoveHook;
|
||||
post?: PostHook;
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
export interface DOMAPI {
|
||||
createElement: (tagName: any) => HTMLElement;
|
||||
createElementNS: (namespaceURI: string, qualifiedName: string) => Element;
|
||||
createTextNode: (text: string) => Text;
|
||||
createComment: (text: string) => Comment;
|
||||
insertBefore: (parentNode: Node, newNode: Node, referenceNode: Node | null) => void;
|
||||
removeChild: (node: Node, child: Node) => void;
|
||||
appendChild: (node: Node, child: Node) => void;
|
||||
parentNode: (node: Node) => Node;
|
||||
nextSibling: (node: Node) => Node;
|
||||
tagName: (elm: Element) => string;
|
||||
setTextContent: (node: Node, text: string | null) => void;
|
||||
getTextContent: (node: Node) => string | null;
|
||||
isElement: (node: Node) => node is Element;
|
||||
isText: (node: Node) => node is Text;
|
||||
isComment: (node: Node) => node is Comment;
|
||||
}
|
||||
|
||||
function createElement(tagName: any): HTMLElement {
|
||||
return document.createElement(tagName);
|
||||
}
|
||||
|
||||
function createElementNS(namespaceURI: string, qualifiedName: string): Element {
|
||||
return document.createElementNS(namespaceURI, qualifiedName);
|
||||
}
|
||||
|
||||
function createTextNode(text: string): Text {
|
||||
return document.createTextNode(text);
|
||||
}
|
||||
|
||||
function createComment(text: string): Comment {
|
||||
return document.createComment(text);
|
||||
}
|
||||
|
||||
function insertBefore(parentNode: Node, newNode: Node, referenceNode: Node | null): void {
|
||||
parentNode.insertBefore(newNode, referenceNode);
|
||||
}
|
||||
|
||||
function removeChild(node: Node, child: Node): void {
|
||||
node.removeChild(child);
|
||||
}
|
||||
|
||||
function appendChild(node: Node, child: Node): void {
|
||||
node.appendChild(child);
|
||||
}
|
||||
|
||||
function parentNode(node: Node): Node | null {
|
||||
return node.parentNode;
|
||||
}
|
||||
|
||||
function nextSibling(node: Node): Node | null {
|
||||
return node.nextSibling;
|
||||
}
|
||||
|
||||
function tagName(elm: Element): string {
|
||||
return elm.tagName;
|
||||
}
|
||||
|
||||
function setTextContent(node: Node, text: string | null): void {
|
||||
node.textContent = text;
|
||||
}
|
||||
|
||||
function getTextContent(node: Node): string | null {
|
||||
return node.textContent;
|
||||
}
|
||||
|
||||
function isElement(node: Node): node is Element {
|
||||
return node.nodeType === 1;
|
||||
}
|
||||
|
||||
function isText(node: Node): node is Text {
|
||||
return node.nodeType === 3;
|
||||
}
|
||||
|
||||
function isComment(node: Node): node is Comment {
|
||||
return node.nodeType === 8;
|
||||
}
|
||||
|
||||
export const htmlDomApi = {
|
||||
createElement,
|
||||
createElementNS,
|
||||
createTextNode,
|
||||
createComment,
|
||||
insertBefore,
|
||||
removeChild,
|
||||
appendChild,
|
||||
parentNode,
|
||||
nextSibling,
|
||||
tagName,
|
||||
setTextContent,
|
||||
getTextContent,
|
||||
isElement,
|
||||
isText,
|
||||
isComment,
|
||||
} as DOMAPI;
|
||||
|
||||
export default htmlDomApi;
|
||||
@@ -1,4 +0,0 @@
|
||||
export const array = Array.isArray;
|
||||
export function primitive(s: any): s is (string | number) {
|
||||
return typeof s === 'string' || typeof s === 'number';
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { VNode, VNodeData } from "../vnode";
|
||||
import { Module } from "./module";
|
||||
|
||||
// because those in TypeScript are too restrictive: https://github.com/Microsoft/TSJS-lib-generator/pull/237
|
||||
declare global {
|
||||
interface Element {
|
||||
setAttribute(name: string, value: string | number | boolean): void;
|
||||
setAttributeNS(
|
||||
namespaceURI: string,
|
||||
qualifiedName: string,
|
||||
value: string | number | boolean
|
||||
): void;
|
||||
}
|
||||
}
|
||||
|
||||
export type Attrs = Record<string, string | number | boolean>;
|
||||
|
||||
const xlinkNS = "http://www.w3.org/1999/xlink";
|
||||
const xmlNS = "http://www.w3.org/XML/1998/namespace";
|
||||
const colonChar = 58;
|
||||
const xChar = 120;
|
||||
|
||||
function updateAttrs(oldVnode: VNode, vnode: VNode): void {
|
||||
var key: string,
|
||||
elm: Element = vnode.elm as Element,
|
||||
oldAttrs = (oldVnode.data as VNodeData).attrs,
|
||||
attrs = (vnode.data as VNodeData).attrs;
|
||||
|
||||
if (!oldAttrs && !attrs) return;
|
||||
if (oldAttrs === attrs) return;
|
||||
oldAttrs = oldAttrs || {};
|
||||
attrs = attrs || {};
|
||||
|
||||
// update modified attributes, add new attributes
|
||||
for (key in attrs) {
|
||||
const cur = attrs[key];
|
||||
const old = oldAttrs[key];
|
||||
if (old !== cur) {
|
||||
if (cur === true) {
|
||||
elm.setAttribute(key, "");
|
||||
} else if (cur === false) {
|
||||
elm.removeAttribute(key);
|
||||
} else {
|
||||
if (key.charCodeAt(0) !== xChar) {
|
||||
elm.setAttribute(key, cur);
|
||||
} else if (key.charCodeAt(3) === colonChar) {
|
||||
// Assume xml namespace
|
||||
elm.setAttributeNS(xmlNS, key, cur);
|
||||
} else if (key.charCodeAt(5) === colonChar) {
|
||||
// Assume xlink namespace
|
||||
elm.setAttributeNS(xlinkNS, key, cur);
|
||||
} else {
|
||||
elm.setAttribute(key, cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// remove removed attributes
|
||||
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
|
||||
// the other option is to remove all attributes with value == undefined
|
||||
for (key in oldAttrs) {
|
||||
if (!(key in attrs)) {
|
||||
elm.removeAttribute(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const attributesModule = {
|
||||
create: updateAttrs,
|
||||
update: updateAttrs
|
||||
} as Module;
|
||||
export default attributesModule;
|
||||
@@ -1,30 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type Classes = Record<string, boolean>
|
||||
|
||||
function updateClass(oldVnode: VNode, vnode: VNode): void {
|
||||
var cur: any, name: string, elm: Element = vnode.elm as Element,
|
||||
oldClass = (oldVnode.data as VNodeData).class,
|
||||
klass = (vnode.data as VNodeData).class;
|
||||
|
||||
if (!oldClass && !klass) return;
|
||||
if (oldClass === klass) return;
|
||||
oldClass = oldClass || {};
|
||||
klass = klass || {};
|
||||
|
||||
for (name in oldClass) {
|
||||
if (!klass[name]) {
|
||||
elm.classList.remove(name);
|
||||
}
|
||||
}
|
||||
for (name in klass) {
|
||||
cur = klass[name];
|
||||
if (cur !== oldClass[name]) {
|
||||
(elm.classList as any)[cur ? 'add' : 'remove'](name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const classModule = {create: updateClass, update: updateClass} as Module;
|
||||
export default classModule;
|
||||
@@ -1,43 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type Dataset = Record<string, string>;
|
||||
|
||||
const CAPS_REGEX = /[A-Z]/g;
|
||||
|
||||
function updateDataset(oldVnode: VNode, vnode: VNode): void {
|
||||
let elm: HTMLElement = vnode.elm as HTMLElement,
|
||||
oldDataset = (oldVnode.data as VNodeData).dataset,
|
||||
dataset = (vnode.data as VNodeData).dataset,
|
||||
key: string;
|
||||
|
||||
if (!oldDataset && !dataset) return;
|
||||
if (oldDataset === dataset) return;
|
||||
oldDataset = oldDataset || {};
|
||||
dataset = dataset || {};
|
||||
const d = elm.dataset;
|
||||
|
||||
for (key in oldDataset) {
|
||||
if (!dataset[key]) {
|
||||
if (d) {
|
||||
if (key in d) {
|
||||
delete d[key];
|
||||
}
|
||||
} else {
|
||||
elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (key in dataset) {
|
||||
if (oldDataset[key] !== dataset[key]) {
|
||||
if (d) {
|
||||
d[key] = dataset[key];
|
||||
} else {
|
||||
elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const datasetModule = {create: updateDataset, update: updateDataset} as Module;
|
||||
export default datasetModule;
|
||||
@@ -1,111 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type On = {
|
||||
[N in keyof HTMLElementEventMap]?: (ev: HTMLElementEventMap[N]) => void
|
||||
} & {
|
||||
[event: string]: EventListener
|
||||
};
|
||||
|
||||
function invokeHandler(handler: any, vnode?: VNode, event?: Event): void {
|
||||
if (typeof handler === "function") {
|
||||
// call function handler
|
||||
handler.call(vnode, event, vnode);
|
||||
} else if (typeof handler === "object") {
|
||||
// call handler with arguments
|
||||
if (typeof handler[0] === "function") {
|
||||
// special case for single argument for performance
|
||||
if (handler.length === 2) {
|
||||
handler[0].call(vnode, handler[1], event, vnode);
|
||||
} else {
|
||||
var args = handler.slice(1);
|
||||
args.push(event);
|
||||
args.push(vnode);
|
||||
handler[0].apply(vnode, args);
|
||||
}
|
||||
} else {
|
||||
// call multiple handlers
|
||||
for (var i = 0; i < handler.length; i++) {
|
||||
invokeHandler(handler[i], vnode, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleEvent(event: Event, vnode: VNode) {
|
||||
var name = event.type,
|
||||
on = (vnode.data as VNodeData).on;
|
||||
|
||||
// call event handler(s) if exists
|
||||
if (on && on[name]) {
|
||||
invokeHandler(on[name], vnode, event);
|
||||
}
|
||||
}
|
||||
|
||||
function createListener() {
|
||||
return function handler(event: Event) {
|
||||
handleEvent(event, (handler as any).vnode);
|
||||
}
|
||||
}
|
||||
|
||||
function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
||||
var oldOn = (oldVnode.data as VNodeData).on,
|
||||
oldListener = (oldVnode as any).listener,
|
||||
oldElm: Element = oldVnode.elm as Element,
|
||||
on = vnode && (vnode.data as VNodeData).on,
|
||||
elm: Element = (vnode && vnode.elm) as Element,
|
||||
name: string;
|
||||
|
||||
// optimization for reused immutable handlers
|
||||
if (oldOn === on) {
|
||||
return;
|
||||
}
|
||||
|
||||
// remove existing listeners which no longer used
|
||||
if (oldOn && oldListener) {
|
||||
// if element changed or deleted we remove all existing listeners unconditionally
|
||||
if (!on) {
|
||||
for (name in oldOn) {
|
||||
// remove listener if element was changed or existing listeners removed
|
||||
oldElm.removeEventListener(name, oldListener, false);
|
||||
}
|
||||
} else {
|
||||
for (name in oldOn) {
|
||||
// remove listener if existing listener removed
|
||||
if (!on[name]) {
|
||||
oldElm.removeEventListener(name, oldListener, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add new listeners which has not already attached
|
||||
if (on) {
|
||||
// reuse existing listener or create new
|
||||
var listener = (vnode as any).listener = (oldVnode as any).listener || createListener();
|
||||
// update vnode for listener
|
||||
listener.vnode = vnode;
|
||||
|
||||
// if element changed or added we add all needed listeners unconditionally
|
||||
if (!oldOn) {
|
||||
for (name in on) {
|
||||
// add listener if element was changed or new listeners added
|
||||
elm.addEventListener(name, listener, false);
|
||||
}
|
||||
} else {
|
||||
for (name in on) {
|
||||
// add listener if new listener added
|
||||
if (!oldOn[name]) {
|
||||
elm.addEventListener(name, listener, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const eventListenersModule = {
|
||||
create: updateEventListeners,
|
||||
update: updateEventListeners,
|
||||
destroy: updateEventListeners
|
||||
} as Module;
|
||||
export default eventListenersModule;
|
||||
@@ -1,165 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type Hero = { id: string }
|
||||
|
||||
var raf = (typeof window !== 'undefined' && window.requestAnimationFrame) || setTimeout;
|
||||
var nextFrame = function(fn: any) { raf(function() { raf(fn); }); };
|
||||
|
||||
function setNextFrame(obj: any, prop: string, val: any): void {
|
||||
nextFrame(function() { obj[prop] = val; });
|
||||
}
|
||||
|
||||
function getTextNodeRect(textNode: Text): ClientRect | undefined {
|
||||
var rect: ClientRect | undefined;
|
||||
if (document.createRange) {
|
||||
var range = document.createRange();
|
||||
range.selectNodeContents(textNode);
|
||||
if (range.getBoundingClientRect) {
|
||||
rect = range.getBoundingClientRect();
|
||||
}
|
||||
}
|
||||
return rect;
|
||||
}
|
||||
|
||||
function calcTransformOrigin(isTextNode: boolean,
|
||||
textRect: ClientRect | undefined,
|
||||
boundingRect: ClientRect): string {
|
||||
if (isTextNode) {
|
||||
if (textRect) {
|
||||
//calculate pixels to center of text from left edge of bounding box
|
||||
var relativeCenterX = textRect.left + textRect.width/2 - boundingRect.left;
|
||||
var relativeCenterY = textRect.top + textRect.height/2 - boundingRect.top;
|
||||
return relativeCenterX + 'px ' + relativeCenterY + 'px';
|
||||
}
|
||||
}
|
||||
return '0 0'; //top left
|
||||
}
|
||||
|
||||
function getTextDx(oldTextRect: ClientRect | undefined,
|
||||
newTextRect: ClientRect | undefined): number {
|
||||
if (oldTextRect && newTextRect) {
|
||||
return ((oldTextRect.left + oldTextRect.width/2) - (newTextRect.left + newTextRect.width/2));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function getTextDy(oldTextRect: ClientRect | undefined,
|
||||
newTextRect: ClientRect | undefined): number {
|
||||
if (oldTextRect && newTextRect) {
|
||||
return ((oldTextRect.top + oldTextRect.height/2) - (newTextRect.top + newTextRect.height/2));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function isTextElement(elm: Element | Text): elm is Text {
|
||||
return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3;
|
||||
}
|
||||
|
||||
var removed: any, created: any;
|
||||
|
||||
function pre() {
|
||||
removed = {};
|
||||
created = [];
|
||||
}
|
||||
|
||||
function create(oldVnode: VNode, vnode: VNode): void {
|
||||
var hero = (vnode.data as VNodeData).hero;
|
||||
if (hero && hero.id) {
|
||||
created.push(hero.id);
|
||||
created.push(vnode);
|
||||
}
|
||||
}
|
||||
|
||||
function destroy(vnode: VNode): void {
|
||||
var hero = (vnode.data as VNodeData).hero;
|
||||
if (hero && hero.id) {
|
||||
var elm = vnode.elm;
|
||||
(vnode as any).isTextNode = isTextElement(elm as Element | Text); //is this a text node?
|
||||
(vnode as any).boundingRect = (elm as Element).getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode
|
||||
(vnode as any).textRect = (vnode as any).isTextNode ? getTextNodeRect((elm as Element).childNodes[0] as Text) : null; //save bounding rect of inner text node
|
||||
var computedStyle = window.getComputedStyle(elm as Element, void 0); //get current styles (includes inherited properties)
|
||||
(vnode as any).savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values
|
||||
removed[hero.id] = vnode;
|
||||
}
|
||||
}
|
||||
|
||||
function post() {
|
||||
var i: number, id: any, newElm: Element, oldVnode: VNode, oldElm: Element,
|
||||
hRatio: number, wRatio: number,
|
||||
oldRect: ClientRect, newRect: ClientRect, dx: number, dy: number,
|
||||
origTransform: string | null, origTransition: string | null,
|
||||
newStyle: CSSStyleDeclaration, oldStyle: CSSStyleDeclaration,
|
||||
newComputedStyle: CSSStyleDeclaration, isTextNode: boolean,
|
||||
newTextRect: ClientRect | undefined, oldTextRect: ClientRect | undefined;
|
||||
for (i = 0; i < created.length; i += 2) {
|
||||
id = created[i];
|
||||
newElm = created[i+1].elm;
|
||||
oldVnode = removed[id];
|
||||
if (oldVnode) {
|
||||
isTextNode = (oldVnode as any).isTextNode && isTextElement(newElm); //Are old & new both text?
|
||||
newStyle = (newElm as HTMLElement).style;
|
||||
newComputedStyle = window.getComputedStyle(newElm, void 0); //get full computed style for new element
|
||||
oldElm = oldVnode.elm as Element;
|
||||
oldStyle = (oldElm as HTMLElement).style;
|
||||
//Overall element bounding boxes
|
||||
newRect = newElm.getBoundingClientRect();
|
||||
oldRect = (oldVnode as any).boundingRect; //previously saved bounding rect
|
||||
//Text node bounding boxes & distances
|
||||
if (isTextNode) {
|
||||
newTextRect = getTextNodeRect(newElm.childNodes[0] as Text);
|
||||
oldTextRect = (oldVnode as any).textRect;
|
||||
dx = getTextDx(oldTextRect, newTextRect);
|
||||
dy = getTextDy(oldTextRect, newTextRect);
|
||||
} else {
|
||||
//Calculate distances between old & new positions
|
||||
dx = oldRect.left - newRect.left;
|
||||
dy = oldRect.top - newRect.top;
|
||||
}
|
||||
hRatio = newRect.height / (Math.max(oldRect.height, 1));
|
||||
wRatio = isTextNode ? hRatio : newRect.width / (Math.max(oldRect.width, 1)); //text scales based on hRatio
|
||||
// Animate new element
|
||||
origTransform = newStyle.transform;
|
||||
origTransition = newStyle.transition;
|
||||
if (newComputedStyle.display === 'inline') //inline elements cannot be transformed
|
||||
newStyle.display = 'inline-block'; //this does not appear to have any negative side effects
|
||||
newStyle.transition = origTransition + 'transform 0s';
|
||||
newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect);
|
||||
newStyle.opacity = '0';
|
||||
newStyle.transform = origTransform + 'translate('+dx+'px, '+dy+'px) ' +
|
||||
'scale('+1/wRatio+', '+1/hRatio+')';
|
||||
setNextFrame(newStyle, 'transition', origTransition);
|
||||
setNextFrame(newStyle, 'transform', origTransform);
|
||||
setNextFrame(newStyle, 'opacity', '1');
|
||||
// Animate old element
|
||||
for (var key in (oldVnode as any).savedStyle) { //re-apply saved inherited properties
|
||||
if (parseInt(key) != key as any as number) {
|
||||
var ms = key.substring(0,2) === 'ms';
|
||||
var moz = key.substring(0,3) === 'moz';
|
||||
var webkit = key.substring(0,6) === 'webkit';
|
||||
if (!ms && !moz && !webkit) //ignore prefixed style properties
|
||||
(oldStyle as any)[key] = (oldVnode as any).savedStyle[key];
|
||||
}
|
||||
}
|
||||
oldStyle.position = 'absolute';
|
||||
oldStyle.top = oldRect.top + 'px'; //start at existing position
|
||||
oldStyle.left = oldRect.left + 'px';
|
||||
oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents
|
||||
oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents
|
||||
oldStyle.margin = '0'; //Margin on hero element leads to incorrect positioning
|
||||
oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect);
|
||||
oldStyle.transform = '';
|
||||
oldStyle.opacity = '1';
|
||||
document.body.appendChild(oldElm);
|
||||
setNextFrame(oldStyle, 'transform', 'translate('+ -dx +'px, '+ -dy +'px) scale('+wRatio+', '+hRatio+')'); //scale must be on far right for translate to be correct
|
||||
setNextFrame(oldStyle, 'opacity', '0');
|
||||
oldElm.addEventListener('transitionend', function (ev: TransitionEvent) {
|
||||
if (ev.propertyName === 'transform')
|
||||
document.body.removeChild(ev.target as Node);
|
||||
});
|
||||
}
|
||||
}
|
||||
removed = created = undefined;
|
||||
}
|
||||
|
||||
export const heroModule = {pre, create, destroy, post} as Module;
|
||||
export default heroModule;
|
||||
@@ -1,10 +0,0 @@
|
||||
import {PreHook, CreateHook, UpdateHook, DestroyHook, RemoveHook, PostHook} from '../hooks';
|
||||
|
||||
export interface Module {
|
||||
pre: PreHook;
|
||||
create: CreateHook;
|
||||
update: UpdateHook;
|
||||
destroy: DestroyHook;
|
||||
remove: RemoveHook;
|
||||
post: PostHook;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type Props = Record<string, any>;
|
||||
|
||||
function updateProps(oldVnode: VNode, vnode: VNode): void {
|
||||
var key: string, cur: any, old: any, elm = vnode.elm,
|
||||
oldProps = (oldVnode.data as VNodeData).props,
|
||||
props = (vnode.data as VNodeData).props;
|
||||
|
||||
if (!oldProps && !props) return;
|
||||
if (oldProps === props) return;
|
||||
oldProps = oldProps || {};
|
||||
props = props || {};
|
||||
|
||||
for (key in oldProps) {
|
||||
if (!props[key]) {
|
||||
delete (elm as any)[key];
|
||||
}
|
||||
}
|
||||
for (key in props) {
|
||||
cur = props[key];
|
||||
old = oldProps[key];
|
||||
if (old !== cur && (key !== 'value' || (elm as any)[key] !== cur)) {
|
||||
(elm as any)[key] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const propsModule = {create: updateProps, update: updateProps} as Module;
|
||||
export default propsModule;
|
||||
@@ -1,103 +0,0 @@
|
||||
import {VNode, VNodeData} from '../vnode';
|
||||
import {Module} from './module';
|
||||
|
||||
export type VNodeStyle = Record<string, string> & {
|
||||
delayed?: Record<string, string>
|
||||
remove?: Record<string, string>
|
||||
}
|
||||
|
||||
// Bindig `requestAnimationFrame` like this fixes a bug in IE/Edge. See #360 and #409.
|
||||
var raf = (typeof window !== 'undefined' && (window.requestAnimationFrame).bind(window)) || setTimeout;
|
||||
var nextFrame = function(fn: any) { raf(function() { raf(fn); }); };
|
||||
var reflowForced = false;
|
||||
|
||||
function setNextFrame(obj: any, prop: string, val: any): void {
|
||||
nextFrame(function() { obj[prop] = val; });
|
||||
}
|
||||
|
||||
function updateStyle(oldVnode: VNode, vnode: VNode): void {
|
||||
var cur: any, name: string, elm = vnode.elm,
|
||||
oldStyle = (oldVnode.data as VNodeData).style,
|
||||
style = (vnode.data as VNodeData).style;
|
||||
|
||||
if (!oldStyle && !style) return;
|
||||
if (oldStyle === style) return;
|
||||
oldStyle = oldStyle || {} as VNodeStyle;
|
||||
style = style || {} as VNodeStyle;
|
||||
var oldHasDel = 'delayed' in oldStyle;
|
||||
|
||||
for (name in oldStyle) {
|
||||
if (!style[name]) {
|
||||
if (name[0] === '-' && name[1] === '-') {
|
||||
(elm as any).style.removeProperty(name);
|
||||
} else {
|
||||
(elm as any).style[name] = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name in style) {
|
||||
cur = style[name];
|
||||
if (name === 'delayed' && style.delayed) {
|
||||
for (let name2 in style.delayed) {
|
||||
cur = style.delayed[name2];
|
||||
if (!oldHasDel || cur !== (oldStyle.delayed as any)[name2]) {
|
||||
setNextFrame((elm as any).style, name2, cur);
|
||||
}
|
||||
}
|
||||
} else if (name !== 'remove' && cur !== oldStyle[name]) {
|
||||
if (name[0] === '-' && name[1] === '-') {
|
||||
(elm as any).style.setProperty(name, cur);
|
||||
} else {
|
||||
(elm as any).style[name] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyDestroyStyle(vnode: VNode): void {
|
||||
var style: any, name: string, elm = vnode.elm, s = (vnode.data as VNodeData).style;
|
||||
if (!s || !(style = s.destroy)) return;
|
||||
for (name in style) {
|
||||
(elm as any).style[name] = style[name];
|
||||
}
|
||||
}
|
||||
|
||||
function applyRemoveStyle(vnode: VNode, rm: () => void): void {
|
||||
var s = (vnode.data as VNodeData).style;
|
||||
if (!s || !s.remove) {
|
||||
rm();
|
||||
return;
|
||||
}
|
||||
if(!reflowForced) {
|
||||
getComputedStyle(document.body).transform;
|
||||
reflowForced = true;
|
||||
}
|
||||
var name: string, elm = vnode.elm, i = 0, compStyle: CSSStyleDeclaration,
|
||||
style = s.remove, amount = 0, applied: Array<string> = [];
|
||||
for (name in style) {
|
||||
applied.push(name);
|
||||
(elm as any).style[name] = style[name];
|
||||
}
|
||||
compStyle = getComputedStyle(elm as Element);
|
||||
var props = (compStyle as any)['transition-property'].split(', ');
|
||||
for (; i < props.length; ++i) {
|
||||
if(applied.indexOf(props[i]) !== -1) amount++;
|
||||
}
|
||||
(elm as Element).addEventListener('transitionend', function (ev: TransitionEvent) {
|
||||
if (ev.target === elm) --amount;
|
||||
if (amount === 0) rm();
|
||||
});
|
||||
}
|
||||
|
||||
function forceReflow() {
|
||||
reflowForced = false;
|
||||
}
|
||||
|
||||
export const styleModule = {
|
||||
pre: forceReflow,
|
||||
create: updateStyle,
|
||||
update: updateStyle,
|
||||
destroy: applyDestroyStyle,
|
||||
remove: applyRemoveStyle
|
||||
} as Module;
|
||||
export default styleModule;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user