mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
229 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 71a9b21472 | |||
| 5cbf43110f | |||
| e00be61b8e | |||
| d615ffd81b | |||
| 8d2b250fef | |||
| 7626cc01b3 | |||
| 392185ab67 | |||
| 392dc0131a | |||
| 4e8e9dee3e | |||
| 25d4cb2aab | |||
| 4724652533 | |||
| b08cc1d084 | |||
| a68d7774c6 | |||
| ed9d820d9e | |||
| 4a2d019161 | |||
| 89eae191b1 | |||
| 3fbc02986c | |||
| a28ce440dc | |||
| 8e018fbbda | |||
| 33f7fc8e83 | |||
| 6a833c54ec | |||
| cb38d795f9 | |||
| 8da68e925b | |||
| 474ffa1cd9 | |||
| e73fb462c5 | |||
| 38c7ad9629 | |||
| d0c76c5854 | |||
| e032314739 | |||
| b2db7f21ed | |||
| 7b8ac13d3f | |||
| 06d852fcf9 | |||
| 7e4baf668a | |||
| fe34ba00a6 | |||
| e5e7790530 | |||
| 3bf91afc3f | |||
| 2529aa3ef2 | |||
| 8d25bddda4 | |||
| 81af21a025 | |||
| 9baea2c1cd | |||
| 8e03f9cd9c | |||
| c5a2f52afb | |||
| 9fd8315c53 | |||
| 85318b3ae6 | |||
| 4b961cbffe | |||
| 2af8cccd65 | |||
| b8d3618afa | |||
| 559fadb62a | |||
| c36333dbbc | |||
| b5c3422b4d | |||
| 23ce19e57a | |||
| aaf40e9bec | |||
| 211f6ebdd6 | |||
| 1707bd240d | |||
| 142b69823f | |||
| 94c8bce810 | |||
| ae172d42e7 | |||
| ddf30a8a97 | |||
| 8d0d8538ad | |||
| 2b0315c03f | |||
| c469cac315 | |||
| b4ad14edc0 | |||
| 718e5264ae | |||
| f5d019bb69 | |||
| afa36f52a0 | |||
| fd6327b068 | |||
| d5098dd138 | |||
| ce052e0992 | |||
| b00188c1ce | |||
| 2c01802b8e | |||
| 20eb848262 | |||
| 8b479749b7 | |||
| f7728b93bd | |||
| 03585d8fea | |||
| 047a9c8993 | |||
| 69d35abe4f | |||
| 1d7503913e | |||
| ee956a1977 | |||
| 3fdc7a48f3 | |||
| d212309f1b | |||
| 8866905f33 | |||
| 50b116c56d | |||
| a823373220 | |||
| e402ee62de | |||
| 5711eb065d | |||
| 6739e79aac | |||
| 1c8dc97fca | |||
| f9cac94dc7 | |||
| c62c3fea19 | |||
| 3845607feb | |||
| 3fcbb9ad16 | |||
| e04b160bff | |||
| bc234d2053 | |||
| 3d0f046d9a | |||
| 4c75bae0e8 | |||
| 54f5819ef9 | |||
| 0c9c5b877b | |||
| b7b0e38fca | |||
| 74bd119bf5 | |||
| 4a0d04e4ae | |||
| 49931104a1 | |||
| 21d1306ec2 | |||
| 21737d33fa | |||
| 23012f3e7c | |||
| 55889febd5 | |||
| 0af46bc123 | |||
| b63cd4c9d9 | |||
| 953778dc50 | |||
| 4f61d9f1e0 | |||
| bc2c7edff4 | |||
| c8d9c0b50e | |||
| 15b25fd838 | |||
| 1db0f5ac9b | |||
| 6465665550 | |||
| 9216c5c24b | |||
| d9bf4284c6 | |||
| ef6fd457f8 | |||
| 455e45c148 | |||
| 5e7f1d5e6d | |||
| 0b05ad619f | |||
| 29a80d0b28 | |||
| 0931a4dc5b | |||
| 4e22dbcad6 | |||
| b283e65ad4 | |||
| f517d44e32 | |||
| 08022b49df | |||
| b96ea79f2b | |||
| 97d8b3ed8c | |||
| 9921ae07b1 | |||
| 41cb5f1abd | |||
| 0762eeb010 | |||
| bc455be720 | |||
| 9145799ae9 | |||
| ce9c2f8613 | |||
| b890e7ceae | |||
| 124211c18b | |||
| be8c3bbf6f | |||
| e162a6fb6c | |||
| 7ec05ff8cf | |||
| a0bfbf6dd0 | |||
| b67cb71048 | |||
| f5b3ef5cf3 | |||
| ecfccf2448 | |||
| f12d3373c9 | |||
| 286090efca | |||
| 2b4ff7b2fd | |||
| c43178a45b | |||
| 033a431e18 | |||
| 42aa9d3ae1 | |||
| 85f26a0286 | |||
| ed4ab51c17 | |||
| 556a4644f0 | |||
| 821bd0b4b8 | |||
| 06a6d890d7 | |||
| c1269288f5 | |||
| 8c17bb0411 | |||
| 7f6782d009 | |||
| 6e5d6aa226 | |||
| 9400c0adad | |||
| 85d4393242 | |||
| 6c8b401092 | |||
| 12be815342 | |||
| 65344dbf1f | |||
| a6f9b26057 | |||
| 6c753bb49f | |||
| 1f079b883e | |||
| 8fb35ed969 | |||
| a3f2d07b40 | |||
| c993278c80 | |||
| 3aa586db43 | |||
| 14db513f3b | |||
| 7bb04185c7 | |||
| 48744cfa87 | |||
| ff76747a05 | |||
| 7e6b1a28a0 | |||
| 58f6724194 | |||
| 3c0f8ac76f | |||
| cb11c0118c | |||
| 27b4eece66 | |||
| 2e3e8cd603 | |||
| 28ee790b3e | |||
| 2922cee6ea | |||
| 7749fd3b96 | |||
| f44b9a38ae | |||
| c7773bfd2a | |||
| bd39797f17 | |||
| 94a595ef5b | |||
| f83846e054 | |||
| a97144366d | |||
| 79983de4ed | |||
| 54e1734f2f | |||
| 4aea093ed9 | |||
| 56087b95cd | |||
| e5940b4b6b | |||
| bbdc9d90d7 | |||
| f2b3ebd1ec | |||
| 55bb09ba1a | |||
| d249f50d09 | |||
| 749f0063ea | |||
| 263f31fea9 | |||
| b891ae7de4 | |||
| c5a80497ac | |||
| e47f604449 | |||
| 7e721a96b5 | |||
| af4f372506 | |||
| 5731358607 | |||
| 1226f015d7 | |||
| b211e75140 | |||
| 8d1dd06340 | |||
| bd3c1265d3 | |||
| 2413c98f50 | |||
| d74b5a03db | |||
| 83532db48f | |||
| 534152eff7 | |||
| 05a678c039 | |||
| 8fbf2172c5 | |||
| ea1376d0ca | |||
| ba483b6e2c | |||
| 2fc71cfb62 | |||
| 08cb83149e | |||
| 7d249d6f09 | |||
| 0addca63a0 | |||
| 5ba73cc09d | |||
| 9106c19066 | |||
| 9f93da4765 | |||
| 9e37b968e8 | |||
| fa6801b523 | |||
| 9edf29a3a1 | |||
| 6a434310ee | |||
| e7967d0779 |
@@ -0,0 +1,27 @@
|
|||||||
|
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
|
||||||
|
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
|
||||||
|
|
||||||
|
name: Node.js CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [ master, owl-next ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
node-version: [12.x, 14.x, 16.x]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Use Node.js ${{ matrix.node-version }}
|
||||||
|
uses: actions/setup-node@v1
|
||||||
|
with:
|
||||||
|
node-version: ${{ matrix.node-version }}
|
||||||
|
- run: npm install
|
||||||
|
- run: npm run test
|
||||||
|
- run: npm run prettier
|
||||||
@@ -15,6 +15,7 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
|
||||||
#ide's
|
#ide's
|
||||||
.vscode
|
.vscode
|
||||||
@@ -24,3 +25,9 @@ node_modules
|
|||||||
|
|
||||||
# Extras temp file
|
# Extras temp file
|
||||||
/tools/owl.js
|
/tools/owl.js
|
||||||
|
|
||||||
|
release-notes.md
|
||||||
|
|
||||||
|
.rpt2_cache
|
||||||
|
|
||||||
|
/temp
|
||||||
@@ -1,34 +1,51 @@
|
|||||||
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">Odoo Web Library</a> 🦉</h1>
|
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">OWL Framework</a> 🦉</h1>
|
||||||
|
|
||||||
_A no nonsense web framework for structured, dynamic and maintainable applications_
|
[](https://www.gnu.org/licenses/lgpl-3.0)
|
||||||
|
[](https://badge.fury.io/js/@odoo%2Fowl)
|
||||||
|
[](https://www.npmjs.com/package/@odoo/owl)
|
||||||
|
|
||||||
|
_Class based components with hooks, reactive state and concurrent mode_
|
||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
The Odoo Web Library (OWL) is a smallish (~18kb gzipped) UI framework intended to
|
The Odoo Web Library (OWL) is a smallish (~<20kb gzipped) UI framework intended to
|
||||||
be the basis for the [Odoo](https://www.odoo.com/) Web Client. Owl is a modern
|
be the basis for the [Odoo](https://www.odoo.com/) Web Client. Owl is a modern
|
||||||
framework, written in Typescript, taking the best ideas from React and Vue in a
|
framework, written in Typescript, taking the best ideas from React and Vue in a
|
||||||
simple and consistent way. Owl's main features are:
|
simple and consistent way. Owl's main features are:
|
||||||
|
|
||||||
- a declarative component system,
|
- a declarative component system,
|
||||||
- a reactivity system based on hooks,
|
- a reactivity system based on hooks,
|
||||||
- a store implementation (for state management),
|
- concurrent mode by default,
|
||||||
- a small frontend router
|
- a store and a frontend router
|
||||||
|
|
||||||
Owl components are defined with ES6 classes, they use QWeb templates, an underlying
|
Owl components are defined with ES6 classes, they use QWeb templates, an
|
||||||
virtual dom, integrates beautifully with hooks, and the rendering is asynchronous.
|
underlying virtual DOM, integrates beautifully with hooks, and the rendering is
|
||||||
|
asynchronous.
|
||||||
|
|
||||||
**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. There
|
**Try it online!** An online playground is available at
|
||||||
are some code examples to showcase some interesting features.
|
[https://odoo.github.io/owl/playground](https://odoo.github.io/owl/playground)
|
||||||
|
to let you experiment with the Owl framework. There are some code examples to
|
||||||
|
showcase some interesting features.
|
||||||
|
|
||||||
Owl is currently mostly stable. Possible future changes are explained in the
|
Owl is currently stable. Possible future changes are explained in the
|
||||||
[roadmap](roadmap.md).
|
[roadmap](roadmap.md).
|
||||||
|
|
||||||
|
## Why Owl?
|
||||||
|
|
||||||
|
Why did Odoo decide to make Yet Another Framework? This is really a question
|
||||||
|
that deserves [a long answer](doc/miscellaneous/why_owl.md). But in short, we believe that
|
||||||
|
while the current state of the art frameworks are excellent, they are not
|
||||||
|
optimized for our use case, and there is still room for something else.
|
||||||
|
|
||||||
|
If you are interested in a comparison with React or Vue, you will
|
||||||
|
find some more additional information [here](doc/miscellaneous/comparison.md).
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
Here is a short example to illustrate interactive components:
|
Here is a short example to illustrate interactive components:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const { Component, QWeb, useState } = owl;
|
const { Component, useState } = owl;
|
||||||
const { xml } = owl.tags;
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
@@ -50,7 +67,7 @@ class App extends Component {
|
|||||||
static components = { Counter };
|
static components = { Counter };
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App({ qweb: new QWeb() });
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -79,10 +96,9 @@ requirements are common and code needs to be maintained by large teams.
|
|||||||
|
|
||||||
Owl is not designed to be fast nor small (even though it is quite good on those
|
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
|
two topics). It is a no nonsense framework to build applications. There is only
|
||||||
one way to define components (with classes).
|
one way to define components (with classes). There is no black magic. It just
|
||||||
|
works.
|
||||||
|
|
||||||
If you are interested in a comparison with React or Vue, you will
|
|
||||||
find some more information [here](doc/comparison.md).
|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@@ -90,178 +106,26 @@ A complete documentation for Owl can be found here:
|
|||||||
|
|
||||||
- [Main documentation page](doc/readme.md).
|
- [Main documentation page](doc/readme.md).
|
||||||
|
|
||||||
The most important sections are:
|
Some of the most important pages are:
|
||||||
|
|
||||||
- [Quick Start](doc/quick_start.md)
|
- [Tutorial: TodoList application](doc/learning/tutorial_todoapp.md)
|
||||||
|
- [How to start an Owl project](doc/learning/quick_start.md)
|
||||||
|
- [QWeb templating language](doc/reference/qweb_templating_language.md)
|
||||||
- [Component](doc/reference/component.md)
|
- [Component](doc/reference/component.md)
|
||||||
- [Hooks](doc/reference/hooks.md)
|
- [Hooks](doc/reference/hooks.md)
|
||||||
|
|
||||||
Found an issue in the documentation? A broken link? Some outdated information?
|
|
||||||
Submit a PR!
|
|
||||||
|
|
||||||
## Installing/Building
|
## Installing Owl
|
||||||
|
|
||||||
|
Owl is available on `npm` and can be installed with the following command:
|
||||||
|
|
||||||
|
```
|
||||||
|
npm install @odoo/owl
|
||||||
|
```
|
||||||
|
|
||||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||||
|
|
||||||
- [owl-0.24.1.js](https://github.com/odoo/owl/releases/download/v0.24.1/owl.js)
|
- [owl-1.0.13](https://github.com/odoo/owl/releases/tag/v1.0.13)
|
||||||
- [owl-0.24.1.min.js](https://github.com/odoo/owl/releases/download/v0.24.1/owl.min.js)
|
|
||||||
|
|
||||||
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 minify` | minify the prebuilt owl.js file |
|
|
||||||
| `npm run test` | run all (owl) tests |
|
|
||||||
|
|
||||||
## Quick Overview
|
|
||||||
|
|
||||||
Owl components in an application are used to define a (dynamic) tree of components.
|
|
||||||
|
|
||||||
```
|
|
||||||
Root
|
|
||||||
/ \
|
|
||||||
A B
|
|
||||||
/ \
|
|
||||||
C D
|
|
||||||
```
|
|
||||||
|
|
||||||
**Environment:** the root component is special: it is created with an environment,
|
|
||||||
which should contain a [`QWeb` instance](doc/reference/qweb.md). The environment is then automatically
|
|
||||||
propagated to each sub components (and accessible in the `this.env` property).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const env = { qweb: new QWeb() };
|
|
||||||
const app = new App(env);
|
|
||||||
app.mount(document.body);
|
|
||||||
```
|
|
||||||
|
|
||||||
The environment is mostly static. Each application is free to add anything to
|
|
||||||
the environment, which is very useful, since this can be accessed by each sub
|
|
||||||
component. Some good use case for that is some configuration keys, session
|
|
||||||
information or generic services (such as doing rpcs, or accessing local storage).
|
|
||||||
Doing it this way means that components are easily testable: we can simply
|
|
||||||
create a test environment with mock services.
|
|
||||||
|
|
||||||
**State:** each component can manage its own local state. It is a simple ES6
|
|
||||||
class, there are no special rules:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Counter extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<button t-on-click="increment">
|
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
|
||||||
</button>`;
|
|
||||||
|
|
||||||
state = { value: 0 };
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
this.render();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The example above shows a component with a local state. Note that since there
|
|
||||||
is nothing magical to the `state` object, we need to manually call the `render`
|
|
||||||
function whenever we update it. This can quickly become annoying (and not
|
|
||||||
efficient if we do it too much). There is a better way: using the `useState`
|
|
||||||
hook, which transforms an object into a reactive version of itself:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const { useState } = owl.hooks;
|
|
||||||
|
|
||||||
class Counter extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<button t-on-click="increment">
|
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
|
||||||
</button>`;
|
|
||||||
|
|
||||||
state = useState({ value: 0 });
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that the `t-on-click` handler can even be replaced by an inline statement:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="state.value++">
|
|
||||||
```
|
|
||||||
|
|
||||||
**Props:** sub components often needs some information from their parents. This
|
|
||||||
is done by adding the required information to the template. This will then be
|
|
||||||
accessible by the sub component in the `props` object. Note that there is an
|
|
||||||
important rule here: the information contained in the `props` object is not
|
|
||||||
owned by the sub component, and should never be modified.
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Child extends Component {
|
|
||||||
static template = xml`<div>Hello <t t-esc="props.name"/></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
class Parent extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div>
|
|
||||||
<Child name="'Owl'" />
|
|
||||||
<Child name="'Framework'" />
|
|
||||||
</div>`;
|
|
||||||
static components = { Child };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Communication:** there are multiple ways to communicate information between
|
|
||||||
components. However, the two most important ways are the following:
|
|
||||||
|
|
||||||
- from parent to children: by using `props`,
|
|
||||||
- from a children to one of its parent: by triggering events.
|
|
||||||
|
|
||||||
The following example illustrate both mechanisms:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class OrderLine extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div t-on-click="add">
|
|
||||||
<div><t t-esc="props.line.name"/></div>
|
|
||||||
<div>Quantity: <t t-esc="props.line.quantity"/></div>
|
|
||||||
</div>`;
|
|
||||||
|
|
||||||
add() {
|
|
||||||
this.trigger("add-to-order", { line: props.line });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Parent extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div t-on-add-to-order="addToOrder">
|
|
||||||
<OrderLine
|
|
||||||
t-foreach="orders"
|
|
||||||
t-as="line"
|
|
||||||
line="line" />
|
|
||||||
</div>`;
|
|
||||||
static components = { OrderLine };
|
|
||||||
orders = useState([{ id: 1, name: "Coffee", quantity: 0 }, { id: 2, name: "Tea", quantity: 0 }]);
|
|
||||||
|
|
||||||
addToOrder(event) {
|
|
||||||
const line = event.detail.line;
|
|
||||||
line.quantity++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the `OrderLine` component trigger a `add-to-order` event. This
|
|
||||||
will generate a DOM event which will bubble along the DOM tree. It will then be
|
|
||||||
intercepted by the parent component, which will then get the line (from the
|
|
||||||
`detail` key) and then increment its quantity. See the section on [event handling](doc/reference/component.md#event-handling)
|
|
||||||
for more details on how events work.
|
|
||||||
|
|
||||||
Note that this example would have also worked if the `OrderLine` component
|
|
||||||
directly modifies the `line` object. However, this is not a good practice: this
|
|
||||||
only works because the `props` object received by the child component is reactive,
|
|
||||||
so the child component is then coupled to the parents implementation.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# 🦉 How to debug Owl applications 🦉
|
||||||
|
|
||||||
|
Non trivial applications become quickly more difficult to understand. It is then
|
||||||
|
useful to have a solid understanding of what is going on. To help with that,
|
||||||
|
logging useful information is extremely valuable. There is a [javascript file](../../tools/debug.js) which can be evaluated in an application.
|
||||||
|
|
||||||
|
Once it is executed, it will log a lot of information on each component main hooks. The following code is a minified version to make it easier to copy/paste:
|
||||||
|
|
||||||
|
```
|
||||||
|
function debugOwl(t,e){let n,o="[OWL_DEBUG]";function r(t){let e;try{e=JSON.stringify(t||{})}catch(t){e="<JSON error>"}return e.length>200&&(e=e.slice(0,200)+"..."),e}if(Object.defineProperty(t.Component,"current",{get:()=>n,set(s){n=s;const i=s.constructor.name;if(e.componentBlackList&&e.componentBlackList.test(i))return;if(e.componentWhiteList&&!e.componentWhiteList.test(i))return;let l;Object.defineProperty(n,"__owl__",{get:()=>l,set(n){!function(n,s,i){let l=`${s}<id=${i}>`,c=t=>console.log(`${o} ${l} ${t}`),u=t=>(!e.methodBlackList||!e.methodBlackList.includes(t))&&!(e.methodWhiteList&&!e.methodWhiteList.includes(t));u("constructor")&&c(`constructor, props=${r(n.props)}`);u("willStart")&&t.hooks.onWillStart(()=>{c("willStart")});u("mounted")&&t.hooks.onMounted(()=>{c("mounted")});u("willUpdateProps")&&t.hooks.onWillUpdateProps(t=>{c(`willUpdateProps, nextprops=${r(t)}`)});u("willPatch")&&t.hooks.onWillPatch(()=>{c("willPatch")});u("patched")&&t.hooks.onPatched(()=>{c("patched")});u("willUnmount")&&t.hooks.onWillUnmount(()=>{c("willUnmount")});const d=n.__render.bind(n);n.__render=function(...t){c("rendering template"),d(...t)};const h=n.render.bind(n);n.render=function(...t){const e=n.__owl__;let o="render";return e.isMounted||e.currentFiber||(o+=" (warning: component is not mounted, this render has no effect)"),c(o),h(...t)};const p=n.mount.bind(n);n.mount=function(...t){return c("mount"),p(...t)}}(s,i,(l=n).id)}})}}),e.logScheduler){let e=t.Component.scheduler.start,n=t.Component.scheduler.stop;t.Component.scheduler.start=function(){this.isRunning||console.log(`${o} scheduler: start running tasks queue`),e.call(this)},t.Component.scheduler.stop=function(){this.isRunning&&console.log(`${o} scheduler: stop running tasks queue`),n.call(this)}}if(e.logStore){let e=t.Store.prototype.dispatch;t.Store.prototype.dispatch=function(t,...n){return console.log(`${o} store: action '${t}' dispatched. Payload: '${r(n)}'`),e.call(this,t,...n)}}}
|
||||||
|
debugOwl(owl, {
|
||||||
|
// componentBlackList: /App/, // regexp
|
||||||
|
// componentWhiteList: /SomeComponent/, // regexp
|
||||||
|
// methodBlackList: ["mounted"], // list of method names
|
||||||
|
// methodWhiteList: ["willStart"], // list of method names
|
||||||
|
logScheduler: false, // display/mute scheduler logs
|
||||||
|
logStore: true, // display/mute store logs
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The above code, once pasted somewhere in the main javascript file of an owl
|
||||||
|
application, will log information looking like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> constructor, props={}
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> mount
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> willStart
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> constructor, props={"id":2,"completed":false,"title":"hey"}
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> willStart
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> constructor, props={"id":4,"completed":false,"title":"aaa"}
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> willStart
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> mounted
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> mounted
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> mounted
|
||||||
|
```
|
||||||
|
|
||||||
|
Each component has an internal `id`, which is very useful when debugging.
|
||||||
|
|
||||||
|
Note that it is certainly useful to run this code at some point in an application,
|
||||||
|
just to get a feel of what each user action implies, for the framework.
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
# 🦉 How to test Components 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Unit Tests](#unit-tests)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
It is a good practice to test applications and components to ensure that they
|
||||||
|
behave as expected. There are many ways to test a user interface: manual
|
||||||
|
testing, integration testing, unit testing, ...
|
||||||
|
|
||||||
|
In this section, we will discuss how to write unit tests for components.
|
||||||
|
|
||||||
|
## Unit Tests
|
||||||
|
|
||||||
|
Writing unit tests for Owl components really depends on the testing framework
|
||||||
|
used in a project. But usually, it involves the following steps:
|
||||||
|
|
||||||
|
- create a test file: for example `SomeComponent.test.js`,
|
||||||
|
- in that file, import the code for `SomeComponent`,
|
||||||
|
- add a test case:
|
||||||
|
- create a real DOM element to use as test fixture,
|
||||||
|
- create a test environment
|
||||||
|
- create an instance of `SomeComponent`, mount it to the fixture
|
||||||
|
- interact with the component and assert some properties.
|
||||||
|
|
||||||
|
To help with this, it is useful to have a `helper.js` file that contains some
|
||||||
|
common utility functions:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export function makeTestFixture() {
|
||||||
|
let fixture = document.createElement("div");
|
||||||
|
document.body.appendChild(fixture);
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function nextTick() {
|
||||||
|
let requestAnimationFrame = owl.Component.scheduler.requestAnimationFrame;
|
||||||
|
return new Promise(function(resolve) {
|
||||||
|
setTimeout(() => requestAnimationFrame(() => resolve()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeTestEnv() {
|
||||||
|
// application specific. It needs a way to load actual templates
|
||||||
|
const templates = ...;
|
||||||
|
|
||||||
|
return {
|
||||||
|
qweb: new QWeb(templates),
|
||||||
|
..., // each service can be mocked here
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With such a file, a typical test suite for Jest will look like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// in SomeComponent.test.js
|
||||||
|
import { SomeComponent } from "../../src/ui/SomeComponent";
|
||||||
|
import { nextTick, makeTestFixture, makeTestEnv} from '../helpers';
|
||||||
|
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let env: Env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
env = makeTestEnv();
|
||||||
|
// we set here the default environment for each component created in the test
|
||||||
|
Component.env = env;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
describe("SomeComponent", () => {
|
||||||
|
test("component behaves as expected", async () => {
|
||||||
|
const props = {...}; // depends on the component
|
||||||
|
const comp = new SomeComponent(null, props);
|
||||||
|
await comp.mount(fixture);
|
||||||
|
|
||||||
|
// do some assertions
|
||||||
|
expect(...).toBe(...);
|
||||||
|
|
||||||
|
fixture.querySelector('button').click();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
// some other assertions
|
||||||
|
expect(...).toBe(...);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that Owl does wait for the next animation frame to actually update the DOM.
|
||||||
|
This is why it is necessary to wait with the `nextTick` (or other methods) to
|
||||||
|
make sure that the DOM is up-to-date.
|
||||||
|
|
||||||
|
It is sometimes useful to wait until Owl is completely done updating components
|
||||||
|
(in particular, if we have a highly concurrent user interface). This next
|
||||||
|
helper simply polls every 20ms the internal Owl task queue and returns a promise
|
||||||
|
which resolves when it is empty:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function afterUpdates() {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let timer = setTimeout(poll, 20);
|
||||||
|
let counter = 0;
|
||||||
|
function poll() {
|
||||||
|
counter++;
|
||||||
|
if (owl.Component.scheduler.tasks.length) {
|
||||||
|
if (counter > 10) {
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
} else {
|
||||||
|
timer = setTimeout(poll);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# 🦉 How to write Single File Components 🦉
|
||||||
|
|
||||||
|
It is very useful to group code by feature instead of by type of file. It makes
|
||||||
|
it easier to scale application to larger size.
|
||||||
|
|
||||||
|
To do so, Owl has two small helpers that make it easy to define a
|
||||||
|
template or a stylesheet inside a javascript (or typescript) file: the
|
||||||
|
[`xml`](../reference/tags.md#xml-tag) and [`css`](../reference/tags.md#css-tag)
|
||||||
|
helper.
|
||||||
|
|
||||||
|
This means that the template, the style and the javascript code can be defined in
|
||||||
|
the same file. For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { Component } = owl;
|
||||||
|
const { xml, css } = owl.tags;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// TEMPLATE
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
const TEMPLATE = xml/* xml */ `
|
||||||
|
<div class="main">
|
||||||
|
<Sidebar/>
|
||||||
|
<Content />
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// STYLE
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
const STYLE = css/* css */ `
|
||||||
|
.main {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 200px auto;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// CODE
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
class Main extends Component {
|
||||||
|
static template = TEMPLATE;
|
||||||
|
static style = STYLE;
|
||||||
|
static components = { Sidebar, Content };
|
||||||
|
|
||||||
|
// rest of component...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that the above example has an inline xml comment, just after the `xml` call.
|
||||||
|
This is useful for some editor plugins, such as the VS Code addon
|
||||||
|
`Comment tagged template`, which, if installed, add syntax highlighting to the
|
||||||
|
content of the template string.
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# 🦉 Quick Overview 🦉
|
||||||
|
|
||||||
|
Owl components in an application are used to define a (dynamic) tree of components.
|
||||||
|
|
||||||
|
```
|
||||||
|
Root
|
||||||
|
/ \
|
||||||
|
A B
|
||||||
|
/ \
|
||||||
|
C D
|
||||||
|
```
|
||||||
|
|
||||||
|
**State:** each component can manage its own local state. It is a simple ES6
|
||||||
|
class, there are no special rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class Counter extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<button t-on-click="increment">
|
||||||
|
Click Me! [<t t-esc="state.value"/>]
|
||||||
|
</button>`;
|
||||||
|
|
||||||
|
state = { value: 0 };
|
||||||
|
|
||||||
|
increment() {
|
||||||
|
this.state.value++;
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The example above shows a component with a local state. Note that since there
|
||||||
|
is nothing magical to the `state` object, we need to manually call the `render`
|
||||||
|
function whenever we update it. This can quickly become annoying (and not
|
||||||
|
efficient if we do it too much). There is a better way: using the `useState`
|
||||||
|
hook, which transforms an object into a reactive version of itself:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { useState } = owl.hooks;
|
||||||
|
|
||||||
|
class Counter extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<button t-on-click="increment">
|
||||||
|
Click Me! [<t t-esc="state.value"/>]
|
||||||
|
</button>`;
|
||||||
|
|
||||||
|
state = useState({ value: 0 });
|
||||||
|
|
||||||
|
increment() {
|
||||||
|
this.state.value++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that the `t-on-click` handler can even be replaced by an inline statement:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="state.value++">
|
||||||
|
```
|
||||||
|
|
||||||
|
**Props:** sub components often needs some information from their parents. This
|
||||||
|
is done by adding the required information to the template. This will then be
|
||||||
|
accessible by the sub component in the `props` object. Note that there is an
|
||||||
|
important rule here: the information contained in the `props` object is not
|
||||||
|
owned by the sub component, and should never be modified.
|
||||||
|
|
||||||
|
```js
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div>Hello <t t-esc="props.name"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Child name="'Owl'" />
|
||||||
|
<Child name="'Framework'" />
|
||||||
|
</div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Communication:** there are multiple ways to communicate information between
|
||||||
|
components. However, the two most important ways are the following:
|
||||||
|
|
||||||
|
- from parent to children: by using `props`,
|
||||||
|
- from a children to one of its parent: by triggering events.
|
||||||
|
|
||||||
|
The following example illustrate both mechanisms:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class OrderLine extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-click="add">
|
||||||
|
<div><t t-esc="props.line.name"/></div>
|
||||||
|
<div>Quantity: <t t-esc="props.line.quantity"/></div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
add() {
|
||||||
|
this.trigger("add-to-order", { line: props.line });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-add-to-order="addToOrder">
|
||||||
|
<OrderLine
|
||||||
|
t-foreach="orders"
|
||||||
|
t-as="line"
|
||||||
|
line="line" />
|
||||||
|
</div>`;
|
||||||
|
static components = { OrderLine };
|
||||||
|
orders = useState([
|
||||||
|
{ id: 1, name: "Coffee", quantity: 0 },
|
||||||
|
{ id: 2, name: "Tea", quantity: 0 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
addToOrder(event) {
|
||||||
|
const line = event.detail.line;
|
||||||
|
line.quantity++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the `OrderLine` component trigger a `add-to-order` event. This
|
||||||
|
will generate a DOM event which will bubble along the DOM tree. It will then be
|
||||||
|
intercepted by the parent component, which will then get the line (from the
|
||||||
|
`detail` key) and then increment its quantity. See the page on [event handling](../reference/event_handling.md)
|
||||||
|
for more details on how events work.
|
||||||
|
|
||||||
|
Note that this example would have also worked if the `OrderLine` component
|
||||||
|
directly modifies the `line` object. However, this is not a good practice: this
|
||||||
|
only works because the `props` object received by the child component is reactive,
|
||||||
|
so the child component is then coupled to the parents implementation.
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
# 🦉 How to start an Owl project 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Simple html file](#simple-html-file)
|
||||||
|
- [With a static server](#with-a-static-server)
|
||||||
|
- [Standard Javascript project](#standard-javascript-project)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Each software project has its specific needs. Many of these needs can be solved
|
||||||
|
with some tooling: `webpack`, `gulp`, css preprocessor, bundlers, transpilers, ...
|
||||||
|
|
||||||
|
Because of that, it is usually not simple to just start a project. Some
|
||||||
|
frameworks provide their own tooling to help with that. But then, you have to
|
||||||
|
integrate and learn how these applications work.
|
||||||
|
|
||||||
|
Owl is designed to be used with no tooling at all. Because of that, Owl can
|
||||||
|
"easily" be integrated in a modern build toolchain. In this section, we will
|
||||||
|
discuss a few different setups to start a project. Each of these setups has
|
||||||
|
advantages and disadvantages in different situations.
|
||||||
|
|
||||||
|
## Simple html file
|
||||||
|
|
||||||
|
The simplest possible setup is the following: a simple javascript file with your
|
||||||
|
code. To do that, let us create the following file structure:
|
||||||
|
|
||||||
|
```
|
||||||
|
hello_owl/
|
||||||
|
index.html
|
||||||
|
owl.js
|
||||||
|
app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
The file `owl.js` can be downloaded from the last release published at
|
||||||
|
[https://github.com/odoo/owl/releases](https://github.com/odoo/owl/releases). It
|
||||||
|
is a single javascript file which export all Owl into the global `owl` object.
|
||||||
|
|
||||||
|
Now, `index.html` should contain the following:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello Owl</title>
|
||||||
|
<script src="owl.js"></script>
|
||||||
|
<script src="app.js"></script>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
And `app.js` should look like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { Component } = owl;
|
||||||
|
const { xml } = owl.tags;
|
||||||
|
const { whenReady } = owl.utils;
|
||||||
|
|
||||||
|
// Owl Components
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>Hello Owl</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup code
|
||||||
|
function setup() {
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
whenReady(setup);
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, simply loading this html file in a browser should display a welcome message.
|
||||||
|
This setup is not fancy, but it is extremely simple. There are no tooling at
|
||||||
|
all required. It can be slightly optimized by using the minified build of Owl.
|
||||||
|
|
||||||
|
## With a static server
|
||||||
|
|
||||||
|
The previous setup has a big disadvantage: the application code is located in a
|
||||||
|
single file. Obviously, we could split it in several files and add multiple
|
||||||
|
`<script>` tags in the html page, but then we need to make sure the script are
|
||||||
|
inserted in the proper order, we need to export each file content in global
|
||||||
|
variables and we lose autocompletion across files.
|
||||||
|
|
||||||
|
There is a low tech solution to this issue: using native javascript modules.
|
||||||
|
This however has a requirement: for security reasons, browsers will not accept
|
||||||
|
modules on content served through the `file` protocol. This means that we need
|
||||||
|
to use a static server.
|
||||||
|
|
||||||
|
Let us start a new project with the following file structure:
|
||||||
|
|
||||||
|
```
|
||||||
|
hello_owl/
|
||||||
|
src/
|
||||||
|
app.js
|
||||||
|
index.html
|
||||||
|
main.js
|
||||||
|
owl.js
|
||||||
|
```
|
||||||
|
|
||||||
|
As previously, the file `owl.js` can be downloaded from the last release published at
|
||||||
|
[https://github.com/odoo/owl/releases](https://github.com/odoo/owl/releases).
|
||||||
|
|
||||||
|
Now, `index.html` should contain the following:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello Owl</title>
|
||||||
|
<script src="owl.js"></script>
|
||||||
|
<script src="main.js" type="module"></script>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
Not that the `main.js` script tag has the `type="module"` attribute. This means
|
||||||
|
that the browser will parse the script as a module, and load all its dependencies.
|
||||||
|
|
||||||
|
Here is the content of `app.js` and `main.js`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// app.js ----------------------------------------------------------------------
|
||||||
|
const { Component } = owl;
|
||||||
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
|
export class App extends Component {
|
||||||
|
static template = xml`<div>Hello Owl</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// main.js ---------------------------------------------------------------------
|
||||||
|
import { App } from "./app.js";
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
owl.utils.whenReady(setup);
|
||||||
|
```
|
||||||
|
|
||||||
|
The `main.js` file import the `app.js` file. Note that the import statement has
|
||||||
|
a `.js` suffix, which is important. Most text editor can understand this syntax
|
||||||
|
and will provide autocompletion.
|
||||||
|
|
||||||
|
Now, to execute this code, we need to serve the `src` folder statically. A low
|
||||||
|
tech way to do that is to use for example the python `SimpleHTTPServer` feature:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ cd src
|
||||||
|
$ python -m SimpleHTTPServer 8022 # now content is available at localhost:8022
|
||||||
|
```
|
||||||
|
|
||||||
|
Another more "javascripty" way to do it is to create a `npm` application. To do
|
||||||
|
that, we can add the following `package.json` file at the root of the project:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "hello_owl",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Starting Owl app",
|
||||||
|
"main": "src/index.html",
|
||||||
|
"scripts": {
|
||||||
|
"serve": "serve src"
|
||||||
|
},
|
||||||
|
"author": "John",
|
||||||
|
"license": "ISC",
|
||||||
|
"devDependencies": {
|
||||||
|
"serve": "^11.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
We can now install the `serve` tool with the command `npm install`, and then,
|
||||||
|
start a static server with the simple `npm run serve` command.
|
||||||
|
|
||||||
|
## Standard Javascript project
|
||||||
|
|
||||||
|
The previous setup works, and is certainly good for some usecases, including
|
||||||
|
quick prototyping. However, it lacks some useful features, such as livereload,
|
||||||
|
a test suite, or bundling the code in a single file.
|
||||||
|
|
||||||
|
Each of these features, and many others, can be done in many different ways.
|
||||||
|
Since it is really not trivial to configure such a project, we provide here an
|
||||||
|
example that can be used as a starting point.
|
||||||
|
|
||||||
|
Our standard Owl project has the following file structure:
|
||||||
|
|
||||||
|
```
|
||||||
|
hello_owl/
|
||||||
|
public/
|
||||||
|
index.html
|
||||||
|
src/
|
||||||
|
components/
|
||||||
|
App.js
|
||||||
|
main.js
|
||||||
|
tests/
|
||||||
|
components/
|
||||||
|
App.test.js
|
||||||
|
helpers.js
|
||||||
|
.gitignore
|
||||||
|
package.json
|
||||||
|
webpack.config.js
|
||||||
|
```
|
||||||
|
|
||||||
|
This project as a `public` folder, meant to contain all static assets, such as
|
||||||
|
images and styles. The `src` folder has the javascript source code, and finally,
|
||||||
|
`tests` contains the test suite.
|
||||||
|
|
||||||
|
Here is the content of `index.html`:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello Owl</title>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that there are no `<script>` tag here. They will be injected by webpack.
|
||||||
|
Now, let's have a look at the javascript files:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// src/components/App.js -------------------------------------------------------
|
||||||
|
import { Component, tags, useState } from "@odoo/owl";
|
||||||
|
|
||||||
|
const { xml } = tags;
|
||||||
|
|
||||||
|
export class App extends Component {
|
||||||
|
static template = xml`<div t-on-click="update">Hello <t t-esc="state.text"/></div>`;
|
||||||
|
state = useState({ text: "Owl" });
|
||||||
|
update() {
|
||||||
|
this.state.text = this.state.text === "Owl" ? "World" : "Owl";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/main.js -----------------------------------------------------------------
|
||||||
|
import { utils } from "@odoo/owl";
|
||||||
|
import { App } from "./components/App";
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.whenReady(setup);
|
||||||
|
|
||||||
|
// tests/components/App.test.js ------------------------------------------------
|
||||||
|
import { App } from "../../src/components/App";
|
||||||
|
import { makeTestFixture, nextTick, click } from "../helpers";
|
||||||
|
|
||||||
|
let fixture;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("App", () => {
|
||||||
|
test("Works as expected...", async () => {
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hello Owl</div>");
|
||||||
|
|
||||||
|
click(fixture, "div");
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hello World</div>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// tests/helpers.js ------------------------------------------------------------
|
||||||
|
import { Component } from "@odoo/owl";
|
||||||
|
import "regenerator-runtime/runtime";
|
||||||
|
|
||||||
|
export async function nextTick() {
|
||||||
|
return new Promise(function (resolve) {
|
||||||
|
setTimeout(() => Component.scheduler.requestAnimationFrame(() => resolve()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeTestFixture() {
|
||||||
|
let fixture = document.createElement("div");
|
||||||
|
document.body.appendChild(fixture);
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function click(elem, selector) {
|
||||||
|
elem.querySelector(selector).dispatchEvent(new Event("click"));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Finally, here is the configuration files `.gitignore`, `package.json` and
|
||||||
|
`webpack.config.js`:
|
||||||
|
|
||||||
|
```
|
||||||
|
node_modules/
|
||||||
|
package-lock.json
|
||||||
|
dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "hello_owl",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Demo app",
|
||||||
|
"main": "src/index.html",
|
||||||
|
"scripts": {
|
||||||
|
"test": "jest",
|
||||||
|
"build": "webpack --mode production",
|
||||||
|
"dev": "webpack-dev-server --mode development"
|
||||||
|
},
|
||||||
|
"author": "Someone",
|
||||||
|
"license": "ISC",
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/core": "^7.8.4",
|
||||||
|
"@babel/plugin-proposal-class-properties": "^7.8.3",
|
||||||
|
"babel-jest": "^25.1.0",
|
||||||
|
"babel-loader": "^8.0.6",
|
||||||
|
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
|
||||||
|
"html-webpack-plugin": "^3.2.0",
|
||||||
|
"jest": "^25.1.0",
|
||||||
|
"regenerator-runtime": "^0.13.3",
|
||||||
|
"serve": "^11.3.0",
|
||||||
|
"webpack": "^4.41.5",
|
||||||
|
"webpack-cli": "^3.3.10",
|
||||||
|
"webpack-dev-server": "^3.10.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@odoo/owl": "^1.0.4"
|
||||||
|
},
|
||||||
|
"babel": {
|
||||||
|
"plugins": ["@babel/plugin-proposal-class-properties"],
|
||||||
|
"env": {
|
||||||
|
"test": {
|
||||||
|
"plugins": ["transform-es2015-modules-commonjs"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"verbose": false,
|
||||||
|
"testRegex": "(/tests/.*(test|spec))\\.js?$",
|
||||||
|
"moduleFileExtensions": ["js"],
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.[t|j]sx?$": "babel-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
const path = require("path");
|
||||||
|
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||||
|
|
||||||
|
const host = process.env.HOST || "localhost";
|
||||||
|
|
||||||
|
module.exports = function (env, argv) {
|
||||||
|
const mode = argv.mode || "development";
|
||||||
|
return {
|
||||||
|
mode: mode,
|
||||||
|
entry: "./src/main.js",
|
||||||
|
output: {
|
||||||
|
filename: "main.js",
|
||||||
|
path: path.resolve(__dirname, "dist"),
|
||||||
|
},
|
||||||
|
module: {
|
||||||
|
rules: [
|
||||||
|
{
|
||||||
|
test: /\.jsx?$/,
|
||||||
|
loader: "babel-loader",
|
||||||
|
exclude: /node_modules/,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
extensions: [".js", ".jsx"],
|
||||||
|
},
|
||||||
|
devServer: {
|
||||||
|
contentBase: path.resolve(__dirname, "public/index.html"),
|
||||||
|
compress: true,
|
||||||
|
hot: true,
|
||||||
|
host,
|
||||||
|
port: 3000,
|
||||||
|
publicPath: "/",
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
new HtmlWebpackPlugin({
|
||||||
|
inject: true,
|
||||||
|
template: path.resolve(__dirname, "public/index.html"),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
With this setup, we can now use the following script commands:
|
||||||
|
|
||||||
|
```
|
||||||
|
npm run build # build the full application in prod mode in dist/
|
||||||
|
|
||||||
|
npm run dev # start a dev server with livereload
|
||||||
|
|
||||||
|
npm run test # run the jest test suite
|
||||||
|
```
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -79,7 +79,7 @@ additional tools, we made a lot of effort to make the most of the web platform.
|
|||||||
|
|
||||||
For example, Owl uses the standard `xml` parser that comes with every browser.
|
For example, Owl uses the standard `xml` parser that comes with every browser.
|
||||||
Because of that, Owl did not have to write its own template parser. Another
|
Because of that, Owl did not have to write its own template parser. Another
|
||||||
example is the [`xml`](reference/tags.md#xml-tag) tag helper function, which makes use of
|
example is the [`xml`](../reference/tags.md#xml-tag) tag helper function, which makes use of
|
||||||
native template literals to allow in a natural way to write `xml` templates
|
native template literals to allow in a natural way to write `xml` templates
|
||||||
directly in the javascript code. This can be easily integrated with editor
|
directly in the javascript code. This can be easily integrated with editor
|
||||||
plugins to have autocompletion inside the template.
|
plugins to have autocompletion inside the template.
|
||||||
@@ -127,7 +127,7 @@ structured than a template language. Note that the tooling is quite impressive:
|
|||||||
there is a syntax highlighter for jsx here on github!
|
there is a syntax highlighter for jsx here on github!
|
||||||
|
|
||||||
By comparison, here is the equivalent Owl component, written with the
|
By comparison, here is the equivalent Owl component, written with the
|
||||||
[`xml`](reference/tags.md#xml-tag) tag helper:
|
[`xml`](../reference/tags.md#xml-tag) tag helper:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class Clock extends Component {
|
class Clock extends Component {
|
||||||
@@ -251,17 +251,17 @@ keeps track of who get data, and retrigger a render when it was changed.
|
|||||||
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
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
|
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
|
not notify a component when the state changes. Instead, components need to connect
|
||||||
to the store like in redux, with the `useStore` hook (see the [store documentation](reference/store.md#connecting-a-component)).
|
to the store like in redux, with the `useStore` hook (see the [store documentation](../reference/store.md#connecting-a-component)).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const actions = {
|
const actions = {
|
||||||
increment({ state }, val) {
|
increment({ state }, val) {
|
||||||
state.counter.value += val;
|
state.counter.value += val;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
counter: { value: 0 }
|
counter: { value: 0 },
|
||||||
};
|
};
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
|
|
||||||
@@ -270,11 +270,12 @@ class Counter extends Component {
|
|||||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||||
Click Me! [<t t-esc="counter.value"/>]
|
Click Me! [<t t-esc="counter.value"/>]
|
||||||
</button>`;
|
</button>`;
|
||||||
counter = useStore(state => state.counter);
|
counter = useStore((state) => state.counter);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
const counter = new Counter({ store, qweb });
|
Counter.env.store = store;
|
||||||
|
const counter = new Counter();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Hooks
|
## Hooks
|
||||||
@@ -314,7 +315,7 @@ This work is based on the new ideas introduced by React hooks.
|
|||||||
|
|
||||||
From the way React and Vue introduce their hooks, it may look like hooks are not
|
From the way React and Vue introduce their hooks, it may look like hooks are not
|
||||||
compatible with class components. However, this is not the case, as shown by
|
compatible with class components. However, this is not the case, as shown by
|
||||||
Owl [hooks](reference/hooks.md). They are inspired by both React and Vue. For example,
|
Owl [hooks](../reference/hooks.md). They are inspired by both React and Vue. For example,
|
||||||
the `useState` hook is named after React, but its API is closer to the `reactive`
|
the `useState` hook is named after React, but its API is closer to the `reactive`
|
||||||
Vue hook.
|
Vue hook.
|
||||||
|
|
||||||
@@ -13,7 +13,6 @@ A rendering occurs in two phases:
|
|||||||
- virtual rendering: this generates the virtual dom in memory, asynchronously
|
- virtual rendering: this generates the virtual dom in memory, asynchronously
|
||||||
- patch: applies a virtual tree to the screen (synchronously)
|
- patch: applies a virtual tree to the screen (synchronously)
|
||||||
|
|
||||||
|
|
||||||
There are several classes involved in a rendering:
|
There are several classes involved in a rendering:
|
||||||
|
|
||||||
- components
|
- components
|
||||||
@@ -21,9 +20,9 @@ There are several classes involved in a rendering:
|
|||||||
- fibers: small objects containing some metadata, associated with a rendering of
|
- fibers: small objects containing some metadata, associated with a rendering of
|
||||||
a specific component
|
a specific component
|
||||||
|
|
||||||
|
|
||||||
Components are organized in a dynamic component tree, visible in the user
|
Components are organized in a dynamic component tree, visible in the user
|
||||||
interface. Whenever a rendering is initiated in a component `C`:
|
interface. Whenever a rendering is initiated in a component `C`:
|
||||||
|
|
||||||
- a fiber is created on `C` with the rendering props information
|
- a fiber is created on `C` with the rendering props information
|
||||||
- the virtual rendering phase starts on C (will asynchronously render all the
|
- the virtual rendering phase starts on C (will asynchronously render all the
|
||||||
child components)
|
child components)
|
||||||
@@ -31,4 +30,3 @@ interface. Whenever a rendering is initiated in a component `C`:
|
|||||||
animation frame, if the fiber is done
|
animation frame, if the fiber is done
|
||||||
- once it is done, the scheduler will call the task callback, which will apply
|
- once it is done, the scheduler will call the task callback, which will apply
|
||||||
the patch (if it was not cancelled in the meantime).
|
the patch (if it was not cancelled in the meantime).
|
||||||
|
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# 🦉 Why Owl ? 🦉
|
||||||
|
|
||||||
|
The common wisdom is that one should not reinvent the wheel, because that would
|
||||||
|
waste effort and resources. It is certainly true in many cases. A javascript
|
||||||
|
framework is a considerable investment, so it is quite logical to ask the question:
|
||||||
|
why did Odoo decide to make OWL instead of using a standard/well known framework,
|
||||||
|
such as React or Vue?
|
||||||
|
|
||||||
|
As you might expect, the answer to that question is not simple. But most of the
|
||||||
|
reasons discussed in this page are a consequence from a single fact: Odoo is
|
||||||
|
extremely modular.
|
||||||
|
|
||||||
|
This means, for example, that the core parts of Odoo are not aware, before runtime,
|
||||||
|
of what files will be loaded/executed, or what will be the state of the UI. Because
|
||||||
|
of that, Odoo cannot rely on a standard build toolchain. Also, this implies that
|
||||||
|
the core parts of Odoo need to be extremely generic. In other words, Odoo is not
|
||||||
|
really an application with a user interface. It is an application which generates
|
||||||
|
a dynamic user interface. And most frameworks are not up to the task.
|
||||||
|
|
||||||
|
Betting on Owl was not an easy choice to make, because there certainly are a lot
|
||||||
|
of conflicting needs that we want to carefully balance. Choosing anything other
|
||||||
|
than a well known framework is bound to be controversial. This page will explain
|
||||||
|
some of the reason why we still believe that building Owl is a worthwile
|
||||||
|
endeavour.
|
||||||
|
|
||||||
|
## Strategy
|
||||||
|
|
||||||
|
It is true that we want to keep control of our technology, in the sense that we
|
||||||
|
do not want to depend on Facebook or Google, or any other large (or small)
|
||||||
|
company. If they decide to change their license, or to go in a direction that
|
||||||
|
will not work for us, this may be a problem. This is even more true because
|
||||||
|
Odoo is not a conventional javascript application, and our needs are probably
|
||||||
|
quite different as most other applications.
|
||||||
|
|
||||||
|
## Class components
|
||||||
|
|
||||||
|
It is clear that the biggest frameworks are moving away from class components.
|
||||||
|
There is an implicit assumption that class components are terrible, and that
|
||||||
|
functional programming is the way to go. React even goes as far as to say that
|
||||||
|
classes are confusing for developers.
|
||||||
|
|
||||||
|
While there is some truth to that, and to the fact that composition is certainly
|
||||||
|
a good mechanism for code reuse, we believe that classes and inheritance are
|
||||||
|
important tools.
|
||||||
|
|
||||||
|
Sharing code between generic components with inheritance is the way Odoo built
|
||||||
|
its web client. And it is clear that inheritance is not the root of all evils.
|
||||||
|
It is often a perfectly simple and appropriate solution. What matter most is
|
||||||
|
the architectural decisions.
|
||||||
|
|
||||||
|
Also, Odoo has another specific use out of class components: each method of a
|
||||||
|
class provides an extension point for addons. This may not be a clean architecture
|
||||||
|
pattern, but it is a pragmatic decision that served Odoo well: classes are
|
||||||
|
sometimes monkey-patched to add behaviour from the outside. A little bit like
|
||||||
|
mixins, but from the outside.
|
||||||
|
|
||||||
|
Using React or Vue would make it significantly harder to monkey patch components,
|
||||||
|
because a lot of the state is hidden in their internals.
|
||||||
|
|
||||||
|
## Tooling
|
||||||
|
|
||||||
|
React or Vue have a huge community, and a lot of effort have been made into their
|
||||||
|
tooling. This is wonderful, but at the same time, a pretty big issue for Odoo:
|
||||||
|
since the assets are totally dynamic (and could change whenever the user install
|
||||||
|
or remove an addon), we need to have all that kind of tooling on the production
|
||||||
|
servers. This is certainly not ideal.
|
||||||
|
|
||||||
|
Also, this makes it very complicated to setup Vue or React tools: Odoo code is
|
||||||
|
not a simple file that import other files. It changes all the time, assets
|
||||||
|
are bundled differently in different contexts. This is the reason why Odoo has
|
||||||
|
its own module system, which are resolve at runtime, by the browser. The
|
||||||
|
dynamic nature of Odoo means that we often need to delay work as late as possible
|
||||||
|
(in other word, we want a JIT user interface!)
|
||||||
|
|
||||||
|
Our ideal framework has minimal (mandatory) tooling, which makes it easier to
|
||||||
|
deploy. Using React without JSX, or Vue without vue file is not very appealing.
|
||||||
|
|
||||||
|
At the same time, Owl is designed to solve this issue: it compiles templates
|
||||||
|
by the browser, it doesn't need much code for that, since we use the XML parser
|
||||||
|
built into each browser. Owl works with or without any additional tooling. It
|
||||||
|
can use template strings to write single file component, and is easy to integrate
|
||||||
|
in any html page, with a simple `<script>` tag.
|
||||||
|
|
||||||
|
## Template based
|
||||||
|
|
||||||
|
Odoo stores template as XML document in a database. This is very powerful, since
|
||||||
|
this allow the use of xpaths to customize other templates. This is a very
|
||||||
|
important feature of odoo, and one of the key to Odoo modularity.
|
||||||
|
|
||||||
|
Because of that, we still expect to write our templates in an XML document.
|
||||||
|
Weirdly enough, no major framework uses XML to store templates, even though it
|
||||||
|
is extremely convenient.
|
||||||
|
|
||||||
|
So, using React or Vue means that we need to make a template compiler. For React,
|
||||||
|
that would be a compiler that would take a QWeb template, and convert it to a
|
||||||
|
React render function. For Vue, it would convert it to a Vue template. Then
|
||||||
|
we need to bundle the vue template compiler as well.
|
||||||
|
|
||||||
|
Not only this would be complex (compiling a templating language into another is
|
||||||
|
not an easy task), but it would negatively impact the developer experience as
|
||||||
|
well. Writing Vue or React components in a QWeb template would certainly be
|
||||||
|
awkward, and very confusing.
|
||||||
|
|
||||||
|
## Developer Experience
|
||||||
|
|
||||||
|
This brings us to the following point: developer experience. We see this choice
|
||||||
|
as an investment for the future, and we want to make onboarding developer as
|
||||||
|
easy as possible.
|
||||||
|
|
||||||
|
While many javascript professionals clearly think that react/vue is not difficult
|
||||||
|
(which is true to some extent), it is alsy true that many non js specialists are
|
||||||
|
overwhelmed with the frontend world: functional component, hooks, and many other
|
||||||
|
fancy words. Also, what is available in the compilation context may be difficult,
|
||||||
|
there is a lot of black magic going on in pretty much every framework. Vue
|
||||||
|
somehow join various namespaces into one, under the hood, and add various internal
|
||||||
|
keys. Svelte transform the code. React require that state transformations are
|
||||||
|
deep, and not shallow.
|
||||||
|
|
||||||
|
Owl is trying very hard to have a simple and familiar API. It uses classes. Its
|
||||||
|
reactivity system is explicit, not implicit. The scoping rules are obvious. In
|
||||||
|
case of doubt, we err on the side of not implementing a feature.
|
||||||
|
|
||||||
|
It is certainly different from React or Vue, but at the same time, kind of
|
||||||
|
familiar for experienced developers.
|
||||||
|
|
||||||
|
## JIT compilation
|
||||||
|
|
||||||
|
There is also a clear trend in the frontend world to compile code
|
||||||
|
as much as possible ahead of time. Most frameworks will compile templates ahead
|
||||||
|
of time. And now Svelte is trying to compile the JS code away, so it can remove
|
||||||
|
itself from the bundle.
|
||||||
|
|
||||||
|
This is certainly reasonable for many usecases. However, this is not what Odoo
|
||||||
|
needs: Odoo will fetch templates from the database and need to compile them only
|
||||||
|
at the last possible moment, so we can apply all necessary xpaths.
|
||||||
|
|
||||||
|
Even more: Odoo needs to be able to generate (and compile) templates at runtime.
|
||||||
|
Currently, Odoo form views interpret a xml description. But the form view code
|
||||||
|
then needs to do a lot of complicated operations. With Owl, we will be able to
|
||||||
|
transform a view description into a QWeb template, then compile that and use it
|
||||||
|
immediately.
|
||||||
|
|
||||||
|
## Reactivity
|
||||||
|
|
||||||
|
There are other design choices that we feel are not optimal in other frameworks.
|
||||||
|
For example, the reactivity system. We like the way Vue did it, but it has a
|
||||||
|
flaw: it is not really optional. There is actually a way to opt out of the reactivity
|
||||||
|
system by freezing the state, but then, it is freezed.
|
||||||
|
|
||||||
|
And there certainly are situations where we need a state, which is not readonly,
|
||||||
|
and not observed. For example, imagine a spreadsheet component. It may have a
|
||||||
|
very large internal state, and it knows exactly when it needs to be rendered
|
||||||
|
(basically, whenever the user perform some action). Then, observing its state
|
||||||
|
is a net performance loss, both for the CPU and the memory.
|
||||||
|
|
||||||
|
## Concurrency
|
||||||
|
|
||||||
|
Many applications are happy to simply display a spinner whenever a new asynchronous
|
||||||
|
action is performed, but Odoo want a different user experience: most asynchronous
|
||||||
|
state changes are not displayed until ready. This is sometimes called a concurrent
|
||||||
|
mode: the UI is rendered in memory, and displayed only when it is ready (and
|
||||||
|
only if it has not been cancelled by subsequent user actions).
|
||||||
|
|
||||||
|
React has now an experimental concurrent mode, but it was not ready when Owl
|
||||||
|
started. Vue has not really an equivalent API (suspense is not what we need).
|
||||||
|
|
||||||
|
Also, React concurrent mode is complex to use. Concurrency was one of the rare
|
||||||
|
strong point of the former Odoo js framework (widgets), and we feel that Owl has
|
||||||
|
now a very strong concurrent mode, which is simple and powerful at the same time.
|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
|
||||||
|
This lengthy discussion showed that there are many small and not so small reasons
|
||||||
|
that current standard frameworks are not tailored to our needs. It is perfectly
|
||||||
|
fine, because they each chose a different set of tradeoffs.
|
||||||
|
|
||||||
|
However, we feel that there is still room in the framework world for something
|
||||||
|
that is different. For a framework that make choices compatible with Odoo.
|
||||||
|
|
||||||
|
And that is why we built Owl 🦉.
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
# 🦉 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: 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 be used to contain some user session information, some
|
|
||||||
configuration keys (for example, isMobile = true/false if we are in mobile mode).
|
|
||||||
|
|
||||||
- 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 component
|
|
||||||
- mount the root component to a DOM element
|
|
||||||
|
|
||||||
Let us now add the javascript to make it work, in `app.js`:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const useState = owl.hooks.useState;
|
|
||||||
|
|
||||||
class ClickCounter extends owl.Component {
|
|
||||||
static template = "clickcounter";
|
|
||||||
state = useState({ value: 0 });
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Application initialization
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
async function start() {
|
|
||||||
const templates = await owl.utils.loadFile("templates.xml");
|
|
||||||
const env = {
|
|
||||||
qweb: new owl.QWeb({ templates })
|
|
||||||
};
|
|
||||||
const counter = new ClickCounter(env);
|
|
||||||
const target = document.getElementById("main");
|
|
||||||
await counter.mount(target);
|
|
||||||
}
|
|
||||||
|
|
||||||
start();
|
|
||||||
```
|
|
||||||
+33
-60
@@ -1,82 +1,55 @@
|
|||||||
# 🦉 OWL Documentation 🦉
|
# 🦉 OWL Documentation 🦉
|
||||||
|
|
||||||
## Owl Content
|
## Learning Owl
|
||||||
|
|
||||||
Owl is a javascript library that contains some core classes and function to help
|
Are you new to Owl? This is the place to start!
|
||||||
build applications. Here is a complete representation of its content:
|
|
||||||
|
|
||||||
```
|
- [Tutorial: create a TodoList application](learning/tutorial_todoapp.md)
|
||||||
owl
|
- [Quick Overview](learning/overview.md)
|
||||||
Component
|
- [How to start an Owl project](learning/quick_start.md)
|
||||||
Context
|
- [How to test Components](learning/how_to_test.md)
|
||||||
QWeb
|
- [How to write Single File Components](learning/how_to_write_sfc.md)
|
||||||
Store
|
- [How to write debug Owl applications](learning/how_to_debug.md)
|
||||||
useState
|
|
||||||
core
|
|
||||||
EventBus
|
|
||||||
Observer
|
|
||||||
hooks
|
|
||||||
onWillStart
|
|
||||||
onMounted
|
|
||||||
onWillUpdateProps
|
|
||||||
onWillPatch
|
|
||||||
onPatched
|
|
||||||
onWillUnmount
|
|
||||||
useContext
|
|
||||||
useState
|
|
||||||
useRef
|
|
||||||
useSubEnv
|
|
||||||
useStore
|
|
||||||
useDispatch
|
|
||||||
useGetters
|
|
||||||
misc
|
|
||||||
AsyncRoot
|
|
||||||
router
|
|
||||||
Link
|
|
||||||
RouteComponent
|
|
||||||
Router
|
|
||||||
tags
|
|
||||||
xml
|
|
||||||
utils
|
|
||||||
debounce
|
|
||||||
escape
|
|
||||||
loadJS
|
|
||||||
loadFile
|
|
||||||
shallowEqual
|
|
||||||
whenReady
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
|
You will find here a complete reference of every feature, class or object
|
||||||
|
provided by Owl.
|
||||||
|
|
||||||
- [Animations](reference/animations.md)
|
- [Animations](reference/animations.md)
|
||||||
- [Component](reference/component.md)
|
- [Component](reference/component.md)
|
||||||
|
- [Content](reference/content.md)
|
||||||
|
- [Concurrency Model](reference/concurrency_model.md)
|
||||||
|
- [Configuration](reference/config.md)
|
||||||
- [Context](reference/context.md)
|
- [Context](reference/context.md)
|
||||||
|
- [Environment](reference/environment.md)
|
||||||
- [Event Bus](reference/event_bus.md)
|
- [Event Bus](reference/event_bus.md)
|
||||||
|
- [Event Handling](reference/event_handling.md)
|
||||||
|
- [Error Handling](reference/error_handling.md)
|
||||||
- [Hooks](reference/hooks.md)
|
- [Hooks](reference/hooks.md)
|
||||||
- [Misc](reference/misc.md)
|
- [Miscellaneous Components](reference/misc.md)
|
||||||
- [Observer](reference/observer.md)
|
- [Observer](reference/observer.md)
|
||||||
- [QWeb](reference/qweb.md)
|
- [Props](reference/props.md)
|
||||||
|
- [Props Validation](reference/props_validation.md)
|
||||||
|
- [QWeb Templating Language](reference/qweb_templating_language.md)
|
||||||
|
- [QWeb Engine](reference/qweb_engine.md)
|
||||||
- [Router](reference/router.md)
|
- [Router](reference/router.md)
|
||||||
- [Store](reference/store.md)
|
- [Store](reference/store.md)
|
||||||
|
- [Slots](reference/slots.md)
|
||||||
- [Tags](reference/tags.md)
|
- [Tags](reference/tags.md)
|
||||||
- [Utils](reference/utils.md)
|
- [Utils](reference/utils.md)
|
||||||
|
|
||||||
## Learning Resources
|
## Other Topics
|
||||||
|
|
||||||
- [Quick Start](quick_start.md)
|
This section provides miscellaneous document that explains some topics
|
||||||
|
which cannot be considered either a tutorial, or reference documentation.
|
||||||
|
|
||||||
## Miscellaneous
|
- [Owl architecture: the Virtual DOM](miscellaneous/vdom.md)
|
||||||
|
- [Owl architecture: the rendering pipeline](miscellaneous/rendering.md)
|
||||||
|
- [Comparison with React/Vue](miscellaneous/comparison.md)
|
||||||
|
- [Why did Odoo built Owl?](miscellaneous/why_owl.md)
|
||||||
|
|
||||||
- [Comparison with React/Vue](comparison.md)
|
---
|
||||||
- [Tooling](tooling.md)
|
|
||||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
|
||||||
|
|
||||||
## Architecture
|
Found an issue in the documentation? A broken link? Some outdated information?
|
||||||
|
Please open an issue or submit a PR!
|
||||||
This section explains in more detail the inner workings of Owl. It is more
|
|
||||||
useful for people working on Owl code.
|
|
||||||
|
|
||||||
- [Virtual DOM](architecture/vdom.md)
|
|
||||||
- [Rendering](architecture/rendering.md)
|
|
||||||
|
|||||||
+95
-634
@@ -11,17 +11,10 @@
|
|||||||
- [Methods](#methods)
|
- [Methods](#methods)
|
||||||
- [Lifecycle](#lifecycle)
|
- [Lifecycle](#lifecycle)
|
||||||
- [Root Component](#root-component)
|
- [Root Component](#root-component)
|
||||||
- [Environment](#environment)
|
|
||||||
- [Composition](#composition)
|
- [Composition](#composition)
|
||||||
- [Event Handling](#event-handling)
|
|
||||||
- [Form Input Bindings](#form-input-bindings)
|
- [Form Input Bindings](#form-input-bindings)
|
||||||
- [`t-key` Directive](#t-key-directive)
|
|
||||||
- [Semantics](#semantics)
|
|
||||||
- [Props Validation](#props-validation)
|
|
||||||
- [References](#references)
|
- [References](#references)
|
||||||
- [Slots](#slots)
|
- [Dynamic sub components](#dynamic-sub-components)
|
||||||
- [Asynchronous Rendering](#asynchronous-rendering)
|
|
||||||
- [Error Handling](#error-handling)
|
|
||||||
- [Functional Components](#functional-components)
|
- [Functional Components](#functional-components)
|
||||||
- [SVG components](#svg-components)
|
- [SVG components](#svg-components)
|
||||||
|
|
||||||
@@ -43,7 +36,7 @@ OWL components are the building blocks for user interface. They are designed to
|
|||||||
and follow the QWeb specification. This is a requirement for Odoo.
|
and follow the QWeb specification. This is a requirement for Odoo.
|
||||||
|
|
||||||
OWL components are defined as a subclass of Component. The rendering is
|
OWL components are defined as a subclass of Component. The rendering is
|
||||||
exclusively done by a [QWeb](qweb.md) template (which needs to be preloaded in QWeb).
|
exclusively done by a [QWeb](qweb_templating_language.md) template (which needs to be preloaded in QWeb).
|
||||||
Rendering a component generates a virtual dom representation
|
Rendering a component generates a virtual dom representation
|
||||||
of the component, which is then patched to the DOM, in order to apply the changes in an efficient way.
|
of the component, which is then patched to the DOM, in order to apply the changes in an efficient way.
|
||||||
|
|
||||||
@@ -81,8 +74,8 @@ a state object is defined, by using the `useState` hook. It is not mandatory to
|
|||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
An Owl component is a small class which represents a component or some UI element.
|
An Owl component is a small class which represents a component or some UI element.
|
||||||
It exists in the context of an environment (`env`), which is propagated from a
|
It exists in the context of an [environment](environment.md) (`env`), which is propagated from a
|
||||||
parent to its children. The environment needs to have a QWeb instance, which
|
parent to its children. The environment needs to have a [QWeb](qweb_templating_language.md) instance, which
|
||||||
will be used to render the component template.
|
will be used to render the component template.
|
||||||
|
|
||||||
Be aware that the name of the component may be significant: if a component does
|
Be aware that the name of the component may be significant: if a component does
|
||||||
@@ -167,7 +160,7 @@ to be called in the constructor.
|
|||||||
- **`el`** (HTMLElement | null): reference to the DOM root node of the element. It is `null` when the
|
- **`el`** (HTMLElement | null): reference to the DOM root node of the element. It is `null` when the
|
||||||
component is not mounted.
|
component is not mounted.
|
||||||
|
|
||||||
- **`env`** (Object): the component environment, which contains a QWeb instance.
|
- **`env`** (Object): the component [environment](environment.md), which contains a QWeb instance.
|
||||||
|
|
||||||
- **`props`** (Object): this is an object containing all the properties given by
|
- **`props`** (Object): this is an object containing all the properties given by
|
||||||
the parent to a child component. For example, in the following situation,
|
the parent to a child component. For example, in the following situation,
|
||||||
@@ -205,13 +198,13 @@ to be called in the constructor.
|
|||||||
* **`props`** (Object, optional): if given, this is an object that describes the
|
* **`props`** (Object, optional): if given, this is an object that describes the
|
||||||
type and shape of the (actual) props given to the component. If Owl mode is
|
type and shape of the (actual) props given to the component. If Owl mode is
|
||||||
`dev`, this will be used to validate the props each time the component is
|
`dev`, this will be used to validate the props each time the component is
|
||||||
created/updated. See [Props Validation](#props-validation) for more information.
|
created/updated. See [Props Validation](props_validation.md) for more information.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class Counter extends owl.Component {
|
class Counter extends owl.Component {
|
||||||
static props = {
|
static props = {
|
||||||
initialValue: Number,
|
initialValue: Number,
|
||||||
optional: true
|
optional: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -224,11 +217,15 @@ to be called in the constructor.
|
|||||||
```js
|
```js
|
||||||
class Counter extends owl.Component {
|
class Counter extends owl.Component {
|
||||||
static defaultProps = {
|
static defaultProps = {
|
||||||
initialValue: 0
|
initialValue: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- **`style`** (string, optional): it should be the return value of the [`css` tag](tags.md#css-tag),
|
||||||
|
which is used to inject stylesheet whenever the component is visible on the
|
||||||
|
screen.
|
||||||
|
|
||||||
There is another static property defined on the `Component` class: `current`.
|
There is another static property defined on the `Component` class: `current`.
|
||||||
This property is set to the currently being defined component (in the constructor).
|
This property is set to the currently being defined component (in the constructor).
|
||||||
This is the way [hooks](hooks.md) are able to get a reference to the target
|
This is the way [hooks](hooks.md) are able to get a reference to the target
|
||||||
@@ -238,36 +235,60 @@ component.
|
|||||||
|
|
||||||
We explain here all the public methods of the `Component` class.
|
We explain here all the public methods of the `Component` class.
|
||||||
|
|
||||||
- **`mount(target, renderBeforeRemount=false)`** (async): this is the main way a
|
- **`mount(target, options)`** (async): this is the main way a
|
||||||
component is added to the DOM: the root component is mounted to a target
|
component is added to the DOM: the root component is mounted to a target
|
||||||
HTMLElement. Obviously, this is asynchronous, since each children need to be
|
HTMLElement (or document fragment). Obviously, this is asynchronous, since each children need to be
|
||||||
created as well. Most applications will need to call `mount` exactly once, on
|
created as well. Most applications will need to call `mount` exactly once, on
|
||||||
the root component.
|
the root component.
|
||||||
|
|
||||||
The `renderBeforeRemount` argument is useful when a component is unmounted and remounted.
|
The `options` argument is an optional object with a `position` key. The
|
||||||
In that case, we may want to rerender the component _before_ it is remounted, if
|
`position` key can have three possible values: `first-child`, `last-child`, `self`.
|
||||||
we know that its state (or something in the environment, or ...) has changed.
|
|
||||||
In that case, it should simply set to `true`.
|
|
||||||
|
|
||||||
- **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
- `first-child`: with this option, the component will be prepended inside the target,
|
||||||
|
- `last-child` (default value): with this option, the component will be
|
||||||
|
appended in the target element,
|
||||||
|
- `self`: the target will be used as the root element for the component. This
|
||||||
|
means that the target has to be an HTMLElement (and not a document fragment).
|
||||||
|
In this situation, it is possible that the component cannot be unmounted. For
|
||||||
|
example, if its target is `document.body`.
|
||||||
|
|
||||||
|
Note that if a component is mounted, unmounted and remounted, it will be
|
||||||
|
automatically re-rendered to ensure that changes in its state (or something
|
||||||
|
in the environment, or in the store, or ...) will be taken into account.
|
||||||
|
|
||||||
|
If a component is mounted inside an element or a fragment which is not in the
|
||||||
|
DOM, then it will be rendered fully, but not active: the `mounted` hooks will
|
||||||
|
not be called. This is sometimes useful if we want to load an application in
|
||||||
|
memory. In that case, we need to mount the root component again in an element
|
||||||
|
which is in the DOM:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(document.createDocumentFragment());
|
||||||
|
// app is rendered in memory, but not active
|
||||||
|
await app.mount(document.body);
|
||||||
|
// app is now visible
|
||||||
|
```
|
||||||
|
|
||||||
|
* **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
||||||
method can be used. Most applications should not call `unmount`, this is more
|
method can be used. Most applications should not call `unmount`, this is more
|
||||||
useful to the underlying component system.
|
useful to the underlying component system.
|
||||||
|
|
||||||
- **`render()`** (async): calling this method directly will cause a rerender. Note
|
* **`render()`** (async): calling this method directly will cause a rerender. Note
|
||||||
that this should be very rare to have to do it manually, the Owl framework is
|
that this should be very rare to have to do it manually, the Owl framework is
|
||||||
most of the time responsible for doing that at an appropriate moment.
|
most of the time responsible for doing that at an appropriate moment.
|
||||||
|
|
||||||
Note that the render method is asynchronous, so one cannot observe the updated
|
Note that the render method is asynchronous, so one cannot observe the updated
|
||||||
DOM in the same stack frame.
|
DOM in the same stack frame.
|
||||||
|
|
||||||
- **`shouldUpdate(nextProps)`**: this method is called each time a component's props
|
* **`shouldUpdate(nextProps)`**: this method is called each time a component's props
|
||||||
are updated. It returns a boolean, which indicates if the component should
|
are updated. It returns a boolean, which indicates if the component should
|
||||||
ignore a props update. If it returns false, then `willUpdateProps` will not
|
ignore a props update. If it returns false, then `willUpdateProps` will not
|
||||||
be called, and no rendering will occur. Its default implementation is to
|
be called, and no rendering will occur. Its default implementation is to
|
||||||
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
||||||
can be useful if we are handling large number of components.
|
can be useful if we are handling large number of components.
|
||||||
|
|
||||||
- **`destroy()`**. As its name suggests, this method will remove the component,
|
* **`destroy()`**. As its name suggests, this method will remove the component,
|
||||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||||
removing the parent/children relationship. This method should almost never be
|
removing the parent/children relationship. This method should almost never be
|
||||||
called directly (except maybe on the root component), but should be done by the
|
called directly (except maybe on the root component), but should be done by the
|
||||||
@@ -285,7 +306,7 @@ developers write components. Here is a complete description of the lifecycle of
|
|||||||
a owl component:
|
a owl component:
|
||||||
|
|
||||||
| Method | Description |
|
| Method | Description |
|
||||||
| ------------------------------------------------ | ------------------------------------------------------------ |
|
| ------------------------------------------------ | ----------------------------------------------------------- |
|
||||||
| **[constructor](#constructorparent-props)** | constructor |
|
| **[constructor](#constructorparent-props)** | constructor |
|
||||||
| **[willStart](#willstart)** | async, before first rendering |
|
| **[willStart](#willstart)** | async, before first rendering |
|
||||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||||
@@ -293,7 +314,7 @@ a owl component:
|
|||||||
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
||||||
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
||||||
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
||||||
| **[catchError](#catcherrorerror)** | catch errors (see [error handling section](#error-handling)) |
|
| **[catchError](#catcherrorerror)** | catch errors (see [error handling page](error_handling.md)) |
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
@@ -392,8 +413,7 @@ scrollbar.
|
|||||||
|
|
||||||
Note that modifying the state is not allowed here. This method is called just
|
Note that modifying the state is not allowed here. This method is called just
|
||||||
before an actual DOM patch, and is only intended to be used to save some local
|
before an actual DOM patch, and is only intended to be used to save some local
|
||||||
DOM state. Also, it will not be called if the component is not in the DOM (this can
|
DOM state. Also, it will not be called if the component is not in the DOM.
|
||||||
happen with components with `t-keepalive`).
|
|
||||||
|
|
||||||
#### `patched(snapshot)`
|
#### `patched(snapshot)`
|
||||||
|
|
||||||
@@ -402,8 +422,8 @@ likely via a change in its state/props or environment).
|
|||||||
|
|
||||||
This method is not called on the initial render. It is useful to interact
|
This method is not called on the initial render. It is useful to interact
|
||||||
with the DOM (for example, through an external library) whenever the
|
with the DOM (for example, through an external library) whenever the
|
||||||
component was patched. Note that this hook will not be called if the compoent is
|
component was patched. Note that this hook will not be called if the component is
|
||||||
not in the DOM (this can happen with components with `t-keepalive`).
|
not in the DOM.
|
||||||
|
|
||||||
Updating the component state in this hook is possible, but not encouraged.
|
Updating the component state in this hook is possible, but not encouraged.
|
||||||
One needs to be careful, because updates here will create an additional rendering, which in
|
One needs to be careful, because updates here will create an additional rendering, which in
|
||||||
@@ -429,8 +449,8 @@ This is the opposite method of `mounted`.
|
|||||||
#### `catchError(error)`
|
#### `catchError(error)`
|
||||||
|
|
||||||
The `catchError` method is useful when we need to intercept and properly react
|
The `catchError` method is useful when we need to intercept and properly react
|
||||||
to (rendering) errors that occur in some sub components. See the section on
|
to (rendering) errors that occur in some sub components. See the page on
|
||||||
[error handling](#error-handling).
|
[error handling](error_handling.md).
|
||||||
|
|
||||||
### Root Component
|
### Root Component
|
||||||
|
|
||||||
@@ -441,49 +461,17 @@ of an Owl application has to be created manually:
|
|||||||
```js
|
```js
|
||||||
class App extends owl.Component { ... }
|
class App extends owl.Component { ... }
|
||||||
|
|
||||||
const qweb = new owl.QWeb({ templates: TEMPLATES });
|
const app = new App();
|
||||||
const env = { qweb: qweb };
|
|
||||||
const app = new App(env);
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
```
|
```
|
||||||
|
|
||||||
The root component needs an environment.
|
The root component does not have a parent nor `props` (see note below). It will be setup with an
|
||||||
|
[environment](environment.md) (either the `env` defined on its class, or a
|
||||||
|
default empty environment).
|
||||||
|
|
||||||
### Environment
|
Note: a root component can however be given a `props` object in its constructor,
|
||||||
|
like this: `new App(null, {some: 'object'});`. It will not be a true `props`
|
||||||
In Owl, an environment is an object with a `qweb` key, which has to be a
|
object, managed by Owl (so, for example, it will never be updated).
|
||||||
[QWeb](qweb.md) instance. This qweb instance will be used to render everything.
|
|
||||||
|
|
||||||
The environment is meant to contain (mostly) static global information and
|
|
||||||
methods for the whole application. For example, settings keys (`mode` to determine
|
|
||||||
if we are in desktop or mobile mode, or `theme`: dark or light), `rpc` methods,
|
|
||||||
session information, ...
|
|
||||||
|
|
||||||
The environment will be given to each child, unchanged, in the `env` property.
|
|
||||||
This can be very useful to share common information/methods. For example, all
|
|
||||||
rpcs can be made through a `rpc` method in the environment. This makes it very
|
|
||||||
easy to test a component.
|
|
||||||
|
|
||||||
Updating the environment is not as simple as changing a component's state: its
|
|
||||||
content is not observed, so updates will not be reflected immediately in the
|
|
||||||
user interface. There is however a mechanism to force root widgets to rerender
|
|
||||||
themselves whenever the environment is modified: one only needs to call the
|
|
||||||
`forceUpdate` method on the QWeb instance. For example, a responsive environment
|
|
||||||
could be done like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
function setupResponsivePlugin(env) {
|
|
||||||
const isMobile = () => window.innerWidth <= 768;
|
|
||||||
env.isMobile = isMobile();
|
|
||||||
const updateEnv = owl.utils.debounce(() => {
|
|
||||||
if (env.isMobile !== isMobile()) {
|
|
||||||
env.isMobile = !env.isMobile;
|
|
||||||
env.qweb.forceUpdate();
|
|
||||||
}
|
|
||||||
}, 15);
|
|
||||||
window.addEventListener("resize", updateEnv);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Composition
|
### Composition
|
||||||
|
|
||||||
@@ -537,66 +525,8 @@ the static `components` key, then fallbacks on the global registry.
|
|||||||
_Props_: In this example, the child component will receive the object `{count: 4}` in its
|
_Props_: In this example, the child component will receive the object `{count: 4}` in its
|
||||||
constructor. This will be assigned to the `props` variable, which can be accessed
|
constructor. This will be assigned to the `props` variable, which can be accessed
|
||||||
on the component (and also, in the template). Whenever the state is updated, then
|
on the component (and also, in the template). Whenever the state is updated, then
|
||||||
the sub component will also be updated automatically.
|
the sub component will also be updated automatically. See the [props section](props.md)
|
||||||
|
for more information.
|
||||||
Note that there are restrictions on valid prop names: `class`, `style` and any
|
|
||||||
string which starts with `t-` are not allowed.
|
|
||||||
|
|
||||||
It is not common, but sometimes we need a dynamic component name and/or dynamic props. In this case,
|
|
||||||
the `t-component` directive can also be used to accept dynamic values with string interpolation (like the [`t-attf-`](qweb.md#dynamic-attributes) directive):
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="ParentComponent">
|
|
||||||
<t t-component="ChildComponent{{id}}" />
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
class ParentComponent {
|
|
||||||
static components = { ChildComponent1, ChildComponent2 };
|
|
||||||
state = { id: 1 };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
And the `t-props` directive can be used to specify totally dynamic props:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="ParentComponent">
|
|
||||||
<Child t-props="some.obj"/>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
class ParentComponent {
|
|
||||||
static components = { Child };
|
|
||||||
some = { obj: { a: 1, b: 2 } };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
There is an even more dynamic way to use `t-component`: its value can be an
|
|
||||||
expression evaluating to an actual component class. In that case, this is the
|
|
||||||
class that will be used to create the component:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class A extends Component<any, any, any> {
|
|
||||||
static template = xml`<span>child a</span>`;
|
|
||||||
}
|
|
||||||
class B extends Component<any, any, any> {
|
|
||||||
static template = xml`<span>child b</span>`;
|
|
||||||
}
|
|
||||||
class App extends Component<any, any, any> {
|
|
||||||
static template = xml`<t t-component="myComponent" t-key="state.child"/>`;
|
|
||||||
|
|
||||||
state = { child: "a" };
|
|
||||||
|
|
||||||
get myComponent() {
|
|
||||||
return this.state.child === "a" ? A : B;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the component `App` selects dynamically the concrete sub
|
|
||||||
component class.
|
|
||||||
|
|
||||||
**CSS and style:** Owl allows the parent to declare
|
**CSS and style:** Owl allows the parent to declare
|
||||||
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||||
@@ -619,116 +549,6 @@ with a class object:
|
|||||||
<MyComponent t-att-class="{a: state.flagA, b: state.flagB}" />
|
<MyComponent t-att-class="{a: state.flagA, b: state.flagB}" />
|
||||||
```
|
```
|
||||||
|
|
||||||
### Event Handling
|
|
||||||
|
|
||||||
In a component's template, it is useful to be able to register handlers on DOM
|
|
||||||
elements to some specific events. This is what makes a template _alive_. There
|
|
||||||
are four different use cases.
|
|
||||||
|
|
||||||
1. Register an event handler on a DOM node (_pure_ DOM event)
|
|
||||||
2. Register an event handler on a component (_pure_ DOM event)
|
|
||||||
3. Register an event handler on a DOM node (_business_ DOM event)
|
|
||||||
4. Register an event handler on a component (_business_ DOM event)
|
|
||||||
|
|
||||||
A _pure_ DOM event is directly triggered by a user interaction (e.g. a `click`).
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="someMethod">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
This will be roughly translated in javascript like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
button.addEventListener("click", component.someMethod.bind(component));
|
|
||||||
```
|
|
||||||
|
|
||||||
The suffix (`click` in this example) is simply the name of the actual DOM
|
|
||||||
event.
|
|
||||||
|
|
||||||
A _business_ DOM event is triggered by a call to `trigger` on a component.
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<MyComponent t-on-menu-loaded="someMethod" />
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
class MyComponent {
|
|
||||||
someWhere() {
|
|
||||||
const payload = ...;
|
|
||||||
this.trigger('menu-loaded', payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The call to `trigger` generates a [_CustomEvent_](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
|
|
||||||
of type `menu-loaded` and dispatches it on the component's DOM element
|
|
||||||
(`this.el`). The event bubbles and is cancelable. The parent component listening
|
|
||||||
to event `menu-loaded` will receive the payload in its `someMethod` handler
|
|
||||||
(in the `detail` property of the event), whenever the event is triggered.
|
|
||||||
|
|
||||||
```js
|
|
||||||
class ParentComponent {
|
|
||||||
someMethod(ev) {
|
|
||||||
const payload = ev.detail;
|
|
||||||
...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
By convention, we use KebabCase for the name of _business_ events.
|
|
||||||
|
|
||||||
The `t-on` directive allows to prebind its arguments. For example,
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="someMethod(expr)">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
Here, `expr` is a valid Owl expression, so it could be `true` or some variable
|
|
||||||
from the rendering context.
|
|
||||||
|
|
||||||
One can also directly specify inline statements. For example,
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="state.counter++">Increment counter</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
Here, `state` must be defined in the rendering context (typically the component)
|
|
||||||
as it will be translated to:
|
|
||||||
|
|
||||||
```js
|
|
||||||
button.addEventListener("click", () => {
|
|
||||||
component.state.counter++;
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
In order to remove the DOM event details from the event handlers (like calls to
|
|
||||||
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
|
||||||
specified as additional suffixes of the `t-on` directive.
|
|
||||||
|
|
||||||
| Modifier | Description |
|
|
||||||
| ---------- | ----------------------------------------------------------------- |
|
|
||||||
| `.stop` | calls `event.stopPropagation()` before calling the method |
|
|
||||||
| `.prevent` | calls `event.preventDefault()` before calling the method |
|
|
||||||
| `.self` | calls the method only if the `event.target` is the element itself |
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click.stop="someMethod">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
|
|
||||||
the order may matter. For instance `t-on-click.prevent.self` will prevent all
|
|
||||||
clicks while `t-on-click.self.prevent` will only prevent clicks on the element
|
|
||||||
itself.
|
|
||||||
|
|
||||||
Finally, empty handlers are tolerated as they could be defined only to apply
|
|
||||||
modifiers. For example,
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click.stop="">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
This will simply stop the propagation of the event.
|
|
||||||
|
|
||||||
### Form Input Bindings
|
### Form Input Bindings
|
||||||
|
|
||||||
It is very common to need to be able to read the value out of an html `input` (or
|
It is very common to need to be able to read the value out of an html `input` (or
|
||||||
@@ -822,252 +642,6 @@ update a number whenever the change is done.
|
|||||||
|
|
||||||
Note: the online playground has an example to show how it works.
|
Note: the online playground has an example to show how it works.
|
||||||
|
|
||||||
### `t-key` Directive
|
|
||||||
|
|
||||||
Even though Owl tries to be as declarative as possible, the DOM does not fully
|
|
||||||
expose its state declaratively in the DOM tree. For example, the scrolling state,
|
|
||||||
the current user selection, the focused element or the state of an input are not
|
|
||||||
set as attribute in the DOM tree. This is why we use a virtual dom
|
|
||||||
algorithm to keep the actual DOM node as much as possible.
|
|
||||||
|
|
||||||
However, in some situations, this is not enough, and we need to help Owl decide
|
|
||||||
if an element is actually the same, or is a different element with the same
|
|
||||||
properties.
|
|
||||||
|
|
||||||
Consider the following situation: we have a list of two items `[{text: "a"}, {text: "b"}]`
|
|
||||||
and we render them in this template:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<p t-foreach="items" t-as="item"><t t-esc="item.text"/></p>
|
|
||||||
```
|
|
||||||
|
|
||||||
The result will be two `<p>` tags with text `a` and `b`. Now, if we swap them,
|
|
||||||
and rerender the template, Owl needs to know what the intent is:
|
|
||||||
|
|
||||||
- should Owl actually swap the DOM nodes,
|
|
||||||
- or should it keep the DOM nodes, but with an updated text content?
|
|
||||||
|
|
||||||
This might look trivial, but it actually matters. These two possibilities lead
|
|
||||||
to different results in some cases. For example, if the user selected the text
|
|
||||||
of the first `p`, swapping them will keep the selection while updating the
|
|
||||||
text content will not.
|
|
||||||
|
|
||||||
There are many other cases where this is important: `input` tags with their
|
|
||||||
value, css classes and animations, scroll position...
|
|
||||||
|
|
||||||
So, the `t-key` directive is used to give an identity to an element. It allows
|
|
||||||
Owl to understand if different elements of a list are actually different or not.
|
|
||||||
|
|
||||||
The above example could be modified by adding an ID: `[{id: 1, text: "a"}, {id: 2, text: "b"}]`.
|
|
||||||
Then, the template could look like this:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<p t-foreach="items" t-as="item" t-key="item.id"><t t-esc="item.text"/></p>
|
|
||||||
```
|
|
||||||
|
|
||||||
The `t-key` directive is useful for lists (`t-foreach`). A key should be
|
|
||||||
a unique number or string (objects will not work: they will be cast to the
|
|
||||||
`"[object Object]"` string, which is obviously not unique).
|
|
||||||
|
|
||||||
Also, the key can be set on a `t` tag or on its children. The following variations
|
|
||||||
are all equivalent:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<p t-foreach="items" t-as="item" t-key="item.id">
|
|
||||||
<t t-esc="item.text"/>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<t t-foreach="items" t-as="item" t-key="item.id">
|
|
||||||
<p t-esc="item.text"/>
|
|
||||||
</t>
|
|
||||||
|
|
||||||
<t t-foreach="items" t-as="item">
|
|
||||||
<p t-key="item.id" t-esc="item.text"/>
|
|
||||||
</t>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Semantics
|
|
||||||
|
|
||||||
We give here an informal description of the way components are created/updated
|
|
||||||
in an application. Here, ordered lists describe actions that are executed
|
|
||||||
sequentially, bullet lists describe actions that are executed in parallel.
|
|
||||||
|
|
||||||
**Scenario 1: initial rendering** Imagine we want to render the following component tree:
|
|
||||||
|
|
||||||
```
|
|
||||||
A
|
|
||||||
/ \
|
|
||||||
B C
|
|
||||||
/ \
|
|
||||||
D E
|
|
||||||
```
|
|
||||||
|
|
||||||
Here is what happen whenever we mount the root
|
|
||||||
component (with some code like `app.mount(document.body)`).
|
|
||||||
|
|
||||||
1. `willStart` is called on `A`
|
|
||||||
|
|
||||||
2. when it is done, template `A` is rendered.
|
|
||||||
|
|
||||||
- component `B` is created
|
|
||||||
1. `willStart` is called on `B`
|
|
||||||
2. template `B` is rendered
|
|
||||||
- component `C` is created
|
|
||||||
1. `willStart` is called on `C`
|
|
||||||
2. template `C` is rendered
|
|
||||||
- component `D` is created
|
|
||||||
1. `willStart` is called on `D`
|
|
||||||
2. template `D` is rendered
|
|
||||||
- component `E` is created
|
|
||||||
1. `willStart` is called on `E`
|
|
||||||
2. template `E` is rendered
|
|
||||||
|
|
||||||
3. component `A` is patched into a detached DOM element. This will create the actual
|
|
||||||
component `A` DOM structure. The patching process will cause recursively the
|
|
||||||
patching of the `B`, `C`, `D` and `E` DOM trees. (so the actual full DOM tree is created
|
|
||||||
in one pass)
|
|
||||||
|
|
||||||
4. the component `A` root element is actually appended to `document.body`
|
|
||||||
|
|
||||||
5. The method `mounted` is called recursively on all components in the following
|
|
||||||
order: `B`, `D`, `E`, `C`, `A`.
|
|
||||||
|
|
||||||
**Scenario 2: rerendering a component**. Now, let's assume that the user clicked on some
|
|
||||||
button in `C`, and this results in a state update, which is supposed to:
|
|
||||||
|
|
||||||
- update `D`,
|
|
||||||
- remove `E`,
|
|
||||||
- add new component `F`.
|
|
||||||
|
|
||||||
So, the component tree should look like this:
|
|
||||||
|
|
||||||
```
|
|
||||||
A
|
|
||||||
/ \
|
|
||||||
B C
|
|
||||||
/ \
|
|
||||||
D F
|
|
||||||
```
|
|
||||||
|
|
||||||
Here is what Owl will do:
|
|
||||||
|
|
||||||
1. because of a state change, the method `render` is called on `C`
|
|
||||||
2. template `C` is rendered again
|
|
||||||
|
|
||||||
- component `D` is updated:
|
|
||||||
1. hook `willUpdateProps` is called on `D` (async)
|
|
||||||
2. template `D` is rerendered
|
|
||||||
- component `F` is created:
|
|
||||||
1. hook `willStart` is called on `E` (async)
|
|
||||||
2. template `F` is rendered
|
|
||||||
|
|
||||||
3. `willPatch` hooks are called recursively on components `C`, `D` (not on `F`,
|
|
||||||
because it is not mounted yet)
|
|
||||||
|
|
||||||
4. component `C` is patched, which will cause recursively:
|
|
||||||
|
|
||||||
2. `willUnmount` hook on `E`, then destruction of `E`,
|
|
||||||
3. (initial) patching of `F`, then hook `mounted` is called on `F`
|
|
||||||
|
|
||||||
5. patching of `D`
|
|
||||||
|
|
||||||
6. `patched` hooks are called on `D`, `C`
|
|
||||||
|
|
||||||
### Props Validation
|
|
||||||
|
|
||||||
As an application becomes complex, it may be quite unsafe to define props in an informal way. This leads to two issues:
|
|
||||||
|
|
||||||
- hard to tell how a component should be used, by looking at its code.
|
|
||||||
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parents.
|
|
||||||
|
|
||||||
A props type system would solve both issues, by describing the types and shapes
|
|
||||||
of the props. Here is how it works in Owl:
|
|
||||||
|
|
||||||
- `props` key is a static key (so, different from `this.props` in a component instance)
|
|
||||||
- it is optional: it is ok for a component to not define a `props` key.
|
|
||||||
- props are validated whenever a component is created/updated
|
|
||||||
- props are only validated in `dev` mode (see [tooling page](../tooling.md#development-mode))
|
|
||||||
- if a key does not match the description, an error is thrown
|
|
||||||
- it validates keys defined in (static) `props`. Additional keys given by the
|
|
||||||
parent will cause an error.
|
|
||||||
|
|
||||||
For example:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class ComponentA extends owl.Component {
|
|
||||||
static props = ['id', 'url'];
|
|
||||||
|
|
||||||
...
|
|
||||||
}
|
|
||||||
|
|
||||||
class ComponentB extends owl.Component {
|
|
||||||
static props = {
|
|
||||||
count: {type: Number},
|
|
||||||
messages: {
|
|
||||||
type: Array,
|
|
||||||
element: {type: Object, shape: {id: Boolean, text: 'string' }
|
|
||||||
},
|
|
||||||
date: Date,
|
|
||||||
combinedVal: [Number, Boolean]
|
|
||||||
};
|
|
||||||
|
|
||||||
...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- it is an object or a list of strings
|
|
||||||
- a list of strings is a simplified props definition, which only lists the name
|
|
||||||
of the props. Also, if the name ends with `?`, it is considered optional.
|
|
||||||
- all props are by default required, unless they are defined with `optional: true`
|
|
||||||
(in that case, validation is only done if there is a value)
|
|
||||||
- valid types are: `Number, String, Boolean, Object, Array, Date, Function`, and all
|
|
||||||
constructor functions (so, if you have a `Person` class, it can be used as a type)
|
|
||||||
- arrays are homogeneous (all elements have the same type/shape)
|
|
||||||
|
|
||||||
For each key, a `prop` definition is either a boolean, a constructor, a list of constructors, or an object:
|
|
||||||
|
|
||||||
- a boolean: indicate that the props exists, and is mandatory.
|
|
||||||
- a constructor: this should describe the type, for example: `id: Number` describe
|
|
||||||
the props `id` as a number
|
|
||||||
- a list of constructors. In that case, this means that we allow more than one
|
|
||||||
type. For example, `id: [Number, String]` means that `id` can be either a string
|
|
||||||
or a number.
|
|
||||||
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed:
|
|
||||||
- `type`: the main type of the prop being validated
|
|
||||||
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. It is optional (not set means that we only validate the array, not its elements),
|
|
||||||
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. It is optional (not set means that we only validate the object, not its elements)
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// only the existence of those 3 keys is documented
|
|
||||||
static props = ['message', 'id', 'date'];
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
// size is optional
|
|
||||||
static props = ['message', 'size?'];
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
static props = {
|
|
||||||
messageIds: {type: Array, element: Number}, // list of number
|
|
||||||
otherArr: {type: Array}, // just array. no validation is made on sub elements
|
|
||||||
otherArr2: Array, // same as otherArr
|
|
||||||
someObj: {type: Object}, // just an object, no internal validation
|
|
||||||
someObj2: {
|
|
||||||
type: Object,
|
|
||||||
shape: {
|
|
||||||
id: Number,
|
|
||||||
name: {type: String, optional: true},
|
|
||||||
url: String
|
|
||||||
]}, // object, with keys id (number), name (string, optional) and url (string)
|
|
||||||
someFlag: Boolean, // a boolean, mandatory (even if `false`)
|
|
||||||
someVal: [Boolean, Date], // either a boolean or a date
|
|
||||||
otherValue: true, // indicates that it is a prop
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
### References
|
### References
|
||||||
|
|
||||||
The `useRef` hook is useful when we need a way to interact with some inside part
|
The `useRef` hook is useful when we need a way to interact with some inside part
|
||||||
@@ -1124,163 +698,50 @@ Note that these two examples uses the suffix `ref` to name the reference. This
|
|||||||
is not mandatory, but it is a useful convention, so we do not forget to access
|
is not mandatory, but it is a useful convention, so we do not forget to access
|
||||||
it with the `el` or `comp` suffix.
|
it with the `el` or `comp` suffix.
|
||||||
|
|
||||||
### Slots
|
### Dynamic sub components
|
||||||
|
|
||||||
To make generic components, it is useful to be able for a parent component to _inject_
|
It is not common, but sometimes we need a dynamic component name. In this case,
|
||||||
some sub template, but still be the owner. For example, a generic dialog component
|
the `t-component` directive can also be used to accept dynamic values with string interpolation (like the [`t-attf-`](qweb_templating_language.md#dynamic-attributes) directive):
|
||||||
will need to render some content, some footer, but with the parent as the
|
|
||||||
rendering context.
|
|
||||||
|
|
||||||
This is what _slots_ are for.
|
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<div t-name="Dialog" class="modal">
|
<div t-name="ParentComponent">
|
||||||
<div class="modal-title"><t t-esc="props.title"/></div>
|
<t t-component="ChildComponent{{id}}" />
|
||||||
<div class="modal-content">
|
|
||||||
<t t-slot="content"/>
|
|
||||||
</div>
|
|
||||||
<div class="modal-footer">
|
|
||||||
<t t-slot="footer"/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
Slots are defined by the caller, with the `t-set` directive:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="SomeComponent">
|
|
||||||
<div>some component</div>
|
|
||||||
<Dialog title="Some Dialog">
|
|
||||||
<t t-set="content">
|
|
||||||
<div>hey</div>
|
|
||||||
</t>
|
|
||||||
<t t-set="footer">
|
|
||||||
<button t-on-click="doSomething">ok</button>
|
|
||||||
</t>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the component `Dialog` will render the slots `content` and `footer`
|
|
||||||
with its parent as rendering context. This means that clicking on the button
|
|
||||||
will execute the `doSomething` method on the parent, not on the dialog.
|
|
||||||
|
|
||||||
Default slot: the first element inside the component which is not a named slot will
|
|
||||||
be considered the `default` slot. For example:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="Parent">
|
|
||||||
<Child>
|
|
||||||
<span>some content</span>
|
|
||||||
</Child>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div t-name="Child">
|
|
||||||
<t t-slot="default"/>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Asynchronous Rendering
|
|
||||||
|
|
||||||
Working with asynchronous code always adds a lot of complexity to a system. Whenever
|
|
||||||
different parts of a system are active at the same time, one needs to think
|
|
||||||
carefully about all possible interactions. Clearly, this is also true for Owl
|
|
||||||
components.
|
|
||||||
|
|
||||||
There are two different common problems with Owl asynchronous rendering model:
|
|
||||||
|
|
||||||
- any component can delay the rendering (initial and subsequent) of the whole
|
|
||||||
application
|
|
||||||
- for a given component, there are two independant situations that will trigger an
|
|
||||||
asynchronous rerendering: a change in the state, or a change in the props.
|
|
||||||
These changes may be done at different times, and Owl has no way of knowing
|
|
||||||
how to reconcile the resulting renderings.
|
|
||||||
|
|
||||||
Here are a few tips on how to work with asynchronous components:
|
|
||||||
|
|
||||||
1. Minimize the use of asynchronous components!
|
|
||||||
2. Maybe move the asynchronous logic in a store, which then triggers (mostly)
|
|
||||||
synchronous renderings
|
|
||||||
3. Lazy loading external libraries is a good use case for async rendering. This
|
|
||||||
is mostly fine, because we can assume that it will only takes a fraction of a
|
|
||||||
second, and only once (see [`owl.utils.loadJS`](utils.md#loadjs))
|
|
||||||
4. For all the other cases, the [`AsyncRoot`](misc.md#asyncroot) component is there to help you. When
|
|
||||||
this component is met, a new rendering
|
|
||||||
sub tree is created, such that the rendering of that component (and its
|
|
||||||
children) is not tied to the rendering of the rest of the interface. It can
|
|
||||||
be used on an asynchronous component, to prevent it from delaying the
|
|
||||||
rendering of the whole interface, or on a synchronous one, such that its
|
|
||||||
rendering isn't delayed by other (asynchronous) components. Note that this
|
|
||||||
directive has no effect on the first rendering, but only on subsequent ones
|
|
||||||
(triggered by state or props changes).
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="ParentComponent">
|
|
||||||
<SyncChild />
|
|
||||||
<AsyncRoot>
|
|
||||||
<AsyncChild/>
|
|
||||||
</AsyncRoot>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
|
|
||||||
By default, whenever an error occurs in the rendering of an Owl application, we
|
|
||||||
destroy the whole application. Otherwise, we cannot offer any guarantee on the
|
|
||||||
state of the resulting component tree. It might be hopelessly corrupted, but
|
|
||||||
without any user-visible state.
|
|
||||||
|
|
||||||
Clearly, it sometimes is a little bit extreme to destroy the application. This
|
|
||||||
is why we have a builtin mechanism to handle rendering errors (and errors coming
|
|
||||||
from lifecycle hooks): the `catchError` hook.
|
|
||||||
|
|
||||||
Whenever the `catchError` lifecycle hook is implemented, all errors coming from
|
|
||||||
sub components rendering and/or lifecycle method calls will be caught and given
|
|
||||||
to the `catchError` method. This allows us to properly handle the error, and to
|
|
||||||
not break the application.
|
|
||||||
|
|
||||||
For example, here is how we could implement an `ErrorBoundary` component:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="ErrorBoundary">
|
|
||||||
<t t-if="state.error">
|
|
||||||
Error handled
|
|
||||||
</t>
|
|
||||||
<t t-else="1">
|
|
||||||
<t t-slot="default" />
|
|
||||||
</t>
|
|
||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class ErrorBoundary extends Component {
|
class ParentComponent {
|
||||||
state = useState({ error: false });
|
static components = { ChildComponent1, ChildComponent2 };
|
||||||
|
state = { id: 1 };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
catchError() {
|
There is an even more dynamic way to use `t-component`: its value can be an
|
||||||
this.state.error = true;
|
expression evaluating to an actual component class. In that case, this is the
|
||||||
|
class that will be used to create the component:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class A extends Component<any, any, any> {
|
||||||
|
static template = xml`<span>child a</span>`;
|
||||||
|
}
|
||||||
|
class B extends Component<any, any, any> {
|
||||||
|
static template = xml`<span>child b</span>`;
|
||||||
|
}
|
||||||
|
class App extends Component<any, any, any> {
|
||||||
|
static template = xml`<t t-component="myComponent" t-key="state.child"/>`;
|
||||||
|
|
||||||
|
state = { child: "a" };
|
||||||
|
|
||||||
|
get myComponent() {
|
||||||
|
return this.state.child === "a" ? A : B;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Using the `ErrorBoundary` is then extremely simple:
|
In this example, the component `App` selects dynamically the concrete sub
|
||||||
|
component class.
|
||||||
|
|
||||||
```xml
|
Note that the `t-component` directive can only be used on `<t>` nodes.
|
||||||
<ErrorBoundary><SomeOtherComponent/></ErrorBoundary>
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that we need to be careful here: the fallback UI should not throw any
|
|
||||||
error, otherwise we risk going into an infinite loop.
|
|
||||||
|
|
||||||
Also, it may be useful to know that whenever an error is caught, it is then
|
|
||||||
broadcasted to the application by an event on the `qweb` instance. It may be
|
|
||||||
useful, for example, to log the error somewhere.
|
|
||||||
|
|
||||||
```js
|
|
||||||
env.qweb.on("error", null, function(error) {
|
|
||||||
// do something
|
|
||||||
// react to the error
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Functional Components
|
### Functional Components
|
||||||
|
|
||||||
@@ -1343,8 +804,8 @@ class RootNode extends Component {
|
|||||||
children: [
|
children: [
|
||||||
{ label: "b" },
|
{ label: "b" },
|
||||||
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
||||||
{ label: "f", children: [{ label: "g" }] }
|
{ label: "f", children: [{ label: "g" }] },
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
# 🦉 Concurrency Model 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Rendering Components](#rendering-components)
|
||||||
|
- [Semantics](#semantics)
|
||||||
|
- [Asynchronous Rendering](#asynchronous-rendering)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Owl was designed from the very beginning with asynchronous components. This comes
|
||||||
|
from the `willStart` and the `willUpdateProps` lifecycle hooks. With these
|
||||||
|
methods, it is possible to build complex highly concurrent applications.
|
||||||
|
|
||||||
|
Owl concurrent mode has several benefits: it makes it possible to delay the
|
||||||
|
rendering until some asynchronous operation is complete, it makes it possible
|
||||||
|
to lazy load libraries, while keeping the previous screen completely functional.
|
||||||
|
It is also good for performance reasons: Owl uses it to only apply the result of
|
||||||
|
many different renderings only once in an animation frame. Owl can cancel
|
||||||
|
a rendering that is no longer relevant, restart it, reuse it in some cases.
|
||||||
|
|
||||||
|
But even though using concurrency is quite simple (and is the default behaviour),
|
||||||
|
asynchrony is difficult, because it introduces an additional dimension that
|
||||||
|
vastly increase the complexity of an application. This section will explain
|
||||||
|
how Owl manages this complexity, how concurrent rendering works in a general way.
|
||||||
|
|
||||||
|
## Rendering Components
|
||||||
|
|
||||||
|
The word _rendering_ is a little vague, so, let us explain more precisely the
|
||||||
|
process by which Owl components are displayed on a screen.
|
||||||
|
|
||||||
|
When a component is mounted or updated, a new rendering is started. It has
|
||||||
|
two phases: _virtual rendering_ and _patching_.
|
||||||
|
|
||||||
|
### Virtual rendering
|
||||||
|
|
||||||
|
This phase represent the process of rendering a template, in memory, which create a virtual representation of the desired component html). The output of this phase is a
|
||||||
|
virtual DOM.
|
||||||
|
|
||||||
|
It is asynchronous: each subcomponents needs to either be created (so, `willStart`
|
||||||
|
will need to be called), or updated (which is done with the `willUpdateProps`
|
||||||
|
method). This is completely a recursive process: a component is the root of a
|
||||||
|
component tree, and each sub component needs to be (virtually) rendered.
|
||||||
|
|
||||||
|
### Patching
|
||||||
|
|
||||||
|
Once a rendering is complete, it will be applied on the next animation frame.
|
||||||
|
This is done synchronously: the whole component tree is patched to the real
|
||||||
|
DOM.
|
||||||
|
|
||||||
|
## Semantics
|
||||||
|
|
||||||
|
We give here an informal description of the way components are created/updated
|
||||||
|
in an application. Here, ordered lists describe actions that are executed
|
||||||
|
sequentially, bullet lists describe actions that are executed in parallel.
|
||||||
|
|
||||||
|
**Scenario 1: initial rendering** Imagine we want to render the following component tree:
|
||||||
|
|
||||||
|
```
|
||||||
|
A
|
||||||
|
/ \
|
||||||
|
B C
|
||||||
|
/ \
|
||||||
|
D E
|
||||||
|
```
|
||||||
|
|
||||||
|
Here is what happen whenever we mount the root
|
||||||
|
component (with some code like `app.mount(document.body)`).
|
||||||
|
|
||||||
|
1. `willStart` is called on `A`
|
||||||
|
|
||||||
|
2. when it is done, template `A` is rendered.
|
||||||
|
|
||||||
|
- component `B` is created
|
||||||
|
1. `willStart` is called on `B`
|
||||||
|
2. template `B` is rendered
|
||||||
|
- component `C` is created
|
||||||
|
1. `willStart` is called on `C`
|
||||||
|
2. template `C` is rendered
|
||||||
|
- component `D` is created
|
||||||
|
1. `willStart` is called on `D`
|
||||||
|
2. template `D` is rendered
|
||||||
|
- component `E` is created
|
||||||
|
1. `willStart` is called on `E`
|
||||||
|
2. template `E` is rendered
|
||||||
|
|
||||||
|
3. each components are patched into a detached DOM element, in the following order:
|
||||||
|
`E`, `D`, `C`, `B`, `A`. (so the actual full DOM tree is created
|
||||||
|
in one pass)
|
||||||
|
|
||||||
|
4. the component `A` root element is actually appended to `document.body`
|
||||||
|
|
||||||
|
5. The method `mounted` is called recursively on all components in the following
|
||||||
|
order: `E`, `D`, `C`, `B`, `A`.
|
||||||
|
|
||||||
|
**Scenario 2: rerendering a component**. Now, let's assume that the user clicked on some
|
||||||
|
button in `C`, and this results in a state update, which is supposed to:
|
||||||
|
|
||||||
|
- update `D`,
|
||||||
|
- remove `E`,
|
||||||
|
- add new component `F`.
|
||||||
|
|
||||||
|
So, the component tree should look like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
A
|
||||||
|
/ \
|
||||||
|
B C
|
||||||
|
/ \
|
||||||
|
D F
|
||||||
|
```
|
||||||
|
|
||||||
|
Here is what Owl will do:
|
||||||
|
|
||||||
|
1. because of a state change, the method `render` is called on `C`
|
||||||
|
2. template `C` is rendered again
|
||||||
|
|
||||||
|
- component `D` is updated:
|
||||||
|
1. hook `willUpdateProps` is called on `D` (async)
|
||||||
|
2. template `D` is rerendered
|
||||||
|
- component `F` is created:
|
||||||
|
1. hook `willStart` is called on `F` (async)
|
||||||
|
2. template `F` is rendered
|
||||||
|
|
||||||
|
3. `willPatch` hooks are called recursively on components `C`, `D` (not on `F`,
|
||||||
|
because it is not mounted yet)
|
||||||
|
|
||||||
|
4. components `F`, `D` are patched in that order
|
||||||
|
|
||||||
|
5. component `C` is patched, which will cause recursively:
|
||||||
|
|
||||||
|
1. `willUnmount` hook on `E`
|
||||||
|
2. destruction of `E`,
|
||||||
|
|
||||||
|
6. `mounted` hook is called on `F`, `patched` hooks are called on `D`, `C`
|
||||||
|
|
||||||
|
Tags are very small helpers 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](../learning/how_to_write_sfc.md).
|
||||||
|
|
||||||
|
### Asynchronous Rendering
|
||||||
|
|
||||||
|
Working with asynchronous code always adds a lot of complexity to a system. Whenever
|
||||||
|
different parts of a system are active at the same time, one needs to think
|
||||||
|
carefully about all possible interactions. Clearly, this is also true for Owl
|
||||||
|
components.
|
||||||
|
|
||||||
|
There are two different common problems with Owl asynchronous rendering model:
|
||||||
|
|
||||||
|
- any component can delay the rendering (initial and subsequent) of the whole
|
||||||
|
application
|
||||||
|
- for a given component, there are two independant situations that will trigger an
|
||||||
|
asynchronous rerendering: a change in the state, or a change in the props.
|
||||||
|
These changes may be done at different times, and Owl has no way of knowing
|
||||||
|
how to reconcile the resulting renderings.
|
||||||
|
|
||||||
|
Here are a few tips on how to work with asynchronous components:
|
||||||
|
|
||||||
|
1. Minimize the use of asynchronous components!
|
||||||
|
2. Maybe move the asynchronous logic in a store, which then triggers (mostly)
|
||||||
|
synchronous renderings
|
||||||
|
3. Lazy loading external libraries is a good use case for async rendering. This
|
||||||
|
is mostly fine, because we can assume that it will only takes a fraction of a
|
||||||
|
second, and only once (see [`owl.utils.loadJS`](utils.md#loadjs))
|
||||||
|
4. For all the other cases, the [`AsyncRoot`](misc.md#asyncroot) component is there to help you. When
|
||||||
|
this component is met, a new rendering
|
||||||
|
sub tree is created, such that the rendering of that component (and its
|
||||||
|
children) is not tied to the rendering of the rest of the interface. It can
|
||||||
|
be used on an asynchronous component, to prevent it from delaying the
|
||||||
|
rendering of the whole interface, or on a synchronous one, such that its
|
||||||
|
rendering isn't delayed by other (asynchronous) components. Note that this
|
||||||
|
directive has no effect on the first rendering, but only on subsequent ones
|
||||||
|
(triggered by state or props changes).
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="ParentComponent">
|
||||||
|
<SyncChild />
|
||||||
|
<AsyncRoot>
|
||||||
|
<AsyncChild/>
|
||||||
|
</AsyncRoot>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# 🦉 Config 🦉
|
||||||
|
|
||||||
|
The Owl framework is designed to work in many situations. However, it is
|
||||||
|
sometimes necessary to customize some behaviour. This is done by using the
|
||||||
|
global `config` object. It provides two settings:
|
||||||
|
|
||||||
|
- [`mode`](#mode) (default value: `prod`),
|
||||||
|
- [`enableTransitions`](#enabletransitions) (default value: `true`).
|
||||||
|
|
||||||
|
## 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, it is sometimes necessary
|
||||||
|
to have better information on what is going on, this is the purpose
|
||||||
|
of the `dev` mode.
|
||||||
|
|
||||||
|
Owl has a mode flag, in `owl.config.mode`. Its default value is `prod`, but
|
||||||
|
it can be set to `dev`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.config.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.
|
||||||
|
|
||||||
|
## `enableTransitions`
|
||||||
|
|
||||||
|
Transitions are usually nice, but they can cause issues in some specific cases,
|
||||||
|
such as automated tests. It is uncomfortable having to wait for a transition
|
||||||
|
to end before moving to the next step.
|
||||||
|
|
||||||
|
To solve this issue, Owl can be configured to ignore the `t-transition` directive.
|
||||||
|
To do that, one only needs to set the `enableTransitions` flag to false:
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.config.enableTransitions = false;
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that it suffers from the same drawback as the "dev" mode: all compiled
|
||||||
|
templates, if any, will keep their current behaviours.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# 🦉 Owl Content 🦉
|
||||||
|
|
||||||
|
Here is a complete visual representation of everything exported by the `owl`
|
||||||
|
global object.
|
||||||
|
|
||||||
|
For example, `Component` is available at `owl.Component` and `EventBus` is
|
||||||
|
exported as `owl.core.EventBus`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Component misc
|
||||||
|
Context AsyncRoot
|
||||||
|
QWeb Portal
|
||||||
|
Store router
|
||||||
|
useState Link
|
||||||
|
config RouteComponent
|
||||||
|
mode Router
|
||||||
|
core tags
|
||||||
|
EventBus css
|
||||||
|
Observer xml
|
||||||
|
hooks utils
|
||||||
|
onWillStart debounce
|
||||||
|
onMounted escape
|
||||||
|
onWillUpdateProps loadJS
|
||||||
|
onWillPatch loadFile
|
||||||
|
onPatched shallowEqual
|
||||||
|
onWillUnmount whenReady
|
||||||
|
useContext
|
||||||
|
useState
|
||||||
|
useRef
|
||||||
|
useSubEnv
|
||||||
|
useStore
|
||||||
|
useDispatch
|
||||||
|
useGetters
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
||||||
@@ -28,10 +28,7 @@ context, and add it to the environment:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const deviceContext = new Context({ isMobile: true });
|
const deviceContext = new Context({ isMobile: true });
|
||||||
const env = {
|
App.env.deviceContext = deviceContext;
|
||||||
qweb: new QWeb({ templates: TEMPLATES }),
|
|
||||||
deviceContext
|
|
||||||
};
|
|
||||||
```
|
```
|
||||||
|
|
||||||
If we want to make it completely responsive, we need to update its value whenever
|
If we want to make it completely responsive, we need to update its value whenever
|
||||||
@@ -60,10 +57,10 @@ class SomeComponent extends Component {
|
|||||||
<t t-if=device.isMobile>
|
<t t-if=device.isMobile>
|
||||||
some simplified user interface
|
some simplified user interface
|
||||||
</t>
|
</t>
|
||||||
<t t-else="1">
|
<t t-else="">
|
||||||
some more sopthisticated user interface
|
a more advanced user interface
|
||||||
</t>
|
</t>
|
||||||
`;
|
</div>`;
|
||||||
device = useContext(this.env.deviceContext);
|
device = useContext(this.env.deviceContext);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# 🦉 Environment 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Setting an Environment](#setting-an-environment)
|
||||||
|
- [Using a sub environment](#using-a-sub-environment)
|
||||||
|
- [Content of an Environment](#content-of-an-environment)
|
||||||
|
- [Special keys](#special-keys)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
An environment is an object which contains a [`QWeb` instance](qweb_engine.md). Whenever
|
||||||
|
a root component is created, it is assigned an environment (see
|
||||||
|
[below](#setting-an-environment) for more info on this). This environment is
|
||||||
|
then automatically given to each sub component (and accessible in the `this.env`
|
||||||
|
property).
|
||||||
|
|
||||||
|
```
|
||||||
|
Root
|
||||||
|
/ \
|
||||||
|
A B
|
||||||
|
```
|
||||||
|
|
||||||
|
This way, all components share the same `QWeb` instance. Owl internally requires
|
||||||
|
that the environment has a `qweb` key which maps to a
|
||||||
|
[`QWeb`](qweb_engine.md) instance. This is the QWeb instance that will be used to
|
||||||
|
render each templates in this specific component tree. Note that if no `QWeb`
|
||||||
|
instance is provided, Owl will simply generate it on the fly.
|
||||||
|
|
||||||
|
The environment is mostly static. Each application is free to add anything to
|
||||||
|
the environment, which is very useful, since this can be accessed by each sub
|
||||||
|
component.
|
||||||
|
|
||||||
|
## Setting an environment
|
||||||
|
|
||||||
|
An Owl application needs an [environment](environment.md) to be executed. The
|
||||||
|
environment has an important key: the [QWeb](qweb_engine.md) instance, which will render
|
||||||
|
all templates.
|
||||||
|
|
||||||
|
Whenever a root component `App` is mounted, Owl will setup a valid environment by
|
||||||
|
following the next steps:
|
||||||
|
|
||||||
|
- take the `env` object defined on `App.env` (if no `env` was explicitly setup,
|
||||||
|
this will return the empty `env` object defined on `Component`)
|
||||||
|
- if `env.qweb` is not set, then Owl will create a `QWeb` instance.
|
||||||
|
|
||||||
|
The correct way to customize an environment is to simply set it up on the root
|
||||||
|
component class, before the first component is created:
|
||||||
|
|
||||||
|
```js
|
||||||
|
App.env = {
|
||||||
|
_t: myTranslateFunction,
|
||||||
|
user: {...},
|
||||||
|
services: {
|
||||||
|
...
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
```
|
||||||
|
|
||||||
|
It is also possible to simply share an environment between all root components,
|
||||||
|
by simply doing this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
Component.env = myEnv; // will be the default env for all components
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that this environment is the global owl environment for an application. The
|
||||||
|
next section explains how to extend an environment for a specific sub component
|
||||||
|
and its children.
|
||||||
|
|
||||||
|
## Using a sub environment
|
||||||
|
|
||||||
|
It is sometimes useful to add one (or more) specific keys to the environment,
|
||||||
|
from the perspective of a specific component and its children. In that case, the
|
||||||
|
solution presented above will not work, since it sets the global environment.
|
||||||
|
|
||||||
|
There is a hook for this situation: [`useSubEnv`](hooks.md#usesubenv).
|
||||||
|
|
||||||
|
```js
|
||||||
|
class FormComponent extends Component {
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
useSubEnv({ myKey: someValue });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Content of an Environment
|
||||||
|
|
||||||
|
Some good use cases for additional keys in the environment are:
|
||||||
|
|
||||||
|
- some configuration keys,
|
||||||
|
- session information,
|
||||||
|
- generic services (such as doing rpcs).
|
||||||
|
|
||||||
|
Doing it this way means that components are easily testable: we can simply
|
||||||
|
create a test environment with mock services.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
async function myEnv() {
|
||||||
|
const templates = await loadTemplates();
|
||||||
|
const qweb = new QWeb({ templates });
|
||||||
|
const session = getSession();
|
||||||
|
|
||||||
|
return {
|
||||||
|
_t: myTranslateFunction,
|
||||||
|
session: session,
|
||||||
|
qweb: qweb,
|
||||||
|
services: {
|
||||||
|
localStorage: localStorage,
|
||||||
|
rpc: rpc,
|
||||||
|
},
|
||||||
|
debug: false,
|
||||||
|
inMobileMode: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
App.env = await myEnv();
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(document.body);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Special Keys
|
||||||
|
|
||||||
|
There are two special key/value added by Owl if not provided in the environment:
|
||||||
|
the `QWeb` instance and a `browser` object:
|
||||||
|
|
||||||
|
- `qweb` will be set to an empty `QWeb` instance. This is absolutely necessary
|
||||||
|
for Owl to be able to render anything
|
||||||
|
- `browser`: this is an object that contains some common access points to the
|
||||||
|
browser methods with a side effect. This is particularly useful when one want
|
||||||
|
to test more advanced components, and be able to mock those methods.
|
||||||
|
|
||||||
|
More specifically, the `browser` object contains the following methods and objects:
|
||||||
|
|
||||||
|
- `setTimeout`
|
||||||
|
- `clearTimeout`
|
||||||
|
- `setInterval`
|
||||||
|
- `clearInterval`
|
||||||
|
- `requestAnimationFrame`
|
||||||
|
- `random`
|
||||||
|
- `Date`
|
||||||
|
- `fetch`
|
||||||
|
- `localStorage`
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# 🦉 Error Handling 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Example](#example)
|
||||||
|
- [Reference](#reference)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
By default, whenever an error occurs in the rendering of an Owl application, we
|
||||||
|
destroy the whole application. Otherwise, we cannot offer any guarantee on the
|
||||||
|
state of the resulting component tree. It might be hopelessly corrupted, but
|
||||||
|
without any user-visible state.
|
||||||
|
|
||||||
|
Clearly, it sometimes is a little bit extreme to destroy the application. This
|
||||||
|
is why we have a builtin mechanism to handle rendering errors (and errors coming
|
||||||
|
from lifecycle hooks): the `catchError` hook.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
For example, here is how we could implement an `ErrorBoundary` component:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="ErrorBoundary">
|
||||||
|
<t t-if="state.error">
|
||||||
|
Error handled
|
||||||
|
</t>
|
||||||
|
<t t-else="">
|
||||||
|
<t t-slot="default" />
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Using the `ErrorBoundary` is then extremely simple:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<ErrorBoundary><SomeOtherComponent/></ErrorBoundary>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that we need to be careful here: the fallback UI should not throw any
|
||||||
|
error, otherwise we risk going into an infinite loop (also, see the page on
|
||||||
|
[slots](slots.md) for more information on the `t-slot` directive).
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
Whenever the `catchError` lifecycle hook is implemented, all errors coming from
|
||||||
|
sub components rendering and/or lifecycle method calls will be caught and given
|
||||||
|
to the `catchError` method. This allows us to properly handle the error, and to
|
||||||
|
not break the application.
|
||||||
|
|
||||||
|
There are important things to know:
|
||||||
|
|
||||||
|
- If an error that occured in the internal rendering cycle is not caught, then
|
||||||
|
Owl will destroy the full application. This is done on purpose, because Owl
|
||||||
|
cannot guarantee that the state is not corrupted from this point on.
|
||||||
|
|
||||||
|
- errors coming from event handlers are NOT managed by `catchError` or any other
|
||||||
|
owl mechanism. This is up to the application developer to properly recover
|
||||||
|
from an error
|
||||||
|
|
||||||
|
Also, it may be useful to know that whenever an error is caught, it is then
|
||||||
|
broadcasted to the application by an event on the `qweb` instance. It may be
|
||||||
|
useful, for example, to log the error somewhere.
|
||||||
|
|
||||||
|
```js
|
||||||
|
env.qweb.on("error", null, function (error) {
|
||||||
|
// do something
|
||||||
|
// react to the error
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -7,7 +7,7 @@ triggering events, and callbacks.
|
|||||||
```js
|
```js
|
||||||
const bus = new owl.core.EventBus();
|
const bus = new owl.core.EventBus();
|
||||||
|
|
||||||
bus.on("some-event", null, function(...args) {
|
bus.on("some-event", null, function (...args) {
|
||||||
console.log(...args);
|
console.log(...args);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# 🦉 Event Handling 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Event Handling](#event-handling)
|
||||||
|
- [Business DOM Events](#business-dom-events)
|
||||||
|
- [Inline Event Handlers](#inline-event-handlers)
|
||||||
|
- [Modifiers](#modifiers)
|
||||||
|
|
||||||
|
## Event Handling
|
||||||
|
|
||||||
|
In a component's template, it is useful to be able to register handlers on DOM
|
||||||
|
elements to some specific events. This is what makes a template _alive_. There
|
||||||
|
are four different use cases.
|
||||||
|
|
||||||
|
1. Register an event handler on a DOM node (_pure_ DOM event)
|
||||||
|
2. Register an event handler on a component (_pure_ DOM event)
|
||||||
|
3. Register an event handler on a DOM node (_business_ DOM event)
|
||||||
|
4. Register an event handler on a component (_business_ DOM event)
|
||||||
|
|
||||||
|
A _pure_ DOM event is directly triggered by a user interaction (e.g. a `click`).
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="someMethod">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
This will be roughly translated in javascript like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.addEventListener("click", component.someMethod.bind(component));
|
||||||
|
```
|
||||||
|
|
||||||
|
The suffix (`click` in this example) is simply the name of the actual DOM
|
||||||
|
event.
|
||||||
|
|
||||||
|
## Business DOM Events
|
||||||
|
|
||||||
|
A _business_ DOM event is triggered by a call to `trigger` on a component.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<MyComponent t-on-menu-loaded="someMethod" />
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
class MyComponent {
|
||||||
|
someWhere() {
|
||||||
|
const payload = ...;
|
||||||
|
this.trigger('menu-loaded', payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The call to `trigger` generates an `OwlEvent`, a subclass of [_CustomEvent_](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
|
||||||
|
with an additional attribute `originalComponent` (the component that triggered
|
||||||
|
the event). The generated event is of type `menu-loaded` and dispatches it on
|
||||||
|
the component's DOM element (`this.el`). The event bubbles and is cancelable.
|
||||||
|
The parent component listening to event `menu-loaded` will receive the payload
|
||||||
|
in its `someMethod` handler (in the `detail` property of the event), whenever
|
||||||
|
the event is triggered.
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ParentComponent {
|
||||||
|
someMethod(ev) {
|
||||||
|
const payload = ev.detail;
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
By convention, we use KebabCase for the name of _business_ events.
|
||||||
|
|
||||||
|
The `t-on` directive allows to prebind its arguments. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="someMethod(expr)">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, `expr` is a valid Owl expression, so it could be `true` or some variable
|
||||||
|
from the rendering context.
|
||||||
|
|
||||||
|
### Type Hinting
|
||||||
|
|
||||||
|
Note that if you work with Typescript, the `trigger` method is generic on the type of the payload.
|
||||||
|
|
||||||
|
You can then describe the type of the event, so you will see typing errors...
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
this.trigger<MyCustomPayload>("my-custom-event", payload);
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
myCustomEventHandler(ev: OwlEvent<MyCustomPayload>) { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Inline Event Handlers
|
||||||
|
|
||||||
|
One can also directly specify inline statements. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="state.counter++">Increment counter</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, `state` must be defined in the rendering context (typically the component)
|
||||||
|
as it will be translated to:
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
context.state.counter++;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Warning: inline expressions are evaluated in the context of the template. This
|
||||||
|
means that they can access the component methods and properties. But if they set
|
||||||
|
a key, the inline statement will actually not modify the component, but a key in
|
||||||
|
a sub scope.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="value = 1">Set value to 1 (does not work!!!)</button>
|
||||||
|
<button t-on-click="state.value = 1">Set state.value to 1 (work as expected)</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Modifiers
|
||||||
|
|
||||||
|
In order to remove the DOM event details from the event handlers (like calls to
|
||||||
|
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
||||||
|
specified as additional suffixes of the `t-on` directive.
|
||||||
|
|
||||||
|
| Modifier | Description |
|
||||||
|
| ---------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `.stop` | calls `event.stopPropagation()` before calling the method |
|
||||||
|
| `.prevent` | calls `event.preventDefault()` before calling the method |
|
||||||
|
| `.self` | calls the method only if the `event.target` is the element itself |
|
||||||
|
| `.capture` | bind the event handler in [capture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) mode. |
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click.stop="someMethod">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
|
||||||
|
the order may matter. For instance `t-on-click.prevent.self` will prevent all
|
||||||
|
clicks while `t-on-click.self.prevent` will only prevent clicks on the element
|
||||||
|
itself.
|
||||||
|
|
||||||
|
Finally, empty handlers are tolerated as they could be defined only to apply
|
||||||
|
modifiers. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click.stop="">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
This will simply stop the propagation of the event.
|
||||||
+29
-7
@@ -17,6 +17,7 @@
|
|||||||
- [`useContext`](#usecontext)
|
- [`useContext`](#usecontext)
|
||||||
- [`useRef`](#useref)
|
- [`useRef`](#useref)
|
||||||
- [`useSubEnv`](#usesubenv)
|
- [`useSubEnv`](#usesubenv)
|
||||||
|
- [`useExternalListener`](#useexternallistener)
|
||||||
- [`useStore`](#usestore)
|
- [`useStore`](#usestore)
|
||||||
- [`useDispatch`](#usedispatch)
|
- [`useDispatch`](#usedispatch)
|
||||||
- [`useGetters`](#usegetters)
|
- [`useGetters`](#usegetters)
|
||||||
@@ -152,9 +153,15 @@ class SomeComponent extends Component {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
In a hook, the `Component.current` static property is the reference to the
|
As you can see, the `useState` hook does not need to be given a reference to
|
||||||
component instance that is currently being created. Hooks need to be called in
|
the component. This is possible because there is a way to get a reference to the
|
||||||
the constructor to ensure that this reference is properly set.
|
current component: the `Component.current` static property is the reference to the
|
||||||
|
component instance that is currently being created.
|
||||||
|
|
||||||
|
Hooks need to be called in the constructor to ensure that this reference is
|
||||||
|
properly set. This is also a good thing for performance reasons (Owl can use
|
||||||
|
this to optimize its implementation), and for a clean architecture (this makes
|
||||||
|
it easier for developers to understand what is really happening in a component).
|
||||||
|
|
||||||
### `useState`
|
### `useState`
|
||||||
|
|
||||||
@@ -252,7 +259,7 @@ function useLoader() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onWillStart(() => updateRecord(component.props.id));
|
onWillStart(() => updateRecord(component.props.id));
|
||||||
onWillUpdateProps(nextProps => updateRecord(nextProps.id));
|
onWillUpdateProps((nextProps) => updateRecord(nextProps.id));
|
||||||
|
|
||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
@@ -290,6 +297,7 @@ class Parent extends Component {
|
|||||||
// here, if component is mounted, refs are active:
|
// here, if component is mounted, refs are active:
|
||||||
// - this.divRef.el is the div HTMLElement
|
// - this.divRef.el is the div HTMLElement
|
||||||
// - this.subRef.comp is the instance of the sub component
|
// - this.subRef.comp is the instance of the sub component
|
||||||
|
// - this.subRef.el is the root HTML node of the sub component (i.e. this.subRef.comp.el)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -297,11 +305,14 @@ class Parent extends Component {
|
|||||||
As shown by the example above, html elements are accessed by using the `el`
|
As shown by the example above, html elements are accessed by using the `el`
|
||||||
key, and components references are accessed with `comp`.
|
key, and components references are accessed with `comp`.
|
||||||
|
|
||||||
Note: if used on a component, the reference will be set in the `refs`
|
Notes:
|
||||||
variable between `willPatch` and `patched`.
|
|
||||||
|
- if used on a component, the reference will be set in the `refs`
|
||||||
|
variable between `willPatch` and `patched`,
|
||||||
|
- on a component, accessing `ref.el` will get the root node of the component.
|
||||||
|
|
||||||
The `t-ref` directive also accepts dynamic values with string interpolation
|
The `t-ref` directive also accepts dynamic values with string interpolation
|
||||||
(like the [`t-attf-`](qweb.md#dynamic-attributes) and
|
(like the [`t-attf-`](qweb_templating_language.md#dynamic-attributes) and
|
||||||
`t-component` directives). For example,
|
`t-component` directives). For example,
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
@@ -344,6 +355,17 @@ will be added to the parent environment. Note that it will extend, not replace
|
|||||||
the parent environment. And of course, the parent environment will not be
|
the parent environment. And of course, the parent environment will not be
|
||||||
affected.
|
affected.
|
||||||
|
|
||||||
|
### `useExternalListener`
|
||||||
|
|
||||||
|
The `useExternalListener` hook helps solve a very common problem: adding and removing
|
||||||
|
a listener on some target whenever a component is mounted/unmounted. For example,
|
||||||
|
a dropdown menu (or its parent) may need to listen to a `click` event on `window`
|
||||||
|
to be closed:
|
||||||
|
|
||||||
|
```js
|
||||||
|
useExternalListener(window, "click", this.closeMenu);
|
||||||
|
```
|
||||||
|
|
||||||
### `useStore`
|
### `useStore`
|
||||||
|
|
||||||
The `useStore` hook is the entry point for a component to connect to the store.
|
The `useStore` hook is the entry point for a component to connect to the store.
|
||||||
|
|||||||
@@ -1,5 +1,116 @@
|
|||||||
# 🦉 Miscellaneous 🦉
|
# 🦉 Miscellaneous 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Portal](#portal)
|
||||||
|
- [AsyncRoot](#asyncroot)
|
||||||
|
|
||||||
|
## `Portal`
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
The component `Portal` is meant to be used as a transparent way to 'teleport' a piece
|
||||||
|
of DOM to the node represented by its sole `target` props.
|
||||||
|
|
||||||
|
This component aims at helping the implementation of the needed infrastructure
|
||||||
|
for modals (as in `bootstrap-modal`).
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
The content it will teleport is defined within the `<Portal>` node and
|
||||||
|
internally uses the `default` [Slot](slots.md).
|
||||||
|
|
||||||
|
This slot must contain only **one** node, which in turn can have as many children as necessary.
|
||||||
|
|
||||||
|
The element under which the content will be teleported is represented as a selector
|
||||||
|
by the `target` props which only accepts a string as value.
|
||||||
|
|
||||||
|
The `target` props only supports static selector, and is not meant to be passed to `Portal`
|
||||||
|
as a variable. Namely, `<Portal target="'body'" />` is the intended use.
|
||||||
|
By contrast, `<Portal target="state.target" />` is not supported.
|
||||||
|
|
||||||
|
The component `Portal` has no particular state, rather it is meant to be a slave to its parent,
|
||||||
|
and ultimately just a way for the parent to teleport a piece of its own DOM elsewhere.
|
||||||
|
|
||||||
|
The `Portal`'s root node is always `<portal/>` and is placed where the teleported content
|
||||||
|
_would have_ been. It is this element that the [teleported events](#expected-behaviors) are re-directed on.
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
The canonic use-case is to implement a Dialog, where a Component may choose to break the natural
|
||||||
|
workflow to help the user put in some data, which it could use later on.
|
||||||
|
|
||||||
|
JavaScript:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { Component } = owl;
|
||||||
|
const { Portal } = owl.misc;
|
||||||
|
|
||||||
|
class TeleportedComponent extends Component {}
|
||||||
|
class App extends Component {
|
||||||
|
static components = { Portal, TeleportedComponent };
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
```
|
||||||
|
|
||||||
|
XML:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<templates>
|
||||||
|
<div t-name="TeleportedComponent">
|
||||||
|
<span>I will move soon enough</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div t-name="App">
|
||||||
|
<span>I am like the rest of us</span>
|
||||||
|
<Portal target="'body'">
|
||||||
|
<TeleportedComponent />
|
||||||
|
</Portal>
|
||||||
|
</div>
|
||||||
|
</templates>
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the `Portal` component will teleport the `TeleportedComponent`'s `div` as a child of the `body`.
|
||||||
|
`TeleportedComponent` is acting as a Dialog here.
|
||||||
|
|
||||||
|
The resulting DOM will look like:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<span>I am like the rest of us</span>
|
||||||
|
<portal></portal>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span>I will move soon enough</span>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Expected Behaviors
|
||||||
|
|
||||||
|
The teleported piece is updated as any other `Component`'s DOM and in the same sequence.
|
||||||
|
Namely the teleported piece will be updated in function of its parents components, and patched as
|
||||||
|
a normal child.
|
||||||
|
|
||||||
|
The [_business_ events](event_handling.md#business-dom-events) triggered by a child component will be stopped
|
||||||
|
to not bubble outside of the `target`. They will, on the other hand, be re-directed onto the
|
||||||
|
`Portal`'s root node and bubble up the DOM as if it were triggered by a regular child component.
|
||||||
|
|
||||||
|
Beware that those re-directed events are copies of the original event.
|
||||||
|
They have:
|
||||||
|
|
||||||
|
- The same payload.
|
||||||
|
- The same `originalComponent` than their original counterpart,
|
||||||
|
that is the actual Component that triggered it.
|
||||||
|
- A **different** `target` property than their original counterpart.
|
||||||
|
The `target` of a re-directed event is necessarily the `Portal`'s root node.
|
||||||
|
|
||||||
|
Pure DOM events do not follow this pattern and are free to bubble their natural, unaltered way
|
||||||
|
up to the `body`.
|
||||||
|
|
||||||
## `AsyncRoot`
|
## `AsyncRoot`
|
||||||
|
|
||||||
When this component is used, a new rendering sub tree is created, such that the
|
When this component is used, a new rendering sub tree is created, such that the
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# 🦉 Props 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Definition](#definition)
|
||||||
|
- [Good Practices](#good-practices)
|
||||||
|
- [Dynamic Props](#dynamic-props)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
In Owl, `props` (short for _properties_) is an object which contains every piece
|
||||||
|
of data given to a component by its parent.
|
||||||
|
|
||||||
|
```js
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div><t t-esc="props.a"/><t t-esc="props.b"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><ComponentA a="state.a" b="'string'"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ a: "fromparent" });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the `Child` component receives two props from its parent: `a`
|
||||||
|
and `b`. They are collected into a `props` object by Owl, with each value being
|
||||||
|
evaluated in the context of the parent. So, `props.a` is equal to `'fromparent'` and
|
||||||
|
`props.b` is equal to `'string'`.
|
||||||
|
|
||||||
|
Note that `props` is an object that only makes sense from the perspective of the
|
||||||
|
child component.
|
||||||
|
|
||||||
|
## Definition
|
||||||
|
|
||||||
|
The `props` object is made of every attributes defined on the template, with the
|
||||||
|
following exceptions:
|
||||||
|
|
||||||
|
- every attribute starting with `t-` are not props (they are QWeb directives),
|
||||||
|
- `style` and `class` attributes are excluded as well (they are applied by Owl on
|
||||||
|
the root element of the component).
|
||||||
|
|
||||||
|
In the following example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div>
|
||||||
|
<ComponentA a="state.a" b="'string'"/>
|
||||||
|
<ComponentB t-if="state.flag" model="model"/>
|
||||||
|
<ComponentC style="color:red;" class="left-pane" />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
the `props` object contains the following keys:
|
||||||
|
|
||||||
|
- for `ComponentA`: `a` and `b`,
|
||||||
|
- for `ComponentB`: `model`,
|
||||||
|
- for `ComponentC`: empty object
|
||||||
|
|
||||||
|
## Good Practices
|
||||||
|
|
||||||
|
A `props` object is a collection of values that come from the parent. As such,
|
||||||
|
they are owned by the parent, and should never be modified by the child:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class MyComponent extends Component {
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
props.a.b = 43; // Never do that!!!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Props should be considered readonly, from the perspective of the child component.
|
||||||
|
If there is a need to modify them, then the request to update them should be
|
||||||
|
sent to the parent (for example, with an event).
|
||||||
|
|
||||||
|
Any value can go in a props. Strings, objects, classes, or even callbacks could
|
||||||
|
be given to a child component (but then, in the case of callbacks, communicating
|
||||||
|
with events seems more appropriate).
|
||||||
|
|
||||||
|
## Dynamic Props
|
||||||
|
|
||||||
|
The `t-props` directive can be used to specify totally dynamic props:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="ParentComponent">
|
||||||
|
<Child t-props="some.obj"/>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ParentComponent {
|
||||||
|
static components = { Child };
|
||||||
|
some = { obj: { a: 1, b: 2 } };
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# 🦉 Props Validation 🦉
|
||||||
|
|
||||||
|
As an application becomes complex, it may be quite unsafe to define props in an informal way. This leads to two issues:
|
||||||
|
|
||||||
|
- hard to tell how a component should be used, by looking at its code.
|
||||||
|
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parents.
|
||||||
|
|
||||||
|
A props type system solves both issues, by describing the types and shapes
|
||||||
|
of the props. Here is how it works in Owl:
|
||||||
|
|
||||||
|
- `props` key is a static key (so, different from `this.props` in a component instance)
|
||||||
|
- it is optional: it is ok for a component to not define a `props` key.
|
||||||
|
- props are validated whenever a component is created/updated
|
||||||
|
- props are only validated in `dev` mode (see [config page](config.md#mode))
|
||||||
|
- if a key does not match the description, an error is thrown
|
||||||
|
- it validates keys defined in (static) `props`. Additional keys given by the
|
||||||
|
parent will cause an error.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ComponentA extends owl.Component {
|
||||||
|
static props = ['id', 'url'];
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
|
||||||
|
class ComponentB extends owl.Component {
|
||||||
|
static props = {
|
||||||
|
count: {type: Number},
|
||||||
|
messages: {
|
||||||
|
type: Array,
|
||||||
|
element: {type: Object, shape: {id: Boolean, text: String }
|
||||||
|
},
|
||||||
|
date: Date,
|
||||||
|
combinedVal: [Number, Boolean]
|
||||||
|
};
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- it is an object or a list of strings
|
||||||
|
- a list of strings is a simplified props definition, which only lists the name
|
||||||
|
of the props. Also, if the name ends with `?`, it is considered optional.
|
||||||
|
- all props are by default required, unless they are defined with `optional: true`
|
||||||
|
(in that case, validation is only done if there is a value)
|
||||||
|
- valid types are: `Number, String, Boolean, Object, Array, Date, Function`, and all
|
||||||
|
constructor functions (so, if you have a `Person` class, it can be used as a type)
|
||||||
|
- arrays are homogeneous (all elements have the same type/shape)
|
||||||
|
|
||||||
|
For each key, a `prop` definition is either a boolean, a constructor, a list of constructors, or an object:
|
||||||
|
|
||||||
|
- a boolean: indicate that the props exists, and is mandatory.
|
||||||
|
- a constructor: this should describe the type, for example: `id: Number` describe
|
||||||
|
the props `id` as a number
|
||||||
|
- a list of constructors. In that case, this means that we allow more than one
|
||||||
|
type. For example, `id: [Number, String]` means that `id` can be either a string
|
||||||
|
or a number.
|
||||||
|
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed (but not mandatory):
|
||||||
|
- `type`: the main type of the prop being validated
|
||||||
|
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. If it is not set, then we only validate the array, not its elements,
|
||||||
|
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. If it is not set, then we only validate the object, not its elements,
|
||||||
|
- `validate`: this is a function which should return a boolean to determine if
|
||||||
|
the value is valid or not. Useful for custom validation logic.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// only the existence of those 3 keys is documented
|
||||||
|
static props = ['message', 'id', 'date'];
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
// size is optional
|
||||||
|
static props = ['message', 'size?'];
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
static props = {
|
||||||
|
messageIds: {type: Array, element: Number}, // list of number
|
||||||
|
otherArr: {type: Array}, // just array. no validation is made on sub elements
|
||||||
|
otherArr2: Array, // same as otherArr
|
||||||
|
someObj: {type: Object}, // just an object, no internal validation
|
||||||
|
someObj2: {
|
||||||
|
type: Object,
|
||||||
|
shape: {
|
||||||
|
id: Number,
|
||||||
|
name: {type: String, optional: true},
|
||||||
|
url: String
|
||||||
|
]}, // object, with keys id (number), name (string, optional) and url (string)
|
||||||
|
someFlag: Boolean, // a boolean, mandatory (even if `false`)
|
||||||
|
someVal: [Boolean, Date], // either a boolean or a date
|
||||||
|
otherValue: true, // indicates that it is a prop
|
||||||
|
kindofsmallnumber: {
|
||||||
|
type: Number,
|
||||||
|
validate: n => (0 <= n && n <= 10)
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
validate: e => ["small", "medium", "large"].includes(e)
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
# 🦉 QWeb Engine 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Reference](#reference)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
[QWeb](https://www.odoo.com/documentation/13.0/reference/qweb.html) is the primary
|
||||||
|
templating engine used by Odoo. The QWeb class in the OWL project is an
|
||||||
|
implementation of that specification with a few interesting points:
|
||||||
|
|
||||||
|
- 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`, ...
|
||||||
|
|
||||||
|
We present in this section the engine, not the templating language.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
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();
|
||||||
|
```
|
||||||
|
|
||||||
|
Its API is quite simple:
|
||||||
|
|
||||||
|
- **`constructor(config)`**: constructor. Takes an optional configuration object
|
||||||
|
with an optional `templates` string to add initial
|
||||||
|
templates (see `addTemplates` for more information on format of the string)
|
||||||
|
and an optional `translateFn` translate function (see the section on
|
||||||
|
[translations](#translations)).
|
||||||
|
|
||||||
|
```js
|
||||||
|
const qweb = new owl.QWeb({ templates: TEMPLATES, translateFn: _t });
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`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
|
||||||
|
ignore templates 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](../miscellaneous/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 a 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</div>`);
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`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](environment.md). As such, it
|
||||||
|
has an extra responsibility: 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).
|
||||||
|
|
||||||
|
### Translations
|
||||||
|
|
||||||
|
take care of this and "cherry-pick" 8464a1b04e7469434f9dcb3d68a543f58cb61b8e
|
||||||
|
|
||||||
|
If properly setup, Owl QWeb engine can translate all rendered templates. To do
|
||||||
|
so, it needs a translate function, which takes a string and returns a string.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const translations = {
|
||||||
|
hello: "bonjour",
|
||||||
|
yes: "oui",
|
||||||
|
no: "non",
|
||||||
|
};
|
||||||
|
const translateFn = (str) => translations[str] || str;
|
||||||
|
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
```
|
||||||
|
|
||||||
|
Once setup, all rendered templates will be translated using `translateFn`:
|
||||||
|
|
||||||
|
- each text node will be replaced with its translation,
|
||||||
|
- each of the following attribute values will be translated as well: `title`,
|
||||||
|
`placeholder`, `label` and `alt`,
|
||||||
|
- translating text nodes can be disabled with the special attribute `t-translation`,
|
||||||
|
if its value is `off`.
|
||||||
|
|
||||||
|
So, with the above `translateFn`, the following templates:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div>hello</div>
|
||||||
|
<div t-translation="off">hello</div>
|
||||||
|
<div>Are you sure?</div>
|
||||||
|
<input placeholder="hello" other="yes"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
will be rendered as:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div>bonjour</div>
|
||||||
|
<div>hello</div>
|
||||||
|
<div>Are you sure?</div>
|
||||||
|
<input placeholder="bonjour" other="yes"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that the translation is done during the compilation of the template, not
|
||||||
|
when it is rendered.
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
# 🦉 QWeb 🦉
|
# 🦉 QWeb Templating Language🦉
|
||||||
|
|
||||||
## Content
|
## Content
|
||||||
|
|
||||||
- [Overview](#overview)
|
- [Overview](#overview)
|
||||||
- [Directives](#directives)
|
- [Directives](#directives)
|
||||||
- [QWeb Engine](#qweb-engine)
|
|
||||||
- [Reference](#reference)
|
- [Reference](#reference)
|
||||||
- [White Spaces](#white-spaces)
|
- [White Spaces](#white-spaces)
|
||||||
- [Root Nodes](#root-nodes)
|
- [Root Nodes](#root-nodes)
|
||||||
@@ -16,23 +15,21 @@
|
|||||||
- [Dynamic Attributes](#dynamic-attributes)
|
- [Dynamic Attributes](#dynamic-attributes)
|
||||||
- [Loops](#loops)
|
- [Loops](#loops)
|
||||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||||
|
- [Dynamic Sub Templates](#dynamic-sub-templates)
|
||||||
- [Translations](#translations)
|
- [Translations](#translations)
|
||||||
- [Debugging](#debugging)
|
- [Debugging](#debugging)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
[QWeb](https://www.odoo.com/documentation/13.0/reference/qweb.html) is the primary templating engine used by Odoo. It is based on the XML format, and used
|
[QWeb](https://www.odoo.com/documentation/13.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
|
mostly to generate HTML. In OWL, QWeb templates are compiled into functions that
|
||||||
generate a virtual dom representation of the HTML.
|
generate a virtual dom representation of the HTML.
|
||||||
|
|
||||||
Template directives are specified as XML attributes prefixed with `t-`, for instance `t-if` for conditionals, with elements and other attributes being rendered directly.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<div>
|
<div>
|
||||||
<span t-if="somecondition">Some string</span>
|
<span t-if="somecondition">Some string</span>
|
||||||
<ul t-else="1">
|
<ul t-else="">
|
||||||
<li t-foreach="messages" t-as="message">
|
<li t-foreach="messages" t-as="message">
|
||||||
<t t-esc="message"/>
|
<t t-esc="message"/>
|
||||||
</li>
|
</li>
|
||||||
@@ -40,19 +37,22 @@ To avoid element rendering, a placeholder element `<t>` is also available, which
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
The QWeb class in the OWL project is an implementation of that specification
|
Template directives are specified as XML attributes prefixed with `t-`, for
|
||||||
with a few interesting points:
|
instance `t-if` for conditionals, with elements and other attributes being
|
||||||
|
rendered directly.
|
||||||
|
|
||||||
- it compiles templates into functions that output a virtual DOM instead of a
|
To avoid element rendering, a placeholder element `<t>` is also available, which
|
||||||
string. This is necessary for the component system.
|
executes its directive but doesn’t generate any output in and of itself.
|
||||||
- it has a few extra directives: `t-component`, `t-on`, ...
|
|
||||||
|
We present in this section the templating language, including its Owl specific
|
||||||
|
extensions.
|
||||||
|
|
||||||
## Directives
|
## Directives
|
||||||
|
|
||||||
We present here a list of all standard QWeb directives:
|
For reference, here is a list of all standard QWeb directives:
|
||||||
|
|
||||||
| Name | Description |
|
| Name | Description |
|
||||||
| ------------------------------ | ------------------------------------------------------------ |
|
| ------------------------------ | -------------------------------------------------------------- |
|
||||||
| `t-esc` | [Outputting safely a value](#outputting-data) |
|
| `t-esc` | [Outputting safely a value](#outputting-data) |
|
||||||
| `t-raw` | [Outputting value, without escaping](#outputting-data) |
|
| `t-raw` | [Outputting value, without escaping](#outputting-data) |
|
||||||
| `t-set`, `t-value` | [Setting variables](#setting-variables) |
|
| `t-set`, `t-value` | [Setting variables](#setting-variables) |
|
||||||
@@ -62,113 +62,23 @@ We present here a list of all standard QWeb directives:
|
|||||||
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
||||||
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
||||||
| `t-translation` | [Disabling the translation of a node](#translations) |
|
| `t-translation` | [Disabling the translation of a node](#translations) |
|
||||||
| `t-name` | [Defining a template (not really a directive)](#qweb-engine) |
|
| `t-name` | [Defining a template (not really a directive)](qweb_engine.md) |
|
||||||
|
|
||||||
The component system in Owl requires additional directives, to express various
|
The component system in Owl requires additional directives, to express various
|
||||||
needs. Here is a list of all Owl specific directives:
|
needs. Here is a list of all Owl specific directives:
|
||||||
|
|
||||||
| Name | Description |
|
| Name | Description |
|
||||||
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
| ------------------------ | ------------------------------------------------------------------------------- |
|
||||||
| `t-component`, `t-props`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
| `t-component`, `t-props` | [Defining a sub component](component.md#composition) |
|
||||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
| `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-key` | [Defining a key (to help virtual dom reconciliation)](#loops) |
|
||||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
| `t-on-*` | [Event handling](event_handling.md) |
|
||||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
| `t-slot` | [Rendering a slot](slots.md) |
|
||||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
| `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();
|
|
||||||
```
|
|
||||||
|
|
||||||
Its API is quite simple:
|
|
||||||
|
|
||||||
- **`constructor(config)`**: constructor. Takes an optional configuration object
|
|
||||||
with an optional `templates` string to add initial
|
|
||||||
templates (see `addTemplates` for more information on format of the string)
|
|
||||||
and an optional `translateFn` translate function (see the section on
|
|
||||||
[translations](#translations)).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const qweb = new owl.QWeb({ templates: TEMPLATES, translateFn: _t });
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`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
|
|
||||||
ignore templates 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](../architecture/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 a 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</div>`);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`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 responsibility: 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
|
## 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
|
||||||
|
|
||||||
White spaces in a template are handled in a special way:
|
White spaces in a template are handled in a special way:
|
||||||
@@ -192,7 +102,7 @@ precisely, the result of a template rendering should have a single root node:
|
|||||||
<!–– ok: result has one single root node ––>
|
<!–– ok: result has one single root node ––>
|
||||||
<t>
|
<t>
|
||||||
<div t-if="someCondition">foo</div>
|
<div t-if="someCondition">foo</div>
|
||||||
<span t-else="1">bar</span>
|
<span t-else="">bar</span>
|
||||||
</t>
|
</t>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -479,20 +389,81 @@ into the global context.
|
|||||||
<!-- new_variable undefined -->
|
<!-- new_variable undefined -->
|
||||||
```
|
```
|
||||||
|
|
||||||
Owl QWeb is used as the template engine for components. Components are frequently
|
Even though Owl tries to be as declarative as possible, the DOM does not fully
|
||||||
updated, and reuse as much of the previous DOM as possible. Loops offer a specific
|
expose its state declaratively in the DOM tree. For example, the scrolling state,
|
||||||
problem for this usecase: how does the template engine know if two rows have
|
the current user selection, the focused element or the state of an input are not
|
||||||
been swapped, or if the content of these rows was changed? To help Owl with that,
|
set as attribute in the DOM tree. This is why we use a virtual dom
|
||||||
there is an additional directive: [`t-key`](component.md#t-key-directive).
|
algorithm to keep the actual DOM node as much as possible.
|
||||||
|
|
||||||
|
However, in some situations, this is not enough, and we need to help Owl decide
|
||||||
|
if an element is actually the same, or is a different element with the same
|
||||||
|
properties.
|
||||||
|
|
||||||
|
Consider the following situation: we have a list of two items `[{text: "a"}, {text: "b"}]`
|
||||||
|
and we render them in this template:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<p t-foreach="state.things" t-as="thing" t-key="thing.id">
|
<p t-foreach="items" t-as="item"><t t-esc="item.text"/></p>
|
||||||
<t t-esc="thing.content"/>
|
```
|
||||||
|
|
||||||
|
The result will be two `<p>` tags with text `a` and `b`. Now, if we swap them,
|
||||||
|
and rerender the template, Owl needs to know what the intent is:
|
||||||
|
|
||||||
|
- should Owl actually swap the DOM nodes,
|
||||||
|
- or should it keep the DOM nodes, but with an updated text content?
|
||||||
|
|
||||||
|
This might look trivial, but it actually matters. These two possibilities lead
|
||||||
|
to different results in some cases. For example, if the user selected the text
|
||||||
|
of the first `p`, swapping them will keep the selection while updating the
|
||||||
|
text content will not.
|
||||||
|
|
||||||
|
There are many other cases where this is important: `input` tags with their
|
||||||
|
value, css classes and animations, scroll position...
|
||||||
|
|
||||||
|
So, the `t-key` directive is used to give an identity to an element. It allows
|
||||||
|
Owl to understand if different elements of a list are actually different or not.
|
||||||
|
|
||||||
|
The above example could be modified by adding an ID: `[{id: 1, text: "a"}, {id: 2, text: "b"}]`.
|
||||||
|
Then, the template could look like this:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<p t-foreach="items" t-as="item" t-key="item.id"><t t-esc="item.text"/></p>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `t-key` directive is useful for lists (`t-foreach`). A key should be
|
||||||
|
a unique number or string (objects will not work: they will be cast to the
|
||||||
|
`"[object Object]"` string, which is obviously not unique).
|
||||||
|
|
||||||
|
Also, the key can be set on a `t` tag or on its children. The following variations
|
||||||
|
are all equivalent:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<p t-foreach="items" t-as="item" t-key="item.id">
|
||||||
|
<t t-esc="item.text"/>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<t t-foreach="items" t-as="item" t-key="item.id">
|
||||||
|
<p t-esc="item.text"/>
|
||||||
|
</t>
|
||||||
|
|
||||||
|
<t t-foreach="items" t-as="item">
|
||||||
|
<p t-key="item.id" t-esc="item.text"/>
|
||||||
|
</t>
|
||||||
```
|
```
|
||||||
|
|
||||||
If there is no `t-key` directive, Owl will use the index as a default key.
|
If there is no `t-key` directive, Owl will use the index as a default key.
|
||||||
|
|
||||||
|
Note: the `t-foreach` directive only accepts arrays (lists) or objects. It does
|
||||||
|
not work with other iterables, such as `Set`. However, it is only a matter of
|
||||||
|
using the `...` javascript operator. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<t t-foreach="...items" t-as="item">...</t>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `...` operator will convert the `Set` (or any other iterables) into a list,
|
||||||
|
which will work with Owl QWeb.
|
||||||
|
|
||||||
### Rendering Sub Templates
|
### Rendering Sub Templates
|
||||||
|
|
||||||
QWeb templates can be used for top level rendering, but they can also be used
|
QWeb templates can be used for top level rendering, but they can also be used
|
||||||
@@ -541,25 +512,36 @@ will result in :
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Translations
|
This can be used to define variables scoped to a sub template:
|
||||||
|
|
||||||
If properly setup, Owl QWeb engine can translate all rendered templates. To do
|
```xml
|
||||||
so, it needs a translate function, which takes a string and returns a string.
|
<t t-call="other-template">
|
||||||
|
<t t-set="var" t-value="1"/>
|
||||||
For example:
|
</t>
|
||||||
|
<!-- "var" does not exist here -->
|
||||||
```js
|
|
||||||
const translations = {
|
|
||||||
hello: "bonjour",
|
|
||||||
yes: "oui",
|
|
||||||
no: "non"
|
|
||||||
};
|
|
||||||
const translateFn = str => translations[str] || str;
|
|
||||||
|
|
||||||
const qweb = new QWeb({ translateFn });
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Once setup, all rendered templates will be translated using `translateFn`:
|
### Dynamic sub templates
|
||||||
|
|
||||||
|
The `t-call` directive can also be used to dynamically call a sub template,
|
||||||
|
using string interpolation. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="main-template">
|
||||||
|
<t t-call="{{template}}">
|
||||||
|
<em>content</em>
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, the name of the template is obtained from the `template` value in the
|
||||||
|
template rendering context.
|
||||||
|
|
||||||
|
### Translations
|
||||||
|
|
||||||
|
By default, QWeb specify that templates should be translated. If this behaviour
|
||||||
|
is not wanted, there is a `t-translation` directive which can turn off
|
||||||
|
translations (if it is set to the `off` value), with the following rules:
|
||||||
|
|
||||||
- each text node will be replaced with its translation,
|
- each text node will be replaced with its translation,
|
||||||
- each of the following attribute values will be translated as well: `title`,
|
- each of the following attribute values will be translated as well: `title`,
|
||||||
@@ -567,26 +549,8 @@ Once setup, all rendered templates will be translated using `translateFn`:
|
|||||||
- translating text nodes can be disabled with the special attribute `t-translation`,
|
- translating text nodes can be disabled with the special attribute `t-translation`,
|
||||||
if its value is `off`.
|
if its value is `off`.
|
||||||
|
|
||||||
So, with the above `translateFn`, the following templates:
|
See [here](qweb_engine.md#translations) for more information on how to setup a
|
||||||
|
translate function in Owl QWeb.
|
||||||
```xml
|
|
||||||
<div>hello</div>
|
|
||||||
<div t-translation="off">hello</div>
|
|
||||||
<div>Are you sure?</div>
|
|
||||||
<input placeholder="hello" other="yes"/>
|
|
||||||
```
|
|
||||||
|
|
||||||
will be rendered as:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div>bonjour</div>
|
|
||||||
<div>hello</div>
|
|
||||||
<div>Are you sure?</div>
|
|
||||||
<input placeholder="bonjour" other="yes"/>
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that the translation is done during the compilation of the template, not
|
|
||||||
when it is rendered.
|
|
||||||
|
|
||||||
### Debugging
|
### Debugging
|
||||||
|
|
||||||
@@ -596,7 +560,7 @@ The javascript QWeb implementation provides two useful debugging directives:
|
|||||||
|
|
||||||
```xml
|
```xml
|
||||||
<t t-if="a_test">
|
<t t-if="a_test">
|
||||||
<t t-debug="">
|
<t t-debug=""/>
|
||||||
</t>
|
</t>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
# 🦉 Router 🦉
|
# 🦉 Router 🦉
|
||||||
|
|
||||||
|
Remove?
|
||||||
|
|
||||||
## Content
|
## Content
|
||||||
|
|
||||||
- [Overview](#overview)
|
- [Overview](#overview)
|
||||||
@@ -67,6 +69,9 @@ function makeEnvironment() {
|
|||||||
await env.router.start();
|
await env.router.start();
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
App.env = makeEnvironment();
|
||||||
|
// create root component here
|
||||||
```
|
```
|
||||||
|
|
||||||
Notice that the router needs to be started. This is an asynchronous operation
|
Notice that the router needs to be started. This is an asynchronous operation
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# 🦉 Slots 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Example](#example)
|
||||||
|
- [Reference](#reference)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Owl is a template based component system. There is therefore a need to be able
|
||||||
|
to make generic components. For example, imagine a generic `Dialog`
|
||||||
|
component, which is able to display some arbitrary content.
|
||||||
|
|
||||||
|
Obviously, we want to use this component everywhere in our application, to
|
||||||
|
display various different content. The `Dialog` component is technically the
|
||||||
|
owner of its content, but is only a container. The user of the `Dialog` is
|
||||||
|
the component that want to _inject_ something inside the `Dialog`. This is
|
||||||
|
exactly what slots are for.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
To make generic components, it is useful to be able for a parent component to _inject_
|
||||||
|
some sub template, but still be the owner. For example, a generic dialog component
|
||||||
|
will need to render some content, some footer, but with the parent as the
|
||||||
|
rendering context.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="Dialog" class="modal">
|
||||||
|
<div class="modal-title"><t t-esc="props.title"/></div>
|
||||||
|
<div class="modal-content">
|
||||||
|
<t t-slot="content"/>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<t t-slot="footer"/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Slots are defined by the caller, with the `t-set-slot` directive:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="SomeComponent">
|
||||||
|
<div>some component</div>
|
||||||
|
<Dialog title="Some Dialog">
|
||||||
|
<t t-set-slot="content">
|
||||||
|
<div>hey</div>
|
||||||
|
</t>
|
||||||
|
<t t-set-slot="footer">
|
||||||
|
<button t-on-click="doSomething">ok</button>
|
||||||
|
</t>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the component `Dialog` will render the slots `content` and `footer`
|
||||||
|
with its parent as rendering context. This means that clicking on the button
|
||||||
|
will execute the `doSomething` method on the parent, not on the dialog.
|
||||||
|
|
||||||
|
Note: Owl previously used the `t-set` directive to define the content of a slot.
|
||||||
|
This is deprecated and should no longer be used in new code.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
Default slot: the first element inside the component which is not a named slot will
|
||||||
|
be considered the `default` slot. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="Parent">
|
||||||
|
<Child>
|
||||||
|
<span>some content</span>
|
||||||
|
</Child>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div t-name="Child">
|
||||||
|
<t t-slot="default"/>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Default content: slots can define a default content, in case the parent did not define them:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="Parent">
|
||||||
|
<Child/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span t-name="Child">
|
||||||
|
<t t-slot="default">default content</t>
|
||||||
|
</span>
|
||||||
|
<!-- will be rendered as: <div><span>default content</span></div> -->
|
||||||
|
```
|
||||||
|
|
||||||
|
Rendering context: the content of the slots is actually rendered with the
|
||||||
|
rendering context corresponding to where it was defined, not where it is
|
||||||
|
positioned. This allows the user to define event handlers that will be bound
|
||||||
|
to the correct component (usually, the grandparent of the slot content).
|
||||||
+50
-27
@@ -25,8 +25,8 @@ component should own which part of the state.
|
|||||||
|
|
||||||
Owl's solution to this issue is a centralized store. It is a class that owns
|
Owl's solution to this issue is a centralized store. It is a class that owns
|
||||||
some (or all) state, and lets the developer update it in a structured way, with
|
some (or all) state, and lets the developer update it in a structured way, with
|
||||||
`actions`. Owl components can then connect to the store, and will be updated if
|
`actions`. Owl components can then connect to the store to read their relevant
|
||||||
necessary.
|
state, and they will be rerendered if the state is updated.
|
||||||
|
|
||||||
Note: Owl store is inspired by React Redux and VueX.
|
Note: Owl store is inspired by React Redux and VueX.
|
||||||
|
|
||||||
@@ -40,14 +40,14 @@ const actions = {
|
|||||||
state.todos.push({
|
state.todos.push({
|
||||||
id: state.nextId++,
|
id: state.nextId++,
|
||||||
message,
|
message,
|
||||||
isCompleted: false
|
isCompleted: false,
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
todos: [],
|
todos: [],
|
||||||
nextId: 1
|
nextId: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
@@ -90,7 +90,7 @@ const config = {
|
|||||||
state,
|
state,
|
||||||
actions,
|
actions,
|
||||||
getters,
|
getters,
|
||||||
env
|
env,
|
||||||
};
|
};
|
||||||
const store = new Store(config);
|
const store = new Store(config);
|
||||||
```
|
```
|
||||||
@@ -110,7 +110,7 @@ const actions = {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
state.loginState = "error";
|
state.loginState = "error";
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ const actions = {
|
|||||||
state.recordId = recordId;
|
state.recordId = recordId;
|
||||||
const data = await doSomeRPC("/read/", recordId);
|
const data = await doSomeRPC("/read/", recordId);
|
||||||
state.recordData = data;
|
state.recordData = data;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -159,7 +159,7 @@ const actions = {
|
|||||||
const data = await doSomeRPC("/read/", recordId);
|
const data = await doSomeRPC("/read/", recordId);
|
||||||
state.recordId = recordId;
|
state.recordId = recordId;
|
||||||
state.recordData = data;
|
state.recordData = data;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -187,14 +187,14 @@ transform the data contained in the store.
|
|||||||
```js
|
```js
|
||||||
const getters = {
|
const getters = {
|
||||||
getPost({ state }, id) {
|
getPost({ state }, id) {
|
||||||
const post = state.posts.find(p => p.id === id);
|
const post = state.posts.find((p) => p.id === id);
|
||||||
const author = state.authors.find(a => a.id === post.id);
|
const author = state.authors.find((a) => a.id === post.id);
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
author,
|
author,
|
||||||
content: post.content
|
content: post.content,
|
||||||
};
|
};
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// somewhere else
|
// somewhere else
|
||||||
@@ -208,7 +208,11 @@ Note that getters are not cached.
|
|||||||
### Connecting a Component
|
### Connecting a Component
|
||||||
|
|
||||||
At some point, we need a way to interact with the store from a component. This
|
At some point, we need a way to interact with the store from a component. This
|
||||||
can be done with the help of the three store hooks:
|
means that the component needs a reference to the store. By default, it looks
|
||||||
|
for it in the `env.store` key. However, this can be configured with the `useStore`
|
||||||
|
hook.
|
||||||
|
|
||||||
|
Every component-store interactions are done with the help of the three store hooks:
|
||||||
|
|
||||||
- [`useStore`](#usestore) to subscribe a component to some part of the store state,
|
- [`useStore`](#usestore) to subscribe a component to some part of the store state,
|
||||||
- [`useDispatch`](#usedispatch) to get a reference to a dispatch function,
|
- [`useDispatch`](#usedispatch) to get a reference to a dispatch function,
|
||||||
@@ -220,20 +224,28 @@ Assume we have this store:
|
|||||||
const actions = {
|
const actions = {
|
||||||
increment({ state }, val) {
|
increment({ state }, val) {
|
||||||
state.counter.value += val;
|
state.counter.value += val;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
counter: { value: 0 }
|
counter: { value: 0 },
|
||||||
};
|
};
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To make it accessible to the complete application, we will put it in the
|
||||||
|
environment:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// in this example, the root component is App
|
||||||
|
App.env.store = store;
|
||||||
|
```
|
||||||
|
|
||||||
A counter component can then select this value and dispatch an action like this:
|
A counter component can then select this value and dispatch an action like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
counter = useStore(state => state.counter);
|
counter = useStore((state) => state.counter);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,19 +264,30 @@ The `useStore` hook is used to select some part of the store state. It accepts
|
|||||||
two arguments:
|
two arguments:
|
||||||
|
|
||||||
- a selector function, which takes the store state as first argument (and the
|
- a selector function, which takes the store state as first argument (and the
|
||||||
component props as second argument) and returns
|
component props as second argument) and which must return the part of the
|
||||||
an object or an array (which will be then observed),
|
store state that will be made available and observed for changes,
|
||||||
- optionally, an object with a `store` key (if we want to override the default
|
- optionally, an object which can have the following optional keys:
|
||||||
store) and an equality function (if we want to specialize the comparison).
|
- a `store` key containing a store object if we want to use another store than
|
||||||
|
the default store,
|
||||||
|
- an `isEqual` key containing an equality function if we want to specialize
|
||||||
|
the comparison (the function must accept two arguments: the previous result
|
||||||
|
and the new result, and must return whether they are equal),
|
||||||
|
- and an `onUpdate` key containing an update function if we want to execute an
|
||||||
|
arbitrary code every time the selected state changes (the function will
|
||||||
|
receive one argument, the new result, and can execute arbitrary code).
|
||||||
|
|
||||||
If the `useStore` callback selects a sub part of the store state, the component
|
If the `useStore` selector returns a sub part of the store state, the component
|
||||||
will only be rerendered whenever this part of the state changes. Otherwise, it
|
will only be rerendered whenever this part of the state changes. Otherwise, it
|
||||||
will perform a strict equality check and will update the component every time this
|
will perform a strict equality check (unless the `isEqual` option is defined,
|
||||||
check fails.
|
then it will call it) and will update the component every time this check fails.
|
||||||
|
|
||||||
Also, it may not be obvious, but it is crucial to remember that the selector
|
Note that if the selector function returns a primitive type, the result of
|
||||||
function should return an object or an array. The reason is that it needs to be
|
`useStore` will be immutable and it will not react to changes. In this case, it
|
||||||
observed, otherwise the component would not be able to react to changes.
|
is important to define the `onUpdate` option to properly update the value
|
||||||
|
manually when it changes.
|
||||||
|
|
||||||
|
Also, the return value from `useStore` is not supposed to be modified. The store
|
||||||
|
state should only be updated with actions.
|
||||||
|
|
||||||
### `useDispatch`
|
### `useDispatch`
|
||||||
|
|
||||||
|
|||||||
+134
-4
@@ -4,16 +4,19 @@
|
|||||||
|
|
||||||
- [Overview](#overview)
|
- [Overview](#overview)
|
||||||
- [`xml` tag](#xml-tag)
|
- [`xml` tag](#xml-tag)
|
||||||
|
- [`css` tag](#css-tag)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Tags are very small helpers to make it easy to write inline templates. There is
|
Tags are very small helpers intended to make it easy to write inline templates
|
||||||
only one currently available tag: `xml`, but we plan to add other tags later,
|
or styles. There are currently two tags: `css` and `xml`. With these functions,
|
||||||
such as a `css` tag, which will be used to write [single file components](../tooling.md#single-file-component).
|
it is possible to write [single file components](../learning/how_to_write_sfc.md).
|
||||||
|
|
||||||
## XML tag
|
## XML tag
|
||||||
|
|
||||||
Without tags, creating a standalone component would look like this:
|
The `xml` tag is certainly the most useful tag. It is used to define an inline
|
||||||
|
QWeb template for a component. Without tags, creating a standalone component
|
||||||
|
would look like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { Component } from 'owl'
|
import { Component } from 'owl'
|
||||||
@@ -52,3 +55,130 @@ class MyComponent extends Component {
|
|||||||
...
|
...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## CSS tag
|
||||||
|
|
||||||
|
The CSS tag is useful to define a css stylesheet in the javascript file:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div class="my-component">some template</div>
|
||||||
|
`;
|
||||||
|
static css`
|
||||||
|
.my-component {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `css` tag registers internally the css information. Then, whenever the first
|
||||||
|
instance of the component is created, will add a `<style>` tag to the document
|
||||||
|
`<head>`.
|
||||||
|
|
||||||
|
Note that to make it more useful, like other css preprocessors, the `css` tag
|
||||||
|
accepts a small extension of the css specification: css scopes can be nested,
|
||||||
|
and the rules will then be expanded by the `css` helper:
|
||||||
|
|
||||||
|
```scss
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
.sub-component h {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
will be formatted as:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.my-component .sub-component h {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This extension brings another useful feature: the `&` selector which refers to
|
||||||
|
the parent selector. For example, we want our component to be red when hovered.
|
||||||
|
We would like to write something like:
|
||||||
|
|
||||||
|
```scss
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
:hover {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
but it will be formatted as:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.my-component :hover {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `&` selector can be used to solve this problem:
|
||||||
|
|
||||||
|
```scss
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
&:hover {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
will be formatted as:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.my-component {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.my-component:hover {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, there is no additional processing done by the `css` tag. However, since it
|
||||||
|
is done in javascript at runtime, we actually have more power. For example:
|
||||||
|
|
||||||
|
1. sharing values between javascript and css:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { theme } from "./theme";
|
||||||
|
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = xml`<div class="my-component">...</div>`;
|
||||||
|
static style = css`
|
||||||
|
.my-component {
|
||||||
|
color: ${theme.MAIN_COLOR};
|
||||||
|
background-color: ${theme.SECONDARY_color};
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. scoping rules to the current component:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { generateUUID } from "./utils";
|
||||||
|
|
||||||
|
const uuid = generateUUID();
|
||||||
|
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = xml`<div data-o-${uuid}="">...</div>`;
|
||||||
|
static style = css`
|
||||||
|
[data-o-${uuid}] {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ not ready yet, resolved directly otherwise). If called with a callback as
|
|||||||
argument, it executes it as soon as the DOM ready (or directly).
|
argument, it executes it as soon as the DOM ready (or directly).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
|
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function ([templates]) {
|
||||||
const qweb = new owl.QWeb({ templates });
|
const qweb = new owl.QWeb({ templates });
|
||||||
const app = new App({ qweb });
|
const app = new App({ qweb });
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
@@ -29,7 +29,7 @@ Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([t
|
|||||||
or alternatively:
|
or alternatively:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
owl.utils.whenReady(function() {
|
owl.utils.whenReady(function () {
|
||||||
const qweb = new owl.QWeb();
|
const qweb = new owl.QWeb();
|
||||||
const app = new App({ qweb });
|
const app = new App({ qweb });
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
|
|||||||
-101
@@ -1,101 +0,0 @@
|
|||||||
# 🦉 Tooling 🦉
|
|
||||||
|
|
||||||
## Content
|
|
||||||
|
|
||||||
- [Overview](#overview)
|
|
||||||
- [Development Mode](#development-mode)
|
|
||||||
- [Playground](#playground)
|
|
||||||
- [Benchmarks](#benchmarks)
|
|
||||||
- [Single File Component](#single-file-component)
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||
## Single File Component
|
|
||||||
|
|
||||||
It is very useful to group code by feature instead of by type of file. It makes
|
|
||||||
it easier to scale application to larger size.
|
|
||||||
|
|
||||||
To do so, Owl currently has a small helper that makes it easy to define a
|
|
||||||
template inside a javascript (or typescript) file: the [`xml`](reference/tags.md#xml-tag)
|
|
||||||
helper. With this, a template is automatically registered to [QWeb](reference/qweb.md).
|
|
||||||
|
|
||||||
This means that the template and the javascript code can be defined in the same
|
|
||||||
file. It is not currently possible to add css to the same file, but Owl may
|
|
||||||
get a `css` tag helper later.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const { Component } = owl;
|
|
||||||
const { xml } = owl.tags;
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// TEMPLATE
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
const TEMPLATE = xml/* xml */ `
|
|
||||||
<div class="main two-columns">
|
|
||||||
<Sidebar/>
|
|
||||||
<Content />
|
|
||||||
</div>`;
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// CODE
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
class MyComponent extends Component {
|
|
||||||
static template = TEMPLATE;
|
|
||||||
static components = { Sidebar, Content };
|
|
||||||
|
|
||||||
// rest of component...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that the above example has an inline xml comment, just after the `xml` call.
|
|
||||||
This is useful for some editor plugins, such as the VS Code addon
|
|
||||||
`Comment tagged template`, which, if installed, add syntax highlighting to the
|
|
||||||
content of the template string.
|
|
||||||
+30
-18
@@ -1,57 +1,68 @@
|
|||||||
{
|
{
|
||||||
"name": "owl-framework",
|
"name": "@odoo/owl",
|
||||||
"version": "0.24.1",
|
"version": "1.0.13",
|
||||||
"description": "Odoo Web Library (OWL)",
|
"description": "Odoo Web Library (OWL)",
|
||||||
"main": "src/index.ts",
|
"main": "dist/owl.cjs.js",
|
||||||
|
"browser": "dist/owl.iife.js",
|
||||||
|
"module": "dist/owl.es.js",
|
||||||
|
"types": "dist/types/index.d.ts",
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.15.3"
|
"node": ">=10.15.3"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
|
||||||
"build:bundle": "rollup -c",
|
"build:bundle": "rollup -c",
|
||||||
"build": "npm run build:js && npm run build:bundle",
|
"build": "npm run build:bundle",
|
||||||
"buildcommonjs": "npm run build:js && npm run build:bundle -- -f cjs",
|
|
||||||
"minify": "uglifyjs dist/owl.js -o dist/owl.min.js --compress --mangle",
|
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
||||||
"tools": "npm run build && npm run tools:serve",
|
"tools": "npm run build && npm run tools:serve",
|
||||||
"pretools:watch": "npm run build",
|
"pretools:watch": "npm run build",
|
||||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
||||||
"prettier": "prettier {src/**/*.ts,tests/**/*.ts,doc/**/*.md} --write"
|
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write",
|
||||||
|
"publish": "npm run build && npm publish",
|
||||||
|
"release": "node tools/release.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/odoo/owl.git"
|
"url": "git+https://github.com/odoo/owl.git"
|
||||||
},
|
},
|
||||||
"author": "Odoo",
|
"author": "Odoo",
|
||||||
"license": "LGPL",
|
"license": "LGPL-3.0-only",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/odoo/owl/issues"
|
"url": "https://github.com/odoo/owl/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/odoo/owl#readme",
|
"homepage": "https://github.com/odoo/owl#readme",
|
||||||
"dependencies": {},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^23.3.12",
|
"@types/jest": "^27.0.1",
|
||||||
|
"@types/node": "^14.11.8",
|
||||||
|
"chalk": "^3.0.0",
|
||||||
"cpx": "^1.5.0",
|
"cpx": "^1.5.0",
|
||||||
"git-rev-sync": "^1.12.0",
|
"git-rev-sync": "^1.12.0",
|
||||||
"jest": "^23.6.0",
|
"github-api": "^3.3.0",
|
||||||
"jest-environment-jsdom": "^24.7.1",
|
"jest": "^27.1.0",
|
||||||
|
"jest-environment-jsdom": "^27.1.0",
|
||||||
"live-server": "^1.2.1",
|
"live-server": "^1.2.1",
|
||||||
"npm-run-all": "^4.1.5",
|
"npm-run-all": "^4.1.5",
|
||||||
"rollup": "^1.6.0",
|
"prettier": "^2.0.4",
|
||||||
"rollup-plugin-typescript2": "^0.20.1",
|
"rollup": "^2.56.3",
|
||||||
|
"rollup-plugin-terser": "^7.0.2",
|
||||||
|
"rollup-plugin-typescript2": "^0.30.0",
|
||||||
"sass": "^1.16.1",
|
"sass": "^1.16.1",
|
||||||
"source-map-support": "^0.5.10",
|
"source-map-support": "^0.5.10",
|
||||||
"ts-jest": "^23.10.5",
|
"ts-jest": "^27.0.5",
|
||||||
"typescript": "^3.6.4",
|
"typescript": "3.9.6",
|
||||||
"uglify-es": "^3.3.9"
|
"uglify-es": "^3.3.9"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
|
"testEnvironment": "jsdom",
|
||||||
"roots": [
|
"roots": [
|
||||||
"<rootDir>/src",
|
"<rootDir>/src",
|
||||||
"<rootDir>/tests"
|
"<rootDir>/tests"
|
||||||
],
|
],
|
||||||
|
"setupFiles": ["./tests/mocks/mockEventTarget.js"],
|
||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.ts?$": "ts-jest"
|
"^.+\\.ts?$": "ts-jest"
|
||||||
},
|
},
|
||||||
@@ -67,6 +78,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"prettier": {
|
"prettier": {
|
||||||
"printWidth": 100
|
"printWidth": 100,
|
||||||
|
"endOfLine": "auto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-25
@@ -1,45 +1,27 @@
|
|||||||
# 🦉 OWL Roadmap 🦉
|
# 🦉 OWL Roadmap 🦉
|
||||||
|
|
||||||
- Current version: 0.24.1
|
- Current version: 1.0.13
|
||||||
- Status: mostly stable
|
- Status: stable
|
||||||
|
|
||||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||||
change!
|
change!
|
||||||
|
|
||||||
### October 2019
|
|
||||||
|
|
||||||
We plan to complete the following tasks:
|
|
||||||
|
|
||||||
- improve API for root widgets (issue #306),
|
|
||||||
- replace `t-keepalive`, and maybe `t-transition` by components (issue #295).
|
|
||||||
|
|
||||||
### November 2019
|
|
||||||
|
|
||||||
Once the previous tasks are done, release version 1.0alpha. This means that the
|
|
||||||
API should be stable. But it could change a little bit if we need it for our
|
|
||||||
work on Odoo.
|
|
||||||
|
|
||||||
### End of 2019
|
|
||||||
|
|
||||||
Release v1.0
|
|
||||||
|
|
||||||
- API should be stable,
|
|
||||||
- we will use semantic versioning,
|
|
||||||
- we will maintain a changelog and an upgrade guide.
|
|
||||||
|
|
||||||
### 1.x
|
### 1.x
|
||||||
|
|
||||||
- add chrome and firefox devtools,
|
- add chrome and firefox devtools,
|
||||||
- add support for single file components,
|
|
||||||
- fix every bugs,
|
- fix every bugs,
|
||||||
- improve documentation,
|
- improve documentation,
|
||||||
- small backward compatible improvements.
|
- small backward compatible improvements.
|
||||||
|
|
||||||
### 2.x (2021? 2022?)
|
### 2.x (2020? 2021? 2022?)
|
||||||
|
|
||||||
|
- stop support for `t-set` directive to define the content of a slot
|
||||||
|
|
||||||
Maybe:
|
Maybe:
|
||||||
|
|
||||||
- reimplement vdom to use *block* system, like Vue 3,
|
- reimplement vdom to use *block* system, like Vue 3, which should make Owl
|
||||||
|
much faster
|
||||||
- refactor `QWeb` to use an intermediate representation (some kind of AST) to
|
- refactor `QWeb` to use an intermediate representation (some kind of AST) to
|
||||||
allow additional optimisations.
|
allow additional optimisations.
|
||||||
|
|
||||||
|
|||||||
+67
-10
@@ -1,14 +1,71 @@
|
|||||||
import { version } from "./package.json";
|
import pkg from "./package.json";
|
||||||
import git from "git-rev-sync";
|
import git from "git-rev-sync";
|
||||||
|
import typescript from 'rollup-plugin-typescript2';
|
||||||
|
import { terser } from "rollup-plugin-terser";
|
||||||
|
|
||||||
|
const name = "owl";
|
||||||
|
const extend = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Meta data to be added on the __info__ object.
|
||||||
|
* Used to let external tools know the current owl version.
|
||||||
|
*/
|
||||||
|
const outro = `
|
||||||
|
__info__.version = '${pkg.version}';
|
||||||
|
__info__.date = '${new Date().toISOString()}';
|
||||||
|
__info__.hash = '${git.short()}';
|
||||||
|
__info__.url = 'https://github.com/odoo/owl';
|
||||||
|
`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate from a string depicting a path a new path for the minified version.
|
||||||
|
* @param {string} pkgFileName file name
|
||||||
|
*/
|
||||||
|
function generateMinifiedNameFromPkgName(pkgFileName) {
|
||||||
|
const parts = pkgFileName.split('.');
|
||||||
|
parts.splice(parts.length - 1, 0, "min");
|
||||||
|
return parts.join('.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the rollup config based on the arguments
|
||||||
|
* @param {string} format format of the bundle
|
||||||
|
* @param {string} generatedFileName generated file name
|
||||||
|
* @param {boolean} minified should it be minified
|
||||||
|
*/
|
||||||
|
function getConfigForFormat(format, generatedFileName, minified = false) {
|
||||||
|
return {
|
||||||
|
file: minified ? generateMinifiedNameFromPkgName(generatedFileName) : generatedFileName,
|
||||||
|
format: format,
|
||||||
|
name: name,
|
||||||
|
extend: extend,
|
||||||
|
outro: outro,
|
||||||
|
freeze: false,
|
||||||
|
plugins: minified ? [terser()] : [],
|
||||||
|
indent: ' ', // indent with 4 spaces
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// rollup.config.js
|
|
||||||
export default {
|
export default {
|
||||||
input: "dist/owl/index.js",
|
input: "src/index.ts",
|
||||||
output: {
|
output: [
|
||||||
file: "dist/owl.js",
|
|
||||||
format: "iife",
|
/**
|
||||||
name: "owl",
|
* Read about module formats:
|
||||||
extend: true,
|
* https://auth0.com/blog/javascript-module-systems-showdown/
|
||||||
outro: `exports.__info__.version = '${version}';\nexports.__info__.date = '${new Date().toISOString()}';\nexports.__info__.hash = '${git.short()}';\nexports.__info__.url = 'https://github.com/odoo/owl';`
|
* https://medium.com/@kelin2025/so-you-wanna-use-es6-modules-714f48b3a953
|
||||||
}
|
*/
|
||||||
|
|
||||||
|
getConfigForFormat('esm', pkg.module),
|
||||||
|
getConfigForFormat('esm', pkg.module, true),
|
||||||
|
getConfigForFormat('cjs', pkg.main),
|
||||||
|
getConfigForFormat('cjs', pkg.main, true),
|
||||||
|
getConfigForFormat('iife', pkg.browser),
|
||||||
|
getConfigForFormat('iife', pkg.browser, true),
|
||||||
|
],
|
||||||
|
plugins: [
|
||||||
|
typescript({
|
||||||
|
useTsconfigDeclarationDir: true
|
||||||
|
}),
|
||||||
|
]
|
||||||
};
|
};
|
||||||
|
|||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
import { Component } from "./component/component";
|
||||||
|
import { ComponentNode } from "./component/component_node";
|
||||||
|
import { Scheduler } from "./component/scheduler";
|
||||||
|
import { TemplateSet } from "./qweb/template_helpers";
|
||||||
|
|
||||||
|
// reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f
|
||||||
|
|
||||||
|
export class App<T extends typeof Component = any> extends TemplateSet {
|
||||||
|
Root: T;
|
||||||
|
props: any;
|
||||||
|
env: any = {};
|
||||||
|
scheduler = new Scheduler(window.requestAnimationFrame.bind(window));
|
||||||
|
root: ComponentNode | null = null;
|
||||||
|
dev: boolean = true;
|
||||||
|
|
||||||
|
constructor(Root: T, props?: any) {
|
||||||
|
super();
|
||||||
|
this.Root = Root;
|
||||||
|
this.props = props;
|
||||||
|
}
|
||||||
|
|
||||||
|
configure(params: any) {
|
||||||
|
if (params.env) {
|
||||||
|
this.env = params.env;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(target: HTMLElement): Promise<InstanceType<T>> {
|
||||||
|
if (!(target instanceof HTMLElement)) {
|
||||||
|
throw new Error("Cannot mount component: the target is not a valid DOM element");
|
||||||
|
}
|
||||||
|
if (!document.body.contains(target)) {
|
||||||
|
throw new Error("Cannot mount a component on a detached dom node");
|
||||||
|
}
|
||||||
|
const node = new ComponentNode(this.Root, this.props, this);
|
||||||
|
this.root = node;
|
||||||
|
return node.mountComponent(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
if (this.root) {
|
||||||
|
this.root.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import type { Setter } from "./block_compiler";
|
||||||
|
|
||||||
|
const { setAttribute, removeAttribute } = Element.prototype;
|
||||||
|
const tokenList = DOMTokenList.prototype;
|
||||||
|
const tokenListAdd = tokenList.add;
|
||||||
|
const tokenListRemove = tokenList.remove;
|
||||||
|
const isArray = Array.isArray;
|
||||||
|
const { split, trim } = String.prototype;
|
||||||
|
const wordRegexp = /\s+/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We regroup here all code related to updating attributes in a very loose sense:
|
||||||
|
* attributes, properties and classs are all managed by the functions in this
|
||||||
|
* file.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function createAttrUpdater(attr: string): Setter<HTMLElement> {
|
||||||
|
return function (this: HTMLElement, value: any) {
|
||||||
|
if (value !== false) {
|
||||||
|
setAttribute.call(this, attr, value === true ? "" : value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attrsSetter(this: HTMLElement, attrs: any) {
|
||||||
|
if (isArray(attrs)) {
|
||||||
|
setAttribute.call(this, attrs[0], attrs[1]);
|
||||||
|
} else {
|
||||||
|
for (let k in attrs) {
|
||||||
|
setAttribute.call(this, k, attrs[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
|
||||||
|
if (isArray(attrs)) {
|
||||||
|
const name = attrs[0];
|
||||||
|
const val = attrs[1];
|
||||||
|
if (name === oldAttrs[0]) {
|
||||||
|
if (val === oldAttrs[1]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setAttribute.call(this, name, val);
|
||||||
|
} else {
|
||||||
|
removeAttribute.call(this, oldAttrs[0]);
|
||||||
|
setAttribute.call(this, name, val);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (let k in oldAttrs) {
|
||||||
|
if (!(k in attrs)) {
|
||||||
|
removeAttribute.call(this, k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let k in attrs) {
|
||||||
|
const val = attrs[k];
|
||||||
|
if (val !== oldAttrs[k]) {
|
||||||
|
setAttribute.call(this, k, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toClassObj(expr: string | number | { [c: string]: any }) {
|
||||||
|
const result: { [c: string]: any } = {};
|
||||||
|
switch (typeof expr) {
|
||||||
|
case "string":
|
||||||
|
// we transform here a list of classes into an object:
|
||||||
|
// 'hey you' becomes {hey: true, you: true}
|
||||||
|
const str = trim.call(expr);
|
||||||
|
if (!str) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
let words = split.call(str, wordRegexp);
|
||||||
|
for (let i = 0, l = words.length; i < l; i++) {
|
||||||
|
result[words[i]] = true;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
case "object":
|
||||||
|
// this is already an object but we may need to split keys:
|
||||||
|
// {'a': true, 'b c': true} should become {a: true, b: true, c: true}
|
||||||
|
for (let key in expr as any) {
|
||||||
|
const value = (expr as any)[key];
|
||||||
|
if (value) {
|
||||||
|
const words = split.call(key, wordRegexp);
|
||||||
|
for (let word of words) {
|
||||||
|
result[word] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
|
||||||
|
case "undefined":
|
||||||
|
return {};
|
||||||
|
case "number":
|
||||||
|
return { [expr as number]: true };
|
||||||
|
default:
|
||||||
|
return { [expr as any]: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setClass(this: HTMLElement, val: any) {
|
||||||
|
val = val === "" ? {} : toClassObj(val);
|
||||||
|
// add classes
|
||||||
|
const cl = this.classList;
|
||||||
|
for (let c in val) {
|
||||||
|
tokenListAdd.call(cl, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateClass(this: HTMLElement, val: any, oldVal: any) {
|
||||||
|
oldVal = oldVal === "" ? {} : toClassObj(oldVal);
|
||||||
|
val = val === "" ? {} : toClassObj(val);
|
||||||
|
const cl = this.classList;
|
||||||
|
// remove classes
|
||||||
|
for (let c in oldVal) {
|
||||||
|
if (!(c in val)) {
|
||||||
|
tokenListRemove.call(cl, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// add classes
|
||||||
|
for (let c in val) {
|
||||||
|
if (!(c in oldVal)) {
|
||||||
|
tokenListAdd.call(cl, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makePropSetter(name: string): Setter<HTMLElement> {
|
||||||
|
return function setProp(this: HTMLElement, value: any) {
|
||||||
|
(this as any)[name] = value;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isProp(tag: string, key: string): boolean {
|
||||||
|
switch (tag) {
|
||||||
|
case "input":
|
||||||
|
return (
|
||||||
|
key === "checked" ||
|
||||||
|
key === "indeterminate" ||
|
||||||
|
key === "value" ||
|
||||||
|
key === "readonly" ||
|
||||||
|
key === "disabled"
|
||||||
|
);
|
||||||
|
case "option":
|
||||||
|
return key === "selected" || key === "disabled";
|
||||||
|
case "textarea":
|
||||||
|
return key === "readonly" || key === "disabled";
|
||||||
|
break;
|
||||||
|
case "button":
|
||||||
|
case "select":
|
||||||
|
case "optgroup":
|
||||||
|
return key === "disabled";
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,602 @@
|
|||||||
|
import {
|
||||||
|
attrsSetter,
|
||||||
|
attrsUpdater,
|
||||||
|
createAttrUpdater,
|
||||||
|
isProp,
|
||||||
|
makePropSetter,
|
||||||
|
setClass,
|
||||||
|
updateClass,
|
||||||
|
} from "./attributes";
|
||||||
|
import { config } from "./config";
|
||||||
|
import { createEventHandler } from "./events";
|
||||||
|
import type { VNode } from "./index";
|
||||||
|
import { VMulti } from "./multi";
|
||||||
|
import { toText } from "./text";
|
||||||
|
|
||||||
|
const getDescriptor = (o: any, p: any) => Object.getOwnPropertyDescriptor(o, p)!;
|
||||||
|
const nodeProto = Node.prototype;
|
||||||
|
const elementProto = Element.prototype;
|
||||||
|
const characterDataProto = CharacterData.prototype;
|
||||||
|
|
||||||
|
const characterDataSetData = getDescriptor(characterDataProto, "data").set!;
|
||||||
|
const nodeGetFirstChild = getDescriptor(nodeProto, "firstChild").get!;
|
||||||
|
const nodeGetNextSibling = getDescriptor(nodeProto, "nextSibling").get!;
|
||||||
|
|
||||||
|
const NO_OP = () => {};
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Main compiler code
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
type BlockType = (data?: any[], children?: VNode[]) => VNode;
|
||||||
|
|
||||||
|
const cache: { [key: string]: BlockType } = {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compiling blocks is a multi-step process:
|
||||||
|
*
|
||||||
|
* 1. build an IntermediateTree from the HTML element. This intermediate tree
|
||||||
|
* is a binary tree structure that encode dynamic info sub nodes, and the
|
||||||
|
* path required to reach them
|
||||||
|
* 2. process the tree to build a block context, which is an object that aggregate
|
||||||
|
* all dynamic info in a list, and also, all ref indexes.
|
||||||
|
* 3. process the context to build appropriate builder/setter functions
|
||||||
|
* 4. make a dynamic block class, which will efficiently collect references and
|
||||||
|
* create/update dynamic locations/children
|
||||||
|
*
|
||||||
|
* @param str
|
||||||
|
* @returns a new block type, that can build concrete blocks
|
||||||
|
*/
|
||||||
|
export function createBlock(str: string): BlockType {
|
||||||
|
if (str in cache) {
|
||||||
|
return cache[str];
|
||||||
|
}
|
||||||
|
|
||||||
|
// step 0: prepare html base element
|
||||||
|
const doc = new DOMParser().parseFromString(`<t>${str}</t>`, "text/xml");
|
||||||
|
const node = doc.firstChild!.firstChild!;
|
||||||
|
if (config.shouldNormalizeDom) {
|
||||||
|
normalizeNode(node as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
// step 1: prepare intermediate tree
|
||||||
|
const tree = buildTree(node);
|
||||||
|
|
||||||
|
// step 2: prepare block context
|
||||||
|
const context = buildContext(tree);
|
||||||
|
|
||||||
|
// step 3: build the final block class
|
||||||
|
const template = tree.el as HTMLElement;
|
||||||
|
const Block = buildBlock(template, context);
|
||||||
|
cache[str] = Block;
|
||||||
|
return Block;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Helper
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function normalizeNode(node: HTMLElement | Text) {
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
if (!/\S/.test((node as Text).textContent!)) {
|
||||||
|
(node as Text).remove();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||||
|
if ((node as HTMLElement).tagName === "pre") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i = node.childNodes.length - 1; i >= 0; --i) {
|
||||||
|
normalizeNode(node.childNodes.item(i) as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// building a intermediate tree
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface DynamicInfo {
|
||||||
|
idx: number;
|
||||||
|
refIdx?: number;
|
||||||
|
type: "text" | "child" | "handler" | "attribute" | "attributes" | "ref";
|
||||||
|
isOnlyChild?: boolean;
|
||||||
|
name?: string;
|
||||||
|
tag?: string;
|
||||||
|
event?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IntermediateTree {
|
||||||
|
parent: IntermediateTree | null;
|
||||||
|
firstChild: IntermediateTree | null;
|
||||||
|
nextSibling: IntermediateTree | null;
|
||||||
|
el: Node;
|
||||||
|
info: DynamicInfo[];
|
||||||
|
forceRef?: boolean;
|
||||||
|
refIdx?: number;
|
||||||
|
refN: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTree(
|
||||||
|
node: Node,
|
||||||
|
parent: IntermediateTree | null = null,
|
||||||
|
domParentTree: IntermediateTree | null = null
|
||||||
|
): IntermediateTree {
|
||||||
|
switch (node.nodeType) {
|
||||||
|
case 1: {
|
||||||
|
// HTMLElement
|
||||||
|
let isActive = false;
|
||||||
|
const tagName = (node as Element).tagName;
|
||||||
|
let el: Node | undefined = undefined;
|
||||||
|
const info: DynamicInfo[] = [];
|
||||||
|
if (tagName.startsWith("block-text-")) {
|
||||||
|
const index = parseInt(tagName.slice(11), 10);
|
||||||
|
info.push({ type: "text", idx: index });
|
||||||
|
el = document.createTextNode("");
|
||||||
|
isActive = true;
|
||||||
|
}
|
||||||
|
if (tagName.startsWith("block-child-")) {
|
||||||
|
domParentTree!.forceRef = true;
|
||||||
|
const index = parseInt(tagName.slice(12), 10);
|
||||||
|
info.push({ type: "child", idx: index });
|
||||||
|
el = document.createTextNode("");
|
||||||
|
isActive = true;
|
||||||
|
}
|
||||||
|
if (!el) {
|
||||||
|
el = document.createElement(tagName);
|
||||||
|
}
|
||||||
|
if (el instanceof HTMLElement) {
|
||||||
|
const attrs = (node as Element).attributes;
|
||||||
|
for (let i = 0; i < attrs.length; i++) {
|
||||||
|
const attrName = attrs[i].name;
|
||||||
|
const attrValue = attrs[i].value;
|
||||||
|
if (attrName.startsWith("block-handler-")) {
|
||||||
|
isActive = true;
|
||||||
|
const idx = parseInt(attrName.slice(14), 10);
|
||||||
|
info.push({
|
||||||
|
type: "handler",
|
||||||
|
idx,
|
||||||
|
event: attrValue,
|
||||||
|
});
|
||||||
|
} else if (attrName.startsWith("block-attribute-")) {
|
||||||
|
isActive = true;
|
||||||
|
const idx = parseInt(attrName.slice(16), 10);
|
||||||
|
info.push({
|
||||||
|
type: "attribute",
|
||||||
|
idx,
|
||||||
|
name: attrValue,
|
||||||
|
tag: tagName,
|
||||||
|
});
|
||||||
|
} else if (attrName === "block-attributes") {
|
||||||
|
isActive = true;
|
||||||
|
info.push({
|
||||||
|
type: "attributes",
|
||||||
|
idx: parseInt(attrValue, 10),
|
||||||
|
});
|
||||||
|
} else if (attrName === "block-ref") {
|
||||||
|
isActive = true;
|
||||||
|
info.push({
|
||||||
|
type: "ref",
|
||||||
|
idx: parseInt(attrValue, 10),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
el.setAttribute(attrs[i].name, attrValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tree: IntermediateTree = {
|
||||||
|
parent,
|
||||||
|
firstChild: null,
|
||||||
|
nextSibling: null,
|
||||||
|
el,
|
||||||
|
info,
|
||||||
|
refN: isActive ? 1 : 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (node.firstChild) {
|
||||||
|
const childNode = node.childNodes[0];
|
||||||
|
if (
|
||||||
|
node.childNodes.length === 1 &&
|
||||||
|
childNode.nodeType === 1 &&
|
||||||
|
(childNode as Element).tagName.startsWith("block-child-")
|
||||||
|
) {
|
||||||
|
const tagName = (childNode as Element).tagName;
|
||||||
|
const index = parseInt(tagName.slice(12), 10);
|
||||||
|
info.push({ idx: index, type: "child", isOnlyChild: true });
|
||||||
|
isActive = true;
|
||||||
|
tree.refN = 1;
|
||||||
|
} else {
|
||||||
|
tree.firstChild = buildTree(node.firstChild, tree, tree);
|
||||||
|
el.appendChild(tree.firstChild.el);
|
||||||
|
let curNode: Node | null = node.firstChild;
|
||||||
|
let curTree: IntermediateTree | null = tree.firstChild;
|
||||||
|
while ((curNode = curNode.nextSibling)) {
|
||||||
|
curTree.nextSibling = buildTree(curNode, curTree, tree);
|
||||||
|
el.appendChild(curTree.nextSibling.el);
|
||||||
|
curTree = curTree.nextSibling;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isActive) {
|
||||||
|
let cur: IntermediateTree | null = tree;
|
||||||
|
while ((cur = cur.parent)) {
|
||||||
|
cur.refN++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
case 3:
|
||||||
|
case 8: {
|
||||||
|
// text node or comment node
|
||||||
|
const el =
|
||||||
|
node.nodeType === 3
|
||||||
|
? document.createTextNode(node.textContent!)
|
||||||
|
: document.createComment(node.textContent!);
|
||||||
|
return {
|
||||||
|
parent: parent,
|
||||||
|
firstChild: null,
|
||||||
|
nextSibling: null,
|
||||||
|
el,
|
||||||
|
info: [],
|
||||||
|
refN: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error("boom");
|
||||||
|
}
|
||||||
|
|
||||||
|
function parentTree(tree: IntermediateTree): IntermediateTree | null {
|
||||||
|
let parent = tree.parent;
|
||||||
|
while (parent && parent.nextSibling === tree) {
|
||||||
|
tree = parent;
|
||||||
|
parent = parent.parent;
|
||||||
|
}
|
||||||
|
return parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Building a block context
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface RefCollector {
|
||||||
|
idx: number;
|
||||||
|
prevIdx: number;
|
||||||
|
getVal: Function;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Setter<T = any> = (this: T, value: any) => void;
|
||||||
|
export type Updater<T = any> = (this: T, value: any, oldVal: any) => void;
|
||||||
|
|
||||||
|
interface Location {
|
||||||
|
refIdx: number;
|
||||||
|
setData: Setter;
|
||||||
|
updateData: Updater;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IndexedLocation extends Location {
|
||||||
|
idx: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Child {
|
||||||
|
parentRefIdx: number;
|
||||||
|
afterRefIdx?: number;
|
||||||
|
isOnlyChild?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockCtx {
|
||||||
|
refN: number;
|
||||||
|
collectors: RefCollector[];
|
||||||
|
locations: IndexedLocation[];
|
||||||
|
children: Child[];
|
||||||
|
cbRefs: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildContext(
|
||||||
|
tree: IntermediateTree,
|
||||||
|
ctx?: BlockCtx,
|
||||||
|
fromIdx?: number,
|
||||||
|
toIdx?: number
|
||||||
|
): BlockCtx {
|
||||||
|
if (!ctx) {
|
||||||
|
const children = new Array(tree.info.filter((v) => v.type === "child").length);
|
||||||
|
ctx = { collectors: [], locations: [], children, cbRefs: [], refN: tree.refN };
|
||||||
|
fromIdx = 0;
|
||||||
|
toIdx = tree.refN - 1;
|
||||||
|
}
|
||||||
|
if (tree.refN) {
|
||||||
|
const initialIdx = fromIdx!;
|
||||||
|
const isRef = tree.forceRef || tree.info.length > 0;
|
||||||
|
const firstChild = tree.firstChild ? tree.firstChild.refN : 0;
|
||||||
|
const nextSibling = tree.nextSibling ? tree.nextSibling.refN : 0;
|
||||||
|
|
||||||
|
//node
|
||||||
|
if (isRef) {
|
||||||
|
for (let info of tree.info) {
|
||||||
|
info.refIdx = initialIdx!;
|
||||||
|
}
|
||||||
|
tree.refIdx = initialIdx!;
|
||||||
|
updateCtx(ctx, tree);
|
||||||
|
fromIdx!++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// right
|
||||||
|
if (nextSibling) {
|
||||||
|
const idx = fromIdx! + firstChild;
|
||||||
|
ctx.collectors.push({ idx, prevIdx: initialIdx, getVal: nodeGetNextSibling });
|
||||||
|
buildContext(tree.nextSibling!, ctx, idx, toIdx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// left
|
||||||
|
if (firstChild) {
|
||||||
|
ctx.collectors.push({ idx: fromIdx!, prevIdx: initialIdx, getVal: nodeGetFirstChild });
|
||||||
|
buildContext(tree.firstChild!, ctx, fromIdx!, toIdx! - nextSibling);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCtx(ctx: BlockCtx, tree: IntermediateTree) {
|
||||||
|
for (let info of tree.info) {
|
||||||
|
switch (info.type) {
|
||||||
|
case "text":
|
||||||
|
ctx.locations.push({
|
||||||
|
idx: info.idx,
|
||||||
|
refIdx: info.refIdx!,
|
||||||
|
setData: setText,
|
||||||
|
updateData: setText,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "child":
|
||||||
|
if (info.isOnlyChild) {
|
||||||
|
// tree is the parentnode here
|
||||||
|
ctx.children[info.idx] = {
|
||||||
|
parentRefIdx: info.refIdx!,
|
||||||
|
isOnlyChild: true,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// tree is the anchor text node
|
||||||
|
ctx.children[info.idx] = {
|
||||||
|
parentRefIdx: parentTree(tree)!.refIdx!,
|
||||||
|
afterRefIdx: info.refIdx!,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "attribute": {
|
||||||
|
const refIdx = info.refIdx!;
|
||||||
|
let updater: any;
|
||||||
|
let setter: any;
|
||||||
|
if (isProp(info.tag!, info.name!)) {
|
||||||
|
const setProp = makePropSetter(info.name!);
|
||||||
|
setter = setProp;
|
||||||
|
updater = setProp;
|
||||||
|
} else if (info.name === "class") {
|
||||||
|
setter = setClass;
|
||||||
|
updater = updateClass;
|
||||||
|
} else {
|
||||||
|
setter = createAttrUpdater(info.name!);
|
||||||
|
updater = setter;
|
||||||
|
}
|
||||||
|
ctx.locations.push({
|
||||||
|
idx: info.idx,
|
||||||
|
refIdx,
|
||||||
|
setData: setter,
|
||||||
|
updateData: updater,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "attributes":
|
||||||
|
ctx.locations.push({
|
||||||
|
idx: info.idx,
|
||||||
|
refIdx: info.refIdx!,
|
||||||
|
setData: attrsSetter,
|
||||||
|
updateData: attrsUpdater,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "handler": {
|
||||||
|
const setupHandler = createEventHandler(info.event!);
|
||||||
|
ctx.locations.push({
|
||||||
|
idx: info.idx,
|
||||||
|
refIdx: info.refIdx!,
|
||||||
|
setData: setupHandler,
|
||||||
|
updateData: setupHandler,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "ref":
|
||||||
|
ctx.cbRefs.push(info.idx);
|
||||||
|
ctx.locations.push({
|
||||||
|
idx: info.idx,
|
||||||
|
refIdx: info.refIdx!,
|
||||||
|
setData: setRef,
|
||||||
|
updateData: NO_OP,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// building the concrete block class
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function buildBlock(template: HTMLElement, ctx: BlockCtx): BlockType {
|
||||||
|
let B = createBlockClass(template, ctx);
|
||||||
|
|
||||||
|
if (ctx.cbRefs.length) {
|
||||||
|
const refs = ctx.cbRefs;
|
||||||
|
B = class extends B {
|
||||||
|
remove() {
|
||||||
|
super.remove();
|
||||||
|
for (let ref of refs) {
|
||||||
|
let fn = (this as any).data[ref];
|
||||||
|
fn(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.children.length) {
|
||||||
|
B = class extends B {
|
||||||
|
children: (VNode | undefined)[] | undefined;
|
||||||
|
constructor(data?: any[], children?: VNode[]) {
|
||||||
|
super(data);
|
||||||
|
this.children = children;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
B.prototype.beforeRemove = VMulti.prototype.beforeRemove;
|
||||||
|
return (data?: any[], children: (VNode | undefined)[] = []) => new B(data, children);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (data?: any[]) => new B(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
type Constructor<T> = new (...args: any[]) => T;
|
||||||
|
type BlockClass = Constructor<VNode<any>>;
|
||||||
|
|
||||||
|
function createBlockClass(template: HTMLElement, ctx: BlockCtx): BlockClass {
|
||||||
|
const { refN, collectors, children } = ctx;
|
||||||
|
const colN = collectors.length;
|
||||||
|
ctx.locations.sort((a, b) => a.idx - b.idx);
|
||||||
|
const locations: Location[] = ctx.locations.map((loc) => ({
|
||||||
|
refIdx: loc.refIdx,
|
||||||
|
setData: loc.setData,
|
||||||
|
updateData: loc.updateData,
|
||||||
|
}));
|
||||||
|
const locN = locations.length;
|
||||||
|
const childN = children.length;
|
||||||
|
const childrenLocs = children;
|
||||||
|
const isDynamic = refN > 0;
|
||||||
|
|
||||||
|
// these values are defined here to make them faster to lookup in the class
|
||||||
|
// block scope
|
||||||
|
const nodeCloneNode = nodeProto.cloneNode;
|
||||||
|
const nodeInsertBefore = nodeProto.insertBefore;
|
||||||
|
const elementRemove = elementProto.remove;
|
||||||
|
|
||||||
|
return class Block {
|
||||||
|
el: HTMLElement | undefined;
|
||||||
|
refs: Node[] | undefined;
|
||||||
|
data: any[] | undefined;
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
children?: (VNode | undefined)[];
|
||||||
|
|
||||||
|
constructor(data?: any[]) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
elementRemove.call(this.el);
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node {
|
||||||
|
return this.el!;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: Block | null, afterNode: Node | null) {
|
||||||
|
const target = other ? other.el! : afterNode;
|
||||||
|
nodeInsertBefore.call(this.parentEl, this.el!, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
const el = nodeCloneNode.call(template, true);
|
||||||
|
nodeInsertBefore.call(parent, el, afterNode);
|
||||||
|
if (isDynamic) {
|
||||||
|
// collecting references
|
||||||
|
const refs: Node[] = new Array(refN);
|
||||||
|
this.refs = refs;
|
||||||
|
refs[0] = el;
|
||||||
|
for (let i = 0; i < colN; i++) {
|
||||||
|
const w = collectors[i];
|
||||||
|
refs[w.idx] = w.getVal.call(refs[w.prevIdx]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// applying data to all update points
|
||||||
|
if (locN) {
|
||||||
|
const data = this.data!;
|
||||||
|
for (let i = 0; i < locN; i++) {
|
||||||
|
const loc = locations[i];
|
||||||
|
loc.setData.call(refs[loc.refIdx], data[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// preparing all children
|
||||||
|
if (childN) {
|
||||||
|
const children = this.children;
|
||||||
|
for (let i = 0; i < childN; i++) {
|
||||||
|
const child = children![i];
|
||||||
|
if (child) {
|
||||||
|
const loc = childrenLocs[i];
|
||||||
|
const afterNode = loc.afterRefIdx ? refs[loc.afterRefIdx] : null;
|
||||||
|
child.isOnlyChild = loc.isOnlyChild;
|
||||||
|
child.mount(refs[loc.parentRefIdx] as any, afterNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.el = el as HTMLElement;
|
||||||
|
this.parentEl = parent;
|
||||||
|
}
|
||||||
|
patch(other: Block, withBeforeRemove: boolean) {
|
||||||
|
if (this === other) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const refs = this.refs!;
|
||||||
|
// update texts/attributes/
|
||||||
|
if (locN) {
|
||||||
|
const data1 = this.data!;
|
||||||
|
const data2 = other.data!;
|
||||||
|
for (let i = 0; i < locN; i++) {
|
||||||
|
const val1 = data1[i];
|
||||||
|
const val2 = data2[i];
|
||||||
|
if (val1 !== val2) {
|
||||||
|
const loc = locations[i];
|
||||||
|
loc.updateData.call(refs[loc.refIdx], val2, val1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.data = data2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// update children
|
||||||
|
if (childN) {
|
||||||
|
let children1 = this.children;
|
||||||
|
const children2 = other.children;
|
||||||
|
for (let i = 0; i < childN; i++) {
|
||||||
|
const child1 = children1![i];
|
||||||
|
const child2 = children2![i];
|
||||||
|
if (child1) {
|
||||||
|
if (child2) {
|
||||||
|
child1.patch(child2, withBeforeRemove);
|
||||||
|
} else {
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
child1.beforeRemove();
|
||||||
|
}
|
||||||
|
child1.remove();
|
||||||
|
children1![i] = undefined;
|
||||||
|
}
|
||||||
|
} else if (child2) {
|
||||||
|
const loc = childrenLocs[i];
|
||||||
|
const afterNode = loc.afterRefIdx ? refs[loc.afterRefIdx] : null;
|
||||||
|
child2.mount(refs[loc.parentRefIdx] as any, afterNode);
|
||||||
|
children1![i] = child2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
const div = document.createElement("div");
|
||||||
|
this.mount(div, null);
|
||||||
|
return div.innerHTML;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function setText(this: Text, value: any) {
|
||||||
|
characterDataSetData.call(this, toText(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRef(this: HTMLElement, fn: any) {
|
||||||
|
fn(this);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
export const config = {
|
||||||
|
// whether or not blockdom should normalize DOM whenever a block is created.
|
||||||
|
// Normalizing dom mean removing empty text nodes (or containing only spaces)
|
||||||
|
shouldNormalizeDom: true,
|
||||||
|
|
||||||
|
// this is the main event handler. Every event handler registered with blockdom
|
||||||
|
// will go through this function, giving it the data registered in the block
|
||||||
|
// and the event
|
||||||
|
mainEventHandler: (data: any, ev: Event) => {
|
||||||
|
if (typeof data === "function") {
|
||||||
|
data(ev);
|
||||||
|
} else if (Array.isArray(data)) {
|
||||||
|
data[0](data[1], ev);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { config } from "./config";
|
||||||
|
|
||||||
|
export function createEventHandler(event: string) {
|
||||||
|
setupSyntheticEvent(event);
|
||||||
|
const key = `__event__${event}`;
|
||||||
|
return function setupHandler(this: HTMLElement, data: any) {
|
||||||
|
(this as any)[key] = data;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function nativeToSyntheticEvent(event: Event, name: string) {
|
||||||
|
const eventKey = `__event__${name}`;
|
||||||
|
let dom = event.target;
|
||||||
|
while (dom !== null) {
|
||||||
|
const data = (dom as any)[eventKey];
|
||||||
|
if (data) {
|
||||||
|
config.mainEventHandler(data, event);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dom = (dom as any).parentNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONFIGURED_SYNTHETIC_EVENTS: { [event: string]: boolean } = {};
|
||||||
|
|
||||||
|
function setupSyntheticEvent(name: string) {
|
||||||
|
if (CONFIGURED_SYNTHETIC_EVENTS[name]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
document.addEventListener(name, (event) => nativeToSyntheticEvent(event, name));
|
||||||
|
CONFIGURED_SYNTHETIC_EVENTS[name] = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import type { VNode } from "./index";
|
||||||
|
|
||||||
|
const nodeProto = Node.prototype;
|
||||||
|
|
||||||
|
const nodeInsertBefore = nodeProto.insertBefore;
|
||||||
|
const nodeRemoveChild = nodeProto.removeChild;
|
||||||
|
|
||||||
|
class VHtml {
|
||||||
|
html: string;
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
content: ChildNode[] = [];
|
||||||
|
|
||||||
|
constructor(html: string) {
|
||||||
|
this.html = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
this.parentEl = parent;
|
||||||
|
const template = document.createElement("template");
|
||||||
|
template.innerHTML = this.html;
|
||||||
|
this.content = [...(template.content.childNodes as any)];
|
||||||
|
for (let elem of this.content) {
|
||||||
|
nodeInsertBefore.call(parent, elem, afterNode);
|
||||||
|
}
|
||||||
|
if (!this.content.length) {
|
||||||
|
const textNode = document.createTextNode("");
|
||||||
|
this.content.push(textNode);
|
||||||
|
nodeInsertBefore.call(parent, textNode, afterNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: VHtml | null, afterNode: Node | null) {
|
||||||
|
const target = other ? other.content[0] : afterNode;
|
||||||
|
const parent = this.parentEl;
|
||||||
|
for (let elem of this.content) {
|
||||||
|
nodeInsertBefore.call(parent, elem, target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VHtml) {
|
||||||
|
if (this === other) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const html2 = other.html;
|
||||||
|
if (this.html !== html2) {
|
||||||
|
const parent = this.parentEl;
|
||||||
|
// insert new html in front of current
|
||||||
|
const afterNode = this.content[0];
|
||||||
|
const template = document.createElement("template");
|
||||||
|
template.innerHTML = html2;
|
||||||
|
const content = [...(template.content.childNodes as any)];
|
||||||
|
for (let elem of content) {
|
||||||
|
nodeInsertBefore.call(parent, elem, afterNode);
|
||||||
|
}
|
||||||
|
if (!content.length) {
|
||||||
|
const textNode = document.createTextNode("");
|
||||||
|
content.push(textNode);
|
||||||
|
nodeInsertBefore.call(parent, textNode, afterNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove current content
|
||||||
|
this.remove();
|
||||||
|
this.content = content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
const parent = this.parentEl;
|
||||||
|
for (let elem of this.content) {
|
||||||
|
nodeRemoveChild.call(parent, elem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node {
|
||||||
|
return this.content[0]!;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return this.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function html(str: string): VNode<VHtml> {
|
||||||
|
return new VHtml(str);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
export { config } from "./config";
|
||||||
|
|
||||||
|
export { toggler } from "./toggler";
|
||||||
|
export { createBlock } from "./block_compiler";
|
||||||
|
export { list } from "./list";
|
||||||
|
export { multi } from "./multi";
|
||||||
|
export { text } from "./text";
|
||||||
|
export { html } from "./html";
|
||||||
|
|
||||||
|
export interface VNode<T = any> {
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null): void;
|
||||||
|
moveBefore(other: T | null, afterNode: Node | null): void;
|
||||||
|
patch(other: T, withBeforeRemove: boolean): void;
|
||||||
|
beforeRemove(): void;
|
||||||
|
remove(): void;
|
||||||
|
firstNode(): Node | undefined;
|
||||||
|
|
||||||
|
el?: undefined | HTMLElement | Text;
|
||||||
|
parentEl?: undefined | HTMLElement;
|
||||||
|
isOnlyChild?: boolean | undefined;
|
||||||
|
key?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BDom = VNode<any>;
|
||||||
|
|
||||||
|
export function mount(vnode: VNode, fixture: HTMLElement) {
|
||||||
|
vnode.mount(fixture, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patch(vnode1: VNode, vnode2: VNode, withBeforeRemove: boolean = false) {
|
||||||
|
vnode1.patch(vnode2, withBeforeRemove);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function remove(vnode: VNode, withBeforeRemove: boolean = false) {
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
vnode.beforeRemove();
|
||||||
|
}
|
||||||
|
vnode.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withKey(vnode: VNode, key: any) {
|
||||||
|
vnode.key = key;
|
||||||
|
return vnode;
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
import type { VNode } from "./index";
|
||||||
|
|
||||||
|
const getDescriptor = (o: any, p: any) => Object.getOwnPropertyDescriptor(o, p)!;
|
||||||
|
const nodeProto = Node.prototype;
|
||||||
|
|
||||||
|
const nodeInsertBefore = nodeProto.insertBefore;
|
||||||
|
const nodeAppendChild = nodeProto.appendChild;
|
||||||
|
const nodeRemoveChild = nodeProto.removeChild;
|
||||||
|
const nodeSetTextContent = getDescriptor(nodeProto, "textContent").set!;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// List Node
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class VList {
|
||||||
|
children: VNode[];
|
||||||
|
anchor: Node | undefined;
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
isOnlyChild?: boolean | undefined;
|
||||||
|
|
||||||
|
constructor(children: VNode[]) {
|
||||||
|
this.children = children;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
const children = this.children;
|
||||||
|
const _anchor = document.createTextNode("");
|
||||||
|
this.anchor = _anchor;
|
||||||
|
nodeInsertBefore.call(parent, _anchor, afterNode);
|
||||||
|
const l = children.length;
|
||||||
|
if (l) {
|
||||||
|
const mount = children[0].mount;
|
||||||
|
for (let i = 0; i < l; i++) {
|
||||||
|
mount.call(children[i], parent, _anchor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.parentEl = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: VList | null, afterNode: Node | null) {
|
||||||
|
if (other) {
|
||||||
|
const next = other!.children[0];
|
||||||
|
afterNode = (next ? next.firstNode() : other!.anchor) || null;
|
||||||
|
}
|
||||||
|
const children = this.children;
|
||||||
|
for (let i = 0, l = children.length; i < l; i++) {
|
||||||
|
children[i].moveBefore(null, afterNode);
|
||||||
|
}
|
||||||
|
this.parentEl!.insertBefore(this.anchor!, afterNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VList, withBeforeRemove: boolean) {
|
||||||
|
if (this === other) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ch1 = this.children;
|
||||||
|
const ch2: VNode[] = other.children;
|
||||||
|
if (ch2.length === 0 && ch1.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.children = ch2;
|
||||||
|
const proto = ch2[0] || ch1[0];
|
||||||
|
const {
|
||||||
|
mount: cMount,
|
||||||
|
patch: cPatch,
|
||||||
|
remove: cRemove,
|
||||||
|
beforeRemove,
|
||||||
|
moveBefore: cMoveBefore,
|
||||||
|
firstNode: cFirstNode,
|
||||||
|
} = proto;
|
||||||
|
|
||||||
|
const _anchor = this.anchor!;
|
||||||
|
const isOnlyChild = this.isOnlyChild;
|
||||||
|
const parent = this.parentEl!;
|
||||||
|
|
||||||
|
// fast path: no new child => only remove
|
||||||
|
if (ch2.length === 0 && isOnlyChild) {
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
for (let i = 0, l = ch1.length; i < l; i++) {
|
||||||
|
beforeRemove.call(ch1[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeSetTextContent.call(parent, "");
|
||||||
|
nodeAppendChild.call(parent, _anchor);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let startIdx1 = 0;
|
||||||
|
let startIdx2 = 0;
|
||||||
|
let startVn1 = ch1[0];
|
||||||
|
let startVn2 = ch2[0];
|
||||||
|
|
||||||
|
let endIdx1 = ch1.length - 1;
|
||||||
|
let endIdx2 = ch2.length - 1;
|
||||||
|
let endVn1 = ch1[endIdx1];
|
||||||
|
let endVn2 = ch2[endIdx2];
|
||||||
|
|
||||||
|
let mapping: any = undefined;
|
||||||
|
// let noFullRemove = this.hasNoComponent;
|
||||||
|
|
||||||
|
while (startIdx1 <= endIdx1 && startIdx2 <= endIdx2) {
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
if (startVn1 === null) {
|
||||||
|
startVn1 = ch1[++startIdx1];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
if (endVn1 === null) {
|
||||||
|
endVn1 = ch1[--endIdx1];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
let startKey1 = startVn1.key;
|
||||||
|
let startKey2 = startVn2.key;
|
||||||
|
if (startKey1 === startKey2) {
|
||||||
|
cPatch.call(startVn1, startVn2, withBeforeRemove);
|
||||||
|
ch2[startIdx2] = startVn1;
|
||||||
|
startVn1 = ch1[++startIdx1];
|
||||||
|
startVn2 = ch2[++startIdx2];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
let endKey1 = endVn1.key;
|
||||||
|
let endKey2 = endVn2.key;
|
||||||
|
if (endKey1 === endKey2) {
|
||||||
|
cPatch.call(endVn1, endVn2, withBeforeRemove);
|
||||||
|
ch2[endIdx2] = endVn1;
|
||||||
|
endVn1 = ch1[--endIdx1];
|
||||||
|
endVn2 = ch2[--endIdx2];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
if (startKey1 === endKey2) {
|
||||||
|
// bnode moved right
|
||||||
|
cPatch.call(startVn1, endVn2, withBeforeRemove);
|
||||||
|
ch2[endIdx2] = startVn1;
|
||||||
|
const nextChild = ch2[endIdx2 + 1];
|
||||||
|
cMoveBefore.call(startVn1, nextChild, _anchor);
|
||||||
|
startVn1 = ch1[++startIdx1];
|
||||||
|
endVn2 = ch2[--endIdx2];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
if (endKey1 === startKey2) {
|
||||||
|
// bnode moved left
|
||||||
|
cPatch.call(endVn1, startVn2, withBeforeRemove);
|
||||||
|
ch2[startIdx2] = endVn1;
|
||||||
|
const nextChild = ch1[startIdx1];
|
||||||
|
cMoveBefore.call(endVn1, nextChild, _anchor);
|
||||||
|
endVn1 = ch1[--endIdx1];
|
||||||
|
startVn2 = ch2[++startIdx2];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
mapping = mapping || createMapping(ch1, startIdx1, endIdx1);
|
||||||
|
let idxInOld = mapping[startKey2];
|
||||||
|
if (idxInOld === undefined) {
|
||||||
|
cMount.call(startVn2, parent, cFirstNode.call(startVn1) || null);
|
||||||
|
} else {
|
||||||
|
const elmToMove = ch1[idxInOld];
|
||||||
|
cMoveBefore.call(elmToMove, startVn1, null);
|
||||||
|
cPatch.call(elmToMove, startVn2, withBeforeRemove);
|
||||||
|
ch2[startIdx2] = elmToMove;
|
||||||
|
ch1[idxInOld] = null as any;
|
||||||
|
}
|
||||||
|
startVn2 = ch2[++startIdx2];
|
||||||
|
}
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
if (startIdx1 <= endIdx1 || startIdx2 <= endIdx2) {
|
||||||
|
if (startIdx1 > endIdx1) {
|
||||||
|
const nextChild = ch2[endIdx2 + 1];
|
||||||
|
const anchor = nextChild ? cFirstNode.call(nextChild) || null : _anchor;
|
||||||
|
for (let i = startIdx2; i <= endIdx2; i++) {
|
||||||
|
cMount.call(ch2[i], parent, anchor);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (let i = startIdx1; i <= endIdx1; i++) {
|
||||||
|
let ch = ch1[i];
|
||||||
|
if (ch) {
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
beforeRemove.call(ch);
|
||||||
|
}
|
||||||
|
cRemove.call(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {
|
||||||
|
const children = this.children;
|
||||||
|
const l = children.length;
|
||||||
|
if (l) {
|
||||||
|
const beforeRemove = children[0].beforeRemove;
|
||||||
|
for (let i = 0; i < l; i++) {
|
||||||
|
beforeRemove.call(children[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
const { parentEl, anchor } = this;
|
||||||
|
if (this.isOnlyChild) {
|
||||||
|
nodeSetTextContent.call(parentEl, "");
|
||||||
|
} else {
|
||||||
|
const children = this.children;
|
||||||
|
const l = children.length;
|
||||||
|
if (l) {
|
||||||
|
const remove = children[0].remove;
|
||||||
|
for (let i = 0; i < l; i++) {
|
||||||
|
remove.call(children[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodeRemoveChild.call(parentEl, anchor!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node | undefined {
|
||||||
|
const child = this.children[0];
|
||||||
|
return child ? child.firstNode() : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.children.map((c) => c!.toString()).join("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function list(children: VNode[]): VNode<VList> {
|
||||||
|
return new VList(children);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMapping(ch1: any[], startIdx1: number, endIdx2: number): { [key: string]: any } {
|
||||||
|
let mapping: any = {};
|
||||||
|
for (let i = startIdx1; i <= endIdx2; i++) {
|
||||||
|
mapping[ch1[i].key] = i;
|
||||||
|
}
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import type { VNode } from "./index";
|
||||||
|
|
||||||
|
const getDescriptor = (o: any, p: any) => Object.getOwnPropertyDescriptor(o, p)!;
|
||||||
|
const nodeProto = Node.prototype;
|
||||||
|
const nodeInsertBefore = nodeProto.insertBefore;
|
||||||
|
const nodeSetTextContent = getDescriptor(nodeProto, "textContent").set!;
|
||||||
|
const nodeRemoveChild = nodeProto.removeChild;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Multi NODE
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export class VMulti {
|
||||||
|
children: (VNode | undefined)[];
|
||||||
|
anchors?: Node[] | undefined;
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
isOnlyChild?: boolean | undefined;
|
||||||
|
|
||||||
|
constructor(children: (VNode | undefined)[]) {
|
||||||
|
this.children = children;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
const children = this.children;
|
||||||
|
const l = children.length;
|
||||||
|
const anchors = new Array(l);
|
||||||
|
for (let i = 0; i < l; i++) {
|
||||||
|
let child = children[i];
|
||||||
|
if (child) {
|
||||||
|
child.mount(parent, afterNode);
|
||||||
|
} else {
|
||||||
|
const childAnchor = document.createTextNode("");
|
||||||
|
anchors[i] = childAnchor;
|
||||||
|
nodeInsertBefore.call(parent, childAnchor, afterNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.anchors = anchors;
|
||||||
|
this.parentEl = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: VMulti | null, afterNode: Node | null) {
|
||||||
|
if (other) {
|
||||||
|
const next = other!.children[0];
|
||||||
|
afterNode = (next ? next.firstNode() : other!.anchors![0]) || null;
|
||||||
|
}
|
||||||
|
const children = this.children;
|
||||||
|
const parent = this.parentEl;
|
||||||
|
const anchors = this.anchors;
|
||||||
|
for (let i = 0, l = children.length; i < l; i++) {
|
||||||
|
let child = children[i];
|
||||||
|
if (child) {
|
||||||
|
child.moveBefore(null, afterNode);
|
||||||
|
} else {
|
||||||
|
const anchor = anchors![i];
|
||||||
|
nodeInsertBefore.call(parent, anchor, afterNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VMulti, withBeforeRemove: boolean) {
|
||||||
|
if (this === other) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const children1 = this.children;
|
||||||
|
const children2 = other.children;
|
||||||
|
const anchors = this.anchors!;
|
||||||
|
const parentEl = this.parentEl!;
|
||||||
|
for (let i = 0, l = children1.length; i < l; i++) {
|
||||||
|
const vn1 = children1[i];
|
||||||
|
const vn2 = children2[i];
|
||||||
|
if (vn1) {
|
||||||
|
if (vn2) {
|
||||||
|
vn1.patch(vn2, withBeforeRemove);
|
||||||
|
} else {
|
||||||
|
const afterNode = vn1.firstNode()!;
|
||||||
|
const anchor = document.createTextNode("");
|
||||||
|
anchors[i] = anchor;
|
||||||
|
nodeInsertBefore.call(parentEl, anchor, afterNode);
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
vn1.beforeRemove();
|
||||||
|
}
|
||||||
|
vn1.remove();
|
||||||
|
children1[i] = undefined;
|
||||||
|
}
|
||||||
|
} else if (vn2) {
|
||||||
|
children1[i] = vn2;
|
||||||
|
const anchor = anchors[i];
|
||||||
|
vn2.mount(parentEl, anchor);
|
||||||
|
nodeRemoveChild.call(parentEl, anchor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {
|
||||||
|
const children = this.children;
|
||||||
|
for (let i = 0, l = children.length; i < l; i++) {
|
||||||
|
const child = children[i];
|
||||||
|
if (child) {
|
||||||
|
child.beforeRemove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
const parentEl = this.parentEl;
|
||||||
|
if (this.isOnlyChild) {
|
||||||
|
nodeSetTextContent.call(parentEl, "");
|
||||||
|
} else {
|
||||||
|
const children = this.children;
|
||||||
|
const anchors = this.anchors;
|
||||||
|
for (let i = 0, l = children.length; i < l; i++) {
|
||||||
|
const child = children[i];
|
||||||
|
if (child) {
|
||||||
|
child.remove();
|
||||||
|
} else {
|
||||||
|
nodeRemoveChild.call(parentEl, anchors![i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node | undefined {
|
||||||
|
const child = this.children[0];
|
||||||
|
return child ? child.firstNode() : this.anchors![0];
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.children.map((c) => c!.toString()).join("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function multi(children: (VNode | undefined)[]): VNode<VMulti> {
|
||||||
|
return new VMulti(children);
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { VNode } from "./index";
|
||||||
|
|
||||||
|
const getDescriptor = (o: any, p: any) => Object.getOwnPropertyDescriptor(o, p)!;
|
||||||
|
const nodeProto = Node.prototype;
|
||||||
|
const characterDataProto = CharacterData.prototype;
|
||||||
|
|
||||||
|
const nodeInsertBefore = nodeProto.insertBefore;
|
||||||
|
const characterDataSetData = getDescriptor(characterDataProto, "data").set!;
|
||||||
|
const nodeRemoveChild = nodeProto.removeChild;
|
||||||
|
|
||||||
|
class VText {
|
||||||
|
text: string;
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
el?: Text;
|
||||||
|
|
||||||
|
constructor(text: string) {
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
this.parentEl = parent;
|
||||||
|
const node = document.createTextNode(toText(this.text));
|
||||||
|
nodeInsertBefore.call(parent, node, afterNode);
|
||||||
|
this.el = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: VText | null, afterNode: Node | null) {
|
||||||
|
const target = other ? other.el! : afterNode;
|
||||||
|
nodeInsertBefore.call(this.parentEl, this.el!, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VText) {
|
||||||
|
const text2 = other.text;
|
||||||
|
if (this.text !== text2) {
|
||||||
|
characterDataSetData.call(this.el!, toText(text2));
|
||||||
|
this.text = text2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
nodeRemoveChild.call(this.parentEl, this.el!);
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node {
|
||||||
|
return this.el!;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return this.text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function text(str: string): VNode<VText> {
|
||||||
|
return new VText(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toText(value: any): string {
|
||||||
|
switch (typeof value) {
|
||||||
|
case "string":
|
||||||
|
return value;
|
||||||
|
case "number":
|
||||||
|
return String(value);
|
||||||
|
case "boolean":
|
||||||
|
return value ? "true" : "false";
|
||||||
|
default:
|
||||||
|
return value || "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { VNode } from "./index";
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Toggler node
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class VToggler {
|
||||||
|
key: string;
|
||||||
|
child: VNode;
|
||||||
|
|
||||||
|
parentEl?: HTMLElement | undefined;
|
||||||
|
|
||||||
|
constructor(key: string, child: VNode) {
|
||||||
|
this.key = key;
|
||||||
|
this.child = child;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, afterNode: Node | null) {
|
||||||
|
this.parentEl = parent;
|
||||||
|
this.child.mount(parent, afterNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: VToggler | null, afterNode: Node | null) {
|
||||||
|
this.child.moveBefore(other ? other.child : null, afterNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VToggler, withBeforeRemove: boolean) {
|
||||||
|
if (this === other) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let child1 = this.child;
|
||||||
|
let child2 = other.child;
|
||||||
|
if (this.key === other.key) {
|
||||||
|
child1.patch(child2, withBeforeRemove);
|
||||||
|
} else {
|
||||||
|
child2.mount(this.parentEl!, child1.firstNode()!);
|
||||||
|
if (withBeforeRemove) {
|
||||||
|
child1.beforeRemove();
|
||||||
|
}
|
||||||
|
child1.remove();
|
||||||
|
this.child = child2;
|
||||||
|
this.key = other.key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
this.child.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
firstNode(): Node | undefined {
|
||||||
|
return this.child.firstNode();
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.child.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toggler(key: string, child: VNode): VNode<VToggler> {
|
||||||
|
return new VToggler(key, child);
|
||||||
|
}
|
||||||
+20
-655
@@ -1,664 +1,29 @@
|
|||||||
import { Observer } from "../core/observer";
|
import type { ComponentNode } from "./component_node";
|
||||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
|
||||||
import { h, patch, VNode } from "../vdom/index";
|
|
||||||
import "./directive";
|
|
||||||
import { Fiber } from "./fiber";
|
|
||||||
import "./props_validation";
|
|
||||||
import { Scheduler } from "./scheduler";
|
|
||||||
|
|
||||||
/**
|
// -----------------------------------------------------------------------------
|
||||||
* Owl Component System
|
// Component Class
|
||||||
*
|
// -----------------------------------------------------------------------------
|
||||||
* This file introduces a declarative and composable component system. It
|
|
||||||
* contains:
|
|
||||||
*
|
|
||||||
* - the Env interface (generic type for the environment)
|
|
||||||
* - the Internal interface (the owl specific metadata attached to a component)
|
|
||||||
* - the Component class
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
export class Component {
|
||||||
// Types/helpers
|
static template: string = "";
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
const raf = window.requestAnimationFrame.bind(window);
|
|
||||||
export const scheduler = new Scheduler(raf);
|
|
||||||
|
|
||||||
/**
|
props: any;
|
||||||
* An Env (environment) is an object that will be (mostly) shared between all
|
env: any;
|
||||||
* components of an Owl application. It is the location which should contain
|
__owl__: ComponentNode;
|
||||||
* the qweb instance necessary to render all components.
|
|
||||||
*
|
|
||||||
* Note that it is totally fine to extend the environment with application
|
|
||||||
* specific keys/objects/whatever. For example, a key `isMobile` (to declare
|
|
||||||
* if we are in "mobile" mode), or a shared bus could be useful.
|
|
||||||
*/
|
|
||||||
export interface Env {
|
|
||||||
qweb: QWeb;
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
constructor(props: any, env: any, node: ComponentNode) {
|
||||||
* This is mostly an internal detail of implementation. The Meta interface is
|
this.props = props;
|
||||||
* useful to typecheck and describe the internal keys used by Owl to manage the
|
this.env = env;
|
||||||
* component tree.
|
this.__owl__ = node;
|
||||||
*/
|
}
|
||||||
interface Internal<T extends Env, Props> {
|
get el(): HTMLElement | Text | undefined {
|
||||||
// each component has a unique id, useful mostly to handle parent/child
|
const node = this.__owl__;
|
||||||
// relationships
|
return node.bdom ? (node.bdom.firstNode() as any) : undefined;
|
||||||
readonly id: number;
|
|
||||||
vnode: VNode | null;
|
|
||||||
pvnode: VNode | null;
|
|
||||||
isMounted: boolean;
|
|
||||||
isDestroyed: boolean;
|
|
||||||
|
|
||||||
// parent and children keys are obviously useful to setup the parent-children
|
|
||||||
// relationship.
|
|
||||||
parent: Component<T, any> | null;
|
|
||||||
children: { [key: number]: Component<T, any> };
|
|
||||||
// children mapping: from templateID to componentID. templateID identifies a
|
|
||||||
// place in a template. The t-component directive needs it to be able to get
|
|
||||||
// the component instance back whenever the template is rerendered.
|
|
||||||
cmap: { [key: number]: number };
|
|
||||||
|
|
||||||
currentFiber: Fiber | null;
|
|
||||||
|
|
||||||
boundHandlers: { [key: number]: any };
|
|
||||||
observer: Observer | null;
|
|
||||||
renderFn: CompiledTemplate;
|
|
||||||
mountedCB: Function | null;
|
|
||||||
willUnmountCB: Function | null;
|
|
||||||
willPatchCB: Function | null;
|
|
||||||
patchedCB: Function | null;
|
|
||||||
willStartCB: Function | null;
|
|
||||||
willUpdatePropsCB: Function | null;
|
|
||||||
classObj: { [key: string]: boolean } | null;
|
|
||||||
refs: { [key: string]: Component<T, any> | HTMLElement | undefined } | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Component
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
let nextId = 1;
|
|
||||||
|
|
||||||
export class Component<T extends Env, Props extends {}> {
|
|
||||||
readonly __owl__: Internal<Env, Props>;
|
|
||||||
static template?: string | null = null;
|
|
||||||
static _template?: string | null = null;
|
|
||||||
static current: Component<any, any> | null = null;
|
|
||||||
static components = {};
|
|
||||||
static props?: any;
|
|
||||||
static defaultProps?: any;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The `el` is the root element of the component. Note that it could be null:
|
|
||||||
* this is the case if the component is not mounted yet, or is destroyed.
|
|
||||||
*/
|
|
||||||
get el(): HTMLElement | null {
|
|
||||||
return this.__owl__.vnode ? (<any>this).__owl__.vnode.elm : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
env: T;
|
setup() {}
|
||||||
props: Props;
|
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
render(): Promise<void> {
|
||||||
// Lifecycle
|
return this.__owl__.render();
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates an instance of Component.
|
|
||||||
*
|
|
||||||
* The root component of a component tree needs an environment:
|
|
||||||
*
|
|
||||||
* ```javascript
|
|
||||||
* const root = new RootComponent(env, props);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* Every other component simply needs a reference to its parent:
|
|
||||||
*
|
|
||||||
* ```javascript
|
|
||||||
* const child = new SomeComponent(parent, props);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* Note that most of the time, only the root component needs to be created by
|
|
||||||
* hand. Other components should be created automatically by the framework (with
|
|
||||||
* the t-component directive in a template)
|
|
||||||
*/
|
|
||||||
constructor(parent: Component<T, any> | T, props?: Props) {
|
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
|
||||||
Component.current = this;
|
|
||||||
if (defaultProps) {
|
|
||||||
props = this.__applyDefaultProps(props, defaultProps);
|
|
||||||
}
|
|
||||||
// is this a good idea?
|
|
||||||
// Pro: if props is empty, we can create easily a component
|
|
||||||
// Con: this is not really safe
|
|
||||||
// Pro: but creating component (by a template) is always unsafe anyway
|
|
||||||
this.props = <Props>props || <Props>{};
|
|
||||||
if (QWeb.dev) {
|
|
||||||
QWeb.utils.validateProps(this.constructor, this.props);
|
|
||||||
}
|
|
||||||
let id: number = nextId++;
|
|
||||||
let p: Component<T, any> | null = null;
|
|
||||||
if (parent instanceof Component) {
|
|
||||||
p = parent;
|
|
||||||
this.env = parent.env;
|
|
||||||
parent.__owl__.children[id] = this;
|
|
||||||
} else {
|
|
||||||
this.env = parent;
|
|
||||||
this.env.qweb.on("update", this, () => {
|
|
||||||
if (this.__owl__.isMounted) {
|
|
||||||
this.render(true);
|
|
||||||
}
|
|
||||||
if (this.__owl__.isDestroyed) {
|
|
||||||
// this is unlikely to happen, but if a root widget is destroyed,
|
|
||||||
// we want to remove our subscription. The usual way to do that
|
|
||||||
// would be to perform some check in the destroy method, but since
|
|
||||||
// it is very performance sensitive, and since this is a rare event,
|
|
||||||
// we simply do it lazily
|
|
||||||
this.env.qweb.off("update", this);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const qweb = this.env.qweb;
|
|
||||||
|
|
||||||
this.__owl__ = {
|
|
||||||
id: id,
|
|
||||||
vnode: null,
|
|
||||||
pvnode: null,
|
|
||||||
isMounted: false,
|
|
||||||
isDestroyed: false,
|
|
||||||
parent: p,
|
|
||||||
children: {},
|
|
||||||
cmap: {},
|
|
||||||
currentFiber: null,
|
|
||||||
boundHandlers: {},
|
|
||||||
mountedCB: null,
|
|
||||||
willUnmountCB: null,
|
|
||||||
willPatchCB: null,
|
|
||||||
patchedCB: null,
|
|
||||||
willStartCB: null,
|
|
||||||
willUpdatePropsCB: null,
|
|
||||||
observer: null,
|
|
||||||
renderFn: qweb.render.bind(qweb, this.__getTemplate(qweb)),
|
|
||||||
classObj: null,
|
|
||||||
refs: null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* willStart is an asynchronous hook that can be implemented to perform some
|
|
||||||
* action before the initial rendering of a component.
|
|
||||||
*
|
|
||||||
* It will be called exactly once before the initial rendering. It is useful
|
|
||||||
* in some cases, for example, to load external assets (such as a JS library)
|
|
||||||
* before the component is rendered.
|
|
||||||
*
|
|
||||||
* Note that a slow willStart method will slow down the rendering of the user
|
|
||||||
* interface. Therefore, some effort should be made to make this method as
|
|
||||||
* fast as possible.
|
|
||||||
*
|
|
||||||
* Note: this method should not be called manually.
|
|
||||||
*/
|
|
||||||
async willStart() {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mounted is a hook that is called each time a component is attached to the
|
|
||||||
* DOM. This is a good place to add some listeners, or to interact with the
|
|
||||||
* DOM, if the component needs to perform some measure for example.
|
|
||||||
*
|
|
||||||
* Note: this method should not be called manually.
|
|
||||||
*
|
|
||||||
* @see willUnmount
|
|
||||||
*/
|
|
||||||
mounted() {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The willUpdateProps is an asynchronous hook, called just before new props
|
|
||||||
* are set. This is useful if the component needs some asynchronous task
|
|
||||||
* performed, depending on the props (for example, assuming that the props are
|
|
||||||
* some record Id, fetching the record data).
|
|
||||||
*
|
|
||||||
* This hook is not called during the first render (but willStart is called
|
|
||||||
* and performs a similar job).
|
|
||||||
*/
|
|
||||||
async willUpdateProps(nextProps: Props) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The willPatch hook is called just before the DOM patching process starts.
|
|
||||||
* It is not called on the initial render. This is useful to get some
|
|
||||||
* information which are in the DOM. For example, the current position of the
|
|
||||||
* scrollbar
|
|
||||||
*/
|
|
||||||
willPatch(): any {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This hook is called whenever a component did actually update its props,
|
|
||||||
* state or env.
|
|
||||||
*
|
|
||||||
* This method is not called on the initial render. It is useful to interact
|
|
||||||
* with the DOM (for example, through an external library) whenever the
|
|
||||||
* component was updated.
|
|
||||||
*
|
|
||||||
* Updating the component state in this hook is possible, but not encouraged.
|
|
||||||
* One need to be careful, because updates here will cause rerender, which in
|
|
||||||
* turn will cause other calls to updated. So, we need to be particularly
|
|
||||||
* careful at avoiding endless cycles.
|
|
||||||
*/
|
|
||||||
patched() {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* willUnmount is a hook that is called each time just before a component is
|
|
||||||
* unmounted from the DOM. This is a good place to remove some listeners, for
|
|
||||||
* example.
|
|
||||||
*
|
|
||||||
* Note: this method should not be called manually.
|
|
||||||
*
|
|
||||||
* @see mounted
|
|
||||||
*/
|
|
||||||
willUnmount() {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* catchError is a method called whenever some error happens in the rendering or
|
|
||||||
* lifecycle hooks of a child.
|
|
||||||
*
|
|
||||||
* It needs to be implemented by a component that is designed to handle the
|
|
||||||
* error properly.
|
|
||||||
*/
|
|
||||||
catchError?(error?: Error): void;
|
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
// Public
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mount the component to a target element.
|
|
||||||
*
|
|
||||||
* This should only be done if the component was created manually. Components
|
|
||||||
* created declaratively in templates are managed by the Owl system.
|
|
||||||
*
|
|
||||||
* Note that a component can be mounted an unmounted several times
|
|
||||||
*/
|
|
||||||
async mount(target: HTMLElement, renderBeforeRemount: boolean = false): Promise<void> {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (__owl__.isMounted) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
if (__owl__.vnode && !renderBeforeRemount) {
|
|
||||||
target.appendChild(this.el!);
|
|
||||||
if (document.body.contains(target)) {
|
|
||||||
this.__callMounted();
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, false);
|
|
||||||
if (!__owl__.vnode) {
|
|
||||||
this.__prepareAndRender(fiber);
|
|
||||||
} else {
|
|
||||||
this.__render(fiber);
|
|
||||||
}
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
scheduler.addFiber(fiber, err => {
|
|
||||||
if (err) {
|
|
||||||
reject(err);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!__owl__.isDestroyed) {
|
|
||||||
this.__patch(fiber.vnode);
|
|
||||||
target.appendChild(this.el!);
|
|
||||||
if (document.body.contains(target)) {
|
|
||||||
this.__callMounted();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The unmount method is the opposite of the mount method. It is useful
|
|
||||||
* to call willUnmount calls and remove the component from the DOM.
|
|
||||||
*/
|
|
||||||
unmount() {
|
|
||||||
if (this.__owl__.isMounted) {
|
|
||||||
this.__callWillUnmount();
|
|
||||||
this.el!.remove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The render method is the main entry point to render a component (once it
|
|
||||||
* is ready. This method is not initially called when the component is
|
|
||||||
* rendered the first time).
|
|
||||||
*
|
|
||||||
* This method will cause all its sub components to potentially rerender
|
|
||||||
* themselves. Note that `render` is not called if a component is updated via
|
|
||||||
* its props.
|
|
||||||
*/
|
|
||||||
async render(force: boolean = false): Promise<void> {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (
|
|
||||||
(!__owl__.isMounted && !__owl__.currentFiber) ||
|
|
||||||
(__owl__.currentFiber && !__owl__.currentFiber.isRendered)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, force);
|
|
||||||
this.__render(fiber);
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
scheduler.addFiber(fiber.root, err => {
|
|
||||||
if (err) {
|
|
||||||
reject(err);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (__owl__.isMounted && fiber === fiber.root) {
|
|
||||||
fiber.patchComponents();
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Destroy the component. This operation is quite complex:
|
|
||||||
* - it recursively destroy all children
|
|
||||||
* - call the willUnmount hooks if necessary
|
|
||||||
* - remove the dom node from the dom
|
|
||||||
*
|
|
||||||
* This should only be called manually if you created the component. Most
|
|
||||||
* components will be automatically destroyed.
|
|
||||||
*/
|
|
||||||
destroy() {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (!__owl__.isDestroyed) {
|
|
||||||
const el = this.el;
|
|
||||||
this.__destroy(__owl__.parent);
|
|
||||||
if (el) {
|
|
||||||
el.remove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This method is called by the component system whenever its props are
|
|
||||||
* updated. If it returns true, then the component will be rendered.
|
|
||||||
* Otherwise, it will skip the rendering (also, its props will not be updated)
|
|
||||||
*/
|
|
||||||
shouldUpdate(nextProps: Props): boolean {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emit a custom event of type 'eventType' with the given 'payload' on the
|
|
||||||
* component's el, if it exists. However, note that the event will only bubble
|
|
||||||
* up to the parent DOM nodes. Thus, it must be called between mounted() and
|
|
||||||
* willUnmount().
|
|
||||||
*/
|
|
||||||
trigger(eventType: string, payload?: any) {
|
|
||||||
if (this.el) {
|
|
||||||
const ev = new CustomEvent(eventType, {
|
|
||||||
bubbles: true,
|
|
||||||
cancelable: true,
|
|
||||||
detail: payload
|
|
||||||
});
|
|
||||||
this.el.dispatchEvent(ev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
// Private
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Private helper to perform a full destroy, from the point of view of an Owl
|
|
||||||
* component. It does not remove the el (this is done only once on the top
|
|
||||||
* level destroyed component, for performance reasons).
|
|
||||||
*
|
|
||||||
* The job of this method is mostly to call willUnmount hooks, and to perform
|
|
||||||
* all necessary internal cleanup.
|
|
||||||
*
|
|
||||||
* Note that it does not call the __callWillUnmount method to avoid visiting
|
|
||||||
* all children many times.
|
|
||||||
*/
|
|
||||||
__destroy(parent: Component<any, any> | null) {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
const isMounted = __owl__.isMounted;
|
|
||||||
if (isMounted) {
|
|
||||||
if (__owl__.willUnmountCB) {
|
|
||||||
__owl__.willUnmountCB();
|
|
||||||
}
|
|
||||||
this.willUnmount();
|
|
||||||
__owl__.isMounted = false;
|
|
||||||
}
|
|
||||||
const children = __owl__.children;
|
|
||||||
for (let key in children) {
|
|
||||||
children[key].__destroy(this);
|
|
||||||
}
|
|
||||||
if (parent) {
|
|
||||||
let id = __owl__.id;
|
|
||||||
delete parent.__owl__.children[id];
|
|
||||||
__owl__.parent = null;
|
|
||||||
}
|
|
||||||
__owl__.isDestroyed = true;
|
|
||||||
delete __owl__.vnode;
|
|
||||||
}
|
|
||||||
|
|
||||||
__callMounted() {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
const children = __owl__.children;
|
|
||||||
for (let id in children) {
|
|
||||||
const comp = children[id];
|
|
||||||
if (!comp.__owl__.isMounted && this.el!.contains(comp.el)) {
|
|
||||||
comp.__callMounted();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
__owl__.isMounted = true;
|
|
||||||
try {
|
|
||||||
this.mounted();
|
|
||||||
if (__owl__.mountedCB) {
|
|
||||||
__owl__.mountedCB();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e); // TODO : add a test
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
__callWillUnmount() {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (__owl__.willUnmountCB) {
|
|
||||||
__owl__.willUnmountCB();
|
|
||||||
}
|
|
||||||
this.willUnmount();
|
|
||||||
__owl__.isMounted = false;
|
|
||||||
const children = __owl__.children;
|
|
||||||
for (let id in children) {
|
|
||||||
const comp = children[id];
|
|
||||||
if (comp.__owl__.isMounted) {
|
|
||||||
comp.__callWillUnmount();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The __updateProps method is called by the t-component directive whenever
|
|
||||||
* it updates a component (so, when the parent template is rerendered).
|
|
||||||
*/
|
|
||||||
async __updateProps(
|
|
||||||
nextProps: Props,
|
|
||||||
parentFiber: Fiber,
|
|
||||||
scope: any,
|
|
||||||
vars: any,
|
|
||||||
previousSibling?: Fiber | null
|
|
||||||
): Promise<void> {
|
|
||||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
|
||||||
if (shouldUpdate) {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
|
||||||
if (!parentFiber.child) {
|
|
||||||
parentFiber.child = fiber;
|
|
||||||
} else {
|
|
||||||
previousSibling!.sibling = fiber;
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
|
||||||
if (defaultProps) {
|
|
||||||
nextProps = this.__applyDefaultProps(nextProps, defaultProps);
|
|
||||||
}
|
|
||||||
if (QWeb.dev) {
|
|
||||||
QWeb.utils.validateProps(this.constructor, nextProps);
|
|
||||||
}
|
|
||||||
await Promise.all([
|
|
||||||
this.willUpdateProps(nextProps),
|
|
||||||
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps)
|
|
||||||
]);
|
|
||||||
if (fiber.isCancelled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.props = nextProps;
|
|
||||||
|
|
||||||
this.__render(fiber);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main patching method. We call the virtual dom patch method here to convert
|
|
||||||
* a virtual dom vnode into some actual dom.
|
|
||||||
*/
|
|
||||||
__patch(vnode) {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
|
||||||
__owl__.vnode = patch(target, vnode);
|
|
||||||
__owl__.currentFiber = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The __prepare method is only called by the t-component directive, when a
|
|
||||||
* subcomponent is created. It gets its scope and vars, if any, from the
|
|
||||||
* parent template.
|
|
||||||
*/
|
|
||||||
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
|
||||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
|
||||||
fiber.shouldPatch = false;
|
|
||||||
if (!parentFiber.child) {
|
|
||||||
parentFiber.child = fiber;
|
|
||||||
} else {
|
|
||||||
previousSibling!.sibling = fiber;
|
|
||||||
}
|
|
||||||
return this.__prepareAndRender(fiber);
|
|
||||||
}
|
|
||||||
|
|
||||||
__getTemplate(qweb: QWeb): string {
|
|
||||||
let p = (<any>this).constructor;
|
|
||||||
if (!p.hasOwnProperty("_template")) {
|
|
||||||
if (p.template) {
|
|
||||||
p._template = p.template;
|
|
||||||
} else {
|
|
||||||
// here, the component and none of its superclasses defines a static `template`
|
|
||||||
// key. So we fall back on looking for a template matching its name (or
|
|
||||||
// one of its subclass).
|
|
||||||
|
|
||||||
let template: string;
|
|
||||||
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
|
||||||
p = p.__proto__;
|
|
||||||
}
|
|
||||||
if (p === Component) {
|
|
||||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
|
||||||
} else {
|
|
||||||
p._template = template;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return p._template;
|
|
||||||
}
|
|
||||||
async __prepareAndRender(fiber: Fiber) {
|
|
||||||
try {
|
|
||||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
|
||||||
} catch (e) {
|
|
||||||
fiber.handleError(e);
|
|
||||||
fiber.vnode = h("div"); // -> we render this div at the end
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
if (this.__owl__.isDestroyed) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
if (!fiber.isCancelled) {
|
|
||||||
this.__render(fiber);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
__render(fiber: Fiber) {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (__owl__.observer) {
|
|
||||||
__owl__.observer.allowMutations = false;
|
|
||||||
}
|
|
||||||
let vnode;
|
|
||||||
try {
|
|
||||||
vnode = __owl__.renderFn!(this, {
|
|
||||||
handlers: __owl__.boundHandlers,
|
|
||||||
fiber: fiber
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
vnode = __owl__.vnode || h("div");
|
|
||||||
fiber.handleError(e);
|
|
||||||
}
|
|
||||||
fiber.vnode = vnode;
|
|
||||||
if (__owl__.observer) {
|
|
||||||
__owl__.observer.allowMutations = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// we apply here the class information described on the component by the
|
|
||||||
// template (so, something like <MyComponent class="..."/>) to the actual
|
|
||||||
// root vnode
|
|
||||||
if (__owl__.classObj) {
|
|
||||||
vnode.data.class = Object.assign(vnode.data.class || {}, __owl__.classObj);
|
|
||||||
}
|
|
||||||
fiber.root.counter--;
|
|
||||||
fiber.isRendered = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Only called by qweb t-component directive
|
|
||||||
*/
|
|
||||||
__mount(fiber: Fiber, elm: HTMLElement): VNode {
|
|
||||||
if (fiber !== this.__owl__.currentFiber) {
|
|
||||||
fiber = this.__owl__.currentFiber!; // TODO: check if we can remove fiber arg
|
|
||||||
}
|
|
||||||
const vnode = fiber.vnode!;
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (__owl__.classObj) {
|
|
||||||
(<any>vnode).data.class = Object.assign((<any>vnode).data.class || {}, __owl__.classObj);
|
|
||||||
}
|
|
||||||
__owl__.vnode = patch(elm, vnode);
|
|
||||||
__owl__.currentFiber = null;
|
|
||||||
if (__owl__.parent!.__owl__.isMounted && !__owl__.isMounted) {
|
|
||||||
this.__callMounted();
|
|
||||||
}
|
|
||||||
return __owl__.vnode;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Only called by qweb t-component directive (when t-keepalive is set)
|
|
||||||
*/
|
|
||||||
__remount() {
|
|
||||||
const __owl__ = this.__owl__;
|
|
||||||
if (!__owl__.isMounted) {
|
|
||||||
__owl__.isMounted = true;
|
|
||||||
this.mounted();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply default props (only top level).
|
|
||||||
*
|
|
||||||
* Note that this method does not modify in place the props, it returns a new
|
|
||||||
* prop object
|
|
||||||
*/
|
|
||||||
__applyDefaultProps(props: Object | undefined, defaultProps: Object): Props {
|
|
||||||
props = props ? Object.assign({}, props) : {};
|
|
||||||
for (let propName in defaultProps) {
|
|
||||||
if (props![propName] === undefined) {
|
|
||||||
props![propName] = defaultProps[propName];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return <Props>props;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
import type { App } from "../app";
|
||||||
|
import { BDom, VNode } from "../blockdom";
|
||||||
|
import { Component } from "./component";
|
||||||
|
import {
|
||||||
|
Fiber,
|
||||||
|
makeChildFiber,
|
||||||
|
makeRootFiber,
|
||||||
|
MountFiber,
|
||||||
|
RootFiber,
|
||||||
|
__internal__destroyed,
|
||||||
|
} from "./fibers";
|
||||||
|
import { STATUS } from "./status";
|
||||||
|
|
||||||
|
export function component(
|
||||||
|
name: string | typeof Component,
|
||||||
|
props: any,
|
||||||
|
key: string,
|
||||||
|
ctx: ComponentNode,
|
||||||
|
parent: any
|
||||||
|
): ComponentNode {
|
||||||
|
let node: any = ctx.children[key];
|
||||||
|
let isDynamic = typeof name !== "string";
|
||||||
|
|
||||||
|
if (node && node.status < STATUS.MOUNTED) {
|
||||||
|
node.destroy();
|
||||||
|
node = undefined;
|
||||||
|
}
|
||||||
|
if (isDynamic && node && node.component.constructor !== name) {
|
||||||
|
node = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentFiber = ctx.fiber!;
|
||||||
|
if (node) {
|
||||||
|
node.updateAndRender(props, parentFiber);
|
||||||
|
} else {
|
||||||
|
// new component
|
||||||
|
const C = isDynamic ? name : parent.constructor.components[name as any];
|
||||||
|
node = new ComponentNode(C, props, ctx.app);
|
||||||
|
ctx.children[key] = node;
|
||||||
|
|
||||||
|
const fiber = makeChildFiber(node, parentFiber);
|
||||||
|
node.initiateRender(fiber);
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Component VNode
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let currentNode: ComponentNode | null = null;
|
||||||
|
|
||||||
|
export function getCurrent(): ComponentNode | null {
|
||||||
|
return currentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LifecycleHook = Function;
|
||||||
|
|
||||||
|
export class ComponentNode<T extends typeof Component = any> implements VNode<ComponentNode> {
|
||||||
|
el?: HTMLElement | Text | undefined;
|
||||||
|
handlers: any = null;
|
||||||
|
app: App;
|
||||||
|
fiber: Fiber | null = null;
|
||||||
|
component: InstanceType<T>;
|
||||||
|
bdom: BDom | null = null;
|
||||||
|
status: STATUS = STATUS.NEW;
|
||||||
|
|
||||||
|
renderFn: Function;
|
||||||
|
children: { [key: string]: ComponentNode } = Object.create(null);
|
||||||
|
slots: any = {};
|
||||||
|
refs: any = {};
|
||||||
|
|
||||||
|
willStart: LifecycleHook[] = [];
|
||||||
|
willUpdateProps: LifecycleHook[] = [];
|
||||||
|
willUnmount: LifecycleHook[] = [];
|
||||||
|
mounted: LifecycleHook[] = [];
|
||||||
|
willPatch: LifecycleHook[] = [];
|
||||||
|
patched: LifecycleHook[] = [];
|
||||||
|
destroyed: LifecycleHook[] = [];
|
||||||
|
|
||||||
|
constructor(C: T, props: any, app: App) {
|
||||||
|
currentNode = this;
|
||||||
|
this.app = app;
|
||||||
|
this.component = new C(props, app.env, this) as any;
|
||||||
|
this.renderFn = app.getTemplate(C.template).bind(null, this.component, this);
|
||||||
|
this.component.setup();
|
||||||
|
}
|
||||||
|
|
||||||
|
mountComponent(target: any): Promise<InstanceType<T>> {
|
||||||
|
const fiber = new MountFiber(this, target);
|
||||||
|
this.app.scheduler.addFiber(fiber);
|
||||||
|
this.initiateRender(fiber);
|
||||||
|
return fiber.promise.then(() => this.component);
|
||||||
|
}
|
||||||
|
|
||||||
|
async initiateRender(fiber: Fiber | MountFiber) {
|
||||||
|
if (this.mounted.length) {
|
||||||
|
fiber.root.mounted.push(fiber);
|
||||||
|
}
|
||||||
|
const component = this.component;
|
||||||
|
const prom = Promise.all(this.willStart.map((f) => f.call(component)));
|
||||||
|
await prom;
|
||||||
|
if (this.status === STATUS.NEW && this.fiber === fiber) {
|
||||||
|
this._render(fiber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async render() {
|
||||||
|
if (this.fiber && !this.fiber.bdom) {
|
||||||
|
return this.fiber.root.promise;
|
||||||
|
}
|
||||||
|
if (!this.bdom && !this.fiber) {
|
||||||
|
// should find a way to return the future mounting promise
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fiber = makeRootFiber(this);
|
||||||
|
this.app.scheduler.addFiber(fiber);
|
||||||
|
await Promise.resolve();
|
||||||
|
if (this.status === STATUS.DESTROYED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.fiber === fiber) {
|
||||||
|
this._render(fiber);
|
||||||
|
}
|
||||||
|
return fiber.root.promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
_render(fiber: Fiber | RootFiber) {
|
||||||
|
try {
|
||||||
|
fiber.bdom = this.renderFn();
|
||||||
|
} catch (e) {
|
||||||
|
fiber.root.error = e;
|
||||||
|
this.handleError(fiber);
|
||||||
|
}
|
||||||
|
fiber.root.counter--;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleError(fiber: Fiber) {
|
||||||
|
fiber.node.app.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
if (this.status === STATUS.MOUNTED) {
|
||||||
|
callWillUnmount(this);
|
||||||
|
this.bdom!.remove();
|
||||||
|
}
|
||||||
|
callDestroyed(this);
|
||||||
|
|
||||||
|
function callWillUnmount(node: ComponentNode) {
|
||||||
|
const component = node.component;
|
||||||
|
for (let cb of node.willUnmount) {
|
||||||
|
cb.call(component);
|
||||||
|
}
|
||||||
|
for (let child of Object.values(node.children)) {
|
||||||
|
if (child.status === STATUS.MOUNTED) {
|
||||||
|
callWillUnmount(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function callDestroyed(node: ComponentNode) {
|
||||||
|
const component = node.component;
|
||||||
|
node.status = STATUS.DESTROYED;
|
||||||
|
for (let child of Object.values(node.children)) {
|
||||||
|
callDestroyed(child);
|
||||||
|
}
|
||||||
|
for (let cb of node.destroyed) {
|
||||||
|
cb.call(component);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateAndRender(props: any, parentFiber: Fiber) {
|
||||||
|
// update
|
||||||
|
const fiber = makeChildFiber(this, parentFiber);
|
||||||
|
if (this.willPatch.length) {
|
||||||
|
parentFiber.root.willPatch.push(fiber);
|
||||||
|
}
|
||||||
|
if (this.patched.length) {
|
||||||
|
parentFiber.root.patched.push(fiber);
|
||||||
|
}
|
||||||
|
const component = this.component;
|
||||||
|
const prom = Promise.all(this.willUpdateProps.map((f) => f.call(component, props)));
|
||||||
|
await prom;
|
||||||
|
if (fiber !== this.fiber) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.component.props = props;
|
||||||
|
this._render(fiber);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Block DOM methods
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
firstNode(): Node | undefined {
|
||||||
|
const bdom = this.bdom;
|
||||||
|
return bdom ? bdom.firstNode() : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(parent: HTMLElement, anchor: ChildNode) {
|
||||||
|
const bdom = this.fiber!.bdom!;
|
||||||
|
this.bdom = bdom;
|
||||||
|
bdom.mount(parent, anchor);
|
||||||
|
this.status = STATUS.MOUNTED;
|
||||||
|
this.fiber!.appliedToDom = true;
|
||||||
|
this.fiber = null;
|
||||||
|
if (this.handlers) {
|
||||||
|
for (let i = 0; i < this.handlers.length; i++) {
|
||||||
|
const handler = this.handlers[i];
|
||||||
|
const eventType = handler[0];
|
||||||
|
const el = bdom.el!;
|
||||||
|
el.addEventListener(eventType, (ev: Event) => {
|
||||||
|
const info = this.handlers![i];
|
||||||
|
const [, ctx, method] = info;
|
||||||
|
(ctx.__owl__.component as any)[method](ev);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
moveBefore(other: ComponentNode | null, afterNode: Node | null) {
|
||||||
|
this.bdom!.moveBefore(other ? other.bdom : null, afterNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
patch() {
|
||||||
|
this.bdom!.patch(this!.fiber!.bdom!, false);
|
||||||
|
this.fiber!.appliedToDom = true;
|
||||||
|
this.fiber = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {
|
||||||
|
visitRemovedNodes(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
this.bdom!.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function visitRemovedNodes(node: ComponentNode) {
|
||||||
|
if (node.status === STATUS.MOUNTED) {
|
||||||
|
const component = node.component;
|
||||||
|
for (let cb of node.willUnmount) {
|
||||||
|
cb.call(component);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let child of Object.values(node.children)) {
|
||||||
|
visitRemovedNodes(child);
|
||||||
|
}
|
||||||
|
node.status = STATUS.DESTROYED;
|
||||||
|
if (node.destroyed.length) {
|
||||||
|
__internal__destroyed.push(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,497 +0,0 @@
|
|||||||
import { QWeb } from "../qweb/index";
|
|
||||||
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
|
||||||
import { MODS_CODE } from "../qweb/extensions";
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-component
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
|
||||||
self: "if (e.target !== vn.elm) {return}"
|
|
||||||
});
|
|
||||||
|
|
||||||
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
|
||||||
for (let k in source) {
|
|
||||||
Object.defineProperty(target, k, {
|
|
||||||
get() {
|
|
||||||
return source[k];
|
|
||||||
},
|
|
||||||
set(val) {
|
|
||||||
source[k] = val;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The t-component directive is certainly a complicated and hard to maintain piece
|
|
||||||
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
|
||||||
* you this advice: Good luck...
|
|
||||||
*
|
|
||||||
* Since it is not 'direct' code, but rather code that generates other code, it
|
|
||||||
* is not easy to understand. To help you, here is a detailed and commented
|
|
||||||
* explanation of the code generated by the t-component directive for the following
|
|
||||||
* situation:
|
|
||||||
* ```xml
|
|
||||||
* <Child
|
|
||||||
* t-key="'somestring'"
|
|
||||||
* flag="state.flag"
|
|
||||||
* t-transition="fade"/>
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* ```js
|
|
||||||
* // we assign utils on top of the function because it will be useful for
|
|
||||||
* // each components
|
|
||||||
* let utils = this.utils;
|
|
||||||
*
|
|
||||||
* // this is the virtual node representing the parent div
|
|
||||||
* let c1 = [], p1 = { key: 1 };
|
|
||||||
* var vn1 = h("div", p1, c1);
|
|
||||||
*
|
|
||||||
* // t-component directive: we start by evaluating the expression given by t-key:
|
|
||||||
* let key5 = "somestring";
|
|
||||||
*
|
|
||||||
* // def3 is the promise that will contain later either the new component
|
|
||||||
* // creation, or the props update...
|
|
||||||
* let def3;
|
|
||||||
*
|
|
||||||
* // this is kind of tricky: we need here to find if the component was already
|
|
||||||
* // created by a previous rendering. This is done by checking the internal
|
|
||||||
* // `cmap` (children map) of the parent component: it maps keys to component ids,
|
|
||||||
* // and, then, if there is an id, we look into the children list to get the
|
|
||||||
* // instance
|
|
||||||
* let w4 =
|
|
||||||
* key5 in context.__owl__.cmap
|
|
||||||
* ? context.__owl__.children[context.__owl__.cmap[key5]]
|
|
||||||
* : false;
|
|
||||||
*
|
|
||||||
* // We keep the index of the position of the component in the closure. We push
|
|
||||||
* // null to reserve the slot, and will replace it later by the component vnode,
|
|
||||||
* // when it will be ready (do not forget that preparing/rendering a component is
|
|
||||||
* // asynchronous)
|
|
||||||
* let _2_index = c1.length;
|
|
||||||
* c1.push(null);
|
|
||||||
*
|
|
||||||
* // we evaluate here the props given to the component. It is done here to be
|
|
||||||
* // able to easily reference it later, and also, it might be an expensive
|
|
||||||
* // computation, so it is certainly better to do it only once
|
|
||||||
* let props4 = { flag: context["state"].flag };
|
|
||||||
*
|
|
||||||
* // If we have a component, currently rendering, but not ready yet, we do not want
|
|
||||||
* // to wait for it to be ready if we can avoid it
|
|
||||||
* if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
|
||||||
* // we check if the props are the same. In that case, we can simply reuse
|
|
||||||
* // the previous rendering and skip all useless work
|
|
||||||
* if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
|
||||||
* def3 = w4.__owl__.renderPromise;
|
|
||||||
* } else {
|
|
||||||
* // if the props are not the same, we destroy the component and starts anew.
|
|
||||||
* // this will be faster than waiting for its rendering, then updating it
|
|
||||||
* w4.destroy();
|
|
||||||
* w4 = false;
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* if (!w4) {
|
|
||||||
* // in this situation, we need to create a new component. First step is
|
|
||||||
* // to get a reference to the class, then create an instance with
|
|
||||||
* // current context as parent, and the props.
|
|
||||||
* let W4 = context.component && context.components[componentKey4] || QWeb.component[componentKey4];
|
|
||||||
|
|
||||||
* if (!W4) {
|
|
||||||
* throw new Error("Cannot find the definition of component 'child'");
|
|
||||||
* }
|
|
||||||
* w4 = new W4(owner, props4);
|
|
||||||
*
|
|
||||||
* // Whenever we rerender the parent component, we need to be sure that we
|
|
||||||
* // are able to find the component instance. To do that, we register it to
|
|
||||||
* // the parent cmap (children map). Note that the 'template' key is
|
|
||||||
* // used here, since this is what identify the component from the template
|
|
||||||
* // perspective.
|
|
||||||
* context.__owl__.cmap[key5] = w4.__owl__.id;
|
|
||||||
*
|
|
||||||
* // __prepare is called, to basically call willStart, then render the
|
|
||||||
* // component
|
|
||||||
* def3 = w4.__prepare();
|
|
||||||
*
|
|
||||||
* def3 = def3.then(vnode => {
|
|
||||||
* // we create here a virtual node for the parent (NOT the component). This
|
|
||||||
* // means that the vdom of the parent will be stopped here, and from
|
|
||||||
* // the parent's perspective, it simply is a vnode with no children.
|
|
||||||
* // However, it shares the same dom element with the component root
|
|
||||||
* // vnode.
|
|
||||||
* let pvnode = h(vnode.sel, { key: key5 });
|
|
||||||
*
|
|
||||||
* // we add hooks to the parent vnode so we can interact with the new
|
|
||||||
* // component at the proper time
|
|
||||||
* pvnode.data.hook = {
|
|
||||||
* insert(vn) {
|
|
||||||
* // the __mount method will patch the component vdom into the elm vn.elm,
|
|
||||||
* // then call the mounted hooks. However, suprisingly, the snabbdom
|
|
||||||
* // patch method actually replace the elm by a new elm, so we need
|
|
||||||
* // to synchronise the pvnode elm with the resulting elm
|
|
||||||
* let nvn = w4.__mount(vnode, vn.elm);
|
|
||||||
* pvnode.elm = nvn.elm;
|
|
||||||
* // what follows is only present if there are animations on the component
|
|
||||||
* utils.transitionInsert(vn, "fade");
|
|
||||||
* },
|
|
||||||
* remove() {
|
|
||||||
* // override with empty function to prevent from removing the node
|
|
||||||
* // directly. It will be removed when destroy is called anyway, which
|
|
||||||
* // delays the removal if there are animations.
|
|
||||||
* },
|
|
||||||
* destroy() {
|
|
||||||
* // if there are animations, we delay the call to destroy on the
|
|
||||||
* // component, if not, we call it directly.
|
|
||||||
* let finalize = () => {
|
|
||||||
* w4.destroy();
|
|
||||||
* };
|
|
||||||
* utils.transitionRemove(vn, "fade", finalize);
|
|
||||||
* }
|
|
||||||
* };
|
|
||||||
* // the pvnode is inserted at the correct position in the div's children
|
|
||||||
* c1[_2_index] = pvnode;
|
|
||||||
*
|
|
||||||
* // we keep here a reference to the parent vnode (representing the
|
|
||||||
* // component, so we can reuse it later whenever we update the component
|
|
||||||
* w4.__owl__.pvnode = pvnode;
|
|
||||||
* });
|
|
||||||
* } else {
|
|
||||||
* // this is the 'update' path of the directive.
|
|
||||||
* // the call to __updateProps is the actual component update
|
|
||||||
* // Note that we only update the props if we cannot reuse the previous
|
|
||||||
* // rendering work (in the case it was rendered with the same props)
|
|
||||||
* def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
|
||||||
* def3 = def3.then(() => {
|
|
||||||
* // if component was destroyed in the meantime, we do nothing (so, this
|
|
||||||
* // means that the parent's element children list will have a null in
|
|
||||||
* // the component's position, which will cause the pvnode to be removed
|
|
||||||
* // when it is patched.
|
|
||||||
* if (w4.__owl__.isDestroyed) {
|
|
||||||
* return;
|
|
||||||
* }
|
|
||||||
* // like above, we register the pvnode to the children list, so it
|
|
||||||
* // will not be patched out of the dom.
|
|
||||||
* let pvnode = w4.__owl__.pvnode;
|
|
||||||
* c1[_2_index] = pvnode;
|
|
||||||
* });
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* // we register the deferred here so the parent can coordinate its patch operation
|
|
||||||
* // with all the children.
|
|
||||||
* extra.promises.push(def3);
|
|
||||||
* return vn1;
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "component",
|
|
||||||
extraNames: ["props", "keepalive"],
|
|
||||||
priority: 100,
|
|
||||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
|
||||||
ctx.addLine("//COMPONENT");
|
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
ctx.rootContext.shouldDefineQWeb = true;
|
|
||||||
ctx.rootContext.shouldDefineParent = true;
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
|
||||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
|
||||||
|
|
||||||
// t-on- events and t-transition
|
|
||||||
const events: [string, string[], string, string][] = [];
|
|
||||||
let transition: string = "";
|
|
||||||
const attributes = (<Element>node).attributes;
|
|
||||||
const props: { [key: string]: string } = {};
|
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
|
||||||
const name = attributes[i].name;
|
|
||||||
const value = attributes[i].textContent!;
|
|
||||||
if (name.startsWith("t-on-")) {
|
|
||||||
const [eventName, ...mods] = name.slice(5).split(".");
|
|
||||||
let extraArgs;
|
|
||||||
let handlerValue = value.replace(/\(.*\)/, function(args) {
|
|
||||||
extraArgs = args.slice(1, -1);
|
|
||||||
return "";
|
|
||||||
});
|
|
||||||
events.push([eventName, mods, handlerValue, extraArgs]);
|
|
||||||
} else if (name === "t-transition") {
|
|
||||||
transition = value;
|
|
||||||
} else if (!name.startsWith("t-")) {
|
|
||||||
if (name !== "class" && name !== "style") {
|
|
||||||
// this is a prop!
|
|
||||||
props[name] = ctx.formatExpression(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// computing the props string representing the props object
|
|
||||||
let propStr = Object.keys(props)
|
|
||||||
.map(k => k + ":" + props[k])
|
|
||||||
.join(",");
|
|
||||||
let defID = ctx.generateID();
|
|
||||||
let componentID = ctx.generateID();
|
|
||||||
|
|
||||||
let locationExpr = `\`__${ctx.generateID()}__`;
|
|
||||||
for (let i = 0; i < ctx.loopNumber - 1; i++) {
|
|
||||||
locationExpr += `\${i${i + 1}}__`;
|
|
||||||
}
|
|
||||||
if (ctx.lastNodeKey || ctx.currentKey) {
|
|
||||||
const k = ctx.lastNodeKey || ctx.currentKey;
|
|
||||||
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
|
|
||||||
} else {
|
|
||||||
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
|
|
||||||
ctx.addLine(`let templateId${componentID} = ${locationExpr};`);
|
|
||||||
}
|
|
||||||
const templateId = `templateId${componentID}`;
|
|
||||||
|
|
||||||
let ref = node.getAttribute("t-ref");
|
|
||||||
let refExpr = "";
|
|
||||||
let refKey: string = "";
|
|
||||||
if (ref) {
|
|
||||||
ctx.rootContext.shouldDefineRefs = true;
|
|
||||||
refKey = `ref${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
|
||||||
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
|
||||||
}
|
|
||||||
let transitionsInsertCode = "";
|
|
||||||
if (transition) {
|
|
||||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
|
||||||
}
|
|
||||||
let finalizeComponentCode = `w${componentID}.${keepAlive ? "unmount" : "destroy"}();`;
|
|
||||||
if (ref && !keepAlive) {
|
|
||||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
|
||||||
}
|
|
||||||
if (transition) {
|
|
||||||
finalizeComponentCode = `let finalize = () => {
|
|
||||||
${finalizeComponentCode}
|
|
||||||
};
|
|
||||||
utils.transitionRemove(vn, '${transition}', finalize);`;
|
|
||||||
}
|
|
||||||
|
|
||||||
let createHook = "";
|
|
||||||
let classAttr = node.getAttribute("class");
|
|
||||||
let tattClass = node.getAttribute("t-att-class");
|
|
||||||
let styleAttr = node.getAttribute("style");
|
|
||||||
let tattStyle = node.getAttribute("t-att-style");
|
|
||||||
if (tattStyle) {
|
|
||||||
const attVar = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`const ${attVar} = ${ctx.formatExpression(tattStyle)};`);
|
|
||||||
tattStyle = attVar;
|
|
||||||
}
|
|
||||||
let classObj = "";
|
|
||||||
if (classAttr || tattClass || styleAttr || tattStyle || events.length) {
|
|
||||||
if (classAttr) {
|
|
||||||
let classDef = classAttr
|
|
||||||
.trim()
|
|
||||||
.split(/\s+/)
|
|
||||||
.map(a => `'${a}':true`)
|
|
||||||
.join(",");
|
|
||||||
classObj = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
|
||||||
}
|
|
||||||
if (tattClass) {
|
|
||||||
let tattExpr = ctx.formatExpression(tattClass);
|
|
||||||
if (tattExpr[0] !== "{" || tattExpr[tattExpr.length - 1] !== "}") {
|
|
||||||
tattExpr = `utils.toObj(${tattExpr})`;
|
|
||||||
}
|
|
||||||
if (classAttr) {
|
|
||||||
ctx.addLine(`Object.assign(${classObj}, ${tattExpr})`);
|
|
||||||
} else {
|
|
||||||
classObj = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`let ${classObj} = ${tattExpr};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let eventsCode = events
|
|
||||||
.map(function([eventName, mods, handlerValue, extraArgs]) {
|
|
||||||
let params = "owner";
|
|
||||||
if (extraArgs) {
|
|
||||||
if (ctx.loopNumber) {
|
|
||||||
let argId = ctx.generateID();
|
|
||||||
// we need to evaluate the arguments now, because the handler will
|
|
||||||
// be set asynchronously later when the widget is ready, and the
|
|
||||||
// context might be different.
|
|
||||||
ctx.addLine(`let arg${argId} = ${ctx.formatExpression(extraArgs)};`);
|
|
||||||
params = `owner, arg${argId}`;
|
|
||||||
} else {
|
|
||||||
params = `owner, ${ctx.formatExpression(extraArgs)}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let handler = `function (e) {`;
|
|
||||||
handler += mods
|
|
||||||
.map(function(mod) {
|
|
||||||
return T_COMPONENT_MODS_CODE[mod];
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
if (handlerValue) {
|
|
||||||
handler += `const fn = owner['${handlerValue}'];`;
|
|
||||||
handler += `if (fn) { fn.call(${params}, e); } else { owner.${handlerValue}; }`;
|
|
||||||
}
|
|
||||||
handler += `}`;
|
|
||||||
return `vn.elm.addEventListener('${eventName}', ${handler});`;
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
|
||||||
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
|
||||||
createHook = `vnode.data.hook = {create(_, vn){${styleCode}${eventsCode}}};`;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addLine(
|
|
||||||
`let w${componentID} = ${templateId} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateId}]] : false;`
|
|
||||||
);
|
|
||||||
let shouldProxy = !ctx.parentNode;
|
|
||||||
if (keepAlive) {
|
|
||||||
ctx.addLine(
|
|
||||||
`const fiber${componentID} = Object.assign(Object.create(extra.fiber), {patchQueue: []});`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (shouldProxy) {
|
|
||||||
let id = ctx.generateID();
|
|
||||||
ctx.rootContext.rootNode = id;
|
|
||||||
shouldProxy = true;
|
|
||||||
ctx.rootContext.shouldDefineResult = true;
|
|
||||||
ctx.addLine(`let vn${id} = {};`);
|
|
||||||
ctx.addLine(`result = vn${id};`);
|
|
||||||
}
|
|
||||||
if (hasDynamicProps) {
|
|
||||||
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
|
||||||
ctx.addLine(`let props${componentID} = Object.assign({${propStr}}, ${dynamicProp});`);
|
|
||||||
} else {
|
|
||||||
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
|
||||||
}
|
|
||||||
ctx.addIf(
|
|
||||||
`w${componentID} && w${componentID}.__owl__.currentFiber && !w${componentID}.__owl__.vnode`
|
|
||||||
);
|
|
||||||
ctx.addLine(`w${componentID}.destroy();`);
|
|
||||||
ctx.addLine(`w${componentID} = false;`);
|
|
||||||
ctx.closeIf();
|
|
||||||
|
|
||||||
let registerCode = "";
|
|
||||||
if (shouldProxy) {
|
|
||||||
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// SLOTS
|
|
||||||
const varDefs: string[] = [];
|
|
||||||
const hasSlots = node.childNodes.length;
|
|
||||||
if (hasSlots) {
|
|
||||||
ctx.rootContext.shouldTrackScope = true;
|
|
||||||
for (let v of Object.values(ctx.variables)) {
|
|
||||||
if (v["id"]) {
|
|
||||||
varDefs.push(v["id"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let scopeVars;
|
|
||||||
if (hasSlots) {
|
|
||||||
let scope = ctx.scopeVars.length ? `Object.assign({}, scope)` : `{}`;
|
|
||||||
let vars = varDefs.length ? `{${varDefs.join(",")}}` : "undefined";
|
|
||||||
scopeVars = `${scope}, ${vars}`;
|
|
||||||
} else {
|
|
||||||
scopeVars = "undefined, undefined";
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addIf(`w${componentID}`);
|
|
||||||
|
|
||||||
// need to update component
|
|
||||||
let patchQueueCode = keepAlive ? `fiber${componentID}` : "extra.fiber";
|
|
||||||
if (keepAlive) {
|
|
||||||
// if we have t-keepalive="1", the component could be unmounted, but then
|
|
||||||
// we __updateProps is called. This is ok, but we do not want to call
|
|
||||||
// the willPatch/patched hooks of the component in this case, so we
|
|
||||||
// disable the patch queue
|
|
||||||
patchQueueCode = `w${componentID}.__owl__.isMounted ? extra.fiber : fiber${componentID}`;
|
|
||||||
}
|
|
||||||
let styleCode = "";
|
|
||||||
if (tattStyle) {
|
|
||||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
|
||||||
`w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
|
|
||||||
", " + scopeVars}, sibling)${styleCode};`
|
|
||||||
);
|
|
||||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
|
||||||
let keepAliveCode = "";
|
|
||||||
if (keepAlive) {
|
|
||||||
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${componentID}.el,vn.elm);vn.elm=w${componentID}.el;w${componentID}.__remount();};`;
|
|
||||||
ctx.addLine(keepAliveCode);
|
|
||||||
}
|
|
||||||
if (registerCode) {
|
|
||||||
ctx.addLine(registerCode);
|
|
||||||
}
|
|
||||||
if (ctx.parentNode) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addElse();
|
|
||||||
|
|
||||||
// new component
|
|
||||||
let dynamicFallback = "";
|
|
||||||
if (!value.match(INTERP_REGEXP)) {
|
|
||||||
dynamicFallback = `|| ${ctx.formatExpression(value)}`;
|
|
||||||
}
|
|
||||||
const interpValue = ctx.interpolate(value);
|
|
||||||
ctx.addLine(`let componentKey${componentID} = ${interpValue};`);
|
|
||||||
ctx.addLine(
|
|
||||||
`let W${componentID} = context.constructor.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}]${dynamicFallback};`
|
|
||||||
);
|
|
||||||
|
|
||||||
// maybe only do this in dev mode...
|
|
||||||
ctx.addLine(
|
|
||||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
|
||||||
);
|
|
||||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
|
||||||
ctx.addLine(`parent.__owl__.cmap[${templateId}] = w${componentID}.__owl__.id;`);
|
|
||||||
|
|
||||||
if (hasSlots) {
|
|
||||||
const clone = <Element>node.cloneNode(true);
|
|
||||||
const slotNodes = clone.querySelectorAll("[t-set]");
|
|
||||||
const slotId = QWeb.nextSlotId++;
|
|
||||||
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
|
||||||
if (slotNodes.length) {
|
|
||||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
|
||||||
const slotNode = slotNodes[i];
|
|
||||||
slotNode.parentElement!.removeChild(slotNode);
|
|
||||||
const key = slotNode.getAttribute("t-set")!;
|
|
||||||
slotNode.removeAttribute("t-set");
|
|
||||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
|
||||||
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (clone.childNodes.length) {
|
|
||||||
const t = clone.ownerDocument!.createElement("t");
|
|
||||||
for (let child of Object.values(clone.childNodes)) {
|
|
||||||
t.appendChild(child);
|
|
||||||
}
|
|
||||||
const slotFn = qweb._compile(`slot_default_template`, t, ctx);
|
|
||||||
QWeb.slots[`${slotId}_default`] = slotFn;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addLine(`let def${defID} = w${componentID}.__prepare(extra.fiber, ${scopeVars}, sibling);`);
|
|
||||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
|
||||||
ctx.addLine(
|
|
||||||
`let pvnode = h('dummy', {key: ${templateId}, hook: {insert(vn) { let nvn=w${componentID}.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeComponentCode}}}});`
|
|
||||||
);
|
|
||||||
ctx.addLine(`const fiber = w${componentID}.__owl__.currentFiber;`);
|
|
||||||
ctx.addLine(
|
|
||||||
`def${defID}.then(function () {if (w${componentID}.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
|
||||||
);
|
|
||||||
if (registerCode) {
|
|
||||||
ctx.addLine(registerCode);
|
|
||||||
}
|
|
||||||
if (ctx.parentNode) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
|
||||||
}
|
|
||||||
ctx.addLine(`w${componentID}.__owl__.pvnode = pvnode;`);
|
|
||||||
|
|
||||||
ctx.closeIf();
|
|
||||||
|
|
||||||
if (classObj) {
|
|
||||||
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addLine(`sibling = w${componentID}.__owl__.currentFiber || sibling;`);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
import { VNode } from "../vdom/index";
|
|
||||||
import { Component } from "./component";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl Fiber Class
|
|
||||||
*
|
|
||||||
* Fibers are small abstractions designed to contain all the internal state
|
|
||||||
* associated with a "rendering work unit", relative to a specific component.
|
|
||||||
*
|
|
||||||
* A rendering will cause the creation of a fiber for each impacted components.
|
|
||||||
*
|
|
||||||
* Fibers capture all that necessary information, which is critical to owl
|
|
||||||
* asynchronous rendering pipeline. Fibers can be cancelled, can be in different
|
|
||||||
* states and in general determine the state of the rendering.
|
|
||||||
*/
|
|
||||||
|
|
||||||
export class Fiber {
|
|
||||||
// The force attribute determines if a rendering should bypass the `shouldUpdate`
|
|
||||||
// method potentially implemented by a component. It is usually set to false.
|
|
||||||
force: boolean;
|
|
||||||
|
|
||||||
// isCancelled means that the rendering corresponding to this fiber and its
|
|
||||||
// children is cancelled. No extra work should be done.
|
|
||||||
isCancelled: boolean = false;
|
|
||||||
|
|
||||||
// the fibers corresponding to component updates (updateProps) need to call
|
|
||||||
// the willPatch and patched hooks from the corresponding component. However,
|
|
||||||
// fibers corresponding to a new component do not need to do that. So, the
|
|
||||||
// shouldPatch hook is the boolean that we check whenever we need to apply
|
|
||||||
// a patch.
|
|
||||||
shouldPatch: boolean = true;
|
|
||||||
|
|
||||||
// isRendered is the last state of a fiber. If true, this means that it has
|
|
||||||
// been rendered and is inert (so, it should not be taken into account when
|
|
||||||
// counting the number of active fibers).
|
|
||||||
isRendered: boolean = false;
|
|
||||||
|
|
||||||
// the counter number is a critical information. It is only necessary for a
|
|
||||||
// root fiber. For that fiber, this number counts the number of active sub
|
|
||||||
// fibers. When that number reaches 0, the fiber can be applied by the
|
|
||||||
// scheduler.
|
|
||||||
counter: number = 0;
|
|
||||||
|
|
||||||
scope: any;
|
|
||||||
vars: any;
|
|
||||||
props: any;
|
|
||||||
|
|
||||||
component: Component<any, any>;
|
|
||||||
vnode: VNode | null = null;
|
|
||||||
|
|
||||||
root: Fiber;
|
|
||||||
child: Fiber | null = null;
|
|
||||||
sibling: Fiber | null = null;
|
|
||||||
parent: Fiber | null = null;
|
|
||||||
|
|
||||||
error?: Error;
|
|
||||||
|
|
||||||
constructor(parent: Fiber | null, component: Component<any, any>, props, scope, vars, force) {
|
|
||||||
this.force = force;
|
|
||||||
this.scope = scope;
|
|
||||||
this.vars = vars;
|
|
||||||
this.props = props;
|
|
||||||
this.component = component;
|
|
||||||
|
|
||||||
this.root = parent ? parent.root : this;
|
|
||||||
this.parent = parent;
|
|
||||||
|
|
||||||
let oldFiber = component.__owl__.currentFiber;
|
|
||||||
if (oldFiber && !oldFiber.isCancelled) {
|
|
||||||
this._remapFiber(oldFiber);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.root.counter++;
|
|
||||||
|
|
||||||
component.__owl__.currentFiber = this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* In some cases, a rendering initiated at some component can detect that it
|
|
||||||
* should be part of a larger rendering initiated somewhere up the component
|
|
||||||
* tree. In that case, it needs to cancel the previous rendering and
|
|
||||||
* remap itself as a part of the current parent rendering.
|
|
||||||
*/
|
|
||||||
_remapFiber(oldFiber: Fiber) {
|
|
||||||
oldFiber.cancel();
|
|
||||||
if (oldFiber === oldFiber.root) {
|
|
||||||
oldFiber.root.counter++;
|
|
||||||
}
|
|
||||||
if (oldFiber.parent && !this.parent) {
|
|
||||||
// re-map links
|
|
||||||
this.parent = oldFiber.parent;
|
|
||||||
this.root = this.parent.root;
|
|
||||||
this.sibling = oldFiber.sibling;
|
|
||||||
if (this.parent.child === oldFiber) {
|
|
||||||
this.parent.child = this;
|
|
||||||
} else {
|
|
||||||
let current = this.parent.child!;
|
|
||||||
while (true) {
|
|
||||||
if (current.sibling === oldFiber) {
|
|
||||||
current.sibling = this;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
current = current.sibling!;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This function has been taken from
|
|
||||||
* https://medium.com/react-in-depth/the-how-and-why-on-reacts-usage-of-linked-list-in-fiber-67f1014d0eb7
|
|
||||||
*/
|
|
||||||
_walk(doWork: (f: Fiber) => Fiber | null) {
|
|
||||||
let root = this;
|
|
||||||
let current: Fiber = this;
|
|
||||||
while (true) {
|
|
||||||
const child = doWork(current);
|
|
||||||
if (child) {
|
|
||||||
current = child;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (current === root) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
while (!current.sibling) {
|
|
||||||
if (!current.parent || current.parent === root) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
current = current.parent;
|
|
||||||
}
|
|
||||||
current = current.sibling;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply the given patch queue from a fiber.
|
|
||||||
* 1) Call 'willPatch' on the component of each patch
|
|
||||||
* 2) Call '__patch' on the component of each patch
|
|
||||||
* 3) Call 'patched' on the component of each patch, in reverse order
|
|
||||||
*/
|
|
||||||
patchComponents() {
|
|
||||||
const patchQueue: Fiber[] = [];
|
|
||||||
const doWork: (Fiber) => Fiber | null = function(f) {
|
|
||||||
if (f.shouldPatch) {
|
|
||||||
patchQueue.push(f);
|
|
||||||
}
|
|
||||||
return f.child;
|
|
||||||
};
|
|
||||||
this._walk(doWork);
|
|
||||||
let component: Component<any, any> = this.component;
|
|
||||||
const patchLen = patchQueue.length;
|
|
||||||
try {
|
|
||||||
for (let i = 0; i < patchLen; i++) {
|
|
||||||
component = patchQueue[i].component;
|
|
||||||
if (component.__owl__.willPatchCB) {
|
|
||||||
component.__owl__.willPatchCB();
|
|
||||||
}
|
|
||||||
component.willPatch();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
for (let i = 0; i < patchLen; i++) {
|
|
||||||
const fiber = patchQueue[i];
|
|
||||||
component = fiber.component;
|
|
||||||
component.__patch(fiber.vnode);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
for (let i = patchLen - 1; i >= 0; i--) {
|
|
||||||
component = patchQueue[i].component;
|
|
||||||
component.patched();
|
|
||||||
if (component.__owl__.patchedCB) {
|
|
||||||
component.__owl__.patchedCB();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancel a fiber and all its children.
|
|
||||||
*/
|
|
||||||
cancel() {
|
|
||||||
this._walk(f => {
|
|
||||||
if (!f.isRendered) {
|
|
||||||
f.root.counter--;
|
|
||||||
}
|
|
||||||
f.isCancelled = true;
|
|
||||||
return f.child;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the global error handler for errors occurring in Owl main lifecycle
|
|
||||||
* methods. Caught errors are triggered on the QWeb instance, and are
|
|
||||||
* potentially given to some parent component which implements `catchError`.
|
|
||||||
*
|
|
||||||
* If there are no such component, we destroy everything. This is better than
|
|
||||||
* being in a corrupted state.
|
|
||||||
*/
|
|
||||||
handleError(error: Error) {
|
|
||||||
let canCatch = false;
|
|
||||||
let component = this.component;
|
|
||||||
let qweb = component.env.qweb;
|
|
||||||
let root = component;
|
|
||||||
while (component && !(canCatch = !!component.catchError)) {
|
|
||||||
root = component;
|
|
||||||
component = component.__owl__.parent!;
|
|
||||||
}
|
|
||||||
qweb.trigger("error", error);
|
|
||||||
|
|
||||||
if (canCatch) {
|
|
||||||
setTimeout(() => {
|
|
||||||
console.error(error);
|
|
||||||
component.catchError!(error);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
this.root.error = error;
|
|
||||||
root.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import type { BDom } from "../blockdom";
|
||||||
|
import { mount } from "../blockdom";
|
||||||
|
import type { ComponentNode } from "./component_node";
|
||||||
|
import { STATUS } from "./status";
|
||||||
|
// import { mountBlock } from "./bdom/block";
|
||||||
|
|
||||||
|
export function makeChildFiber(node: ComponentNode, parent: Fiber): Fiber {
|
||||||
|
let current = node.fiber;
|
||||||
|
if (current) {
|
||||||
|
// current is necessarily a rootfiber here
|
||||||
|
let root = parent.root;
|
||||||
|
cancelFibers(root, current.children);
|
||||||
|
current.children = [];
|
||||||
|
current.parent = parent;
|
||||||
|
root.counter++;
|
||||||
|
current.root = root;
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
return new Fiber(node, parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeRootFiber(node: ComponentNode): Fiber {
|
||||||
|
let current = node.fiber;
|
||||||
|
if (current) {
|
||||||
|
let root = current.root;
|
||||||
|
root.counter -= cancelFibers(root, current.children);
|
||||||
|
current.children = [];
|
||||||
|
root.counter++;
|
||||||
|
current.bdom = null;
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
const fiber = new RootFiber(node);
|
||||||
|
if (node.willPatch.length) {
|
||||||
|
fiber.willPatch.push(fiber);
|
||||||
|
}
|
||||||
|
if (node.patched.length) {
|
||||||
|
fiber.patched.push(fiber);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fiber;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns number of not-yet rendered fibers cancelled
|
||||||
|
*/
|
||||||
|
function cancelFibers(root: any, fibers: Fiber[]): number {
|
||||||
|
let result = 0;
|
||||||
|
for (let fiber of fibers) {
|
||||||
|
fiber.node.fiber = null;
|
||||||
|
fiber.root = root;
|
||||||
|
if (!fiber.bdom) {
|
||||||
|
result++;
|
||||||
|
}
|
||||||
|
result += cancelFibers(root, fiber.children);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Fiber {
|
||||||
|
node: ComponentNode;
|
||||||
|
bdom: BDom | null = null;
|
||||||
|
root: RootFiber;
|
||||||
|
parent: Fiber | null;
|
||||||
|
children: Fiber[] = [];
|
||||||
|
appliedToDom = false;
|
||||||
|
|
||||||
|
constructor(node: ComponentNode, parent: Fiber | null) {
|
||||||
|
this.node = node;
|
||||||
|
node.fiber = this;
|
||||||
|
this.parent = parent;
|
||||||
|
if (parent) {
|
||||||
|
const root = parent.root;
|
||||||
|
root.counter++;
|
||||||
|
this.root = root;
|
||||||
|
parent.children.push(this);
|
||||||
|
} else {
|
||||||
|
this.root = this as any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RootFiber extends Fiber {
|
||||||
|
counter: number = 1;
|
||||||
|
error: Error | null = null;
|
||||||
|
resolve: any;
|
||||||
|
promise: Promise<any>;
|
||||||
|
reject: any;
|
||||||
|
|
||||||
|
// only add stuff in this if they have registered some hooks
|
||||||
|
willPatch: Fiber[] = [];
|
||||||
|
patched: Fiber[] = [];
|
||||||
|
mounted: Fiber[] = [];
|
||||||
|
|
||||||
|
constructor(node: ComponentNode) {
|
||||||
|
super(node, null);
|
||||||
|
this.counter = 1;
|
||||||
|
|
||||||
|
this.promise = new Promise((resolve, reject) => {
|
||||||
|
this.resolve = resolve;
|
||||||
|
this.reject = reject;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
complete() {
|
||||||
|
const node = this.node;
|
||||||
|
|
||||||
|
// Step 1: calling all willPatch lifecycle hooks
|
||||||
|
for (let fiber of this.willPatch) {
|
||||||
|
// because of the asynchronous nature of the rendering, some parts of the
|
||||||
|
// UI may have been rendered, then deleted in a followup rendering, and we
|
||||||
|
// do not want to call onWillPatch in that case.
|
||||||
|
let node = fiber.node;
|
||||||
|
if (node.fiber === fiber) {
|
||||||
|
const component = node.component;
|
||||||
|
for (let cb of node.willPatch) {
|
||||||
|
cb.call(component);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: patching the dom
|
||||||
|
node.bdom!.patch(this.bdom!, Object.keys(node.children).length > 0);
|
||||||
|
this.appliedToDom = true;
|
||||||
|
|
||||||
|
// Step 3: calling all destroyed hooks
|
||||||
|
for (let node of __internal__destroyed) {
|
||||||
|
for (let cb of node.destroyed) {
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
__internal__destroyed.length = 0;
|
||||||
|
|
||||||
|
// Step 4: calling all mounted lifecycle hooks
|
||||||
|
let current;
|
||||||
|
let mountedFibers = this.mounted;
|
||||||
|
while ((current = mountedFibers.pop())) {
|
||||||
|
if (current.appliedToDom) {
|
||||||
|
for (let cb of current.node.mounted) {
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 5: calling all patched hooks
|
||||||
|
let patchedFibers = this.patched;
|
||||||
|
while ((current = patchedFibers.pop())) {
|
||||||
|
if (current.appliedToDom) {
|
||||||
|
for (let cb of current.node.patched) {
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// unregistering the fiber
|
||||||
|
node.fiber = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export let __internal__destroyed: ComponentNode[] = [];
|
||||||
|
|
||||||
|
export class MountFiber extends RootFiber {
|
||||||
|
target: HTMLElement;
|
||||||
|
|
||||||
|
constructor(node: ComponentNode, target: HTMLElement) {
|
||||||
|
super(node);
|
||||||
|
this.target = target;
|
||||||
|
}
|
||||||
|
complete() {
|
||||||
|
const node = this.node;
|
||||||
|
node.bdom = this.bdom;
|
||||||
|
mount(node.bdom!, this.target);
|
||||||
|
node.status = STATUS.MOUNTED;
|
||||||
|
this.appliedToDom = true;
|
||||||
|
let current;
|
||||||
|
let mountedFibers = this.mounted;
|
||||||
|
while ((current = mountedFibers.pop())) {
|
||||||
|
if (current.appliedToDom) {
|
||||||
|
for (let cb of current.node.mounted) {
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
node.fiber = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
export function mainEventHandler(data: any, ev: Event) {
|
||||||
|
if (typeof data === "function") {
|
||||||
|
data(ev);
|
||||||
|
} else {
|
||||||
|
const ctx = data[0];
|
||||||
|
const method = data[1];
|
||||||
|
const args = data[2] || [];
|
||||||
|
ctx.__owl__.component[method](...args, ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
import { QWeb } from "../qweb/index";
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Prop validation helper
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the component props (or next props) against the (static) props
|
|
||||||
* description. This is potentially an expensive operation: it may needs to
|
|
||||||
* visit recursively the props and all the children to check if they are valid.
|
|
||||||
* This is why it is only done in 'dev' mode.
|
|
||||||
*/
|
|
||||||
|
|
||||||
QWeb.utils.validateProps = function(Widget, props: Object) {
|
|
||||||
const propsDef = (<any>Widget).props;
|
|
||||||
if (propsDef instanceof Array) {
|
|
||||||
// list of strings (prop names)
|
|
||||||
for (let i = 0, l = propsDef.length; i < l; i++) {
|
|
||||||
const propName = propsDef[i];
|
|
||||||
if (propName[propName.length - 1] === "?") {
|
|
||||||
// optional prop
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (!(propName in props)) {
|
|
||||||
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (let key in props) {
|
|
||||||
if (!propsDef.includes(key) && !propsDef.includes(key + "?")) {
|
|
||||||
throw new Error(`Unknown prop '${key}' given to component '${Widget.name}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (propsDef) {
|
|
||||||
// propsDef is an object now
|
|
||||||
for (let propName in propsDef) {
|
|
||||||
if (props[propName] === undefined) {
|
|
||||||
if (propsDef[propName] && !propsDef[propName].optional) {
|
|
||||||
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let isValid = isValidProp(props[propName], propsDef[propName]);
|
|
||||||
if (!isValid) {
|
|
||||||
throw new Error(`Props '${propName}' of invalid type in component '${Widget.name}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (let propName in props) {
|
|
||||||
if (!(propName in propsDef)) {
|
|
||||||
throw new Error(`Unknown prop '${propName}' given to component '${Widget.name}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if an invidual prop value matches its (static) prop definition
|
|
||||||
*/
|
|
||||||
function isValidProp(prop, propDef): boolean {
|
|
||||||
if (propDef === true) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (typeof propDef === "function") {
|
|
||||||
// Check if a value is constructed by some Constructor. Note that there is a
|
|
||||||
// slight abuse of language: we want to consider primitive values as well.
|
|
||||||
//
|
|
||||||
// So, even though 1 is not an instance of Number, we want to consider that
|
|
||||||
// it is valid.
|
|
||||||
if (typeof prop === "object") {
|
|
||||||
return prop instanceof propDef;
|
|
||||||
}
|
|
||||||
return typeof prop === propDef.name.toLowerCase();
|
|
||||||
} else if (propDef instanceof Array) {
|
|
||||||
// If this code is executed, this means that we want to check if a prop
|
|
||||||
// matches at least one of its descriptor.
|
|
||||||
let result = false;
|
|
||||||
for (let i = 0, iLen = propDef.length; i < iLen; i++) {
|
|
||||||
result = result || isValidProp(prop, propDef[i]);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
// propsDef is an object
|
|
||||||
let result = isValidProp(prop, propDef.type);
|
|
||||||
if (propDef.type === Array) {
|
|
||||||
for (let i = 0, iLen = prop.length; i < iLen; i++) {
|
|
||||||
result = result && isValidProp(prop[i], propDef.element);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (propDef.type === Object) {
|
|
||||||
const shape = propDef.shape;
|
|
||||||
for (let key in shape) {
|
|
||||||
result = result && isValidProp(prop[key], shape[key]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
+50
-38
@@ -1,66 +1,78 @@
|
|||||||
import { Fiber } from "./fiber";
|
import { Fiber, RootFiber } from "./fibers";
|
||||||
|
import { STATUS } from "./status";
|
||||||
|
|
||||||
/**
|
// -----------------------------------------------------------------------------
|
||||||
* Owl Scheduler Class
|
// Scheduler
|
||||||
*
|
// -----------------------------------------------------------------------------
|
||||||
* The scheduler is the part of Owl that will effectively apply a rendering
|
|
||||||
* whenever a fiber is ready.
|
|
||||||
*
|
|
||||||
* Briefly, it can be used to register root fibers. Whenever there is an
|
|
||||||
* active root fiber, it will poll continuously each animation frame (so, about
|
|
||||||
* once every 16ms) and whenever a root fiber is ready, it will apply it.
|
|
||||||
*/
|
|
||||||
|
|
||||||
interface Task {
|
|
||||||
fiber: Fiber;
|
|
||||||
callback: (err?: Error) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Scheduler {
|
export class Scheduler {
|
||||||
tasks: Task[] = [];
|
tasks: Set<RootFiber> = new Set();
|
||||||
isRunning: boolean = false;
|
isRunning: boolean = false;
|
||||||
requestAnimationFrame: typeof window.requestAnimationFrame;
|
requestAnimationFrame: Window["requestAnimationFrame"];
|
||||||
|
|
||||||
constructor(requestAnimationFrame) {
|
constructor(requestAnimationFrame: Window["requestAnimationFrame"]) {
|
||||||
this.requestAnimationFrame = requestAnimationFrame;
|
this.requestAnimationFrame = requestAnimationFrame;
|
||||||
}
|
}
|
||||||
|
|
||||||
addFiber(fiber, callback) {
|
start() {
|
||||||
this.tasks.push({ fiber, callback });
|
this.isRunning = true;
|
||||||
if (this.isRunning) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.scheduleTasks();
|
this.scheduleTasks();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.isRunning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
addFiber(fiber: Fiber) {
|
||||||
|
this.tasks.add(fiber.root);
|
||||||
|
if (!this.isRunning) {
|
||||||
|
this.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process all current tasks. This only applies to the fibers that are ready.
|
* Process all current tasks. This only applies to the fibers that are ready.
|
||||||
* Other tasks are left unchanged.
|
* Other tasks are left unchanged.
|
||||||
*/
|
*/
|
||||||
flush() {
|
flush() {
|
||||||
let tasks = this.tasks;
|
this.tasks.forEach((fiber) => {
|
||||||
this.tasks = [];
|
if (fiber.root !== fiber) {
|
||||||
tasks = tasks.filter(task => {
|
// this is wrong! should be something like
|
||||||
if (task.fiber.isCancelled) {
|
// if (this.tasks.has(fiber.root)) {
|
||||||
return false;
|
// // parent rendering has completed
|
||||||
|
// fiber.resolve();
|
||||||
|
// this.tasks.delete(fiber);
|
||||||
|
// }
|
||||||
|
this.tasks.delete(fiber);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (task.fiber.counter === 0) {
|
if (fiber.error) {
|
||||||
task.callback(task.fiber.error);
|
this.tasks.delete(fiber);
|
||||||
return false;
|
fiber.reject(fiber.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fiber.node.status === STATUS.DESTROYED) {
|
||||||
|
this.tasks.delete(fiber);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fiber.counter === 0) {
|
||||||
|
if (!fiber.error) {
|
||||||
|
fiber.complete();
|
||||||
|
}
|
||||||
|
fiber.resolve();
|
||||||
|
this.tasks.delete(fiber);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
});
|
});
|
||||||
this.tasks = tasks.concat(this.tasks);
|
if (this.tasks.size === 0) {
|
||||||
|
this.stop();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduleTasks() {
|
scheduleTasks() {
|
||||||
this.isRunning = true;
|
|
||||||
this.requestAnimationFrame(() => {
|
this.requestAnimationFrame(() => {
|
||||||
this.flush();
|
this.flush();
|
||||||
if (this.tasks.length > 0) {
|
if (this.isRunning) {
|
||||||
this.scheduleTasks();
|
this.scheduleTasks();
|
||||||
} else {
|
|
||||||
this.isRunning = false;
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { Component } from "./component";
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Status
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const enum STATUS {
|
||||||
|
NEW,
|
||||||
|
MOUNTED, // is ready, and in DOM. It has a valid el
|
||||||
|
DESTROYED,
|
||||||
|
}
|
||||||
|
|
||||||
|
type STATUS_DESCR = "new" | "mounted" | "destroyed";
|
||||||
|
|
||||||
|
export function status(component: Component): STATUS_DESCR {
|
||||||
|
switch (component.__owl__.status) {
|
||||||
|
case STATUS.NEW:
|
||||||
|
return "new";
|
||||||
|
case STATUS.MOUNTED:
|
||||||
|
return "mounted";
|
||||||
|
case STATUS.DESTROYED:
|
||||||
|
return "destroyed";
|
||||||
|
}
|
||||||
|
}
|
||||||
-111
@@ -1,111 +0,0 @@
|
|||||||
import { Component, scheduler } from "./component/component";
|
|
||||||
import { EventBus } from "./core/event_bus";
|
|
||||||
import { Observer } from "./core/observer";
|
|
||||||
import { onWillUnmount } from "./hooks";
|
|
||||||
/**
|
|
||||||
* The `Context` object provides a way to share data between an arbitrary number
|
|
||||||
* of component. Usually, data is passed from a parent to its children component,
|
|
||||||
* but when we have to deal with some mostly global information, this can be
|
|
||||||
* annoying, since each component will need to pass the information to each
|
|
||||||
* children, even though some or most of them will not use the information.
|
|
||||||
*
|
|
||||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
|
||||||
* hook) to its state, and will be updated whenever the context state is updated.
|
|
||||||
*/
|
|
||||||
export class Context extends EventBus {
|
|
||||||
state: any;
|
|
||||||
observer: Observer;
|
|
||||||
rev: number = 1;
|
|
||||||
// mapping from component id to last observed context id
|
|
||||||
mapping: { [componentId: number]: number } = {};
|
|
||||||
|
|
||||||
constructor(state: Object = {}) {
|
|
||||||
super();
|
|
||||||
this.observer = new Observer();
|
|
||||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
|
||||||
this.state = this.observer.observe(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instead of using trigger to emit an update event, we actually implement
|
|
||||||
* our own function to do that. The reason is that we need to be smarter than
|
|
||||||
* a simple trigger function: we need to wait for parent components to be
|
|
||||||
* done before doing children components. The reason is that if an update
|
|
||||||
* as an effect of destroying a children, we do not want to call the
|
|
||||||
* mapStoreToProps function of the child, nor rendering it.
|
|
||||||
*
|
|
||||||
* This method is not optimal if we have a bunch of asynchronous components:
|
|
||||||
* we wait sequentially for each component to be completed before updating the
|
|
||||||
* next. However, the only things that matters is that children are updated
|
|
||||||
* after their parents. So, this could be optimized by being smarter, and
|
|
||||||
* updating all widgets concurrently, except for parents/children.
|
|
||||||
*
|
|
||||||
* A potential cheap way to improve this situation is to keep track of the
|
|
||||||
* depth of a component in the component tree. A root component has a depth of
|
|
||||||
* 1, then its children of 2 and so on... Then, we can update all components
|
|
||||||
* with the same depth in parallel.
|
|
||||||
*/
|
|
||||||
async __notifyComponents() {
|
|
||||||
const rev = ++this.rev;
|
|
||||||
const subs = this.subscriptions.update || [];
|
|
||||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
|
||||||
const sub = subs[i];
|
|
||||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
|
||||||
if (shouldCallback) {
|
|
||||||
const render = sub.callback.call(sub.owner, rev);
|
|
||||||
scheduler.flush();
|
|
||||||
await render;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The`useContext` hook is the normal way for a component to register themselve
|
|
||||||
* to context state changes. The `useContext` method returns the context state
|
|
||||||
*/
|
|
||||||
export function useContext(ctx: Context): any {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
return useContextWithCB(ctx, component, component.render.bind(component));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useContextWithCB(ctx: Context, component: Component<any, any>, method): any {
|
|
||||||
const __owl__ = component.__owl__;
|
|
||||||
const id = __owl__.id;
|
|
||||||
const mapping = ctx.mapping;
|
|
||||||
if (id in mapping) {
|
|
||||||
return ctx.state;
|
|
||||||
}
|
|
||||||
if (!__owl__.observer) {
|
|
||||||
__owl__.observer = new Observer();
|
|
||||||
__owl__.observer.notifyCB = component.render.bind(component);
|
|
||||||
}
|
|
||||||
const currentCB = __owl__.observer.notifyCB;
|
|
||||||
__owl__.observer.notifyCB = function() {
|
|
||||||
if (ctx.rev > mapping[id]) {
|
|
||||||
// in this case, the context has been updated since we were rendering
|
|
||||||
// last, and we do not need to render here with the observer. A
|
|
||||||
// rendering is coming anyway, with the correct props.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
currentCB();
|
|
||||||
};
|
|
||||||
|
|
||||||
mapping[id] = 0;
|
|
||||||
const renderFn = __owl__.renderFn;
|
|
||||||
__owl__.renderFn = function(comp, params) {
|
|
||||||
mapping[id] = ctx.rev;
|
|
||||||
return renderFn(comp, params);
|
|
||||||
};
|
|
||||||
ctx.on("update", component, async contextRev => {
|
|
||||||
if (mapping[id] < contextRev) {
|
|
||||||
mapping[id] = contextRev;
|
|
||||||
await method();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
onWillUnmount(() => {
|
|
||||||
ctx.off("update", component);
|
|
||||||
delete mapping[id];
|
|
||||||
});
|
|
||||||
return ctx.state;
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
/**
|
|
||||||
* We define here a simple event bus: it can
|
|
||||||
* - emit events
|
|
||||||
* - add/remove listeners.
|
|
||||||
*
|
|
||||||
* This is a useful pattern of communication in many cases. For OWL, each
|
|
||||||
* components and stores are event buses.
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Types
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export type Callback = (...args: any[]) => void;
|
|
||||||
|
|
||||||
export interface Subscription {
|
|
||||||
owner: any;
|
|
||||||
callback: Callback;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// EventBus
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export class EventBus {
|
|
||||||
subscriptions: { [eventType: string]: Subscription[] } = {};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a listener for the 'eventType' events.
|
|
||||||
*
|
|
||||||
* Note that the 'owner' of this event can be anything, but will more likely
|
|
||||||
* be a component or a class. The idea is that the callback will be called with
|
|
||||||
* the proper owner bound.
|
|
||||||
*
|
|
||||||
* Also, the owner should be kind of unique. This will be used to remove the
|
|
||||||
* listener.
|
|
||||||
*/
|
|
||||||
on(eventType: string, owner: any, callback: Callback) {
|
|
||||||
if (!callback) {
|
|
||||||
throw new Error("Missing callback");
|
|
||||||
}
|
|
||||||
if (!this.subscriptions[eventType]) {
|
|
||||||
this.subscriptions[eventType] = [];
|
|
||||||
}
|
|
||||||
this.subscriptions[eventType].push({
|
|
||||||
owner,
|
|
||||||
callback
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove a listener
|
|
||||||
*/
|
|
||||||
off(eventType: string, owner: any) {
|
|
||||||
const subs = this.subscriptions[eventType];
|
|
||||||
if (subs) {
|
|
||||||
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emit an event of type 'eventType'. Any extra arguments will be passed to
|
|
||||||
* the listeners callback.
|
|
||||||
*/
|
|
||||||
trigger(eventType: string, ...args: any[]) {
|
|
||||||
const subs = this.subscriptions[eventType] || [];
|
|
||||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
|
||||||
const sub = subs[i];
|
|
||||||
sub.callback.call(sub.owner, ...args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove all subscriptions.
|
|
||||||
*/
|
|
||||||
clear() {
|
|
||||||
this.subscriptions = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
/**
|
|
||||||
* Owl Observer
|
|
||||||
*
|
|
||||||
* This code contains the logic that allows Owl to observe and react to state
|
|
||||||
* changes.
|
|
||||||
*
|
|
||||||
* This is a Observer class that can observe any JS values. The way it works
|
|
||||||
* can be summarized thusly:
|
|
||||||
* - primitive values are not observed at all
|
|
||||||
* - Objects and arrays are observed by replacing them with a Proxy
|
|
||||||
* - each object/array metadata are tracked in a weakmap, and keep a revision
|
|
||||||
* number
|
|
||||||
*
|
|
||||||
* Note that this code is loosely inspired by Vue.
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Observer
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
export class Observer {
|
|
||||||
rev: number = 1;
|
|
||||||
allowMutations: boolean = true;
|
|
||||||
dirty: boolean = false;
|
|
||||||
weakMap: WeakMap<any, any> = new WeakMap();
|
|
||||||
|
|
||||||
notifyCB() {}
|
|
||||||
async notifyChange() {
|
|
||||||
this.dirty = true;
|
|
||||||
await Promise.resolve();
|
|
||||||
if (this.dirty) {
|
|
||||||
this.dirty = false;
|
|
||||||
this.notifyCB();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
observe<T>(value: T, parent?: any): T {
|
|
||||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
|
||||||
// fun fact: typeof null === 'object'
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
let metadata = this.weakMap.get(value) || this._observe(value, parent);
|
|
||||||
return metadata.proxy;
|
|
||||||
}
|
|
||||||
|
|
||||||
revNumber(value): number {
|
|
||||||
const metadata = this.weakMap.get(value);
|
|
||||||
return metadata ? metadata.rev : 0;
|
|
||||||
}
|
|
||||||
deepRevNumber(value): number {
|
|
||||||
const metadata = this.weakMap.get(value);
|
|
||||||
return metadata ? metadata.deepRev : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
_observe(value, parent) {
|
|
||||||
var self = this;
|
|
||||||
|
|
||||||
const proxy = new Proxy(value, {
|
|
||||||
get(target, k) {
|
|
||||||
const targetValue = target[k];
|
|
||||||
return self.observe(targetValue, value);
|
|
||||||
},
|
|
||||||
set(target, key: string, newVal): boolean {
|
|
||||||
const value = target[key];
|
|
||||||
if (newVal !== value) {
|
|
||||||
if (!self.allowMutations) {
|
|
||||||
throw new Error(
|
|
||||||
`Observed state cannot be changed here! (key: "${key}", val: "${newVal}")`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
self._updateRevNumber(target);
|
|
||||||
target[key] = newVal;
|
|
||||||
self.notifyChange();
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
deleteProperty(target, key) {
|
|
||||||
if (key in target) {
|
|
||||||
delete target[key];
|
|
||||||
self._updateRevNumber(target);
|
|
||||||
self.notifyChange();
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const metadata = {
|
|
||||||
value,
|
|
||||||
proxy,
|
|
||||||
rev: this.rev,
|
|
||||||
deepRev: this.rev,
|
|
||||||
parent
|
|
||||||
};
|
|
||||||
|
|
||||||
this.weakMap.set(value, metadata);
|
|
||||||
this.weakMap.set(metadata.proxy, metadata);
|
|
||||||
return metadata;
|
|
||||||
}
|
|
||||||
|
|
||||||
_updateRevNumber(target: any) {
|
|
||||||
this.rev++;
|
|
||||||
let metadata = this.weakMap.get(target);
|
|
||||||
metadata.rev!++;
|
|
||||||
let parent = target;
|
|
||||||
do {
|
|
||||||
metadata = this.weakMap.get(parent);
|
|
||||||
metadata.deepRev++;
|
|
||||||
} while ((parent = metadata.parent) && parent !== target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export class EventBus extends EventTarget {
|
||||||
|
trigger(name: string, payload?: any) {
|
||||||
|
this.dispatchEvent(new CustomEvent(name, { detail: payload }));
|
||||||
|
}
|
||||||
|
}
|
||||||
-128
@@ -1,128 +0,0 @@
|
|||||||
import { Component } from "./component/component";
|
|
||||||
import { Observer } from "./core/observer";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl Hook System
|
|
||||||
*
|
|
||||||
* This file introduces the concept of hooks, similar to React or Vue hooks.
|
|
||||||
* We have currently an implementation of:
|
|
||||||
* - useState (reactive state)
|
|
||||||
* - onMounted
|
|
||||||
* - onWillUnmount
|
|
||||||
* - useRef
|
|
||||||
*/
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// useState
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the main way a component can be made reactive. The useState hook
|
|
||||||
* will return an observed object (or array). Changes to that value will then
|
|
||||||
* trigger a rerendering of the current component.
|
|
||||||
*/
|
|
||||||
export function useState<T>(state: T): T {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
const __owl__ = component.__owl__;
|
|
||||||
if (!__owl__.observer) {
|
|
||||||
__owl__.observer = new Observer();
|
|
||||||
__owl__.observer.notifyCB = component.render.bind(component);
|
|
||||||
}
|
|
||||||
return __owl__.observer.observe(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// Life cycle hooks
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
|
||||||
if (reverse) {
|
|
||||||
return function(cb) {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
if (component.__owl__[method]) {
|
|
||||||
const current = component.__owl__[method];
|
|
||||||
component.__owl__[method] = function() {
|
|
||||||
current.call(component);
|
|
||||||
cb.call(component);
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
component.__owl__[method] = cb;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return function(cb) {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
if (component.__owl__[method]) {
|
|
||||||
const current = component.__owl__[method];
|
|
||||||
component.__owl__[method] = function() {
|
|
||||||
cb.call(component);
|
|
||||||
current.call(component);
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
component.__owl__[method] = cb;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeAsyncHook(method: string) {
|
|
||||||
return function(cb) {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
if (component.__owl__[method]) {
|
|
||||||
const current = component.__owl__[method];
|
|
||||||
component.__owl__[method] = function(...args) {
|
|
||||||
return Promise.all[(current.call(component, ...args), cb.call(component, ...args))];
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
component.__owl__[method] = cb;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const onMounted = makeLifecycleHook("mountedCB", true);
|
|
||||||
export const onWillUnmount = makeLifecycleHook("willUnmountCB");
|
|
||||||
export const onWillPatch = makeLifecycleHook("willPatchCB");
|
|
||||||
export const onPatched = makeLifecycleHook("patchedCB", true);
|
|
||||||
|
|
||||||
export const onWillStart = makeAsyncHook("willStartCB");
|
|
||||||
export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// useRef
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The purpose of this hook is to allow components to get a reference to a sub
|
|
||||||
* html node or component.
|
|
||||||
*/
|
|
||||||
interface Ref {
|
|
||||||
el: HTMLElement | null;
|
|
||||||
comp: Component<any, any> | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useRef(name: string): Ref {
|
|
||||||
const __owl__ = Component.current!.__owl__;
|
|
||||||
return {
|
|
||||||
get el(): HTMLElement | null {
|
|
||||||
const val = __owl__.refs && __owl__.refs[name];
|
|
||||||
return val instanceof HTMLElement ? val : null;
|
|
||||||
},
|
|
||||||
get comp(): Component<any, any> | null {
|
|
||||||
const val = __owl__.refs && __owl__.refs[name];
|
|
||||||
return val instanceof Component ? val : null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// useSubEnv
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This hook is a simple way to let components use a sub environment. Note that
|
|
||||||
* like for all hooks, it is important that this is only called in the
|
|
||||||
* constructor method.
|
|
||||||
*/
|
|
||||||
export function useSubEnv(nextEnv) {
|
|
||||||
const component = Component.current!;
|
|
||||||
component.env = Object.assign(Object.create(component.env), nextEnv);
|
|
||||||
}
|
|
||||||
+70
-51
@@ -1,54 +1,73 @@
|
|||||||
/**
|
import {
|
||||||
* This file is the main file packaged by rollup (see rollup.config.js). From
|
config,
|
||||||
* this file, we export all public owl elements.
|
createBlock,
|
||||||
*
|
html,
|
||||||
* Note that dynamic values, such as a date or a commit hash are added by rollup
|
list,
|
||||||
*/
|
mount as blockMount,
|
||||||
import { EventBus } from "./core/event_bus";
|
multi,
|
||||||
import { Observer } from "./core/observer";
|
patch,
|
||||||
import { QWeb } from "./qweb/index";
|
remove,
|
||||||
import * as _store from "./store";
|
text,
|
||||||
import * as _utils from "./utils";
|
toggler,
|
||||||
import * as _tags from "./tags";
|
} from "./blockdom";
|
||||||
import { AsyncRoot } from "./misc/async_root";
|
import { mainEventHandler } from "./component/handler";
|
||||||
import * as _hooks from "./hooks";
|
|
||||||
import * as _context from "./context";
|
|
||||||
import { Link } from "./router/link";
|
|
||||||
import { RouteComponent } from "./router/route_component";
|
|
||||||
import { Router } from "./router/router";
|
|
||||||
|
|
||||||
export { Component } from "./component/component";
|
config.shouldNormalizeDom = false;
|
||||||
export { QWeb };
|
config.mainEventHandler = mainEventHandler;
|
||||||
|
|
||||||
|
export const blockDom = {
|
||||||
|
config,
|
||||||
|
// bdom entry points
|
||||||
|
mount: blockMount,
|
||||||
|
patch,
|
||||||
|
remove,
|
||||||
|
// bdom block types
|
||||||
|
list,
|
||||||
|
multi,
|
||||||
|
text,
|
||||||
|
toggler,
|
||||||
|
createBlock,
|
||||||
|
html,
|
||||||
|
};
|
||||||
|
|
||||||
|
// import { makeBlockClass } from "./_old_bdom/element";
|
||||||
|
import { App } from "./app";
|
||||||
|
import { Component } from "./component/component";
|
||||||
|
import { getCurrent } from "./component/component_node";
|
||||||
|
// import { getCurrent } from "./b_node";
|
||||||
|
|
||||||
|
export { App, Component };
|
||||||
|
|
||||||
|
export async function mount<T extends typeof Component>(
|
||||||
|
C: T,
|
||||||
|
target: HTMLElement
|
||||||
|
): Promise<InstanceType<T>> {
|
||||||
|
const app = new App(C);
|
||||||
|
return app.mount(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useComponent(): Component {
|
||||||
|
const current = getCurrent();
|
||||||
|
return current!.component;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { status } from "./component/status";
|
||||||
|
export { Portal } from "./misc/portal";
|
||||||
|
export { Memo } from "./misc/memo";
|
||||||
|
export { xml } from "./tags";
|
||||||
|
export { useState } from "./reactivity";
|
||||||
|
export { useRef } from "./refs";
|
||||||
|
export { EventBus } from "./event_bus";
|
||||||
|
|
||||||
|
export {
|
||||||
|
onWillStart,
|
||||||
|
onMounted,
|
||||||
|
onWillUnmount,
|
||||||
|
onWillUpdateProps,
|
||||||
|
onWillPatch,
|
||||||
|
onPatched,
|
||||||
|
onRender,
|
||||||
|
onDestroyed,
|
||||||
|
} from "./lifecycle_hooks";
|
||||||
|
|
||||||
export const Context = _context.Context;
|
|
||||||
export const useState = _hooks.useState;
|
|
||||||
export const core = { EventBus, Observer };
|
|
||||||
export const router = { Router, RouteComponent, Link };
|
|
||||||
export const Store = _store.Store;
|
|
||||||
export const utils = _utils;
|
|
||||||
export const tags = _tags;
|
|
||||||
export const misc = { AsyncRoot };
|
|
||||||
export const hooks = Object.assign({}, _hooks, {
|
|
||||||
useContext: _context.useContext,
|
|
||||||
useDispatch: _store.useDispatch,
|
|
||||||
useGetters: _store.useGetters,
|
|
||||||
useStore: _store.useStore
|
|
||||||
});
|
|
||||||
export const __info__ = {};
|
export const __info__ = {};
|
||||||
|
|
||||||
Object.defineProperty(__info__, "mode", {
|
|
||||||
get() {
|
|
||||||
return QWeb.dev ? "dev" : "prod";
|
|
||||||
},
|
|
||||||
set(mode: string) {
|
|
||||||
QWeb.dev = mode === "dev";
|
|
||||||
if (QWeb.dev) {
|
|
||||||
const url = `https://github.com/odoo/owl/blob/master/doc/tooling.md#development-mode`;
|
|
||||||
console.warn(
|
|
||||||
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
console.log(`Owl is now running in 'prod' mode.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { getCurrent } from "./component/component_node";
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// hooks
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function onWillStart(fn: () => Promise<void> | void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.willStart.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onWillUpdateProps(fn: (nextProps: any) => Promise<void> | void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.willUpdateProps.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onMounted(fn: () => void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.mounted.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onWillPatch(fn: () => Promise<void> | any | void) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.willPatch.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onPatched(fn: () => void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.patched.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onWillUnmount(fn: () => Promise<void> | void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.willUnmount.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onDestroyed(fn: () => Promise<void> | void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
node.destroyed.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onRender(fn: () => void | any) {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
const renderFn = node.renderFn;
|
||||||
|
node.renderFn = () => {
|
||||||
|
fn();
|
||||||
|
return renderFn();
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { Component } from "../component/component";
|
|
||||||
import { xml } from "../tags";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* AsyncRoot
|
|
||||||
*
|
|
||||||
* Owl is by default asynchronous, and the user interface will wait for all its
|
|
||||||
* subcomponents to be rendered before updating the DOM. This is most of the
|
|
||||||
* time what we want, but in some cases, it makes sense to "detach" a component
|
|
||||||
* from this coordination. This is the goal of the AsyncRoot component.
|
|
||||||
*/
|
|
||||||
|
|
||||||
export class AsyncRoot extends Component<any, any> {
|
|
||||||
static template = xml`<t t-slot="default"/>`;
|
|
||||||
|
|
||||||
async __updateProps(nextProps, parentFiber) {
|
|
||||||
this.render(parentFiber.force);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Component } from "../component/component";
|
||||||
|
import type { ComponentNode } from "../component/component_node";
|
||||||
|
import { xml } from "../tags";
|
||||||
|
import { Fiber } from "../component/fibers";
|
||||||
|
|
||||||
|
export class Memo extends Component {
|
||||||
|
static template = xml`<t t-slot="default"/>`;
|
||||||
|
|
||||||
|
constructor(props: any, env: any, node: ComponentNode) {
|
||||||
|
super(props, env, node);
|
||||||
|
|
||||||
|
// prevent patching process conditionally
|
||||||
|
let applyPatch = false;
|
||||||
|
const patchFn = node.patch;
|
||||||
|
node.patch = () => {
|
||||||
|
if (applyPatch) {
|
||||||
|
patchFn.call(node);
|
||||||
|
applyPatch = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// check props change, and render/apply patch if it changed
|
||||||
|
let prevProps = props;
|
||||||
|
const updateAndRender = node.updateAndRender;
|
||||||
|
node.updateAndRender = function (props: any, parentFiber: Fiber) {
|
||||||
|
const shouldUpdate = !shallowEqual(prevProps, props);
|
||||||
|
if (shouldUpdate) {
|
||||||
|
prevProps = props;
|
||||||
|
updateAndRender.call(node, props, parentFiber);
|
||||||
|
applyPatch = true;
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* we assume that each object have the same set of keys
|
||||||
|
*/
|
||||||
|
function shallowEqual(p1: any, p2: any): boolean {
|
||||||
|
for (let k in p1) {
|
||||||
|
if (p1[k] !== p2[k]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { ComponentNode } from "../component/component_node";
|
||||||
|
import { Component } from "../component/component";
|
||||||
|
import { xml } from "../tags";
|
||||||
|
import { BDom, text, VNode } from "../blockdom";
|
||||||
|
|
||||||
|
const VText: any = text("").constructor;
|
||||||
|
|
||||||
|
class VPortal extends VText implements Partial<VNode<VPortal>> {
|
||||||
|
// selector: string;
|
||||||
|
realBDom: BDom | null;
|
||||||
|
target: HTMLElement | null = null;
|
||||||
|
|
||||||
|
constructor(selector: string, realBDom: BDom) {
|
||||||
|
super("");
|
||||||
|
this.selector = selector;
|
||||||
|
this.realBDom = realBDom;
|
||||||
|
}
|
||||||
|
mount(parent: HTMLElement, anchor: ChildNode) {
|
||||||
|
super.mount(parent, anchor);
|
||||||
|
this.target = document.querySelector(this.selector) as any;
|
||||||
|
if (!this.target) {
|
||||||
|
let el: any = this.el;
|
||||||
|
while (el && el.parentElement instanceof HTMLElement) {
|
||||||
|
el = el.parentElement;
|
||||||
|
}
|
||||||
|
this.target = el && el.querySelector(this.selector);
|
||||||
|
if (!this.target) {
|
||||||
|
throw new Error("invalid portal target");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.realBDom!.mount(this.target!, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeRemove() {
|
||||||
|
this.realBDom!.beforeRemove();
|
||||||
|
}
|
||||||
|
remove() {
|
||||||
|
super.remove();
|
||||||
|
this.realBDom!.remove();
|
||||||
|
this.realBDom = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
patch(other: VPortal) {
|
||||||
|
super.patch(other);
|
||||||
|
if (this.realBDom) {
|
||||||
|
this.realBDom.patch(other.realBDom!, true);
|
||||||
|
} else {
|
||||||
|
this.realBDom = other.realBDom;
|
||||||
|
this.realBDom!.mount(this.target!, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Portal extends Component {
|
||||||
|
static template = xml`<t t-slot="default"/>`;
|
||||||
|
|
||||||
|
constructor(props: any, env: any, node: ComponentNode) {
|
||||||
|
super(props, env, node);
|
||||||
|
node._render = function (fiber: any) {
|
||||||
|
const bdom = new VPortal(props.target, this.renderFn());
|
||||||
|
fiber.bdom = bdom;
|
||||||
|
fiber.root.counter--;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,337 +0,0 @@
|
|||||||
import { CompilationContext } from "./compilation_context";
|
|
||||||
import { QWebExprVar } from "./expression_parser";
|
|
||||||
import { QWeb } from "./qweb";
|
|
||||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl QWeb Directives
|
|
||||||
*
|
|
||||||
* This file contains the implementation of most standard QWeb directives:
|
|
||||||
* - t-esc
|
|
||||||
* - t-raw
|
|
||||||
* - t-set/t-value
|
|
||||||
* - t-if/t-elif/t-else
|
|
||||||
* - t-call
|
|
||||||
* - t-foreach/t-as
|
|
||||||
* - t-debug
|
|
||||||
* - t-log
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-esc and t-raw
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.utils.getFragment = function(str: string): DocumentFragment {
|
|
||||||
const temp = document.createElement("template");
|
|
||||||
temp.innerHTML = str;
|
|
||||||
return temp.content;
|
|
||||||
};
|
|
||||||
|
|
||||||
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
|
||||||
|
|
||||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
|
||||||
if (value === "0" && ctx.caller) {
|
|
||||||
qweb._compileNode(ctx.caller, ctx);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value.xml instanceof NodeList) {
|
|
||||||
for (let node of Array.from(value.xml)) {
|
|
||||||
qweb._compileNode(<ChildNode>node, ctx);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let exprID: string;
|
|
||||||
if (typeof value === "string") {
|
|
||||||
exprID = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
|
||||||
} else {
|
|
||||||
exprID = value.id;
|
|
||||||
}
|
|
||||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
|
||||||
if (ctx.escaping) {
|
|
||||||
if (ctx.parentTextNode) {
|
|
||||||
ctx.addLine(`vn${ctx.parentTextNode}.text += ${exprID};`);
|
|
||||||
} else if (ctx.parentNode) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push({text: ${exprID}});`);
|
|
||||||
} else {
|
|
||||||
let nodeID = ctx.generateID();
|
|
||||||
ctx.rootContext.rootNode = nodeID;
|
|
||||||
ctx.rootContext.parentTextNode = nodeID;
|
|
||||||
ctx.addLine(`var vn${nodeID} = {text: ${exprID}};`);
|
|
||||||
if (ctx.rootContext.shouldDefineResult) {
|
|
||||||
ctx.addLine(`result = vn${nodeID}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(...utils.htmlToVDOM(${exprID}));`);
|
|
||||||
}
|
|
||||||
if (node.childNodes.length) {
|
|
||||||
ctx.addElse();
|
|
||||||
qweb._compileChildren(node, ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "esc",
|
|
||||||
priority: 70,
|
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
|
||||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
|
||||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "raw",
|
|
||||||
priority: 80,
|
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
|
||||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
|
||||||
compileValueNode(value, node, qweb, ctx);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-set
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "set",
|
|
||||||
extraNames: ["value"],
|
|
||||||
priority: 60,
|
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
|
||||||
const variable = node.getAttribute("t-set")!;
|
|
||||||
let value = node.getAttribute("t-value")!;
|
|
||||||
if (value) {
|
|
||||||
const formattedValue = ctx.formatExpression(value);
|
|
||||||
if (ctx.variables.hasOwnProperty(variable)) {
|
|
||||||
ctx.addLine(`${(<QWebExprVar>ctx.variables[variable]).id} = ${formattedValue}`);
|
|
||||||
} else {
|
|
||||||
const varName = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
|
||||||
ctx.variables[variable] = {
|
|
||||||
id: varName,
|
|
||||||
expr: formattedValue
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ctx.variables[variable] = {
|
|
||||||
xml: node.childNodes
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-if, t-elif, t-else
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "if",
|
|
||||||
priority: 20,
|
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
|
||||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
|
||||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : cond.id);
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
finalize({ ctx }) {
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "elif",
|
|
||||||
priority: 30,
|
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
|
||||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
|
||||||
ctx.addLine(`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : cond.id}) {`);
|
|
||||||
ctx.indent();
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
finalize({ ctx }) {
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "else",
|
|
||||||
priority: 40,
|
|
||||||
atNodeEncounter({ ctx }): boolean {
|
|
||||||
ctx.addLine(`else {`);
|
|
||||||
ctx.indent();
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
finalize({ ctx }) {
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-call
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "call",
|
|
||||||
priority: 50,
|
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
|
||||||
if (node.nodeName !== "t") {
|
|
||||||
throw new Error("Invalid tag for t-call directive (should be 't')");
|
|
||||||
}
|
|
||||||
const subTemplate = node.getAttribute("t-call")!;
|
|
||||||
const nodeTemplate = qweb.templates[subTemplate];
|
|
||||||
if (!nodeTemplate) {
|
|
||||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
|
||||||
}
|
|
||||||
const nodeCopy = node.cloneNode(true) as Element;
|
|
||||||
nodeCopy.removeAttribute("t-call");
|
|
||||||
|
|
||||||
// extract variables from nodecopy
|
|
||||||
const tempCtx = new CompilationContext();
|
|
||||||
tempCtx.nextID = ctx.rootContext.nextID;
|
|
||||||
tempCtx.allowMultipleRoots = true;
|
|
||||||
qweb._compileNode(nodeCopy, tempCtx);
|
|
||||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
|
||||||
ctx.rootContext.nextID = tempCtx.nextID;
|
|
||||||
|
|
||||||
const templateMap = Object.create(ctx.templates);
|
|
||||||
// open new scope, if necessary
|
|
||||||
const hasNewVariables = Object.keys(tempCtx.variables).length > 0;
|
|
||||||
|
|
||||||
// compile sub template
|
|
||||||
let subCtx = ctx.subContext("caller", nodeCopy).subContext("variables", Object.create(vars));
|
|
||||||
subCtx = subCtx.subContext("templates", templateMap);
|
|
||||||
|
|
||||||
if (templateMap[subTemplate]) {
|
|
||||||
// OUCH, IT IS A RECURSIVE TEMPLATE SITUATION...
|
|
||||||
// This is a tricky situation... We obviously cannot inline the compiled
|
|
||||||
// template. So, what we need to do is to compile it, and make sure we
|
|
||||||
// properly transfer everything from the current scope to the sub template.
|
|
||||||
ctx.rootContext.shouldTrackScope = true;
|
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
let subTemplateName;
|
|
||||||
if (ctx.hasParentWidget) {
|
|
||||||
subTemplateName = ctx.templateName;
|
|
||||||
} else {
|
|
||||||
subTemplateName = `__${ctx.generateID()}`;
|
|
||||||
subCtx.variables = {};
|
|
||||||
let id = 0;
|
|
||||||
for (let v in vars) {
|
|
||||||
subCtx.variables[v] = vars[v];
|
|
||||||
(vars[v] as any).id = `_v${id++}`;
|
|
||||||
}
|
|
||||||
const subTemplateFn = qweb._compile(subTemplateName, nodeTemplate.elem, subCtx);
|
|
||||||
qweb.recursiveFns[subTemplateName] = subTemplateFn;
|
|
||||||
}
|
|
||||||
let varCode = `{}`;
|
|
||||||
if (Object.keys(vars).length) {
|
|
||||||
let id = 0;
|
|
||||||
const content = Object.values(vars)
|
|
||||||
.map((v: any) => `_v${id++}: ${v.expr}`)
|
|
||||||
.join(",");
|
|
||||||
varCode = `{${content}}`;
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
|
||||||
`this.recursiveFns['${subTemplateName}'].call(this, context, Object.assign({}, extra, {parentNode: c${ctx.parentNode}, fiber: {vars: ${varCode}, scope}}));`
|
|
||||||
);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
templateMap[subTemplate] = true;
|
|
||||||
|
|
||||||
if (hasNewVariables) {
|
|
||||||
ctx.addLine("{");
|
|
||||||
ctx.indent();
|
|
||||||
// add new variables, if any
|
|
||||||
for (let key in tempCtx.variables) {
|
|
||||||
const v = tempCtx.variables[key];
|
|
||||||
if ((<QWebExprVar>v).expr) {
|
|
||||||
ctx.addLine(`let ${(<QWebExprVar>v).id} = ${(<QWebExprVar>v).expr};`);
|
|
||||||
}
|
|
||||||
// todo: handle XML variables...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
|
||||||
|
|
||||||
// close new scope
|
|
||||||
if (hasNewVariables) {
|
|
||||||
ctx.dedent();
|
|
||||||
ctx.addLine("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-foreach
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "foreach",
|
|
||||||
extraNames: ["as"],
|
|
||||||
priority: 10,
|
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
|
||||||
ctx.rootContext.shouldProtectContext = true;
|
|
||||||
ctx = ctx.subContext("loopNumber", ctx.loopNumber + 1);
|
|
||||||
const elems = node.getAttribute("t-foreach")!;
|
|
||||||
const name = node.getAttribute("t-as")!;
|
|
||||||
let arrayID = ctx.generateID();
|
|
||||||
ctx.addLine(`var _${arrayID} = ${ctx.formatExpression(elems)};`);
|
|
||||||
ctx.addLine(`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`);
|
|
||||||
let keysID = ctx.generateID();
|
|
||||||
let valuesID = ctx.generateID();
|
|
||||||
ctx.addLine(`var _${keysID} = _${valuesID} = _${arrayID};`);
|
|
||||||
ctx.addIf(`!(_${arrayID} instanceof Array)`);
|
|
||||||
ctx.addLine(`_${keysID} = Object.keys(_${arrayID});`);
|
|
||||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
|
||||||
ctx.closeIf();
|
|
||||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
|
||||||
const loopVar = `i${ctx.loopNumber}`;
|
|
||||||
ctx.addLine(`for (let ${loopVar} = 0; ${loopVar} < _length${keysID}; ${loopVar}++) {`);
|
|
||||||
ctx.indent();
|
|
||||||
ctx.addToScope(name + "_first", `${loopVar} === 0`);
|
|
||||||
ctx.addToScope(name + "_last", `${loopVar} === _length${keysID} - 1`);
|
|
||||||
ctx.addToScope(name + "_index", loopVar);
|
|
||||||
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
|
|
||||||
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
|
|
||||||
const nodeCopy = <Element>node.cloneNode(true);
|
|
||||||
let shouldWarn =
|
|
||||||
!nodeCopy.hasAttribute("t-key") &&
|
|
||||||
node.children.length === 1 &&
|
|
||||||
node.children[0].tagName !== "t" &&
|
|
||||||
!node.children[0].hasAttribute("t-key");
|
|
||||||
if (shouldWarn) {
|
|
||||||
console.warn(
|
|
||||||
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
nodeCopy.removeAttribute("t-foreach");
|
|
||||||
qweb._compileNode(nodeCopy, ctx);
|
|
||||||
ctx.dedent();
|
|
||||||
ctx.addLine("}");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-debug
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "debug",
|
|
||||||
priority: 1,
|
|
||||||
atNodeEncounter({ ctx }) {
|
|
||||||
ctx.addLine("debugger;");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-log
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "log",
|
|
||||||
priority: 1,
|
|
||||||
atNodeEncounter({ ctx, value }) {
|
|
||||||
const expr = ctx.formatExpression(value);
|
|
||||||
ctx.addLine(`console.log(${expr})`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
import { compileExpr, QWebVar, QWebExprVar } from "./expression_parser";
|
|
||||||
|
|
||||||
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Compilation Context
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export class CompilationContext {
|
|
||||||
nextID: number = 1;
|
|
||||||
code: string[] = [];
|
|
||||||
variables: { [key: string]: QWebVar } = {};
|
|
||||||
escaping: boolean = false;
|
|
||||||
parentNode: number | null = null;
|
|
||||||
parentTextNode: number | null = null;
|
|
||||||
rootNode: number | null = null;
|
|
||||||
indentLevel: number = 0;
|
|
||||||
rootContext: CompilationContext;
|
|
||||||
caller: Element | undefined;
|
|
||||||
shouldDefineOwner: boolean = false;
|
|
||||||
shouldDefineParent: boolean = false;
|
|
||||||
shouldDefineQWeb: boolean = false;
|
|
||||||
shouldDefineUtils: boolean = false;
|
|
||||||
shouldDefineRefs: boolean = false;
|
|
||||||
shouldDefineResult: boolean = true;
|
|
||||||
shouldDefineSibling: boolean = true;
|
|
||||||
shouldProtectContext: boolean = false;
|
|
||||||
shouldTrackScope: boolean = false;
|
|
||||||
loopNumber: number = 0;
|
|
||||||
inPreTag: boolean = false;
|
|
||||||
templateName: string;
|
|
||||||
allowMultipleRoots: boolean = false;
|
|
||||||
hasParentWidget: boolean = false;
|
|
||||||
scopeVars: any[] = [];
|
|
||||||
currentKey: string = "";
|
|
||||||
lastNodeKey: string = ""; // temp variable to communicate to previous caller
|
|
||||||
templates: { [key: string]: boolean } = {};
|
|
||||||
|
|
||||||
constructor(name?: string) {
|
|
||||||
this.rootContext = this;
|
|
||||||
this.templateName = name || "noname";
|
|
||||||
this.templates[this.templateName] = true;
|
|
||||||
this.addLine("var h = this.h;");
|
|
||||||
}
|
|
||||||
|
|
||||||
generateID(): number {
|
|
||||||
const id = this.rootContext.nextID++;
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
generateCode(): string[] {
|
|
||||||
const shouldTrackScope = this.shouldTrackScope && this.scopeVars.length;
|
|
||||||
if (shouldTrackScope) {
|
|
||||||
// add some vars to scope if needed
|
|
||||||
for (let scopeVar of this.scopeVars.reverse()) {
|
|
||||||
let { index, key, indent } = scopeVar;
|
|
||||||
const prefix = new Array(indent + 2).join(" ");
|
|
||||||
this.code.splice(index + 1, 0, prefix + `scope.${key} = context.${key};`);
|
|
||||||
}
|
|
||||||
this.code.unshift(" const scope = Object.create(null);");
|
|
||||||
}
|
|
||||||
if (this.shouldProtectContext) {
|
|
||||||
this.code.unshift(" context = Object.create(context);");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineResult) {
|
|
||||||
this.code.unshift(" let result;");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineSibling) {
|
|
||||||
this.code.unshift(" let sibling = null;");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineRefs) {
|
|
||||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineOwner) {
|
|
||||||
// this is necessary to prevent some directives (t-forach for ex) to
|
|
||||||
// pollute the rendering context by adding some keys in it.
|
|
||||||
this.code.unshift(" let owner = context;");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineParent) {
|
|
||||||
if (this.hasParentWidget) {
|
|
||||||
this.code.unshift(" let parent = extra.parent;");
|
|
||||||
} else {
|
|
||||||
this.code.unshift(" let parent = context;");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (this.shouldDefineQWeb) {
|
|
||||||
this.code.unshift(" let QWeb = this.constructor;");
|
|
||||||
}
|
|
||||||
if (this.shouldDefineUtils) {
|
|
||||||
this.code.unshift(" let utils = this.constructor.utils;");
|
|
||||||
}
|
|
||||||
return this.code;
|
|
||||||
}
|
|
||||||
|
|
||||||
withParent(node: number): CompilationContext {
|
|
||||||
if (
|
|
||||||
!this.allowMultipleRoots &&
|
|
||||||
this === this.rootContext &&
|
|
||||||
(this.parentNode || this.parentTextNode)
|
|
||||||
) {
|
|
||||||
throw new Error("A template should not have more than one root node");
|
|
||||||
}
|
|
||||||
if (!this.rootContext.rootNode) {
|
|
||||||
this.rootContext.rootNode = node;
|
|
||||||
}
|
|
||||||
if (!this.parentNode && this.rootContext.shouldDefineResult) {
|
|
||||||
this.addLine(`result = vn${node};`);
|
|
||||||
}
|
|
||||||
return this.subContext("parentNode", node);
|
|
||||||
}
|
|
||||||
|
|
||||||
subContext(key: keyof CompilationContext, value: any): CompilationContext {
|
|
||||||
const newContext = Object.create(this);
|
|
||||||
newContext[key] = value;
|
|
||||||
return newContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
indent() {
|
|
||||||
this.indentLevel++;
|
|
||||||
}
|
|
||||||
|
|
||||||
dedent() {
|
|
||||||
this.indentLevel--;
|
|
||||||
}
|
|
||||||
|
|
||||||
addLine(line: string): number {
|
|
||||||
const prefix = new Array(this.indentLevel + 2).join(" ");
|
|
||||||
this.code.push(prefix + line);
|
|
||||||
return this.code.length - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
addToScope(key: string, expr: string) {
|
|
||||||
const index = this.addLine(`context.${key} = ${expr};`);
|
|
||||||
this.rootContext.scopeVars.push({ index, key, indent: this.indentLevel });
|
|
||||||
}
|
|
||||||
|
|
||||||
addIf(condition: string) {
|
|
||||||
this.addLine(`if (${condition}) {`);
|
|
||||||
this.indent();
|
|
||||||
}
|
|
||||||
|
|
||||||
addElse() {
|
|
||||||
this.dedent();
|
|
||||||
this.addLine("} else {");
|
|
||||||
this.indent();
|
|
||||||
}
|
|
||||||
|
|
||||||
closeIf() {
|
|
||||||
this.dedent();
|
|
||||||
this.addLine("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
getValue(val: any): QWebExprVar | string {
|
|
||||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Prepare an expression for being consumed at render time. Its main job
|
|
||||||
* is to
|
|
||||||
* - replace unknown variables by a lookup in the context
|
|
||||||
* - replace already defined variables by their internal name
|
|
||||||
*/
|
|
||||||
formatExpression(expr: string): string {
|
|
||||||
return compileExpr(expr, this.variables);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Perform string interpolation on the given string. Note that if the whole
|
|
||||||
* string is an expression, it simply returns it (formatted and enclosed in
|
|
||||||
* parentheses).
|
|
||||||
* For instance:
|
|
||||||
* 'Hello {{x}}!' -> `Hello ${x}`
|
|
||||||
* '{{x ? 'a': 'b'}}' -> (x ? 'a' : 'b')
|
|
||||||
*/
|
|
||||||
interpolate(s: string): string {
|
|
||||||
let matches = s.match(INTERP_REGEXP);
|
|
||||||
if (matches && matches[0].length === s.length) {
|
|
||||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
|
||||||
}
|
|
||||||
|
|
||||||
let r = s.replace(/\{\{.*?\}\}/g, s => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
|
||||||
return "`" + r + "`";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,997 @@
|
|||||||
|
import { BDom } from "../blockdom";
|
||||||
|
import { compileExpr, compileExprToArray, interpolate, INTERP_REGEXP } from "./inline_expressions";
|
||||||
|
import {
|
||||||
|
AST,
|
||||||
|
ASTComment,
|
||||||
|
ASTComponent,
|
||||||
|
ASTDebug,
|
||||||
|
ASTDomNode,
|
||||||
|
ASTLog,
|
||||||
|
ASTMulti,
|
||||||
|
ASTSlot,
|
||||||
|
ASTTCall,
|
||||||
|
ASTTCallBlock,
|
||||||
|
ASTTEsc,
|
||||||
|
ASTText,
|
||||||
|
ASTTForEach,
|
||||||
|
ASTTif,
|
||||||
|
ASTTKey,
|
||||||
|
ASTTRaw,
|
||||||
|
ASTTSet,
|
||||||
|
ASTType,
|
||||||
|
parse,
|
||||||
|
} from "./parser";
|
||||||
|
|
||||||
|
export type Template = (context: any, vnode: any, key?: string) => BDom;
|
||||||
|
export type TemplateFunction = (blocks: any, utils: any) => Template;
|
||||||
|
|
||||||
|
type BlockType = "block" | "text" | "multi" | "list" | "html";
|
||||||
|
|
||||||
|
export function compileTemplate(template: string, name?: string): TemplateFunction {
|
||||||
|
const compiler = new QWebCompiler(template, name);
|
||||||
|
return compiler.compile();
|
||||||
|
}
|
||||||
|
|
||||||
|
// using a non-html document so that <inner/outer>HTML serializes as XML instead
|
||||||
|
// of HTML (as we will parse it as xml later)
|
||||||
|
const xmlDoc = document.implementation.createDocument(null, null, null);
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// BlockDescription
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class BlockDescription {
|
||||||
|
static nextBlockId = 1;
|
||||||
|
static nextDataId = 1;
|
||||||
|
|
||||||
|
varName: string;
|
||||||
|
blockName: string;
|
||||||
|
isRoot: boolean = false;
|
||||||
|
hasDynamicChildren: boolean = false;
|
||||||
|
children: BlockDescription[] = [];
|
||||||
|
data: string[] = [];
|
||||||
|
dom?: Node;
|
||||||
|
currentDom?: Element;
|
||||||
|
childNumber: number = 0;
|
||||||
|
target: CodeTarget;
|
||||||
|
type: BlockType;
|
||||||
|
parentVar: string = "";
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
constructor(target: CodeTarget, type: BlockType) {
|
||||||
|
this.id = BlockDescription.nextBlockId++;
|
||||||
|
this.varName = "b" + this.id;
|
||||||
|
this.blockName = "block" + this.id;
|
||||||
|
this.target = target;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
insertData(str: string): number {
|
||||||
|
const id = "d" + BlockDescription.nextDataId++;
|
||||||
|
this.target.addLine(`let ${id} = ${str};`);
|
||||||
|
return this.data.push(id) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
insert(dom: Node) {
|
||||||
|
if (this.currentDom) {
|
||||||
|
this.currentDom.appendChild(dom);
|
||||||
|
} else {
|
||||||
|
this.dom = dom;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
generateExpr(expr: string): string {
|
||||||
|
if (this.type === "block") {
|
||||||
|
const hasChildren = this.children.length;
|
||||||
|
let params = this.data.length ? `[${this.data.join(", ")}]` : hasChildren ? "[]" : "";
|
||||||
|
if (hasChildren) {
|
||||||
|
params += ", [" + this.children.map((c) => c.varName).join(", ") + "]";
|
||||||
|
}
|
||||||
|
return `${this.blockName}(${params})`;
|
||||||
|
} else if (this.type === "list") {
|
||||||
|
return `list(c${this.id})`;
|
||||||
|
}
|
||||||
|
return expr;
|
||||||
|
}
|
||||||
|
|
||||||
|
asXmlString() {
|
||||||
|
// Can't use outerHTML on text/comment nodes
|
||||||
|
// append dom to any element and use innerHTML instead
|
||||||
|
const t = xmlDoc.createElement('t');
|
||||||
|
t.appendChild(this.dom!);
|
||||||
|
return t.innerHTML;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Compiler code
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
const FNAMEREGEXP = /^[$A-Z_][0-9A-Z_$]*$/i;
|
||||||
|
|
||||||
|
interface Context {
|
||||||
|
block: BlockDescription | null;
|
||||||
|
index: number | string;
|
||||||
|
forceNewBlock: boolean;
|
||||||
|
preventRoot?: boolean;
|
||||||
|
isLast?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
class CodeTarget {
|
||||||
|
name: string;
|
||||||
|
signature: string = "";
|
||||||
|
indentLevel = 0;
|
||||||
|
loopLevel = 0;
|
||||||
|
code: string[] = [];
|
||||||
|
hasRoot = false;
|
||||||
|
hasCache = false;
|
||||||
|
|
||||||
|
constructor(name: string) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
addLine(line: string, idx?: number) {
|
||||||
|
const prefix = new Array(this.indentLevel + 2).join(" ");
|
||||||
|
if (idx === undefined) {
|
||||||
|
this.code.push(prefix + line);
|
||||||
|
} else {
|
||||||
|
this.code.splice(idx, 0, prefix + line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QWebCompiler {
|
||||||
|
blocks: BlockDescription[] = [];
|
||||||
|
nextId = 1;
|
||||||
|
nextBlockId = 1;
|
||||||
|
shouldProtectScope: boolean = false;
|
||||||
|
shouldDefineAssign: boolean = false;
|
||||||
|
shouldDefineKey0: boolean = false;
|
||||||
|
hasSafeContext: boolean | null = null;
|
||||||
|
hasRef: boolean = false;
|
||||||
|
// hasTCall: boolean = false;
|
||||||
|
isDebug: boolean = false;
|
||||||
|
functions: CodeTarget[] = [];
|
||||||
|
target = new CodeTarget("main");
|
||||||
|
templateName: string;
|
||||||
|
template: string;
|
||||||
|
ast: AST;
|
||||||
|
staticCalls: { id: string; template: string }[] = [];
|
||||||
|
|
||||||
|
constructor(template: string, name?: string) {
|
||||||
|
this.template = template;
|
||||||
|
this.ast = parse(template);
|
||||||
|
// console.warn(this.ast);
|
||||||
|
if (name) {
|
||||||
|
this.templateName = name;
|
||||||
|
} else {
|
||||||
|
if (template.length > 250) {
|
||||||
|
this.templateName = template.slice(0, 250) + "...";
|
||||||
|
} else {
|
||||||
|
this.templateName = template;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compile(): TemplateFunction {
|
||||||
|
const ast = this.ast;
|
||||||
|
this.isDebug = ast.type === ASTType.TDebug;
|
||||||
|
BlockDescription.nextBlockId = 1;
|
||||||
|
BlockDescription.nextDataId = 1;
|
||||||
|
this.compileAST(ast, { block: null, index: 0, forceNewBlock: false, isLast: true });
|
||||||
|
const code = this.generateCode();
|
||||||
|
// console.warn(code);
|
||||||
|
return new Function("bdom, helpers", code) as TemplateFunction;
|
||||||
|
}
|
||||||
|
|
||||||
|
addLine(line: string) {
|
||||||
|
this.target.addLine(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
generateId(prefix: string = ""): string {
|
||||||
|
return `${prefix}${this.nextId++}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateBlockName(): string {
|
||||||
|
return `block${this.blocks.length + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
insertAnchor(block: BlockDescription) {
|
||||||
|
const tag = `block-child-${block.children.length}`;
|
||||||
|
const anchor = xmlDoc.createElement(tag);
|
||||||
|
block.insert(anchor);
|
||||||
|
}
|
||||||
|
|
||||||
|
createBlock(
|
||||||
|
parentBlock: BlockDescription | null,
|
||||||
|
type: BlockType,
|
||||||
|
ctx: Context
|
||||||
|
): BlockDescription {
|
||||||
|
const hasRoot = this.target.hasRoot;
|
||||||
|
const block = new BlockDescription(this.target, type);
|
||||||
|
if (!hasRoot && !ctx.preventRoot) {
|
||||||
|
this.target.hasRoot = true;
|
||||||
|
block.isRoot = true;
|
||||||
|
}
|
||||||
|
if (parentBlock) {
|
||||||
|
parentBlock.children.push(block);
|
||||||
|
if (parentBlock.type === "list") {
|
||||||
|
block.parentVar = `c${parentBlock.id}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
insertBlock(expression: string, block: BlockDescription, ctx: Context): string | null {
|
||||||
|
let id: string | null = null;
|
||||||
|
const blockExpr = block.generateExpr(expression);
|
||||||
|
if (block.parentVar) {
|
||||||
|
this.addLine(
|
||||||
|
`${block.parentVar}[${ctx.index}] = withKey(${blockExpr}, key${this.target.loopLevel});`
|
||||||
|
);
|
||||||
|
} else if (block.isRoot && !ctx.preventRoot) {
|
||||||
|
this.addLine(`return ${blockExpr};`);
|
||||||
|
} else {
|
||||||
|
this.addLine(`let ${block.varName} = ${blockExpr};`);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateCode(): string {
|
||||||
|
let mainCode = this.target.code;
|
||||||
|
this.target.code = [];
|
||||||
|
this.target.indentLevel = 0;
|
||||||
|
// define blocks and utility functions
|
||||||
|
this.addLine(`let { text, createBlock, list, multi, html, toggler, component } = bdom;`);
|
||||||
|
this.addLine(
|
||||||
|
`let { withDefault, getTemplate, prepareList, withKey, zero, call, callSlot, capture, shallowEqual } = helpers;`
|
||||||
|
);
|
||||||
|
if (this.shouldDefineAssign) {
|
||||||
|
this.addLine(`let assign = Object.assign;`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let { id, template } of this.staticCalls) {
|
||||||
|
this.addLine(`const ${id} = getTemplate(${template});`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// define all blocks
|
||||||
|
if (this.blocks.length) {
|
||||||
|
this.addLine(``);
|
||||||
|
for (let block of this.blocks) {
|
||||||
|
if (block.dom) {
|
||||||
|
this.addLine(`let ${block.blockName} = createBlock(\`${block.asXmlString()}\`);`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// define all slots
|
||||||
|
for (let fn of this.functions) {
|
||||||
|
this.generateFunctions(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// // generate main code
|
||||||
|
this.target.indentLevel = 0;
|
||||||
|
this.addLine(``);
|
||||||
|
this.addLine(`return function template(ctx, node, key = "") {`);
|
||||||
|
if (this.hasRef) {
|
||||||
|
this.addLine(` const refs = ctx.__owl__.refs;`);
|
||||||
|
}
|
||||||
|
if (this.shouldProtectScope) {
|
||||||
|
this.addLine(` ctx = Object.create(ctx);`);
|
||||||
|
}
|
||||||
|
if (this.target.hasCache) {
|
||||||
|
this.addLine(` let cache = ctx.cache || {};`);
|
||||||
|
this.addLine(` let nextCache = ctx.cache = {};`);
|
||||||
|
}
|
||||||
|
// if (this.shouldDefineKey0) {
|
||||||
|
// this.addLine(` let key0;`);
|
||||||
|
// }
|
||||||
|
for (let line of mainCode) {
|
||||||
|
this.addLine(line);
|
||||||
|
}
|
||||||
|
// console.warn(this.target.code.join('\n'))
|
||||||
|
if (!this.target.hasRoot) {
|
||||||
|
throw new Error("missing root block");
|
||||||
|
}
|
||||||
|
this.addLine("}");
|
||||||
|
const code = this.target.code.join("\n");
|
||||||
|
|
||||||
|
if (this.isDebug) {
|
||||||
|
const msg = `[Owl Debug]\n${code}`;
|
||||||
|
console.log(msg);
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateFunctions(fn: CodeTarget) {
|
||||||
|
this.addLine("");
|
||||||
|
this.addLine(`const ${fn.name} = ${fn.signature}`);
|
||||||
|
if (fn.hasCache) {
|
||||||
|
this.addLine(`let cache = ctx.cache || {};`);
|
||||||
|
this.addLine(`let nextCache = ctx.cache = {};`);
|
||||||
|
}
|
||||||
|
for (let line of fn.code) {
|
||||||
|
this.addLine(line);
|
||||||
|
}
|
||||||
|
this.addLine(`}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
captureExpression(expr: string): string {
|
||||||
|
const tokens = compileExprToArray(expr);
|
||||||
|
const mapping = new Map<string, string>();
|
||||||
|
return tokens
|
||||||
|
.map((tok) => {
|
||||||
|
if (tok.varName) {
|
||||||
|
if (!mapping.has(tok.varName)) {
|
||||||
|
const varId = this.generateId("v");
|
||||||
|
mapping.set(tok.varName, varId);
|
||||||
|
this.addLine(`const ${varId} = ${tok.value};`);
|
||||||
|
}
|
||||||
|
tok.value = mapping.get(tok.varName)!;
|
||||||
|
}
|
||||||
|
return tok.value;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
compileAST(ast: AST, ctx: Context) {
|
||||||
|
switch (ast.type) {
|
||||||
|
case ASTType.Comment:
|
||||||
|
this.compileComment(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.Text:
|
||||||
|
this.compileText(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.DomNode:
|
||||||
|
this.compileTDomNode(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TEsc:
|
||||||
|
this.compileTEsc(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TRaw:
|
||||||
|
this.compileTRaw(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TIf:
|
||||||
|
this.compileTIf(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TForEach:
|
||||||
|
this.compileTForeach(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TKey:
|
||||||
|
this.compileTKey(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.Multi:
|
||||||
|
this.compileMulti(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TCall:
|
||||||
|
this.compileTCall(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TCallBlock:
|
||||||
|
this.compileTCallBlock(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TSet:
|
||||||
|
this.compileTSet(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TComponent:
|
||||||
|
this.compileComponent(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TDebug:
|
||||||
|
this.compileDebug(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TLog:
|
||||||
|
this.compileLog(ast, ctx);
|
||||||
|
break;
|
||||||
|
case ASTType.TSlot:
|
||||||
|
this.compileTSlot(ast, ctx);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileDebug(ast: ASTDebug, ctx: Context) {
|
||||||
|
this.addLine(`debugger;`);
|
||||||
|
if (ast.content) {
|
||||||
|
this.compileAST(ast.content, ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileLog(ast: ASTLog, ctx: Context) {
|
||||||
|
this.addLine(`console.log(${compileExpr(ast.expr)});`);
|
||||||
|
if (ast.content) {
|
||||||
|
this.compileAST(ast.content, ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileComment(ast: ASTComment, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
const isNewBlock = !block || forceNewBlock;
|
||||||
|
if (isNewBlock) {
|
||||||
|
block = this.createBlock(block, "block", ctx);
|
||||||
|
this.blocks.push(block);
|
||||||
|
}
|
||||||
|
const text = xmlDoc.createComment(ast.value);
|
||||||
|
block!.insert(text);
|
||||||
|
if (isNewBlock) {
|
||||||
|
this.insertBlock("", block!, ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileText(ast: ASTText, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
if (!block || forceNewBlock) {
|
||||||
|
block = this.createBlock(block, "text", ctx);
|
||||||
|
this.insertBlock(`text(\`${ast.value}\`)`, block, {
|
||||||
|
...ctx,
|
||||||
|
forceNewBlock: forceNewBlock && !block,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const createFn = ast.type === ASTType.Text ? xmlDoc.createTextNode : xmlDoc.createComment;
|
||||||
|
block.insert(createFn.call(xmlDoc, ast.value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
generateHandlerCode(handler: string, event: string = ""): string {
|
||||||
|
let args: string = "";
|
||||||
|
const name: string = handler.replace(/\(.*\)/, function (_args) {
|
||||||
|
args = _args.slice(1, -1);
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
const isMethodCall = name.match(FNAMEREGEXP);
|
||||||
|
if (isMethodCall) {
|
||||||
|
let handlerFn: string;
|
||||||
|
if (args) {
|
||||||
|
const argId = this.generateId("arg");
|
||||||
|
this.addLine(`const ${argId} = [${compileExpr(args)}];`);
|
||||||
|
handlerFn = `'${name}', ${argId}`;
|
||||||
|
} else {
|
||||||
|
handlerFn = `'${name}'`;
|
||||||
|
}
|
||||||
|
return `[${event ? `\`${event}\`` + ", " : ""}ctx, ${handlerFn!}]`;
|
||||||
|
} else {
|
||||||
|
let code = this.captureExpression(handler);
|
||||||
|
code = `{const res = (() => { return ${code} })(); if (typeof res === 'function') { res(e) }}`;
|
||||||
|
let handlerFn = `(e) => ${code}`;
|
||||||
|
if (event) {
|
||||||
|
handlerFn = `[\`${event}\`, ${handlerFn}]`;
|
||||||
|
}
|
||||||
|
return handlerFn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTDomNode(ast: ASTDomNode, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
const isNewBlock = !block || forceNewBlock;
|
||||||
|
let codeIdx = this.target.code.length;
|
||||||
|
if (isNewBlock) {
|
||||||
|
block = this.createBlock(block, "block", ctx);
|
||||||
|
this.blocks.push(block);
|
||||||
|
}
|
||||||
|
|
||||||
|
// attributes
|
||||||
|
const attrs: { [key: string]: string } = {};
|
||||||
|
for (let key in ast.attrs) {
|
||||||
|
if (key.startsWith("t-attf")) {
|
||||||
|
let expr = interpolate(ast.attrs[key]);
|
||||||
|
const idx = block!.insertData(expr);
|
||||||
|
attrs["block-attribute-" + idx] = key.slice(7);
|
||||||
|
// console.warn('ccc', staticAttrs)
|
||||||
|
} else if (key.startsWith("t-att")) {
|
||||||
|
let expr = compileExpr(ast.attrs[key]);
|
||||||
|
const idx = block!.insertData(expr);
|
||||||
|
if (key === "t-att") {
|
||||||
|
attrs[`block-attributes`] = String(idx);
|
||||||
|
} else {
|
||||||
|
attrs[`block-attribute-${idx}`] = key.slice(6);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
attrs[key] = ast.attrs[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// event handlers
|
||||||
|
for (let ev in ast.on) {
|
||||||
|
const name = this.generateHandlerCode(ast.on[ev]);
|
||||||
|
const idx = block!.insertData(name);
|
||||||
|
attrs[`block-handler-${idx}`] = ev;
|
||||||
|
}
|
||||||
|
|
||||||
|
// t-ref
|
||||||
|
if (ast.ref) {
|
||||||
|
this.hasRef = true;
|
||||||
|
const isDynamic = INTERP_REGEXP.test(ast.ref);
|
||||||
|
if (isDynamic) {
|
||||||
|
const str = ast.ref.replace(
|
||||||
|
INTERP_REGEXP,
|
||||||
|
(expr) => "${" + this.captureExpression(expr.slice(2, -2)) + "}"
|
||||||
|
);
|
||||||
|
const idx = block!.insertData(`(el) => refs[\`${str}\`] = el`);
|
||||||
|
attrs["block-ref"] = String(idx);
|
||||||
|
} else {
|
||||||
|
const idx = block!.insertData(`(el) => refs[\`${ast.ref}\`] = el`);
|
||||||
|
attrs["block-ref"] = String(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const dom = xmlDoc.createElement(ast.tag);
|
||||||
|
for (const [attr, val] of Object.entries(attrs)) {
|
||||||
|
if (!(attr === "class" && val === "")) {
|
||||||
|
dom.setAttribute(attr, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
block!.insert(dom);
|
||||||
|
if (ast.content.length) {
|
||||||
|
const initialDom = block!.currentDom;
|
||||||
|
block!.currentDom = dom;
|
||||||
|
const children = ast.content;
|
||||||
|
for (let i = 0; i < children.length; i++) {
|
||||||
|
const child = ast.content[i];
|
||||||
|
const subCtx: Context = {
|
||||||
|
block: block,
|
||||||
|
index: block!.childNumber,
|
||||||
|
forceNewBlock: false,
|
||||||
|
isLast: ctx.isLast && i === children.length - 1,
|
||||||
|
};
|
||||||
|
this.compileAST(child, subCtx);
|
||||||
|
}
|
||||||
|
block!.currentDom = initialDom;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNewBlock) {
|
||||||
|
this.insertBlock(`${block!.blockName}(ddd)`, block!, ctx)!;
|
||||||
|
// may need to rewrite code!
|
||||||
|
if (block!.children.length && block!.hasDynamicChildren) {
|
||||||
|
const code = this.target.code;
|
||||||
|
const children = block!.children.slice();
|
||||||
|
let current = children.shift();
|
||||||
|
for (let i = codeIdx; i < code.length; i++) {
|
||||||
|
if (code[i].trimStart().startsWith(`let ${current!.varName}`)) {
|
||||||
|
code[i] = code[i].replace(`let ${current!.varName}`, current!.varName);
|
||||||
|
current = children.shift();
|
||||||
|
if (!current) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.target.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTEsc(ast: ASTTEsc, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
let expr: string;
|
||||||
|
if (ast.expr === "0") {
|
||||||
|
expr = `ctx[zero]`;
|
||||||
|
} else {
|
||||||
|
expr = compileExpr(ast.expr);
|
||||||
|
if (ast.defaultValue) {
|
||||||
|
expr = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!block || forceNewBlock) {
|
||||||
|
block = this.createBlock(block, "text", ctx);
|
||||||
|
this.insertBlock(`text(${expr})`, block, { ...ctx, forceNewBlock: forceNewBlock && !block });
|
||||||
|
} else {
|
||||||
|
const idx = block.insertData(expr);
|
||||||
|
const text = xmlDoc.createElement(`block-text-${idx}`);
|
||||||
|
block.insert(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTRaw(ast: ASTTRaw, ctx: Context) {
|
||||||
|
let { block } = ctx;
|
||||||
|
if (block) {
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "html", ctx);
|
||||||
|
let expr = ast.expr === "0" ? "ctx[zero]" : compileExpr(ast.expr);
|
||||||
|
if (ast.body) {
|
||||||
|
const nextId = BlockDescription.nextBlockId;
|
||||||
|
const subCtx: Context = { block: null, index: 0, forceNewBlock: true };
|
||||||
|
this.compileAST({ type: ASTType.Multi, content: ast.body }, subCtx);
|
||||||
|
expr = `withDefault(${expr}, b${nextId})`;
|
||||||
|
}
|
||||||
|
this.insertBlock(`html(${expr})`, block, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTIf(ast: ASTTif, ctx: Context, nextNode?: ASTDomNode) {
|
||||||
|
let { block, forceNewBlock, index } = ctx;
|
||||||
|
let currentIndex = index;
|
||||||
|
const codeIdx = this.target.code.length;
|
||||||
|
const isNewBlock = !block || (block.type !== "multi" && forceNewBlock);
|
||||||
|
if (block) {
|
||||||
|
block.hasDynamicChildren = true;
|
||||||
|
}
|
||||||
|
if (!block || (block.type !== "multi" && forceNewBlock)) {
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
}
|
||||||
|
this.addLine(`if (${compileExpr(ast.condition)}) {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.insertAnchor(block!);
|
||||||
|
const subCtx: Context = { block: block, index: currentIndex, forceNewBlock: true };
|
||||||
|
this.compileAST(ast.content, subCtx);
|
||||||
|
this.target.indentLevel--;
|
||||||
|
if (ast.tElif) {
|
||||||
|
for (let clause of ast.tElif) {
|
||||||
|
this.addLine(`} else if (${compileExpr(clause.condition)}) {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.insertAnchor(block);
|
||||||
|
const subCtx: Context = {
|
||||||
|
block: block,
|
||||||
|
index: currentIndex,
|
||||||
|
forceNewBlock: true,
|
||||||
|
};
|
||||||
|
this.compileAST(clause.content, subCtx);
|
||||||
|
this.target.indentLevel--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ast.tElse) {
|
||||||
|
this.addLine(`} else {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.insertAnchor(block);
|
||||||
|
const subCtx: Context = {
|
||||||
|
block: block,
|
||||||
|
index: currentIndex,
|
||||||
|
forceNewBlock: true,
|
||||||
|
};
|
||||||
|
this.compileAST(ast.tElse, subCtx);
|
||||||
|
this.target.indentLevel--;
|
||||||
|
}
|
||||||
|
this.addLine("}");
|
||||||
|
if (isNewBlock) {
|
||||||
|
// note: this part is duplicated from end of compiledomnode:
|
||||||
|
if (block!.children.length) {
|
||||||
|
const code = this.target.code;
|
||||||
|
const children = block!.children.slice();
|
||||||
|
let current = children.shift();
|
||||||
|
for (let i = codeIdx; i < code.length; i++) {
|
||||||
|
if (code[i].trimStart().startsWith(`let ${current!.varName}`)) {
|
||||||
|
code[i] = code[i].replace(`let ${current!.varName}`, current!.varName);
|
||||||
|
current = children.shift();
|
||||||
|
if (!current) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.target.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// note: this part is duplicated from end of compilemulti:
|
||||||
|
const args = block!.children.map((c) => c.varName).join(", ");
|
||||||
|
this.insertBlock(`multi([${args}])`, block!, ctx)!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTForeach(ast: ASTTForEach, ctx: Context) {
|
||||||
|
let { block } = ctx;
|
||||||
|
if (block) {
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "list", ctx);
|
||||||
|
this.target.loopLevel++;
|
||||||
|
const loopVar = `i${this.target.loopLevel}`;
|
||||||
|
this.addLine(`ctx = Object.create(ctx);`);
|
||||||
|
// const cId = this.generateId();
|
||||||
|
const vals = `v${block.id}`;
|
||||||
|
const keys = `k${block.id}`;
|
||||||
|
const l = `l${block.id}`;
|
||||||
|
const c = `c${block.id}`;
|
||||||
|
this.addLine(
|
||||||
|
`const [${keys}, ${vals}, ${l}, ${c}] = prepareList(${compileExpr(ast.collection)});`
|
||||||
|
);
|
||||||
|
this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.addLine(`ctx[\`${ast.elem}\`] = ${vals}[${loopVar}];`);
|
||||||
|
if (!ast.hasNoFirst) {
|
||||||
|
this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`);
|
||||||
|
}
|
||||||
|
if (!ast.hasNoLast) {
|
||||||
|
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${vals}.length - 1;`);
|
||||||
|
}
|
||||||
|
if (!ast.hasNoIndex) {
|
||||||
|
this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`);
|
||||||
|
}
|
||||||
|
if (!ast.hasNoValue) {
|
||||||
|
this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
|
||||||
|
}
|
||||||
|
this.addLine(`let key${this.target.loopLevel} = ${ast.key ? compileExpr(ast.key) : loopVar};`);
|
||||||
|
let id: string;
|
||||||
|
if (ast.memo) {
|
||||||
|
this.target.hasCache = true;
|
||||||
|
this.shouldDefineAssign = true;
|
||||||
|
id = this.generateId();
|
||||||
|
this.addLine(`let memo${id} = ${compileExpr(ast.memo)}`);
|
||||||
|
this.addLine(`let vnode${id} = cache[key${this.target.loopLevel}];`);
|
||||||
|
this.addLine(`if (vnode${id}) {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.addLine(`if (shallowEqual(vnode${id}.memo, memo${id})) {`);
|
||||||
|
this.target.indentLevel++;
|
||||||
|
this.addLine(`${c}[${loopVar}] = vnode${id};`);
|
||||||
|
this.addLine(`nextCache[key${this.target.loopLevel}] = vnode${id};`);
|
||||||
|
this.addLine(`continue;`);
|
||||||
|
this.target.indentLevel--;
|
||||||
|
this.addLine("}");
|
||||||
|
this.target.indentLevel--;
|
||||||
|
this.addLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
const subCtx: Context = {
|
||||||
|
block: block, //collectionBlock,
|
||||||
|
index: loopVar,
|
||||||
|
forceNewBlock: true,
|
||||||
|
};
|
||||||
|
this.compileAST(ast.body, subCtx);
|
||||||
|
if (!ast.key) {
|
||||||
|
console.warn(
|
||||||
|
`"Directive t-foreach should always be used with a t-key! (in template: '${this.templateName}')"`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (ast.memo) {
|
||||||
|
this.addLine(
|
||||||
|
`nextCache[key${this.target.loopLevel}] = assign(${c}[${loopVar}], {memo: memo${id!}});`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.target.indentLevel--;
|
||||||
|
this.target.loopLevel--;
|
||||||
|
this.addLine(`}`);
|
||||||
|
if (!ctx.isLast) {
|
||||||
|
this.addLine(`ctx = ctx.__proto__;`);
|
||||||
|
}
|
||||||
|
this.insertBlock("l", block, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTKey(ast: ASTTKey, ctx: Context) {
|
||||||
|
this.compileAST(ast.content, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
compileMulti(ast: ASTMulti, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
const isNewBlock = !block || forceNewBlock;
|
||||||
|
let codeIdx = this.target.code.length;
|
||||||
|
if (isNewBlock) {
|
||||||
|
const n = ast.content.filter((c) => c.type !== ASTType.TSet).length;
|
||||||
|
if (n <= 1) {
|
||||||
|
for (let child of ast.content) {
|
||||||
|
this.compileAST(child, ctx);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
}
|
||||||
|
let index = 0;
|
||||||
|
for (let i = 0, l = ast.content.length; i < l; i++) {
|
||||||
|
const child = ast.content[i];
|
||||||
|
const isTSet = child.type === ASTType.TSet;
|
||||||
|
const subCtx: Context = {
|
||||||
|
block: block,
|
||||||
|
index: index,
|
||||||
|
forceNewBlock: !isTSet,
|
||||||
|
preventRoot: ctx.preventRoot,
|
||||||
|
isLast: ctx.isLast && i === l - 1,
|
||||||
|
};
|
||||||
|
this.compileAST(child, subCtx);
|
||||||
|
if (!isTSet) {
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isNewBlock) {
|
||||||
|
if (block!.hasDynamicChildren) {
|
||||||
|
if (block!.children.length) {
|
||||||
|
const code = this.target.code;
|
||||||
|
const children = block!.children.slice();
|
||||||
|
let current = children.shift();
|
||||||
|
for (let i = codeIdx; i < code.length; i++) {
|
||||||
|
if (code[i].trimStart().startsWith(`let ${current!.varName}`)) {
|
||||||
|
code[i] = code[i].replace(`let ${current!.varName}`, current!.varName);
|
||||||
|
current = children.shift();
|
||||||
|
if (!current) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.target.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const args = block!.children.map((c) => c.varName).join(", ");
|
||||||
|
this.insertBlock(`multi([${args}])`, block!, ctx)!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTCall(ast: ASTTCall, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
// this.hasTCall = true;
|
||||||
|
if (ast.body) {
|
||||||
|
this.addLine(`ctx = Object.create(ctx);`);
|
||||||
|
const nextId = BlockDescription.nextBlockId;
|
||||||
|
const subCtx: Context = { block: null, index: 0, forceNewBlock: true, preventRoot: true };
|
||||||
|
this.compileAST({ type: ASTType.Multi, content: ast.body }, subCtx);
|
||||||
|
if (nextId !== BlockDescription.nextBlockId) {
|
||||||
|
this.addLine(`ctx[zero] = b${nextId};`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const isDynamic = INTERP_REGEXP.test(ast.name);
|
||||||
|
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
|
||||||
|
if (block) {
|
||||||
|
if (!forceNewBlock) {
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const key = `key + \`${this.generateComponentKey()}\``;
|
||||||
|
if (isDynamic) {
|
||||||
|
const templateVar = this.generateId("template");
|
||||||
|
this.addLine(`const ${templateVar} = ${subTemplate};`);
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
this.insertBlock(`call(${templateVar}, ctx, node, ${key})`, block!, {
|
||||||
|
...ctx,
|
||||||
|
forceNewBlock: !block,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const id = this.generateId(`callTemplate_`);
|
||||||
|
this.staticCalls.push({ id, template: subTemplate });
|
||||||
|
// console.warn('coucoup', this.target.hasRoot)
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
this.insertBlock(`${id}(ctx, node, ${key})`, block!, { ...ctx, forceNewBlock: !block });
|
||||||
|
}
|
||||||
|
if (ast.body && !ctx.isLast) {
|
||||||
|
this.addLine(`ctx = ctx.__proto__;`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTCallBlock(ast: ASTTCallBlock, ctx: Context) {
|
||||||
|
let { block, forceNewBlock } = ctx;
|
||||||
|
if (block) {
|
||||||
|
if (!forceNewBlock) {
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
this.insertBlock(compileExpr(ast.name), block, { ...ctx, forceNewBlock: !block });
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTSet(ast: ASTTSet, ctx: Context) {
|
||||||
|
this.shouldProtectScope = true;
|
||||||
|
const expr = ast.value ? compileExpr(ast.value || "") : "null";
|
||||||
|
if (ast.body) {
|
||||||
|
const subCtx: Context = { block: null, index: 0, forceNewBlock: true };
|
||||||
|
const nextId = `b${BlockDescription.nextBlockId}`;
|
||||||
|
this.compileAST({ type: ASTType.Multi, content: ast.body }, subCtx);
|
||||||
|
const value = ast.value ? (nextId ? `withDefault(${expr}, ${nextId})` : expr) : nextId;
|
||||||
|
this.addLine(`ctx[\`${ast.name}\`] = ${value};`);
|
||||||
|
} else {
|
||||||
|
let value: string;
|
||||||
|
if (ast.defaultValue) {
|
||||||
|
if (ast.value) {
|
||||||
|
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
|
||||||
|
} else {
|
||||||
|
value = `\`${ast.defaultValue}\``;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
value = expr;
|
||||||
|
}
|
||||||
|
this.addLine(`ctx[\`${ast.name}\`] = ${value};`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
generateComponentKey() {
|
||||||
|
const parts = [this.generateId("__")];
|
||||||
|
for (let i = 0; i < this.target.loopLevel; i++) {
|
||||||
|
parts.push(`\${key${i + 1}}`);
|
||||||
|
}
|
||||||
|
return parts.join("__");
|
||||||
|
}
|
||||||
|
|
||||||
|
compileComponent(ast: ASTComponent, ctx: Context) {
|
||||||
|
let { block } = ctx;
|
||||||
|
let extraArgs: { [key: string]: string } = {};
|
||||||
|
|
||||||
|
// props
|
||||||
|
const props: string[] = [];
|
||||||
|
for (let p in ast.props) {
|
||||||
|
props.push(`${p}: ${compileExpr(ast.props[p]) || undefined}`);
|
||||||
|
}
|
||||||
|
const propString = `{${props.join(",")}}`;
|
||||||
|
|
||||||
|
// cmap key
|
||||||
|
const key = this.generateComponentKey();
|
||||||
|
let expr: string;
|
||||||
|
if (ast.isDynamic) {
|
||||||
|
expr = this.generateId("Comp");
|
||||||
|
this.addLine(`let ${expr} = ${compileExpr(ast.name)};`);
|
||||||
|
} else {
|
||||||
|
expr = `\`${ast.name}\``;
|
||||||
|
}
|
||||||
|
let blockArgs = `${expr}, ${propString}, key + \`${key}\`, node, ctx`;
|
||||||
|
|
||||||
|
// slots
|
||||||
|
const hasSlot = !!Object.keys(ast.slots).length;
|
||||||
|
let slotDef: string;
|
||||||
|
if (hasSlot) {
|
||||||
|
if (this.hasSafeContext === null) {
|
||||||
|
this.hasSafeContext = !this.template.includes("t-set") && !this.template.includes("t-call");
|
||||||
|
}
|
||||||
|
let ctxStr = "ctx";
|
||||||
|
if (this.target.loopLevel || !this.hasSafeContext) {
|
||||||
|
ctxStr = this.generateId("ctx");
|
||||||
|
this.addLine(`const ${ctxStr} = capture(ctx);`);
|
||||||
|
}
|
||||||
|
let slotStr: string[] = [];
|
||||||
|
const initialTarget = this.target;
|
||||||
|
for (let slotName in ast.slots) {
|
||||||
|
let name = this.generateId("slot");
|
||||||
|
const slot = new CodeTarget(name);
|
||||||
|
slot.signature = "ctx => (node, key) => {";
|
||||||
|
this.functions.push(slot);
|
||||||
|
this.target = slot;
|
||||||
|
const subCtx: Context = { block: null, index: 0, forceNewBlock: true };
|
||||||
|
this.compileAST(ast.slots[slotName], subCtx);
|
||||||
|
if (this.hasRef) {
|
||||||
|
slot.signature = "ctx => node => {";
|
||||||
|
slot.code.unshift(` const refs = ctx.__owl__.refs`);
|
||||||
|
slotStr.push(`'${slotName}': ${name}(${ctxStr})`);
|
||||||
|
} else {
|
||||||
|
slotStr.push(`'${slotName}': ${name}(${ctxStr})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.target = initialTarget;
|
||||||
|
slotDef = `{${slotStr.join(", ")}}`;
|
||||||
|
extraArgs.slots = slotDef;
|
||||||
|
}
|
||||||
|
|
||||||
|
// handlers
|
||||||
|
const hasHandlers = Object.keys(ast.handlers).length;
|
||||||
|
if (hasHandlers) {
|
||||||
|
const vars = Object.keys(ast.handlers).map((ev) => {
|
||||||
|
let id = this.generateId("h");
|
||||||
|
this.addLine(`let ${id} = ${this.generateHandlerCode(ast.handlers[ev], ev)};`);
|
||||||
|
return id;
|
||||||
|
});
|
||||||
|
extraArgs.handlers = `[${vars}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (block && ctx.forceNewBlock === false) {
|
||||||
|
// todo: check the forcenewblock condition
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
let blockExpr = `component(${blockArgs})`;
|
||||||
|
if (Object.keys(extraArgs).length) {
|
||||||
|
this.shouldDefineAssign = true;
|
||||||
|
const content = Object.keys(extraArgs).map((k) => `${k}: ${extraArgs[k]}`);
|
||||||
|
blockExpr = `assign(${blockExpr}, {${content.join(", ")}})`;
|
||||||
|
}
|
||||||
|
if (ast.isDynamic) {
|
||||||
|
blockExpr = `toggler(${expr}, ${blockExpr})`;
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
this.insertBlock(blockExpr, block, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTSlot(ast: ASTSlot, ctx: Context) {
|
||||||
|
let { block } = ctx;
|
||||||
|
let blockString: string;
|
||||||
|
let slotName;
|
||||||
|
let dynamic = false;
|
||||||
|
if (ast.name.match(INTERP_REGEXP)) {
|
||||||
|
dynamic = true;
|
||||||
|
slotName = interpolate(ast.name);
|
||||||
|
} else {
|
||||||
|
slotName = "'" + ast.name + "'";
|
||||||
|
}
|
||||||
|
if (ast.defaultContent) {
|
||||||
|
let name = this.generateId("defaultSlot");
|
||||||
|
const slot = new CodeTarget(name);
|
||||||
|
slot.signature = "ctx => {";
|
||||||
|
this.functions.push(slot);
|
||||||
|
const initialTarget = this.target;
|
||||||
|
const subCtx: Context = { block: null, index: 0, forceNewBlock: true };
|
||||||
|
this.target = slot;
|
||||||
|
this.compileAST(ast.defaultContent, subCtx);
|
||||||
|
this.target = initialTarget;
|
||||||
|
blockString = `callSlot(ctx, node, key, ${slotName}, ${name}, ${dynamic})`;
|
||||||
|
} else {
|
||||||
|
if (dynamic) {
|
||||||
|
let name = this.generateId("slot");
|
||||||
|
this.addLine(`const ${name} = ${slotName};`);
|
||||||
|
blockString = `toggler(${name}, callSlot(ctx, node, key, ${name}))`;
|
||||||
|
} else {
|
||||||
|
blockString = `callSlot(ctx, node, key, ${slotName})`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (block) {
|
||||||
|
this.insertAnchor(block);
|
||||||
|
}
|
||||||
|
block = this.createBlock(block, "multi", ctx);
|
||||||
|
this.insertBlock(blockString, block, { ...ctx, forceNewBlock: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,276 +0,0 @@
|
|||||||
import { VNode } from "../vdom/index";
|
|
||||||
import { QWeb } from "./qweb";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl QWeb Extensions
|
|
||||||
*
|
|
||||||
* This file contains the implementation of non standard QWeb directives, added
|
|
||||||
* by Owl and that will only work on Owl projects:
|
|
||||||
*
|
|
||||||
* - t-on
|
|
||||||
* - t-ref
|
|
||||||
* - t-transition
|
|
||||||
* - t-mounted
|
|
||||||
* - t-slot
|
|
||||||
* - t-model
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-on
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// these are pieces of code that will be injected into the event handler if
|
|
||||||
// modifiers are specified
|
|
||||||
export const MODS_CODE = {
|
|
||||||
prevent: "e.preventDefault();",
|
|
||||||
self: "if (e.target !== this.elm) {return}",
|
|
||||||
stop: "e.stopPropagation();"
|
|
||||||
};
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "on",
|
|
||||||
priority: 90,
|
|
||||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
const [eventName, ...mods] = fullName.slice(5).split(".");
|
|
||||||
if (!eventName) {
|
|
||||||
throw new Error("Missing event name with t-on directive");
|
|
||||||
}
|
|
||||||
let extraArgs;
|
|
||||||
let handlerName = value.replace(/\(.*\)/, function(args) {
|
|
||||||
extraArgs = args.slice(1, -1);
|
|
||||||
return "";
|
|
||||||
});
|
|
||||||
let params = extraArgs ? `owner, ${ctx.formatExpression(extraArgs)}` : "owner";
|
|
||||||
let handler = `function (e) {`;
|
|
||||||
handler += mods
|
|
||||||
.map(function(mod) {
|
|
||||||
return MODS_CODE[mod];
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
if (handlerName) {
|
|
||||||
if (!extraArgs) {
|
|
||||||
handler += `const fn = context['${handlerName}'];`;
|
|
||||||
handler += `if (fn) { fn.call(${params}, e); } else { context.${handlerName}; }`;
|
|
||||||
handler += `}`;
|
|
||||||
ctx.addLine(
|
|
||||||
`extra.handlers['${eventName}' + ${nodeID}] = extra.handlers['${eventName}' + ${nodeID}] || ${handler};`
|
|
||||||
);
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
|
||||||
} else {
|
|
||||||
const handlerKey = `handler${ctx.generateID()}`;
|
|
||||||
ctx.addLine(
|
|
||||||
`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`
|
|
||||||
);
|
|
||||||
handler += `if (${handlerKey}) { ${handlerKey}(e); } else { context.${value}; }`;
|
|
||||||
handler += `}`;
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
handler += "}";
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-ref
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "ref",
|
|
||||||
priority: 95,
|
|
||||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
|
||||||
ctx.rootContext.shouldDefineRefs = true;
|
|
||||||
const refKey = `ref${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
|
||||||
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
|
||||||
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-transition
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.utils.nextFrame = function(cb: () => void) {
|
|
||||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
|
||||||
};
|
|
||||||
|
|
||||||
QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
|
||||||
const elm = <HTMLElement>vn.elm;
|
|
||||||
// remove potential duplicated vnode that is currently being removed, to
|
|
||||||
// prevent from having twice the same node in the DOM during an animation
|
|
||||||
const dup = elm.parentElement && elm.parentElement!.querySelector(`*[data-owl-key='${vn.key}']`);
|
|
||||||
if (dup) {
|
|
||||||
dup.remove();
|
|
||||||
}
|
|
||||||
|
|
||||||
elm.classList.add(name + "-enter");
|
|
||||||
elm.classList.add(name + "-enter-active");
|
|
||||||
const finalize = () => {
|
|
||||||
elm.classList.remove(name + "-enter-active");
|
|
||||||
elm.classList.remove(name + "-enter-to");
|
|
||||||
};
|
|
||||||
this.nextFrame(() => {
|
|
||||||
elm.classList.remove(name + "-enter");
|
|
||||||
elm.classList.add(name + "-enter-to");
|
|
||||||
whenTransitionEnd(elm, finalize);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
QWeb.utils.transitionRemove = function(vn: VNode, name: string, rm: () => void) {
|
|
||||||
const elm = <HTMLElement>vn.elm;
|
|
||||||
elm.setAttribute("data-owl-key", vn.key!);
|
|
||||||
|
|
||||||
elm.classList.add(name + "-leave");
|
|
||||||
elm.classList.add(name + "-leave-active");
|
|
||||||
const finalize = () => {
|
|
||||||
elm.classList.remove(name + "-leave-active");
|
|
||||||
elm.classList.remove(name + "-leave-to");
|
|
||||||
rm();
|
|
||||||
};
|
|
||||||
this.nextFrame(() => {
|
|
||||||
elm.classList.remove(name + "-leave");
|
|
||||||
elm.classList.add(name + "-leave-to");
|
|
||||||
whenTransitionEnd(elm, finalize);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
function getTimeout(delays: Array<string>, durations: Array<string>): number {
|
|
||||||
/* istanbul ignore next */
|
|
||||||
while (delays.length < durations.length) {
|
|
||||||
delays = delays.concat(delays);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Math.max.apply(
|
|
||||||
null,
|
|
||||||
durations.map((d, i) => {
|
|
||||||
return toMs(d) + toMs(delays[i]);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
|
|
||||||
// in a locale-dependent way, using a comma instead of a dot.
|
|
||||||
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
|
|
||||||
// as a floor function) causing unexpected behaviors
|
|
||||||
function toMs(s: string): number {
|
|
||||||
return Number(s.slice(0, -1).replace(",", ".")) * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
function whenTransitionEnd(elm: HTMLElement, cb) {
|
|
||||||
const styles = window.getComputedStyle(elm);
|
|
||||||
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
|
||||||
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
|
||||||
const timeout: number = getTimeout(delays, durations);
|
|
||||||
if (timeout > 0) {
|
|
||||||
elm.addEventListener("transitionend", cb, { once: true });
|
|
||||||
} else {
|
|
||||||
cb();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "transition",
|
|
||||||
priority: 96,
|
|
||||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
let name = value;
|
|
||||||
const hooks = {
|
|
||||||
insert: `utils.transitionInsert(vn, '${name}');`,
|
|
||||||
remove: `utils.transitionRemove(vn, '${name}', rm);`
|
|
||||||
};
|
|
||||||
for (let hookName in hooks) {
|
|
||||||
addNodeHook(hookName, hooks[hookName]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-slot
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "slot",
|
|
||||||
priority: 80,
|
|
||||||
atNodeEncounter({ ctx, value }): boolean {
|
|
||||||
const slotKey = ctx.generateID();
|
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
ctx.addLine(
|
|
||||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
|
||||||
);
|
|
||||||
ctx.addIf(`slot${slotKey}`);
|
|
||||||
let parentNode = `c${ctx.parentNode}`;
|
|
||||||
if (!ctx.parentNode) {
|
|
||||||
ctx.rootContext.shouldDefineResult = true;
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
parentNode = `children${ctx.nextID++}`;
|
|
||||||
ctx.addLine(`let ${parentNode}= []`);
|
|
||||||
ctx.addLine(`result = {}`);
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
|
||||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, vars: extra.vars, parent: owner}));`
|
|
||||||
);
|
|
||||||
if (!ctx.parentNode) {
|
|
||||||
ctx.addLine(`utils.defineProxy(result, ${parentNode}[0]);`);
|
|
||||||
}
|
|
||||||
ctx.closeIf();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-model
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.utils.toNumber = function(val: string): number | string {
|
|
||||||
const n = parseFloat(val);
|
|
||||||
return isNaN(n) ? val : n;
|
|
||||||
};
|
|
||||||
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "model",
|
|
||||||
priority: 42,
|
|
||||||
atNodeCreation({ ctx, nodeID, value, node, fullName, addNodeHook }) {
|
|
||||||
const type = node.getAttribute("type");
|
|
||||||
let handler;
|
|
||||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
|
||||||
const expr = ctx.formatExpression(value);
|
|
||||||
if (node.tagName === "select") {
|
|
||||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
|
||||||
addNodeHook("create", `n.elm.value=${expr};`);
|
|
||||||
event = "change";
|
|
||||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
|
||||||
} else if (type === "checkbox") {
|
|
||||||
ctx.addLine(`p${nodeID}.props = {checked: ${expr}};`);
|
|
||||||
handler = `(ev) => {${expr} = ev.target.checked}`;
|
|
||||||
} else if (type === "radio") {
|
|
||||||
const nodeValue = node.getAttribute("value")!;
|
|
||||||
ctx.addLine(`p${nodeID}.props = {checked:${expr} === '${nodeValue}'};`);
|
|
||||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
|
||||||
event = "click";
|
|
||||||
} else {
|
|
||||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
|
||||||
const trimCode = fullName.includes(".trim") ? ".trim()" : "";
|
|
||||||
let valueCode = `ev.target.value${trimCode}`;
|
|
||||||
if (fullName.includes(".number")) {
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
valueCode = `utils.toNumber(${valueCode})`;
|
|
||||||
}
|
|
||||||
handler = `(ev) => {${expr} = ${valueCode}}`;
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
|
||||||
`extra.handlers['${event}' + ${nodeID}] = extra.handlers['${event}' + ${nodeID}] || (${handler});`
|
|
||||||
);
|
|
||||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// t-key
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
QWeb.addDirective({
|
|
||||||
name: "key",
|
|
||||||
priority: 45,
|
|
||||||
atNodeEncounter({ ctx, value }) {
|
|
||||||
let id = ctx.generateID();
|
|
||||||
ctx.addLine(`const nodeKey${id} = ${ctx.formatExpression(value)};`);
|
|
||||||
ctx.lastNodeKey = `nodeKey${id}`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
import "./base_directives";
|
|
||||||
import "./extensions";
|
|
||||||
|
|
||||||
export { CompiledTemplate, QWeb } from "./qweb";
|
|
||||||
@@ -25,30 +25,27 @@
|
|||||||
// Misc types, constants and helpers
|
// Misc types, constants and helpers
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,typeof,eval,void,Math,RegExp,Array,Object,Date".split(
|
const RESERVED_WORDS =
|
||||||
|
"true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||||
","
|
","
|
||||||
);
|
);
|
||||||
|
|
||||||
const WORD_REPLACEMENT = {
|
const WORD_REPLACEMENT: { [key: string]: string } = Object.assign(Object.create(null), {
|
||||||
and: "&&",
|
and: "&&",
|
||||||
or: "||",
|
or: "||",
|
||||||
gt: ">",
|
gt: ">",
|
||||||
gte: ">=",
|
gte: ">=",
|
||||||
lt: "<",
|
lt: "<",
|
||||||
lte: "<="
|
lte: "<=",
|
||||||
};
|
});
|
||||||
|
|
||||||
export interface QWebExprVar {
|
export interface QWebVar {
|
||||||
id: string;
|
id: string; // foo
|
||||||
expr: string;
|
expr: string; // scope.foo (local variables => only foo)
|
||||||
|
value?: string; // 1 + 3
|
||||||
|
hasBody?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QWebXMLVar {
|
|
||||||
xml: NodeList;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type QWebVar = QWebExprVar | QWebXMLVar;
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Tokenizer
|
// Tokenizer
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -61,6 +58,7 @@ type TKind =
|
|||||||
| "RIGHT_PAREN"
|
| "RIGHT_PAREN"
|
||||||
| "COMMA"
|
| "COMMA"
|
||||||
| "VALUE"
|
| "VALUE"
|
||||||
|
| "TEMPLATE_STRING"
|
||||||
| "SYMBOL"
|
| "SYMBOL"
|
||||||
| "OPERATOR"
|
| "OPERATOR"
|
||||||
| "COLON";
|
| "COLON";
|
||||||
@@ -68,10 +66,13 @@ type TKind =
|
|||||||
interface Token {
|
interface Token {
|
||||||
type: TKind;
|
type: TKind;
|
||||||
value: string;
|
value: string;
|
||||||
|
originalValue?: string;
|
||||||
size?: number;
|
size?: number;
|
||||||
|
varName?: string;
|
||||||
|
replace?: Function;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
const STATIC_TOKEN_MAP: { [key: string]: TKind } = Object.assign(Object.create(null), {
|
||||||
"{": "LEFT_BRACE",
|
"{": "LEFT_BRACE",
|
||||||
"}": "RIGHT_BRACE",
|
"}": "RIGHT_BRACE",
|
||||||
"[": "LEFT_BRACKET",
|
"[": "LEFT_BRACKET",
|
||||||
@@ -79,17 +80,19 @@ const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
|||||||
":": "COLON",
|
":": "COLON",
|
||||||
",": "COMMA",
|
",": "COMMA",
|
||||||
"(": "LEFT_PAREN",
|
"(": "LEFT_PAREN",
|
||||||
")": "RIGHT_PAREN"
|
")": "RIGHT_PAREN",
|
||||||
};
|
});
|
||||||
|
|
||||||
const OPERATORS = ".,===,==,+,!==,!=,!,||,&&,>=,>,<=,<,?,-,*,/,%".split(",");
|
// note that the space after typeof is relevant. It makes sure that the formatted
|
||||||
|
// expression has a space after typeof
|
||||||
|
const OPERATORS = "...,.,===,==,+,!==,!=,!,||,&&,>=,>,<=,<,?,-,*,/,%,typeof ,=>,=,;,in ".split(",");
|
||||||
|
|
||||||
type Tokenizer = (expr: string) => Token | false;
|
type Tokenizer = (expr: string) => Token | false;
|
||||||
|
|
||||||
let tokenizeString: Tokenizer = function(expr) {
|
let tokenizeString: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
let start = s;
|
let start = s;
|
||||||
if (s !== "'" && s !== '"') {
|
if (s !== "'" && s !== '"' && s !== "`") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -111,10 +114,21 @@ let tokenizeString: Tokenizer = function(expr) {
|
|||||||
throw new Error("Invalid expression");
|
throw new Error("Invalid expression");
|
||||||
}
|
}
|
||||||
s += start;
|
s += start;
|
||||||
|
if (start === "`") {
|
||||||
|
return {
|
||||||
|
type: "TEMPLATE_STRING",
|
||||||
|
value: s,
|
||||||
|
replace(replacer: any) {
|
||||||
|
return s.replace(/\$\{(.*?)\}/g, (match, group) => {
|
||||||
|
return "${" + replacer(group) + "}";
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
return { type: "VALUE", value: s };
|
return { type: "VALUE", value: s };
|
||||||
};
|
};
|
||||||
|
|
||||||
let tokenizeNumber: Tokenizer = function(expr) {
|
let tokenizeNumber: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
if (s && s.match(/[0-9]/)) {
|
if (s && s.match(/[0-9]/)) {
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -128,7 +142,7 @@ let tokenizeNumber: Tokenizer = function(expr) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let tokenizeSymbol: Tokenizer = function(expr) {
|
let tokenizeSymbol: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
if (s && s.match(/[a-zA-Z_\$]/)) {
|
if (s && s.match(/[a-zA-Z_\$]/)) {
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -145,7 +159,7 @@ let tokenizeSymbol: Tokenizer = function(expr) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const tokenizeStatic: Tokenizer = function(expr) {
|
const tokenizeStatic: Tokenizer = function (expr) {
|
||||||
const char = expr[0];
|
const char = expr[0];
|
||||||
if (char && char in STATIC_TOKEN_MAP) {
|
if (char && char in STATIC_TOKEN_MAP) {
|
||||||
return { type: STATIC_TOKEN_MAP[char], value: char };
|
return { type: STATIC_TOKEN_MAP[char], value: char };
|
||||||
@@ -153,7 +167,7 @@ const tokenizeStatic: Tokenizer = function(expr) {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const tokenizeOperator: Tokenizer = function(expr) {
|
const tokenizeOperator: Tokenizer = function (expr) {
|
||||||
for (let op of OPERATORS) {
|
for (let op of OPERATORS) {
|
||||||
if (expr.startsWith(op)) {
|
if (expr.startsWith(op)) {
|
||||||
return { type: "OPERATOR", value: op };
|
return { type: "OPERATOR", value: op };
|
||||||
@@ -165,9 +179,9 @@ const tokenizeOperator: Tokenizer = function(expr) {
|
|||||||
const TOKENIZERS = [
|
const TOKENIZERS = [
|
||||||
tokenizeString,
|
tokenizeString,
|
||||||
tokenizeNumber,
|
tokenizeNumber,
|
||||||
|
tokenizeOperator,
|
||||||
tokenizeSymbol,
|
tokenizeSymbol,
|
||||||
tokenizeStatic,
|
tokenizeStatic,
|
||||||
tokenizeOperator
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -210,6 +224,11 @@ export function tokenize(expr: string): Token[] {
|
|||||||
// Expression "evaluator"
|
// Expression "evaluator"
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const isLeftSeparator = (token: Token) =>
|
||||||
|
token && (token.type === "LEFT_BRACE" || token.type === "COMMA");
|
||||||
|
const isRightSeparator = (token: Token) =>
|
||||||
|
token && (token.type === "RIGHT_BRACE" || token.type === "COMMA");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is the main function exported by this file. This is the code that will
|
* This is the main function exported by this file. This is the code that will
|
||||||
* process an expression (given as a string) and returns another expression with
|
* process an expression (given as a string) and returns another expression with
|
||||||
@@ -230,35 +249,100 @@ export function tokenize(expr: string): Token[] {
|
|||||||
* - unless the previous token is a dot (in that case, this is a property: `a.b`)
|
* - unless the previous token is a dot (in that case, this is a property: `a.b`)
|
||||||
* - or if the previous token is a left brace or a comma, and the next token is
|
* - or if the previous token is a left brace or a comma, and the next token is
|
||||||
* a colon (in that case, this is an object key: `{a: b}`)
|
* a colon (in that case, this is an object key: `{a: b}`)
|
||||||
|
*
|
||||||
|
* Some specific code is also required to support arrow functions. If we detect
|
||||||
|
* the arrow operator, then we add the current (or some previous tokens) token to
|
||||||
|
* the list of variables so it does not get replaced by a lookup in the context
|
||||||
*/
|
*/
|
||||||
export function compileExpr(expr: string, vars: { [key: string]: QWebVar }): string {
|
export function compileExprToArray(expr: string): Token[] {
|
||||||
|
const localVars = new Set<string>();
|
||||||
const tokens = tokenize(expr);
|
const tokens = tokenize(expr);
|
||||||
let result = "";
|
let i = 0;
|
||||||
for (let i = 0; i < tokens.length; i++) {
|
let stack = []; // to track last opening [ or {
|
||||||
|
|
||||||
|
while (i < tokens.length) {
|
||||||
let token = tokens[i];
|
let token = tokens[i];
|
||||||
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
|
||||||
// we need to find if it is a variable
|
|
||||||
let isVar = true;
|
|
||||||
let prevToken = tokens[i - 1];
|
let prevToken = tokens[i - 1];
|
||||||
|
let nextToken = tokens[i + 1];
|
||||||
|
let groupType = stack[stack.length - 1];
|
||||||
|
|
||||||
|
switch (token.type) {
|
||||||
|
case "LEFT_BRACE":
|
||||||
|
case "LEFT_BRACKET":
|
||||||
|
stack.push(token.type);
|
||||||
|
break;
|
||||||
|
case "RIGHT_BRACE":
|
||||||
|
case "RIGHT_BRACKET":
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value);
|
||||||
|
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
||||||
if (prevToken) {
|
if (prevToken) {
|
||||||
|
// normalize missing tokens: {a} should be equivalent to {a:a}
|
||||||
|
if (
|
||||||
|
groupType === "LEFT_BRACE" &&
|
||||||
|
isLeftSeparator(prevToken) &&
|
||||||
|
isRightSeparator(nextToken)
|
||||||
|
) {
|
||||||
|
tokens.splice(i + 1, 0, { type: "COLON", value: ":" }, { ...token });
|
||||||
|
nextToken = tokens[i + 1];
|
||||||
|
}
|
||||||
|
|
||||||
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
||||||
isVar = false;
|
isVar = false;
|
||||||
} else if (prevToken.type === "LEFT_BRACE" || prevToken.type === "COMMA") {
|
} else if (prevToken.type === "LEFT_BRACE" || prevToken.type === "COMMA") {
|
||||||
let nextToken = tokens[i + 1];
|
|
||||||
if (nextToken && nextToken.type === "COLON") {
|
if (nextToken && nextToken.type === "COLON") {
|
||||||
isVar = false;
|
isVar = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isVar) {
|
}
|
||||||
if (token.value in vars && "id" in vars[token.value]) {
|
if (token.type === "TEMPLATE_STRING") {
|
||||||
token.value = (<QWebExprVar>vars[token.value]).id;
|
token.value = token.replace!((expr: any) => compileExpr(expr));
|
||||||
|
}
|
||||||
|
if (nextToken && nextToken.type === "OPERATOR" && nextToken.value === "=>") {
|
||||||
|
if (token.type === "RIGHT_PAREN") {
|
||||||
|
let j = i - 1;
|
||||||
|
while (j > 0 && tokens[j].type !== "LEFT_PAREN") {
|
||||||
|
if (tokens[j].type === "SYMBOL" && tokens[j].originalValue) {
|
||||||
|
tokens[j].value = tokens[j].originalValue!;
|
||||||
|
localVars.add(tokens[j].value); //] = { id: tokens[j].value, expr: tokens[j].value };
|
||||||
|
}
|
||||||
|
j--;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
token.value = `context['${token.value}']`;
|
localVars.add(token.value); //] = { id: token.value, expr: token.value };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isVar) {
|
||||||
|
token.varName = token.value;
|
||||||
|
if (!localVars.has(token.value)) {
|
||||||
|
token.originalValue = token.value;
|
||||||
|
token.value = `ctx['${token.value}']`;
|
||||||
}
|
}
|
||||||
result += token.value;
|
|
||||||
}
|
}
|
||||||
return result;
|
i++;
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compileExpr(expr: string): string {
|
||||||
|
return compileExprToArray(expr)
|
||||||
|
.map((t) => t.value)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||||
|
const INTERP_GROUP_REGEXP = /\{\{.*?\}\}/g;
|
||||||
|
|
||||||
|
export function interpolate(s: string): string {
|
||||||
|
let matches = s.match(INTERP_REGEXP);
|
||||||
|
if (matches && matches[0].length === s.length) {
|
||||||
|
return `(${compileExpr(s.slice(2, -2))})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let r = s.replace(INTERP_GROUP_REGEXP, (s) => "${" + compileExpr(s.slice(2, -2)) + "}");
|
||||||
|
return "`" + r + "`";
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,798 @@
|
|||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// AST Type definition
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const enum ASTType {
|
||||||
|
Text,
|
||||||
|
Comment,
|
||||||
|
DomNode,
|
||||||
|
Multi,
|
||||||
|
TEsc,
|
||||||
|
TIf,
|
||||||
|
TSet,
|
||||||
|
TCall,
|
||||||
|
TRaw,
|
||||||
|
TForEach,
|
||||||
|
TKey,
|
||||||
|
TComponent,
|
||||||
|
TDebug,
|
||||||
|
TLog,
|
||||||
|
TSlot,
|
||||||
|
TCallBlock,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTText {
|
||||||
|
type: ASTType.Text;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTComment {
|
||||||
|
type: ASTType.Comment;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTDomNode {
|
||||||
|
type: ASTType.DomNode;
|
||||||
|
tag: string;
|
||||||
|
attrs: { [key: string]: string };
|
||||||
|
content: AST[];
|
||||||
|
ref: string | null;
|
||||||
|
on: { [key: string]: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTMulti {
|
||||||
|
type: ASTType.Multi;
|
||||||
|
content: AST[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTEsc {
|
||||||
|
type: ASTType.TEsc;
|
||||||
|
expr: string;
|
||||||
|
defaultValue: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTRaw {
|
||||||
|
type: ASTType.TRaw;
|
||||||
|
expr: string;
|
||||||
|
body: AST[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTif {
|
||||||
|
type: ASTType.TIf;
|
||||||
|
condition: string;
|
||||||
|
content: AST;
|
||||||
|
tElif: { condition: string; content: AST }[] | null;
|
||||||
|
tElse: AST | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTSet {
|
||||||
|
type: ASTType.TSet;
|
||||||
|
name: string;
|
||||||
|
value: string | null; // value defined in attribute
|
||||||
|
defaultValue: string | null; // value defined in body, if text
|
||||||
|
body: AST[] | null; // content of body if not text
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTForEach {
|
||||||
|
type: ASTType.TForEach;
|
||||||
|
collection: string;
|
||||||
|
elem: string;
|
||||||
|
key: string | null;
|
||||||
|
body: AST;
|
||||||
|
memo: string;
|
||||||
|
isOnlyChild: boolean;
|
||||||
|
hasNoComponent: boolean;
|
||||||
|
hasNoFirst: boolean;
|
||||||
|
hasNoLast: boolean;
|
||||||
|
hasNoIndex: boolean;
|
||||||
|
hasNoValue: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTKey {
|
||||||
|
type: ASTType.TKey;
|
||||||
|
expr: string;
|
||||||
|
content: AST;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTCall {
|
||||||
|
type: ASTType.TCall;
|
||||||
|
name: string;
|
||||||
|
body: AST[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTComponent {
|
||||||
|
type: ASTType.TComponent;
|
||||||
|
name: string;
|
||||||
|
isDynamic: boolean;
|
||||||
|
props: { [name: string]: string };
|
||||||
|
handlers: { [event: string]: string };
|
||||||
|
slots: { [name: string]: AST };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTSlot {
|
||||||
|
type: ASTType.TSlot;
|
||||||
|
name: string;
|
||||||
|
defaultContent: AST | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTTCallBlock {
|
||||||
|
type: ASTType.TCallBlock;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTDebug {
|
||||||
|
type: ASTType.TDebug;
|
||||||
|
content: AST | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ASTLog {
|
||||||
|
type: ASTType.TLog;
|
||||||
|
expr: string;
|
||||||
|
content: AST | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AST =
|
||||||
|
| ASTText
|
||||||
|
| ASTComment
|
||||||
|
| ASTDomNode
|
||||||
|
| ASTMulti
|
||||||
|
| ASTTEsc
|
||||||
|
| ASTTif
|
||||||
|
| ASTTSet
|
||||||
|
| ASTTCall
|
||||||
|
| ASTTRaw
|
||||||
|
| ASTTForEach
|
||||||
|
| ASTTKey
|
||||||
|
| ASTComponent
|
||||||
|
| ASTSlot
|
||||||
|
| ASTTCallBlock
|
||||||
|
| ASTLog
|
||||||
|
| ASTDebug;
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Parser
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
interface ParsingContext {
|
||||||
|
inPreTag: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parse(xml: string): AST {
|
||||||
|
const template = `<t>${xml}</t>`;
|
||||||
|
const doc = parseXML(template);
|
||||||
|
const ctx = { inPreTag: false };
|
||||||
|
const ast = parseNode(doc.firstChild!, ctx);
|
||||||
|
if (!ast) {
|
||||||
|
return { type: ASTType.Text, value: "" };
|
||||||
|
}
|
||||||
|
return ast;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNode(node: ChildNode, ctx: ParsingContext): AST | null {
|
||||||
|
if (!(node instanceof Element)) {
|
||||||
|
return parseTextCommentNode(node, ctx);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
parseTDebugLog(node, ctx) ||
|
||||||
|
parseTForEach(node, ctx) ||
|
||||||
|
parseTIf(node, ctx) ||
|
||||||
|
parseTCall(node, ctx) ||
|
||||||
|
parseTCallBlock(node, ctx) ||
|
||||||
|
parseTEscNode(node, ctx) ||
|
||||||
|
parseTKey(node, ctx) ||
|
||||||
|
parseTSlot(node, ctx) ||
|
||||||
|
parseTRawNode(node, ctx) ||
|
||||||
|
parseComponent(node, ctx) ||
|
||||||
|
parseDOMNode(node, ctx) ||
|
||||||
|
parseTSetNode(node, ctx) ||
|
||||||
|
parseTNode(node, ctx)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// <t /> tag
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTNode(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (node.tagName !== "t") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const children: AST[] = [];
|
||||||
|
for (let child of node.childNodes) {
|
||||||
|
const ast = parseNode(child, ctx);
|
||||||
|
if (ast) {
|
||||||
|
children.push(ast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (children.length) {
|
||||||
|
case 0:
|
||||||
|
return null;
|
||||||
|
case 1:
|
||||||
|
return children[0];
|
||||||
|
default:
|
||||||
|
return {
|
||||||
|
type: ASTType.Multi,
|
||||||
|
content: children,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Text and Comment Nodes
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
const lineBreakRE = /[\r\n]/;
|
||||||
|
const whitespaceRE = /\s+/g;
|
||||||
|
|
||||||
|
function parseTextCommentNode(node: ChildNode, ctx: ParsingContext): AST | null {
|
||||||
|
if (node.nodeType === 3) {
|
||||||
|
let value = node.textContent || "";
|
||||||
|
if (!ctx.inPreTag) {
|
||||||
|
if (lineBreakRE.test(value) && !value.trim()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
value = value.replace(whitespaceRE, " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { type: ASTType.Text, value };
|
||||||
|
} else if (node.nodeType === 8) {
|
||||||
|
return { type: ASTType.Comment, value: node.textContent || "" };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// debugging
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTDebugLog(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (node.hasAttribute("t-debug")) {
|
||||||
|
node.removeAttribute("t-debug");
|
||||||
|
return {
|
||||||
|
type: ASTType.TDebug,
|
||||||
|
content: parseNode(node, ctx),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.hasAttribute("t-log")) {
|
||||||
|
const expr = node.getAttribute("t-log")!;
|
||||||
|
node.removeAttribute("t-log");
|
||||||
|
return {
|
||||||
|
type: ASTType.TLog,
|
||||||
|
expr,
|
||||||
|
content: parseNode(node, ctx),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Regular dom node
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (node.tagName === "t") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const children: AST[] = [];
|
||||||
|
if (node.tagName === "pre") {
|
||||||
|
ctx = { inPreTag: true };
|
||||||
|
}
|
||||||
|
let ref = null;
|
||||||
|
if (node.hasAttribute("t-ref")) {
|
||||||
|
ref = node.getAttribute("t-ref");
|
||||||
|
node.removeAttribute("t-ref");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let child of node.childNodes) {
|
||||||
|
const ast = parseNode(child, ctx);
|
||||||
|
if (ast) {
|
||||||
|
children.push(ast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const attrs: ASTDomNode["attrs"] = {};
|
||||||
|
const on: ASTDomNode["on"] = {};
|
||||||
|
|
||||||
|
for (let attr of node.getAttributeNames()) {
|
||||||
|
const value = node.getAttribute(attr)!;
|
||||||
|
if (attr.startsWith("t-on")) {
|
||||||
|
if (attr === "t-on") {
|
||||||
|
throw new Error("Missing event name with t-on directive");
|
||||||
|
}
|
||||||
|
on[attr.slice(5)] = value;
|
||||||
|
} else {
|
||||||
|
if (attr.startsWith("t-") && !attr.startsWith("t-att")) {
|
||||||
|
throw new Error(`Unknown QWeb directive: '${attr}'`);
|
||||||
|
}
|
||||||
|
attrs[attr] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (children.length === 1 && children[0].type === ASTType.TForEach) {
|
||||||
|
children[0].isOnlyChild = true;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: ASTType.DomNode,
|
||||||
|
tag: node.tagName,
|
||||||
|
attrs,
|
||||||
|
on,
|
||||||
|
ref,
|
||||||
|
content: children,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-esc
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTEscNode(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-esc")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const escValue = node.getAttribute("t-esc")!;
|
||||||
|
node.removeAttribute("t-esc");
|
||||||
|
const tesc: AST = {
|
||||||
|
type: ASTType.TEsc,
|
||||||
|
expr: escValue,
|
||||||
|
defaultValue: node.textContent || "",
|
||||||
|
};
|
||||||
|
let ref = node.getAttribute("t-ref");
|
||||||
|
node.removeAttribute("t-ref");
|
||||||
|
const ast = parseNode(node, ctx);
|
||||||
|
if (!ast) {
|
||||||
|
return tesc;
|
||||||
|
}
|
||||||
|
if (ast && ast.type === ASTType.DomNode) {
|
||||||
|
return {
|
||||||
|
type: ASTType.DomNode,
|
||||||
|
tag: ast.tag,
|
||||||
|
attrs: ast.attrs,
|
||||||
|
on: ast.on,
|
||||||
|
ref,
|
||||||
|
content: [tesc],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (ast && ast.type === ASTType.TComponent) {
|
||||||
|
return {
|
||||||
|
...ast,
|
||||||
|
slots: { default: tesc },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return tesc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-raw
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTRawNode(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-raw")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const expr = node.getAttribute("t-raw")!;
|
||||||
|
node.removeAttribute("t-raw");
|
||||||
|
|
||||||
|
const tRaw: AST = { type: ASTType.TRaw, expr, body: null };
|
||||||
|
const ref = node.getAttribute("t-ref");
|
||||||
|
node.removeAttribute("t-ref");
|
||||||
|
const ast = parseNode(node, ctx);
|
||||||
|
if (!ast) {
|
||||||
|
return tRaw;
|
||||||
|
}
|
||||||
|
if (ast && ast.type === ASTType.DomNode) {
|
||||||
|
tRaw.body = ast.content.length ? ast.content : null;
|
||||||
|
return {
|
||||||
|
type: ASTType.DomNode,
|
||||||
|
tag: ast.tag,
|
||||||
|
attrs: ast.attrs,
|
||||||
|
on: ast.on,
|
||||||
|
ref,
|
||||||
|
content: [tRaw],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return tRaw;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-foreach and t-key
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTForEach(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-foreach")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const html = node.outerHTML;
|
||||||
|
const collection = node.getAttribute("t-foreach")!;
|
||||||
|
node.removeAttribute("t-foreach");
|
||||||
|
const elem = node.getAttribute("t-as") || "";
|
||||||
|
node.removeAttribute("t-as");
|
||||||
|
const key = node.getAttribute("t-key");
|
||||||
|
node.removeAttribute("t-key");
|
||||||
|
const memo = node.getAttribute("t-memo") || "";
|
||||||
|
node.removeAttribute("t-memo");
|
||||||
|
const body = parseNode(node, ctx);
|
||||||
|
|
||||||
|
if (!body) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasNoTCall = !html.includes("t-call");
|
||||||
|
const hasNoFirst = hasNoTCall && !html.includes(`${elem}_first`);
|
||||||
|
const hasNoLast = hasNoTCall && !html.includes(`${elem}_last`);
|
||||||
|
const hasNoIndex = hasNoTCall && !html.includes(`${elem}_index`);
|
||||||
|
const hasNoValue = hasNoTCall && !html.includes(`${elem}_value`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: ASTType.TForEach,
|
||||||
|
collection,
|
||||||
|
elem,
|
||||||
|
body,
|
||||||
|
memo,
|
||||||
|
key,
|
||||||
|
isOnlyChild: false,
|
||||||
|
hasNoComponent: hasNoComponent(body),
|
||||||
|
hasNoFirst,
|
||||||
|
hasNoLast,
|
||||||
|
hasNoIndex,
|
||||||
|
hasNoValue,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns true if we are sure the ast does not contain any component
|
||||||
|
*/
|
||||||
|
function hasNoComponent(ast: AST): boolean {
|
||||||
|
switch (ast.type) {
|
||||||
|
case ASTType.TComponent:
|
||||||
|
case ASTType.TRaw:
|
||||||
|
case ASTType.TCall:
|
||||||
|
case ASTType.TCallBlock:
|
||||||
|
case ASTType.TSlot:
|
||||||
|
return false;
|
||||||
|
case ASTType.TSet:
|
||||||
|
case ASTType.Text:
|
||||||
|
case ASTType.Comment:
|
||||||
|
case ASTType.TEsc:
|
||||||
|
return true;
|
||||||
|
case ASTType.TKey:
|
||||||
|
return hasNoComponent(ast.content);
|
||||||
|
case ASTType.TDebug:
|
||||||
|
case ASTType.TLog:
|
||||||
|
return ast.content ? hasNoComponent(ast.content) : true;
|
||||||
|
case ASTType.TForEach:
|
||||||
|
return ast.hasNoComponent;
|
||||||
|
case ASTType.Multi:
|
||||||
|
case ASTType.DomNode: {
|
||||||
|
for (let elem of ast.content) {
|
||||||
|
if (!hasNoComponent(elem)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case ASTType.TIf: {
|
||||||
|
if (!hasNoComponent(ast.content)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (ast.tElif) {
|
||||||
|
for (let elem of ast.tElif) {
|
||||||
|
if (!hasNoComponent(elem.content)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ast.tElse && !hasNoComponent(ast.tElse)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTKey(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-key")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const key = node.getAttribute("t-key")!;
|
||||||
|
node.removeAttribute("t-key");
|
||||||
|
const body = parseNode(node, ctx);
|
||||||
|
if (!body) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { type: ASTType.TKey, expr: key, content: body };
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-call
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTCall(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-call")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const subTemplate = node.getAttribute("t-call")!;
|
||||||
|
|
||||||
|
node.removeAttribute("t-call");
|
||||||
|
if (node.tagName !== "t") {
|
||||||
|
const ast = parseNode(node, ctx);
|
||||||
|
const tcall: AST = { type: ASTType.TCall, name: subTemplate, body: null };
|
||||||
|
if (ast && ast.type === ASTType.DomNode) {
|
||||||
|
ast.content = [tcall];
|
||||||
|
return ast;
|
||||||
|
}
|
||||||
|
if (ast && ast.type === ASTType.TComponent) {
|
||||||
|
return {
|
||||||
|
...ast,
|
||||||
|
slots: { default: tcall },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const body: AST[] = [];
|
||||||
|
for (let child of node.childNodes) {
|
||||||
|
const ast = parseNode(child, ctx);
|
||||||
|
if (ast) {
|
||||||
|
body.push(ast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: ASTType.TCall,
|
||||||
|
name: subTemplate,
|
||||||
|
body: body.length ? body : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-call-block
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTCallBlock(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-call-block")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const name = node.getAttribute("t-call-block")!;
|
||||||
|
return {
|
||||||
|
type: ASTType.TCallBlock,
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-if
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTIf(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-if")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const condition = node.getAttribute("t-if")!;
|
||||||
|
node.removeAttribute("t-if");
|
||||||
|
const content = parseNode(node, ctx);
|
||||||
|
if (!content) {
|
||||||
|
throw new Error("hmmm");
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextElement = node.nextElementSibling;
|
||||||
|
// t-elifs
|
||||||
|
const tElifs: any[] = [];
|
||||||
|
while (nextElement && nextElement.hasAttribute("t-elif")) {
|
||||||
|
const condition = nextElement.getAttribute("t-elif");
|
||||||
|
nextElement.removeAttribute("t-elif");
|
||||||
|
const tElif = parseNode(nextElement, ctx);
|
||||||
|
const next = nextElement.nextElementSibling;
|
||||||
|
nextElement.remove();
|
||||||
|
nextElement = next;
|
||||||
|
if (tElif) {
|
||||||
|
tElifs.push({ condition, content: tElif });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// t-else
|
||||||
|
let tElse: AST | null = null;
|
||||||
|
if (nextElement && nextElement.hasAttribute("t-else")) {
|
||||||
|
nextElement.removeAttribute("t-else");
|
||||||
|
tElse = parseNode(nextElement, ctx);
|
||||||
|
nextElement.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: ASTType.TIf,
|
||||||
|
condition,
|
||||||
|
content,
|
||||||
|
tElif: tElifs.length ? tElifs : null,
|
||||||
|
tElse,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// t-set directive
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTSetNode(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-set")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const name = node.getAttribute("t-set")!;
|
||||||
|
const value = node.getAttribute("t-value") || null;
|
||||||
|
const defaultValue = node.innerHTML === node.textContent ? node.textContent || null : null;
|
||||||
|
let body: AST[] | null = null;
|
||||||
|
if (node.textContent !== node.innerHTML) {
|
||||||
|
body = [];
|
||||||
|
for (let child of node.childNodes) {
|
||||||
|
let childAst = parseNode(child, ctx);
|
||||||
|
if (childAst) {
|
||||||
|
body.push(childAst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { type: ASTType.TSet, name, value, defaultValue, body };
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Components
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseComponent(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
let name = node.tagName;
|
||||||
|
const firstLetter = name[0];
|
||||||
|
let isDynamic = node.hasAttribute("t-component");
|
||||||
|
|
||||||
|
if (!(firstLetter === firstLetter.toUpperCase() || isDynamic)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (isDynamic) {
|
||||||
|
name = node.getAttribute("t-component")!;
|
||||||
|
node.removeAttribute("t-component");
|
||||||
|
}
|
||||||
|
|
||||||
|
const props: ASTComponent["props"] = {};
|
||||||
|
const handlers: ASTComponent["handlers"] = {};
|
||||||
|
for (let name of node.getAttributeNames()) {
|
||||||
|
const value = node.getAttribute(name)!;
|
||||||
|
if (name.startsWith("t-on-")) {
|
||||||
|
handlers[name.slice(5)] = value;
|
||||||
|
} else {
|
||||||
|
props[name] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const slots: ASTComponent["slots"] = {};
|
||||||
|
if (node.hasChildNodes()) {
|
||||||
|
const clone = <Element>node.cloneNode(true);
|
||||||
|
|
||||||
|
// named slots
|
||||||
|
const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
|
||||||
|
for (let slotNode of slotNodes) {
|
||||||
|
const name = slotNode.getAttribute("t-set-slot")!;
|
||||||
|
|
||||||
|
// check if this is defined in a sub component (in which case it should
|
||||||
|
// be ignored)
|
||||||
|
let el = slotNode.parentElement!;
|
||||||
|
let isInSubComponent = false;
|
||||||
|
while (el !== clone) {
|
||||||
|
if (el!.hasAttribute("t-component") || el!.tagName[0] === el!.tagName[0].toUpperCase()) {
|
||||||
|
isInSubComponent = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
el = el.parentElement!;
|
||||||
|
}
|
||||||
|
if (isInSubComponent) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
slotNode.removeAttribute("t-set-slot");
|
||||||
|
slotNode.remove();
|
||||||
|
const slotAst = parseNode(slotNode, ctx);
|
||||||
|
if (slotAst) {
|
||||||
|
slots[name] = slotAst;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// default slot
|
||||||
|
const defaultContent = parseChildNodes(clone, ctx);
|
||||||
|
if (defaultContent) {
|
||||||
|
slots.default = defaultContent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { type: ASTType.TComponent, name, isDynamic, props, handlers, slots };
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Slots
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseTSlot(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
if (!node.hasAttribute("t-slot")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: ASTType.TSlot,
|
||||||
|
name: node.getAttribute("t-slot")!,
|
||||||
|
defaultContent: parseChildNodes(node, ctx),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// helpers
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function parseChildNodes(node: Element, ctx: ParsingContext): AST | null {
|
||||||
|
const children: AST[] = [];
|
||||||
|
for (let child of node.childNodes) {
|
||||||
|
const childAst = parseNode(child, ctx);
|
||||||
|
if (childAst) {
|
||||||
|
children.push(childAst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (children.length) {
|
||||||
|
case 0:
|
||||||
|
return null;
|
||||||
|
case 1:
|
||||||
|
return children[0];
|
||||||
|
default:
|
||||||
|
return { type: ASTType.Multi, content: children };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function parseXML(xml: string): Document {
|
||||||
|
const parser = new DOMParser();
|
||||||
|
|
||||||
|
const doc = parser.parseFromString(xml, "text/xml");
|
||||||
|
if (doc.getElementsByTagName("parsererror").length) {
|
||||||
|
let msg = "Invalid XML in template.";
|
||||||
|
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
|
||||||
|
if (parsererrorText) {
|
||||||
|
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
|
||||||
|
const re = /\d+/g;
|
||||||
|
const firstMatch = re.exec(parsererrorText);
|
||||||
|
if (firstMatch) {
|
||||||
|
const lineNumber = Number(firstMatch[0]);
|
||||||
|
const line = xml.split("\n")[lineNumber - 1];
|
||||||
|
const secondMatch = re.exec(parsererrorText);
|
||||||
|
if (line && secondMatch) {
|
||||||
|
const columnIndex = Number(secondMatch[0]) - 1;
|
||||||
|
if (line[columnIndex]) {
|
||||||
|
msg +=
|
||||||
|
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
|
||||||
|
`${line}\n${"-".repeat(columnIndex - 1)}^`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error(msg);
|
||||||
|
}
|
||||||
|
let tbranch = doc.querySelectorAll("[t-elif], [t-else]");
|
||||||
|
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
||||||
|
let node = tbranch[i];
|
||||||
|
let prevElem = node.previousElementSibling!;
|
||||||
|
let pattr = (name: string) => prevElem.getAttribute(name);
|
||||||
|
let nattr = (name: string) => +!!node.getAttribute(name);
|
||||||
|
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
||||||
|
if (pattr("t-foreach")) {
|
||||||
|
throw new Error(
|
||||||
|
"t-if cannot stay at the same level as t-foreach when using t-elif or t-else"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
["t-if", "t-elif", "t-else"].map(nattr).reduce(function (a, b) {
|
||||||
|
return a + b;
|
||||||
|
}) > 1
|
||||||
|
) {
|
||||||
|
throw new Error("Only one conditional branching directive is allowed per node");
|
||||||
|
}
|
||||||
|
// All text (with only spaces) and comment nodes (nodeType 8) between
|
||||||
|
// branch nodes are removed
|
||||||
|
let textNode;
|
||||||
|
while ((textNode = node.previousSibling) !== prevElem) {
|
||||||
|
if (textNode!.nodeValue!.trim().length && textNode!.nodeType !== 8) {
|
||||||
|
throw new Error("text is not allowed between branching directives");
|
||||||
|
}
|
||||||
|
textNode!.remove();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error(
|
||||||
|
"t-elif and t-else directives must be preceded by a t-if or t-elif directive"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
@@ -1,769 +0,0 @@
|
|||||||
import { EventBus } from "../core/event_bus";
|
|
||||||
import { h, patch, VNode } from "../vdom/index";
|
|
||||||
import { CompilationContext } from "./compilation_context";
|
|
||||||
import { shallowEqual } from "../utils";
|
|
||||||
import { addNS } from "../vdom/vdom";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl QWeb Engine
|
|
||||||
*
|
|
||||||
* In this file, you will find a QWeb engine/template compiler. It is the core
|
|
||||||
* of how Owl component works.
|
|
||||||
*
|
|
||||||
* Briefly, Owl QWeb compiles XML templates into functions that output a virtual
|
|
||||||
* DOM representation.
|
|
||||||
*
|
|
||||||
* We have here:
|
|
||||||
* - a CompilationContext class, which is an internal object that contains all
|
|
||||||
* compilation specific information, while a template is being compiled.
|
|
||||||
* - a QWeb class: this is the code of the QWeb compiler.
|
|
||||||
*
|
|
||||||
* Note that this file does not contain the implementation of the QWeb
|
|
||||||
* directives (see qweb_directives.ts and qweb_extensions.ts).
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Types
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
export type EvalContext = { [key: string]: any };
|
|
||||||
export type CompiledTemplate = (context: EvalContext, extra: any) => VNode;
|
|
||||||
|
|
||||||
interface Template {
|
|
||||||
elem: Element;
|
|
||||||
fn: CompiledTemplate;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CompilationInfo {
|
|
||||||
node: Element;
|
|
||||||
qweb: QWeb;
|
|
||||||
ctx: CompilationContext;
|
|
||||||
fullName: string;
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface NodeCreationCompilationInfo extends CompilationInfo {
|
|
||||||
nodeID: number;
|
|
||||||
addNodeHook: Function;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Directive {
|
|
||||||
name: string;
|
|
||||||
extraNames?: string[];
|
|
||||||
priority: number;
|
|
||||||
// if return true, then directive is fully applied and there is no need to
|
|
||||||
// keep processing node. Otherwise, we keep going.
|
|
||||||
atNodeEncounter?(info: CompilationInfo): boolean | void;
|
|
||||||
atNodeCreation?(info: NodeCreationCompilationInfo): void;
|
|
||||||
finalize?(info: CompilationInfo): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface QWebConfig {
|
|
||||||
templates?: string;
|
|
||||||
translateFn?(text: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Const/global stuff/helpers
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
|
|
||||||
|
|
||||||
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
|
|
||||||
|
|
||||||
const lineBreakRE = /[\r\n]/;
|
|
||||||
const whitespaceRE = /\s+/g;
|
|
||||||
|
|
||||||
const NODE_HOOKS_PARAMS = {
|
|
||||||
create: "(_, n)",
|
|
||||||
insert: "vn",
|
|
||||||
remove: "(vn, rm)",
|
|
||||||
destroy: "()"
|
|
||||||
};
|
|
||||||
|
|
||||||
interface Utils {
|
|
||||||
toObj(expr: any): Object;
|
|
||||||
shallowEqual(p1: Object, p2: Object): boolean;
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
const UTILS: Utils = {
|
|
||||||
toObj(expr) {
|
|
||||||
if (typeof expr === "string") {
|
|
||||||
expr = expr.trim();
|
|
||||||
if (!expr) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
let words = expr.split(/\s+/);
|
|
||||||
let result = {};
|
|
||||||
for (let i = 0; i < words.length; i++) {
|
|
||||||
result[words[i]] = true;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
return expr;
|
|
||||||
},
|
|
||||||
shallowEqual,
|
|
||||||
addNameSpace(vnode) {
|
|
||||||
addNS(vnode.data, vnode.children, vnode.sel);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
function parseXML(xml: string): Document {
|
|
||||||
const parser = new DOMParser();
|
|
||||||
|
|
||||||
const doc = parser.parseFromString(xml, "text/xml");
|
|
||||||
if (doc.getElementsByTagName("parsererror").length) {
|
|
||||||
let msg = "Invalid XML in template.";
|
|
||||||
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
|
|
||||||
if (parsererrorText) {
|
|
||||||
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
|
|
||||||
const re = /\d+/g;
|
|
||||||
const firstMatch = re.exec(parsererrorText);
|
|
||||||
if (firstMatch) {
|
|
||||||
const lineNumber = Number(firstMatch[0]);
|
|
||||||
const line = xml.split("\n")[lineNumber - 1];
|
|
||||||
const secondMatch = re.exec(parsererrorText);
|
|
||||||
if (line && secondMatch) {
|
|
||||||
const columnIndex = Number(secondMatch[0]) - 1;
|
|
||||||
if (line[columnIndex]) {
|
|
||||||
msg +=
|
|
||||||
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
|
|
||||||
`${line}\n${"-".repeat(columnIndex - 1)}^`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(msg);
|
|
||||||
}
|
|
||||||
return doc;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// QWeb rendering engine
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export class QWeb extends EventBus {
|
|
||||||
templates: { [name: string]: Template };
|
|
||||||
static utils = UTILS;
|
|
||||||
static components = Object.create(null);
|
|
||||||
|
|
||||||
static DIRECTIVE_NAMES: { [key: string]: 1 } = {
|
|
||||||
name: 1,
|
|
||||||
att: 1,
|
|
||||||
attf: 1,
|
|
||||||
translation: 1
|
|
||||||
};
|
|
||||||
static DIRECTIVES: Directive[] = [];
|
|
||||||
|
|
||||||
static TEMPLATES: { [name: string]: Template } = {};
|
|
||||||
|
|
||||||
static nextId: number = 1;
|
|
||||||
|
|
||||||
h = h;
|
|
||||||
// dev mode enables better error messages or more costly validations
|
|
||||||
static dev: boolean = false;
|
|
||||||
|
|
||||||
// slots contains sub templates defined with t-set inside t-component nodes, and
|
|
||||||
// are meant to be used by the t-slot directive.
|
|
||||||
static slots = {};
|
|
||||||
static nextSlotId = 1;
|
|
||||||
|
|
||||||
// recursiveTemplates contains sub templates called with t-call, but which
|
|
||||||
// ends up in recursive situations. This is very similar to the slot situation,
|
|
||||||
// as in we need to propagate the scope.
|
|
||||||
recursiveFns = {};
|
|
||||||
|
|
||||||
isUpdating: boolean = false;
|
|
||||||
translateFn?: QWebConfig["translateFn"];
|
|
||||||
|
|
||||||
constructor(config: QWebConfig = {}) {
|
|
||||||
super();
|
|
||||||
this.templates = Object.create(QWeb.TEMPLATES);
|
|
||||||
if (config.templates) {
|
|
||||||
this.addTemplates(config.templates);
|
|
||||||
}
|
|
||||||
if (config.translateFn) {
|
|
||||||
this.translateFn = config.translateFn;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static addDirective(directive: Directive) {
|
|
||||||
if (directive.name in QWeb.DIRECTIVE_NAMES) {
|
|
||||||
throw new Error(`Directive "${directive.name} already registered`);
|
|
||||||
}
|
|
||||||
QWeb.DIRECTIVES.push(directive);
|
|
||||||
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
|
||||||
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
|
||||||
if (directive.extraNames) {
|
|
||||||
directive.extraNames.forEach(n => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static registerComponent(name: string, Component: any) {
|
|
||||||
if (QWeb.components[name]) {
|
|
||||||
throw new Error(`Component '${name}' has already been registered`);
|
|
||||||
}
|
|
||||||
QWeb.components[name] = Component;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register globally a template. All QWeb instances will obtain their
|
|
||||||
* templates from their own template map, and then, from the global static
|
|
||||||
* TEMPLATES property.
|
|
||||||
*/
|
|
||||||
static registerTemplate(name: string, template: string) {
|
|
||||||
if (QWeb.TEMPLATES[name]) {
|
|
||||||
throw new Error(`Template '${name}' has already been registered`);
|
|
||||||
}
|
|
||||||
const qweb = new QWeb();
|
|
||||||
qweb.addTemplate(name, template);
|
|
||||||
QWeb.TEMPLATES[name] = qweb.templates[name];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a template to the internal template map. Note that it is not
|
|
||||||
* immediately compiled.
|
|
||||||
*/
|
|
||||||
addTemplate(name: string, xmlString: string, allowDuplicate?: boolean) {
|
|
||||||
if (allowDuplicate && name in this.templates) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const doc = parseXML(xmlString);
|
|
||||||
if (!doc.firstChild) {
|
|
||||||
throw new Error("Invalid template (should not be empty)");
|
|
||||||
}
|
|
||||||
this._addTemplate(name, <Element>doc.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load templates from a xml (as a string or xml document). This will look up
|
|
||||||
* for the first <templates> tag, and will consider each child of this as a
|
|
||||||
* template, with the name given by the t-name attribute.
|
|
||||||
*/
|
|
||||||
addTemplates(xmlstr: string | Document) {
|
|
||||||
const doc = typeof xmlstr === "string" ? parseXML(xmlstr) : xmlstr;
|
|
||||||
const templates = doc.getElementsByTagName("templates")[0];
|
|
||||||
if (!templates) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (let elem of <any>templates.children) {
|
|
||||||
const name = elem.getAttribute("t-name");
|
|
||||||
this._addTemplate(name, elem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_addTemplate(name: string, elem: Element) {
|
|
||||||
if (name in this.templates) {
|
|
||||||
throw new Error(`Template ${name} already defined`);
|
|
||||||
}
|
|
||||||
this._processTemplate(elem);
|
|
||||||
const template = {
|
|
||||||
elem,
|
|
||||||
fn: function(this: QWeb, context, extra) {
|
|
||||||
const compiledFunction = this._compile(name, elem);
|
|
||||||
template.fn = compiledFunction;
|
|
||||||
return compiledFunction.call(this, context, extra);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
this.templates[name] = template;
|
|
||||||
}
|
|
||||||
|
|
||||||
_processTemplate(elem: Element) {
|
|
||||||
let tbranch = elem.querySelectorAll("[t-elif], [t-else]");
|
|
||||||
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
|
||||||
let node = tbranch[i];
|
|
||||||
let prevElem = node.previousElementSibling!;
|
|
||||||
let pattr = function(name) {
|
|
||||||
return prevElem.getAttribute(name);
|
|
||||||
};
|
|
||||||
let nattr = function(name) {
|
|
||||||
return +!!node.getAttribute(name);
|
|
||||||
};
|
|
||||||
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
|
||||||
if (pattr("t-foreach")) {
|
|
||||||
throw new Error(
|
|
||||||
"t-if cannot stay at the same level as t-foreach when using t-elif or t-else"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
["t-if", "t-elif", "t-else"].map(nattr).reduce(function(a, b) {
|
|
||||||
return a + b;
|
|
||||||
}) > 1
|
|
||||||
) {
|
|
||||||
throw new Error("Only one conditional branching directive is allowed per node");
|
|
||||||
}
|
|
||||||
// All text nodes between branch nodes are removed
|
|
||||||
let textNode;
|
|
||||||
while ((textNode = node.previousSibling) !== prevElem) {
|
|
||||||
if (textNode.nodeValue.trim().length) {
|
|
||||||
throw new Error("text is not allowed between branching directives");
|
|
||||||
}
|
|
||||||
textNode.remove();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new Error(
|
|
||||||
"t-elif and t-else directives must be preceded by a t-if or t-elif directive"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Render a template
|
|
||||||
*
|
|
||||||
* @param {string} name the template should already have been added
|
|
||||||
*/
|
|
||||||
render(name: string, context: EvalContext = {}, extra: any = null): VNode {
|
|
||||||
const template = this.templates[name];
|
|
||||||
if (!template) {
|
|
||||||
throw new Error(`Template ${name} does not exist`);
|
|
||||||
}
|
|
||||||
return template.fn.call(this, context, extra);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Render a template to a html string.
|
|
||||||
*
|
|
||||||
* Note that this is more limited than the `render` method: it is not suitable
|
|
||||||
* to render a full component tree, since this is an asynchronous operation.
|
|
||||||
* This method can only render templates without components.
|
|
||||||
*/
|
|
||||||
renderToString(name: string, context: EvalContext = {}, extra?: any): string {
|
|
||||||
const vnode = this.render(name, context, extra);
|
|
||||||
if (vnode.sel === undefined) {
|
|
||||||
return vnode.text!;
|
|
||||||
}
|
|
||||||
const node = document.createElement(vnode.sel);
|
|
||||||
const result = patch(node, vnode);
|
|
||||||
return (<HTMLElement>result.elm).outerHTML;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Force all widgets connected to this QWeb instance to rerender themselves.
|
|
||||||
*
|
|
||||||
* This method is mostly useful for external code that want to modify the
|
|
||||||
* application in some cases. For example, a router plugin.
|
|
||||||
*/
|
|
||||||
forceUpdate() {
|
|
||||||
this.isUpdating = true;
|
|
||||||
Promise.resolve().then(() => {
|
|
||||||
if (this.isUpdating) {
|
|
||||||
this.isUpdating = false;
|
|
||||||
this.trigger("update");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
_compile(name: string, elem: Element, parentContext?: CompilationContext): CompiledTemplate {
|
|
||||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
|
||||||
const ctx = new CompilationContext(name);
|
|
||||||
if (elem.tagName !== "t") {
|
|
||||||
ctx.shouldDefineResult = false;
|
|
||||||
}
|
|
||||||
if (parentContext) {
|
|
||||||
ctx.templates = Object.create(parentContext.templates);
|
|
||||||
ctx.variables = Object.create(parentContext.variables);
|
|
||||||
ctx.nextID = parentContext.nextID + 1;
|
|
||||||
ctx.parentNode = parentContext.parentNode || ctx.nextID++;
|
|
||||||
ctx.allowMultipleRoots = true;
|
|
||||||
ctx.hasParentWidget = true;
|
|
||||||
ctx.shouldDefineResult = false;
|
|
||||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
|
||||||
|
|
||||||
for (let v in parentContext.variables) {
|
|
||||||
let variable = <any>parentContext.variables[v];
|
|
||||||
if (variable.id) {
|
|
||||||
ctx.addLine(`let ${variable.id} = extra.fiber.vars.${variable.id}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (parentContext) {
|
|
||||||
ctx.addLine(" Object.assign(context, extra.fiber.scope);");
|
|
||||||
}
|
|
||||||
this._compileNode(elem, ctx);
|
|
||||||
|
|
||||||
if (!parentContext) {
|
|
||||||
if (ctx.shouldDefineResult) {
|
|
||||||
ctx.addLine(`return result;`);
|
|
||||||
} else {
|
|
||||||
if (!ctx.rootNode) {
|
|
||||||
throw new Error(`A template should have one root node (${ctx.templateName})`);
|
|
||||||
}
|
|
||||||
ctx.addLine(`return vn${ctx.rootNode};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let code = ctx.generateCode();
|
|
||||||
|
|
||||||
let template;
|
|
||||||
try {
|
|
||||||
template = new Function("context", "extra", code.join("\n")) as CompiledTemplate;
|
|
||||||
} catch (e) {
|
|
||||||
const templateName = ctx.templateName.replace(/`/g, "'");
|
|
||||||
console.groupCollapsed(`Invalid Code generated by ${templateName}`);
|
|
||||||
console.warn(code.join("\n"));
|
|
||||||
console.groupEnd();
|
|
||||||
throw new Error(
|
|
||||||
`Invalid generated code while compiling template '${templateName}': ${e.message}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (isDebug) {
|
|
||||||
const tpl = this.templates[name];
|
|
||||||
if (tpl) {
|
|
||||||
const msg = `Template: ${tpl.elem.outerHTML}\nCompiled code:\n${template.toString()}`;
|
|
||||||
console.log(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return template;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate code from an xml node
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
_compileNode(node: ChildNode, ctx: CompilationContext) {
|
|
||||||
if (!(node instanceof Element)) {
|
|
||||||
// this is a text node, there are no directive to apply
|
|
||||||
let text = node.textContent!;
|
|
||||||
if (!ctx.inPreTag) {
|
|
||||||
if (lineBreakRE.test(text) && !text.trim()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
text = text.replace(whitespaceRE, " ");
|
|
||||||
}
|
|
||||||
if (this.translateFn) {
|
|
||||||
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
|
||||||
text = this.translateFn(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (ctx.parentNode) {
|
|
||||||
if (node.nodeType === 3) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
|
||||||
} else if (node.nodeType === 8) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(h('!', \`${text}\`));`);
|
|
||||||
}
|
|
||||||
} else if (ctx.parentTextNode) {
|
|
||||||
ctx.addLine(`vn${ctx.parentTextNode}.text += \`${text}\`;`);
|
|
||||||
} else {
|
|
||||||
// this is an unusual situation: this text node is the result of the
|
|
||||||
// template rendering.
|
|
||||||
let nodeID = ctx.generateID();
|
|
||||||
ctx.addLine(`var vn${nodeID} = {text: \`${text}\`};`);
|
|
||||||
ctx.addLine(`result = vn${nodeID};`);
|
|
||||||
ctx.rootContext.rootNode = nodeID;
|
|
||||||
ctx.rootContext.parentTextNode = nodeID;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const firstLetter = node.tagName[0];
|
|
||||||
if (firstLetter === firstLetter.toUpperCase()) {
|
|
||||||
// this is a component, we modify in place the xml document to change
|
|
||||||
// <SomeComponent ... /> to <t t-component="SomeComponent" ... />
|
|
||||||
node.setAttribute("t-component", node.tagName);
|
|
||||||
}
|
|
||||||
const attributes = (<Element>node).attributes;
|
|
||||||
|
|
||||||
const validDirectives: {
|
|
||||||
directive: Directive;
|
|
||||||
value: string;
|
|
||||||
fullName: string;
|
|
||||||
}[] = [];
|
|
||||||
|
|
||||||
const finalizers: typeof validDirectives = [];
|
|
||||||
|
|
||||||
// maybe this is not optimal: we iterate on all attributes here, and again
|
|
||||||
// just after for each directive.
|
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
|
||||||
let attrName = attributes[i].name;
|
|
||||||
if (attrName.startsWith("t-")) {
|
|
||||||
let dName = attrName.slice(2).split(/-|\./)[0];
|
|
||||||
if (!(dName in QWeb.DIRECTIVE_NAMES)) {
|
|
||||||
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
|
||||||
}
|
|
||||||
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
|
|
||||||
const tNode = document.createElement("t");
|
|
||||||
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
|
|
||||||
for (let child of Array.from(node.childNodes)) {
|
|
||||||
tNode.appendChild(child);
|
|
||||||
}
|
|
||||||
node.appendChild(tNode);
|
|
||||||
node.removeAttribute(attrName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const DIR_N = QWeb.DIRECTIVES.length;
|
|
||||||
const ATTR_N = attributes.length;
|
|
||||||
let withHandlers = false;
|
|
||||||
for (let i = 0; i < DIR_N; i++) {
|
|
||||||
let directive = QWeb.DIRECTIVES[i];
|
|
||||||
let fullName;
|
|
||||||
let value;
|
|
||||||
for (let j = 0; j < ATTR_N; j++) {
|
|
||||||
const name = attributes[j].name;
|
|
||||||
if (
|
|
||||||
name === "t-" + directive.name ||
|
|
||||||
name.startsWith("t-" + directive.name + "-") ||
|
|
||||||
name.startsWith("t-" + directive.name + ".")
|
|
||||||
) {
|
|
||||||
fullName = name;
|
|
||||||
value = attributes[j].textContent;
|
|
||||||
validDirectives.push({ directive, value, fullName });
|
|
||||||
if (directive.name === "on" || directive.name === "model") {
|
|
||||||
withHandlers = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let { directive, value, fullName } of validDirectives) {
|
|
||||||
if (directive.finalize) {
|
|
||||||
finalizers.push({ directive, value, fullName });
|
|
||||||
}
|
|
||||||
if (directive.atNodeEncounter) {
|
|
||||||
const isDone = directive.atNodeEncounter({
|
|
||||||
node,
|
|
||||||
qweb: this,
|
|
||||||
ctx,
|
|
||||||
fullName,
|
|
||||||
value
|
|
||||||
});
|
|
||||||
if (isDone) {
|
|
||||||
for (let { directive, value, fullName } of finalizers) {
|
|
||||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.nodeName !== "t") {
|
|
||||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
|
||||||
ctx = ctx.withParent(nodeID);
|
|
||||||
ctx = ctx.subContext("currentKey", ctx.lastNodeKey);
|
|
||||||
let nodeHooks = {};
|
|
||||||
let addNodeHook = function(hook, handler) {
|
|
||||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
|
||||||
nodeHooks[hook].push(handler);
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let { directive, value, fullName } of validDirectives) {
|
|
||||||
if (directive.atNodeCreation) {
|
|
||||||
directive.atNodeCreation({
|
|
||||||
node,
|
|
||||||
qweb: this,
|
|
||||||
ctx,
|
|
||||||
fullName,
|
|
||||||
value,
|
|
||||||
nodeID,
|
|
||||||
addNodeHook
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(nodeHooks).length) {
|
|
||||||
ctx.addLine(`p${nodeID}.hook = {`);
|
|
||||||
for (let hook in nodeHooks) {
|
|
||||||
ctx.addLine(` ${hook}: ${NODE_HOOKS_PARAMS[hook]} => {`);
|
|
||||||
for (let handler of nodeHooks[hook]) {
|
|
||||||
ctx.addLine(` ${handler}`);
|
|
||||||
}
|
|
||||||
ctx.addLine(` },`);
|
|
||||||
}
|
|
||||||
ctx.addLine(`};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (node.nodeName === "pre") {
|
|
||||||
ctx = ctx.subContext("inPreTag", true);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._compileChildren(node, ctx);
|
|
||||||
// svg support
|
|
||||||
// we hadd svg namespace if it is a svg or if it is a g, but only if it is
|
|
||||||
// the root node. This is the easiest way to support svg sub components:
|
|
||||||
// they need to have a g tag as root. Otherwise, we would need a complete
|
|
||||||
// list of allowed svg tags.
|
|
||||||
const shouldAddNS =
|
|
||||||
node.nodeName === "svg" || (node.nodeName === "g" && ctx.rootNode === ctx.parentNode);
|
|
||||||
if (shouldAddNS) {
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
ctx.addLine(`utils.addNameSpace(vn${ctx.parentNode});`);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let { directive, value, fullName } of finalizers) {
|
|
||||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_compileGenericNode(
|
|
||||||
node: ChildNode,
|
|
||||||
ctx: CompilationContext,
|
|
||||||
withHandlers: boolean = true
|
|
||||||
): number {
|
|
||||||
// nodeType 1 is generic tag
|
|
||||||
if (node.nodeType !== 1) {
|
|
||||||
throw new Error("unsupported node type");
|
|
||||||
}
|
|
||||||
const attributes = (<Element>node).attributes;
|
|
||||||
const attrs: string[] = [];
|
|
||||||
const props: string[] = [];
|
|
||||||
const tattrs: number[] = [];
|
|
||||||
|
|
||||||
function handleBooleanProps(key, val) {
|
|
||||||
let isProp = false;
|
|
||||||
if (node.nodeName === "input" && key === "checked") {
|
|
||||||
let type = (<Element>node).getAttribute("type");
|
|
||||||
if (type === "checkbox" || type === "radio") {
|
|
||||||
isProp = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (node.nodeName === "option" && key === "selected") {
|
|
||||||
isProp = true;
|
|
||||||
}
|
|
||||||
if (key === "disabled" && DISABLED_TAGS.indexOf(node.nodeName) > -1) {
|
|
||||||
isProp = true;
|
|
||||||
}
|
|
||||||
if ((key === "readonly" && node.nodeName === "input") || node.nodeName === "textarea") {
|
|
||||||
isProp = true;
|
|
||||||
}
|
|
||||||
if (isProp) {
|
|
||||||
props.push(`${key}: _${val}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let classObj = "";
|
|
||||||
|
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
|
||||||
let name = attributes[i].name;
|
|
||||||
let value = attributes[i].textContent!;
|
|
||||||
|
|
||||||
if (this.translateFn && TRANSLATABLE_ATTRS.includes(name)) {
|
|
||||||
value = this.translateFn(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
// regular attributes
|
|
||||||
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
|
||||||
const attID = ctx.generateID();
|
|
||||||
if (name === "class") {
|
|
||||||
let classDef = value
|
|
||||||
.trim()
|
|
||||||
.split(/\s+/)
|
|
||||||
.map(a => `'${a}':true`)
|
|
||||||
.join(",");
|
|
||||||
classObj = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
|
||||||
} else {
|
|
||||||
ctx.addLine(`var _${attID} = '${value}';`);
|
|
||||||
if (!name.match(/^[a-zA-Z]+$/)) {
|
|
||||||
// attribute contains 'non letters' => we want to quote it
|
|
||||||
name = '"' + name + '"';
|
|
||||||
}
|
|
||||||
attrs.push(`${name}: _${attID}`);
|
|
||||||
handleBooleanProps(name, attID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// dynamic attributes
|
|
||||||
if (name.startsWith("t-att-")) {
|
|
||||||
let attName = name.slice(6);
|
|
||||||
const v = ctx.getValue(value);
|
|
||||||
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : v.id;
|
|
||||||
|
|
||||||
if (attName === "class") {
|
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
|
||||||
formattedValue = `utils.toObj(${formattedValue})`;
|
|
||||||
if (classObj) {
|
|
||||||
ctx.addLine(`Object.assign(${classObj}, ${formattedValue})`);
|
|
||||||
} else {
|
|
||||||
classObj = `_${ctx.generateID()}`;
|
|
||||||
ctx.addLine(`let ${classObj} = ${formattedValue};`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const attID = ctx.generateID();
|
|
||||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
|
||||||
// attribute contains 'non letters' => we want to quote it
|
|
||||||
attName = '"' + attName + '"';
|
|
||||||
}
|
|
||||||
// we need to combine dynamic with non dynamic attributes:
|
|
||||||
// class="a" t-att-class="'yop'" should be rendered as class="a yop"
|
|
||||||
const attValue = (<Element>node).getAttribute(attName);
|
|
||||||
if (attValue) {
|
|
||||||
const attValueID = ctx.generateID();
|
|
||||||
ctx.addLine(`var _${attValueID} = ${formattedValue};`);
|
|
||||||
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
|
||||||
const attrIndex = attrs.findIndex(att => att.startsWith(attName + ":"));
|
|
||||||
attrs.splice(attrIndex, 1);
|
|
||||||
}
|
|
||||||
ctx.addLine(`var _${attID} = ${formattedValue};`);
|
|
||||||
attrs.push(`${attName}: _${attID}`);
|
|
||||||
handleBooleanProps(attName, attID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (name.startsWith("t-attf-")) {
|
|
||||||
let attName = name.slice(7);
|
|
||||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
|
||||||
// attribute contains 'non letters' => we want to quote it
|
|
||||||
attName = '"' + attName + '"';
|
|
||||||
}
|
|
||||||
const formattedExpr = ctx.interpolate(value);
|
|
||||||
const attID = ctx.generateID();
|
|
||||||
let staticVal = (<Element>node).getAttribute(attName);
|
|
||||||
if (staticVal) {
|
|
||||||
ctx.addLine(`var _${attID} = '${staticVal} ' + ${formattedExpr};`);
|
|
||||||
} else {
|
|
||||||
ctx.addLine(`var _${attID} = ${formattedExpr};`);
|
|
||||||
}
|
|
||||||
attrs.push(`${attName}: _${attID}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// t-att= attributes
|
|
||||||
if (name === "t-att") {
|
|
||||||
let id = ctx.generateID();
|
|
||||||
ctx.addLine(`var _${id} = ${ctx.formatExpression(value!)};`);
|
|
||||||
tattrs.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let nodeID = ctx.generateID();
|
|
||||||
let nodeKey = ctx.lastNodeKey || nodeID;
|
|
||||||
const parts = [`key:${nodeKey}`];
|
|
||||||
if (attrs.length + tattrs.length > 0) {
|
|
||||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
|
||||||
}
|
|
||||||
if (props.length > 0) {
|
|
||||||
parts.push(`props:{${props.join(",")}}`);
|
|
||||||
}
|
|
||||||
if (classObj) {
|
|
||||||
parts.push(`class:${classObj}`);
|
|
||||||
}
|
|
||||||
if (withHandlers) {
|
|
||||||
parts.push(`on:{}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.addLine(`let c${nodeID} = [], p${nodeID} = {${parts.join(",")}};`);
|
|
||||||
for (let id of tattrs) {
|
|
||||||
ctx.addIf(`_${id} instanceof Array`);
|
|
||||||
ctx.addLine(`p${nodeID}.attrs[_${id}[0]] = _${id}[1];`);
|
|
||||||
ctx.addElse();
|
|
||||||
ctx.addLine(`for (let key in _${id}) {`);
|
|
||||||
ctx.indent();
|
|
||||||
ctx.addLine(`p${nodeID}.attrs[key] = _${id}[key];`);
|
|
||||||
ctx.dedent();
|
|
||||||
ctx.addLine(`}`);
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
ctx.addLine(`var vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`);
|
|
||||||
if (ctx.parentNode) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return nodeID;
|
|
||||||
}
|
|
||||||
|
|
||||||
_compileChildren(node: ChildNode, ctx: CompilationContext) {
|
|
||||||
if (node.childNodes.length > 0) {
|
|
||||||
for (let child of Array.from(node.childNodes)) {
|
|
||||||
this._compileNode(child, ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
// import { compileTemplate, Template } from "./qweb/index";
|
||||||
|
import { BDom, createBlock, html, list, multi, text, toggler } from "../blockdom";
|
||||||
|
import { component } from "../component/component_node";
|
||||||
|
import { Template, compileTemplate } from "./compiler";
|
||||||
|
|
||||||
|
const bdom = { text, createBlock, list, multi, html, toggler, component };
|
||||||
|
|
||||||
|
export const globalTemplates: { [key: string]: string } = {};
|
||||||
|
|
||||||
|
function withDefault(value: any, defaultValue: any): any {
|
||||||
|
return value === undefined || value === null || value === false ? defaultValue : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function callSlot(
|
||||||
|
ctx: any,
|
||||||
|
parent: any,
|
||||||
|
key: string,
|
||||||
|
name: string,
|
||||||
|
defaultSlot?: (ctx: any, key: string) => BDom,
|
||||||
|
dynamic?: boolean
|
||||||
|
): BDom | null {
|
||||||
|
const slots = ctx.__owl__.slots;
|
||||||
|
const slotFn = slots[name];
|
||||||
|
const slotBDom = slotFn ? slotFn(parent, key) : null;
|
||||||
|
if (defaultSlot) {
|
||||||
|
let child1: BDom | undefined = undefined;
|
||||||
|
let child2: BDom | undefined = undefined;
|
||||||
|
// const result = new BMulti(2);
|
||||||
|
if (slotBDom) {
|
||||||
|
child1 = dynamic ? toggler(name, slotBDom) : slotBDom;
|
||||||
|
} else {
|
||||||
|
child2 = defaultSlot(parent, key);
|
||||||
|
}
|
||||||
|
return multi([child1, child2]);
|
||||||
|
}
|
||||||
|
return slotBDom;
|
||||||
|
}
|
||||||
|
|
||||||
|
function capture(ctx: any): any {
|
||||||
|
const component = ctx.__owl__.component;
|
||||||
|
const result = Object.create(component);
|
||||||
|
for (let k in ctx) {
|
||||||
|
result[k] = ctx[k];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withKey(elem: any, k: string) {
|
||||||
|
elem.key = k;
|
||||||
|
return elem;
|
||||||
|
}
|
||||||
|
|
||||||
|
function prepareList(collection: any): [any[], any[], number, any[]] {
|
||||||
|
let keys: any[];
|
||||||
|
let values: any[];
|
||||||
|
|
||||||
|
if (Array.isArray(collection)) {
|
||||||
|
keys = collection;
|
||||||
|
values = collection;
|
||||||
|
} else if (collection) {
|
||||||
|
values = Object.keys(collection);
|
||||||
|
keys = Object.values(collection);
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid loop expression");
|
||||||
|
}
|
||||||
|
const n = values.length;
|
||||||
|
return [keys, values, n, new Array(n)];
|
||||||
|
}
|
||||||
|
export const UTILS = {
|
||||||
|
// elem,
|
||||||
|
// setText,
|
||||||
|
withDefault,
|
||||||
|
zero: Symbol("zero"),
|
||||||
|
callSlot,
|
||||||
|
capture,
|
||||||
|
// toClassObj,
|
||||||
|
withKey,
|
||||||
|
prepareList,
|
||||||
|
shallowEqual,
|
||||||
|
};
|
||||||
|
|
||||||
|
export class TemplateSet {
|
||||||
|
rawTemplates: { [name: string]: string } = Object.create(globalTemplates);
|
||||||
|
templates: { [name: string]: Template } = {};
|
||||||
|
utils: typeof UTILS;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
const call = (subTemplate: string, ctx: any, parent: any) => {
|
||||||
|
const template = this.getTemplate(subTemplate);
|
||||||
|
return toggler(subTemplate, template(ctx, parent));
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTemplate = (name: string) => this.getTemplate(name);
|
||||||
|
this.utils = Object.assign({}, UTILS, { getTemplate, call });
|
||||||
|
}
|
||||||
|
|
||||||
|
addTemplate(name: string, template: string, options: { allowDuplicate?: boolean } = {}) {
|
||||||
|
if (name in this.rawTemplates && !options.allowDuplicate) {
|
||||||
|
throw new Error(`Template ${name} already defined`);
|
||||||
|
}
|
||||||
|
this.rawTemplates[name] = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTemplate(name: string): Template {
|
||||||
|
if (!(name in this.templates)) {
|
||||||
|
const rawTemplate = this.rawTemplates[name];
|
||||||
|
if (rawTemplate === undefined) {
|
||||||
|
throw new Error(`Missing template: "${name}"`);
|
||||||
|
}
|
||||||
|
const templateFn = compileTemplate(rawTemplate, name);
|
||||||
|
|
||||||
|
// first add a function to lazily get the template, in case there is a
|
||||||
|
// recursive call to the template name
|
||||||
|
this.templates[name] = (context, parent) => this.templates[name](context, parent);
|
||||||
|
const template = templateFn(bdom, this.utils);
|
||||||
|
this.templates[name] = template;
|
||||||
|
}
|
||||||
|
return this.templates[name];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function shallowEqual(l1: any[], l2: any[]): boolean {
|
||||||
|
for (let i = 0, l = l1.length; i < l; i++) {
|
||||||
|
if (l1[i] !== l2[i]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { getCurrent } from "./component/component_node";
|
||||||
|
|
||||||
|
export function useState<T>(state: T): T {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
return observe(state, () => node.render());
|
||||||
|
}
|
||||||
|
|
||||||
|
type CB = () => void;
|
||||||
|
const observers: WeakMap<any, PSet<CB>> = new WeakMap();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PSet (for Prototypal Set) are sets that can lookup in their "parent sets", if
|
||||||
|
* any.
|
||||||
|
*/
|
||||||
|
|
||||||
|
class PSet<T> extends Set<T> {
|
||||||
|
parent?: PSet<T>;
|
||||||
|
|
||||||
|
static createChild<T>(parent: PSet<T>): PSet<T> {
|
||||||
|
const pset: PSet<T> = new PSet();
|
||||||
|
pset.parent = parent;
|
||||||
|
return pset;
|
||||||
|
}
|
||||||
|
|
||||||
|
has(key: T): boolean {
|
||||||
|
if (super.has(key)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return this.parent ? this.parent.has(key) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
*[Symbol.iterator](): Generator<T> {
|
||||||
|
let iterator = super[Symbol.iterator]();
|
||||||
|
for (let elem of iterator) {
|
||||||
|
yield elem;
|
||||||
|
}
|
||||||
|
if (this.parent) {
|
||||||
|
for (let elem of this.parent) {
|
||||||
|
yield elem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function observe<T>(value: T, cb: CB): T {
|
||||||
|
if (isNotObservable(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if (observers.has(value)) {
|
||||||
|
const callbacks = observers.get(value)!;
|
||||||
|
callbacks.add(cb);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
const callbacks: PSet<CB> = new PSet();
|
||||||
|
callbacks.add(cb);
|
||||||
|
return observeValue(value, callbacks);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unobserve<T>(value: T, cb: () => void) {
|
||||||
|
if (isNotObservable(value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (observers.has(value)) {
|
||||||
|
const callbacks = observers.get(value)!;
|
||||||
|
callbacks.delete(cb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNotObservable(value: any): boolean {
|
||||||
|
return (
|
||||||
|
value === null || typeof value !== "object" || value instanceof Date || value instanceof Promise
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* value should
|
||||||
|
* 1. be observable
|
||||||
|
* 2. not yet be observed
|
||||||
|
*/
|
||||||
|
function observeValue(value: any, callbacks: PSet<CB>): any {
|
||||||
|
const proxy = new Proxy(value as any, {
|
||||||
|
get(target: any, key: any): any {
|
||||||
|
const current = target[key];
|
||||||
|
if (isNotObservable(current)) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
if (observers.has(current)) {
|
||||||
|
// this is wrong ?
|
||||||
|
observers.get(current)!.parent = callbacks;
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
const subCallbacks = PSet.createChild(callbacks);
|
||||||
|
const subValue = observeValue(current, subCallbacks);
|
||||||
|
target[key] = subValue;
|
||||||
|
return subValue;
|
||||||
|
},
|
||||||
|
set(target: any, key: any, value: any): boolean {
|
||||||
|
// TODO: check if current !== target or proxy ??
|
||||||
|
const current = target[key];
|
||||||
|
if (current !== value) {
|
||||||
|
if (isNotObservable(value)) {
|
||||||
|
target[key] = value;
|
||||||
|
} else {
|
||||||
|
// TODO: test following scenario:
|
||||||
|
// 1. obj1 = observer({a:1}, somecb);
|
||||||
|
// 2. unobserve(obj1, somecb)
|
||||||
|
// 3. obj1.a = {b: 2};
|
||||||
|
// check that somecb was not called
|
||||||
|
// obj1.a.b = 3;
|
||||||
|
// check again that somecb was not called
|
||||||
|
if (observers.has(value)) {
|
||||||
|
const pset = observers.get(value)!;
|
||||||
|
pset.parent = callbacks;
|
||||||
|
target[key] = value;
|
||||||
|
} else {
|
||||||
|
const subCallbacks = PSet.createChild(callbacks);
|
||||||
|
target[key] = observeValue(value, subCallbacks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notify(target);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
deleteProperty(target: any, key: any) {
|
||||||
|
if (key in target) {
|
||||||
|
delete target[key];
|
||||||
|
notify(target);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
observers.set(value, callbacks);
|
||||||
|
observers.set(proxy, callbacks);
|
||||||
|
return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify(value: any) {
|
||||||
|
const cbs = observers.get(value)!;
|
||||||
|
for (let cb of cbs) {
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// useRef
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
import type { Component } from "./component/component";
|
||||||
|
import { getCurrent } from "./component/component_node";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The purpose of this hook is to allow components to get a reference to a sub
|
||||||
|
* html node or component.
|
||||||
|
*/
|
||||||
|
interface Ref<C extends Component = Component> {
|
||||||
|
el: HTMLElement | null;
|
||||||
|
comp: C | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRef<C extends Component = Component>(name: string): Ref<C> {
|
||||||
|
const node = getCurrent()!;
|
||||||
|
return {
|
||||||
|
get el(): HTMLElement | null {
|
||||||
|
const val = node.refs[name];
|
||||||
|
return val!;
|
||||||
|
// if (val instanceof HTMLElement) {
|
||||||
|
// return val;
|
||||||
|
// } else if (val instanceof Component) {
|
||||||
|
// return val.el;
|
||||||
|
// }
|
||||||
|
// return null;
|
||||||
|
},
|
||||||
|
get comp(): C | null {
|
||||||
|
return null;
|
||||||
|
// const val = node.refs && node.refs[name];
|
||||||
|
// return val instanceof Component ? (val as C) : null;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { Component } from "../component/component";
|
|
||||||
import { xml } from "../tags";
|
|
||||||
import { Destination, RouterEnv } from "./router";
|
|
||||||
|
|
||||||
type Props = Destination;
|
|
||||||
|
|
||||||
export class Link<Env extends RouterEnv> extends Component<Env, Props> {
|
|
||||||
static template = xml`
|
|
||||||
<a t-att-class="{'router-link-active': isActive }"
|
|
||||||
t-att-href="href"
|
|
||||||
t-on-click="navigate">
|
|
||||||
<t t-slot="default"/>
|
|
||||||
</a>
|
|
||||||
`;
|
|
||||||
|
|
||||||
href: string = this.env.router.destToPath(this.props);
|
|
||||||
|
|
||||||
async willUpdateProps(nextProps) {
|
|
||||||
this.href = this.env.router.destToPath(nextProps);
|
|
||||||
}
|
|
||||||
|
|
||||||
get isActive() {
|
|
||||||
if (this.env.router.mode === "hash") {
|
|
||||||
return (<any>document.location).hash === this.href;
|
|
||||||
}
|
|
||||||
return (<any>document.location).pathname === this.href;
|
|
||||||
}
|
|
||||||
|
|
||||||
navigate(ev) {
|
|
||||||
// don't redirect with control keys
|
|
||||||
if (ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// don't redirect on right click
|
|
||||||
if (ev.button !== undefined && ev.button !== 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// don't redirect if `target="_blank"`
|
|
||||||
if (ev.currentTarget && ev.currentTarget.getAttribute) {
|
|
||||||
const target = ev.currentTarget.getAttribute("target");
|
|
||||||
if (/\b_blank\b/i.test(target)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ev.preventDefault();
|
|
||||||
this.env.router.navigate(this.props);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { Component } from "../component/component";
|
|
||||||
import { xml } from "../tags";
|
|
||||||
|
|
||||||
export class RouteComponent extends Component<any, {}> {
|
|
||||||
static template = xml`
|
|
||||||
<t>
|
|
||||||
<t
|
|
||||||
t-if="routeComponent"
|
|
||||||
t-component="routeComponent"
|
|
||||||
t-key="env.router.currentRouteName"
|
|
||||||
t-props="env.router.currentParams" />
|
|
||||||
</t>
|
|
||||||
`;
|
|
||||||
|
|
||||||
get routeComponent(): any {
|
|
||||||
return this.env.router.currentRoute && this.env.router.currentRoute.component;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
import { Env } from "../component/component";
|
|
||||||
import { QWeb } from "../qweb/index";
|
|
||||||
import { shallowEqual } from "../utils";
|
|
||||||
|
|
||||||
type NavigationGuard = (info: {
|
|
||||||
env: Env;
|
|
||||||
to: Route | null;
|
|
||||||
from: Route | null;
|
|
||||||
}) => boolean | Destination;
|
|
||||||
|
|
||||||
export interface Route {
|
|
||||||
name: string;
|
|
||||||
path: string;
|
|
||||||
component?: any;
|
|
||||||
redirect?: Destination;
|
|
||||||
params: string[];
|
|
||||||
beforeRouteEnter?: NavigationGuard;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type RouteParams = { [key: string]: string | number };
|
|
||||||
|
|
||||||
export interface RouterEnv extends Env {
|
|
||||||
router: Router;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Destination {
|
|
||||||
path?: string;
|
|
||||||
to?: string;
|
|
||||||
params?: RouteParams;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PositiveMatchResult {
|
|
||||||
type: "match";
|
|
||||||
route: Route;
|
|
||||||
params: RouteParams;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface NegativeMatchResult {
|
|
||||||
type: "nomatch";
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CancelledMatch {
|
|
||||||
type: "cancelled";
|
|
||||||
}
|
|
||||||
|
|
||||||
type MatchResult = PositiveMatchResult | NegativeMatchResult | CancelledMatch;
|
|
||||||
|
|
||||||
interface Options {
|
|
||||||
mode: Router["mode"];
|
|
||||||
}
|
|
||||||
|
|
||||||
const paramRegexp = /\{\{(.*?)\}\}/;
|
|
||||||
|
|
||||||
export class Router {
|
|
||||||
currentRoute: Route | null = null;
|
|
||||||
currentParams: RouteParams | null = null;
|
|
||||||
mode: "history" | "hash";
|
|
||||||
|
|
||||||
routes: { [id: string]: Route };
|
|
||||||
routeIds: string[];
|
|
||||||
env: RouterEnv;
|
|
||||||
|
|
||||||
constructor(env: Env, routes: Partial<Route>[], options: Options = { mode: "history" }) {
|
|
||||||
env.router = this;
|
|
||||||
this.mode = options.mode;
|
|
||||||
this.env = env as RouterEnv;
|
|
||||||
|
|
||||||
this.routes = {};
|
|
||||||
this.routeIds = [];
|
|
||||||
let nextId = 1;
|
|
||||||
for (let partialRoute of routes) {
|
|
||||||
if (!partialRoute.name) {
|
|
||||||
partialRoute.name = "__route__" + nextId++;
|
|
||||||
}
|
|
||||||
if (partialRoute.component) {
|
|
||||||
QWeb.registerComponent("__component__" + partialRoute.name, partialRoute.component);
|
|
||||||
}
|
|
||||||
if (partialRoute.redirect) {
|
|
||||||
this.validateDestination(partialRoute.redirect);
|
|
||||||
}
|
|
||||||
partialRoute.params = partialRoute.path ? findParams(partialRoute.path) : [];
|
|
||||||
this.routes[partialRoute.name] = partialRoute as Route;
|
|
||||||
this.routeIds.push(partialRoute.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
// Public API
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
|
|
||||||
async start() {
|
|
||||||
(this as any)._listener = ev => this._navigate(this.currentPath(), ev);
|
|
||||||
window.addEventListener("popstate", (this as any)._listener);
|
|
||||||
if (this.mode === "hash") {
|
|
||||||
window.addEventListener("hashchange", (this as any)._listener);
|
|
||||||
}
|
|
||||||
const result = await this.matchAndApplyRules(this.currentPath());
|
|
||||||
if (result.type === "match") {
|
|
||||||
this.currentRoute = result.route;
|
|
||||||
this.currentParams = result.params;
|
|
||||||
const currentPath = this.routeToPath(result.route, result.params);
|
|
||||||
if (currentPath !== this.currentPath()) {
|
|
||||||
this.setUrlFromPath(currentPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async navigate(to: Destination): Promise<boolean> {
|
|
||||||
const path = this.destToPath(to);
|
|
||||||
return this._navigate(path);
|
|
||||||
}
|
|
||||||
async _navigate(path: string, ev?: any): Promise<boolean> {
|
|
||||||
const initialName = this.currentRouteName;
|
|
||||||
const initialParams = this.currentParams;
|
|
||||||
const result = await this.matchAndApplyRules(path);
|
|
||||||
if (result.type === "match") {
|
|
||||||
const finalPath = this.routeToPath(result.route, result.params);
|
|
||||||
const isPopStateEvent = ev && ev instanceof PopStateEvent;
|
|
||||||
if (!isPopStateEvent) {
|
|
||||||
this.setUrlFromPath(finalPath);
|
|
||||||
}
|
|
||||||
this.currentRoute = result.route;
|
|
||||||
this.currentParams = result.params;
|
|
||||||
} else if (result.type === "nomatch") {
|
|
||||||
this.currentRoute = null;
|
|
||||||
this.currentParams = null;
|
|
||||||
}
|
|
||||||
const didChange =
|
|
||||||
this.currentRouteName !== initialName || !shallowEqual(this.currentParams, initialParams);
|
|
||||||
if (didChange) {
|
|
||||||
this.env.qweb.forceUpdate();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
destToPath(dest: Destination): string {
|
|
||||||
this.validateDestination(dest);
|
|
||||||
return dest.path || this.routeToPath(this.routes[dest.to!], dest.params!);
|
|
||||||
}
|
|
||||||
|
|
||||||
get currentRouteName(): string | null {
|
|
||||||
return this.currentRoute && this.currentRoute.name;
|
|
||||||
}
|
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
// Private helpers
|
|
||||||
//--------------------------------------------------------------------------
|
|
||||||
|
|
||||||
private setUrlFromPath(path: string) {
|
|
||||||
const separator = this.mode === "hash" ? location.pathname : "";
|
|
||||||
const url = location.origin + separator + path;
|
|
||||||
if (url !== window.location.href) {
|
|
||||||
window.history.pushState({}, path, url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private validateDestination(dest: Destination) {
|
|
||||||
if ((!dest.path && !dest.to) || (dest.path && dest.to)) {
|
|
||||||
throw new Error(`Invalid destination: ${JSON.stringify(dest)}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private routeToPath(route: Route, params: RouteParams): string {
|
|
||||||
const path = route.path;
|
|
||||||
const parts = path.split("/");
|
|
||||||
const l = parts.length;
|
|
||||||
for (let i = 0; i < l; i++) {
|
|
||||||
const part = parts[i];
|
|
||||||
const match = part.match(paramRegexp);
|
|
||||||
if (match) {
|
|
||||||
const key = match[1].split(".")[0];
|
|
||||||
parts[i] = <string>params[key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const prefix = this.mode === "hash" ? "#" : "";
|
|
||||||
return prefix + parts.join("/");
|
|
||||||
}
|
|
||||||
|
|
||||||
private currentPath(): string {
|
|
||||||
let result = this.mode === "history" ? window.location.pathname : window.location.hash.slice(1);
|
|
||||||
return result || "/";
|
|
||||||
}
|
|
||||||
|
|
||||||
private match(path: string): MatchResult {
|
|
||||||
for (let routeId of this.routeIds) {
|
|
||||||
let route = this.routes[routeId];
|
|
||||||
let params = this.getRouteParams(route, path);
|
|
||||||
if (params) {
|
|
||||||
return {
|
|
||||||
type: "match",
|
|
||||||
route: route,
|
|
||||||
params: params
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { type: "nomatch" };
|
|
||||||
}
|
|
||||||
|
|
||||||
private async matchAndApplyRules(path: string): Promise<MatchResult> {
|
|
||||||
const result = this.match(path);
|
|
||||||
if (result.type === "match") {
|
|
||||||
return this.applyRules(result);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async applyRules(matchResult: PositiveMatchResult): Promise<MatchResult> {
|
|
||||||
const route = matchResult.route;
|
|
||||||
if (route.redirect) {
|
|
||||||
const path = this.destToPath(route.redirect);
|
|
||||||
return this.matchAndApplyRules(path);
|
|
||||||
}
|
|
||||||
if (route.beforeRouteEnter) {
|
|
||||||
const result = await route.beforeRouteEnter({
|
|
||||||
env: this.env,
|
|
||||||
from: this.currentRoute,
|
|
||||||
to: route
|
|
||||||
});
|
|
||||||
if (result === false) {
|
|
||||||
return { type: "cancelled" };
|
|
||||||
} else if (result !== true) {
|
|
||||||
// we want to navigate to another destination
|
|
||||||
const path = this.destToPath(result);
|
|
||||||
return this.matchAndApplyRules(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return matchResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getRouteParams(route: Route, path: string): RouteParams | false {
|
|
||||||
if (route.path === "*") {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
if (path.startsWith("#")) {
|
|
||||||
path = path.slice(1);
|
|
||||||
}
|
|
||||||
const descrParts = route.path.split("/");
|
|
||||||
const targetParts = path.split("/");
|
|
||||||
const l = descrParts.length;
|
|
||||||
if (l !== targetParts.length) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const result = {};
|
|
||||||
for (let i = 0; i < l; i++) {
|
|
||||||
const descr = descrParts[i];
|
|
||||||
let target: string | number = targetParts[i];
|
|
||||||
const match = descr.match(paramRegexp);
|
|
||||||
if (match) {
|
|
||||||
const [key, suffix] = match[1].split(".");
|
|
||||||
if (suffix === "number") {
|
|
||||||
target = parseInt(target, 10);
|
|
||||||
}
|
|
||||||
result[key] = target;
|
|
||||||
} else if (descr !== target) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function findParams(str: string): string[] {
|
|
||||||
const globalParamRegexp = /\{\{(.*?)\}\}/g;
|
|
||||||
const result: string[] = [];
|
|
||||||
let m;
|
|
||||||
do {
|
|
||||||
m = globalParamRegexp.exec(str);
|
|
||||||
if (m) {
|
|
||||||
result.push(m[1].split(".")[0]);
|
|
||||||
}
|
|
||||||
} while (m);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
-142
@@ -1,142 +0,0 @@
|
|||||||
import { Component } from "./component/component";
|
|
||||||
import { Env } from "./component/component";
|
|
||||||
import { Context, useContextWithCB } from "./context";
|
|
||||||
import { onWillUpdateProps } from "./hooks";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owl Store
|
|
||||||
*
|
|
||||||
* We have here:
|
|
||||||
* - a Store class
|
|
||||||
* - useStore hook
|
|
||||||
* - useDispatch hook
|
|
||||||
* - useGetters hook
|
|
||||||
*
|
|
||||||
* The Owl store is our answer to the problem of managing complex state across
|
|
||||||
* components. The main idea is that the store owns some state, allow external
|
|
||||||
* code to modify it through actions, and for each state changes,
|
|
||||||
* connected component will be notified, and updated if necessary.
|
|
||||||
*
|
|
||||||
* Note that this code is partly inspired by VueX and React/Redux
|
|
||||||
*/
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Store Definition
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
|
||||||
export type Getter = ({ state: any, getters }, payload?) => any;
|
|
||||||
|
|
||||||
interface StoreConfig {
|
|
||||||
env?: Env;
|
|
||||||
state?: any;
|
|
||||||
actions?: { [name: string]: Action };
|
|
||||||
getters?: { [name: string]: Getter };
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Store extends Context {
|
|
||||||
actions: any;
|
|
||||||
env: any;
|
|
||||||
getters: { [name: string]: (payload?) => any };
|
|
||||||
updateFunctions: { [key: number]: (() => boolean)[] };
|
|
||||||
|
|
||||||
constructor(config: StoreConfig) {
|
|
||||||
super(config.state);
|
|
||||||
this.actions = config.actions;
|
|
||||||
this.env = config.env;
|
|
||||||
this.getters = {};
|
|
||||||
this.updateFunctions = [];
|
|
||||||
if (config.getters) {
|
|
||||||
const firstArg = {
|
|
||||||
state: this.state,
|
|
||||||
getters: this.getters
|
|
||||||
};
|
|
||||||
for (let g in config.getters) {
|
|
||||||
this.getters[g] = config.getters[g].bind(this, firstArg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatch(action: string, ...payload: any): Promise<void> | void {
|
|
||||||
if (!this.actions[action]) {
|
|
||||||
throw new Error(`[Error] action ${action} is undefined`);
|
|
||||||
}
|
|
||||||
const result = this.actions[action](
|
|
||||||
{
|
|
||||||
dispatch: this.dispatch.bind(this),
|
|
||||||
env: this.env,
|
|
||||||
state: this.state,
|
|
||||||
getters: this.getters
|
|
||||||
},
|
|
||||||
...payload
|
|
||||||
);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SelectorOptions {
|
|
||||||
store?: Store;
|
|
||||||
isEqual?: (a: any, b: any) => boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isStrictEqual = (a, b) => a === b;
|
|
||||||
|
|
||||||
export function useStore(selector, options: SelectorOptions = {}): any {
|
|
||||||
const component: Component<any, any> = Component.current!;
|
|
||||||
const store = options.store || (component.env.store as Store);
|
|
||||||
let result = selector(store.state, component.props);
|
|
||||||
const hashFn = store.observer.deepRevNumber.bind(store.observer);
|
|
||||||
let revNumber = hashFn(result) || result;
|
|
||||||
const isEqual = options.isEqual || isStrictEqual;
|
|
||||||
if (!store.updateFunctions[component.__owl__.id]) {
|
|
||||||
store.updateFunctions[component.__owl__.id] = [];
|
|
||||||
}
|
|
||||||
const updateFunctions = store.updateFunctions[component.__owl__.id];
|
|
||||||
updateFunctions.push(function(): boolean {
|
|
||||||
const oldResult = result;
|
|
||||||
result = selector(store!.state, component.props);
|
|
||||||
const newRevNumber = hashFn(result);
|
|
||||||
if (
|
|
||||||
(newRevNumber > 0 && revNumber !== newRevNumber) ||
|
|
||||||
(newRevNumber === 0 && !isEqual(oldResult, result))
|
|
||||||
) {
|
|
||||||
revNumber = newRevNumber;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
useContextWithCB(store, component, function(): Promise<void> | void {
|
|
||||||
let shouldRender = false;
|
|
||||||
updateFunctions.forEach(function(updateFn) {
|
|
||||||
shouldRender = updateFn() || shouldRender;
|
|
||||||
});
|
|
||||||
if (shouldRender) {
|
|
||||||
return component.render();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
onWillUpdateProps(props => {
|
|
||||||
// FIXME: only do that if not keepalive + do it in destroy in that case
|
|
||||||
delete store.updateFunctions[component.__owl__.id];
|
|
||||||
result = selector(store.state, props);
|
|
||||||
});
|
|
||||||
return new Proxy(result, {
|
|
||||||
get(target, k) {
|
|
||||||
return result[k];
|
|
||||||
},
|
|
||||||
set(target, k, v) {
|
|
||||||
result[k] = v;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDispatch(store?: Store): Store["dispatch"] {
|
|
||||||
store = store || (Component.current!.env.store as Store);
|
|
||||||
return store.dispatch.bind(store);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useGetters(store?: Store): Store["getters"] {
|
|
||||||
store = store || (Component.current!.env.store as Store);
|
|
||||||
return store.getters;
|
|
||||||
}
|
|
||||||
+9
-22
@@ -1,27 +1,14 @@
|
|||||||
import { QWeb } from "./qweb/index";
|
import { globalTemplates } from "./qweb/template_helpers";
|
||||||
|
|
||||||
/**
|
// -----------------------------------------------------------------------------
|
||||||
* Owl Tags
|
// Global templates
|
||||||
*
|
// -----------------------------------------------------------------------------
|
||||||
* We have here a (very) small collection of tag functions:
|
|
||||||
*
|
|
||||||
* - xml
|
|
||||||
*
|
|
||||||
* The plan is to add a few other tags such as css, globalcss.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
export function xml(strings: TemplateStringsArray, ...args: any[]) {
|
||||||
* XML tag helper for defining templates. With this, one can simply define
|
const name = `__template__${xml.nextId++}`;
|
||||||
* an inline template with just the template xml:
|
|
||||||
* ```js
|
|
||||||
* class A extends Component {
|
|
||||||
* static template = xml`<div>some template</div>`;
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function xml(strings, ...args) {
|
|
||||||
const name = `__template__${QWeb.nextId++}`;
|
|
||||||
const value = String.raw(strings, ...args);
|
const value = String.raw(strings, ...args);
|
||||||
QWeb.registerTemplate(name, value);
|
globalTemplates[name] = value;
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
xml.nextId = 1;
|
||||||
|
|||||||
-104
@@ -1,104 +0,0 @@
|
|||||||
/**
|
|
||||||
* Owl Utils
|
|
||||||
*
|
|
||||||
* We have here a small collection of utility functions:
|
|
||||||
*
|
|
||||||
* - whenReady
|
|
||||||
* - loadJS
|
|
||||||
* - loadFile
|
|
||||||
* - escape
|
|
||||||
* - debounce
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function whenReady(fn?: any) {
|
|
||||||
return new Promise(function(resolve) {
|
|
||||||
if (document.readyState !== "loading") {
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
document.addEventListener("DOMContentLoaded", resolve, false);
|
|
||||||
}
|
|
||||||
}).then(fn || function() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadedScripts: { [key: string]: Promise<void> } = {};
|
|
||||||
|
|
||||||
export function loadJS(url: string): Promise<void> {
|
|
||||||
if (url in loadedScripts) {
|
|
||||||
return loadedScripts[url];
|
|
||||||
}
|
|
||||||
const promise: Promise<void> = new Promise(function(resolve, reject) {
|
|
||||||
const script = document.createElement("script");
|
|
||||||
script.type = "text/javascript";
|
|
||||||
script.src = url;
|
|
||||||
script.onload = function() {
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
script.onerror = function() {
|
|
||||||
reject(`Error loading file '${url}'`);
|
|
||||||
};
|
|
||||||
const head = document.head || document.getElementsByTagName("head")[0];
|
|
||||||
head.appendChild(script);
|
|
||||||
});
|
|
||||||
loadedScripts[url] = promise;
|
|
||||||
return promise;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadFile(url: string): Promise<string> {
|
|
||||||
const result = await fetch(url);
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new Error("Error while fetching xml templates");
|
|
||||||
}
|
|
||||||
return await result.text();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function escape(str: string | number | undefined): string {
|
|
||||||
if (str === undefined) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
if (typeof str === "number") {
|
|
||||||
return String(str);
|
|
||||||
}
|
|
||||||
return str
|
|
||||||
.replace(/&/g, "&")
|
|
||||||
.replace(/</g, "<")
|
|
||||||
.replace(/>/g, ">")
|
|
||||||
.replace(/"/g, "'")
|
|
||||||
.replace(/`/g, "`");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a function, that, as long as it continues to be invoked, will not
|
|
||||||
* be triggered. The function will be called after it stops being called for
|
|
||||||
* N milliseconds. If `immediate` is passed, trigger the function on the
|
|
||||||
* leading edge, instead of the trailing.
|
|
||||||
*
|
|
||||||
* Inspired by https://davidwalsh.name/javascript-debounce-function
|
|
||||||
*/
|
|
||||||
export function debounce(func: Function, wait: number, immediate?: boolean): Function {
|
|
||||||
let timeout;
|
|
||||||
return function(this: any) {
|
|
||||||
const context = this;
|
|
||||||
const args = arguments;
|
|
||||||
function later() {
|
|
||||||
timeout = null;
|
|
||||||
if (!immediate) {
|
|
||||||
func.apply(context, args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const callNow = immediate && !timeout;
|
|
||||||
clearTimeout(timeout);
|
|
||||||
timeout = setTimeout(later, wait);
|
|
||||||
if (callNow) {
|
|
||||||
func.apply(context, args);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function shallowEqual(p1, p2): boolean {
|
|
||||||
for (let k in p1) {
|
|
||||||
if (p1[k] !== p2[k]) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { VNode, h } from "./vdom";
|
|
||||||
|
|
||||||
const parser = new DOMParser();
|
|
||||||
|
|
||||||
export function htmlToVDOM(html: string): VNode[] {
|
|
||||||
const doc = parser.parseFromString(html, "text/html");
|
|
||||||
const result: VNode[] = [];
|
|
||||||
for (let child of doc.body.childNodes) {
|
|
||||||
result.push(htmlToVNode(child));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
function htmlToVNode(node: ChildNode): VNode {
|
|
||||||
if (!(node instanceof Element)) {
|
|
||||||
return { text: node.textContent! } as VNode;
|
|
||||||
}
|
|
||||||
const attrs = {};
|
|
||||||
for (let attr of node.attributes) {
|
|
||||||
attrs[attr.name] = attr.textContent;
|
|
||||||
}
|
|
||||||
const children: VNode[] = [];
|
|
||||||
if (node.hasChildNodes) {
|
|
||||||
for (let c of node.childNodes) {
|
|
||||||
children.push(htmlToVNode(c));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h((node as Element).tagName, { attrs }, children);
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { attrsModule, classModule, eventListenersModule, propsModule } from "./modules";
|
|
||||||
import { init } from "./vdom";
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// patch
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export { h, VNode } from "./vdom";
|
|
||||||
|
|
||||||
export const patch = init([eventListenersModule, attrsModule, propsModule, classModule]);
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
import { Module, VNode, VNodeData } from "./vdom";
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// module/props.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// module/eventlisteners.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
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 (let i = 0, iLen = handler.length; i < iLen; 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;
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// attributes.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
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 attrsModule = {
|
|
||||||
create: updateAttrs,
|
|
||||||
update: updateAttrs
|
|
||||||
} as Module;
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// class.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
function updateClass(oldVnode: VNode, vnode: VNode): void {
|
|
||||||
var cur: any,
|
|
||||||
name: string,
|
|
||||||
elm: 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 || {};
|
|
||||||
|
|
||||||
elm = vnode.elm as Element;
|
|
||||||
|
|
||||||
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;
|
|
||||||
@@ -1,614 +0,0 @@
|
|||||||
/**
|
|
||||||
* Owl VDOM
|
|
||||||
*
|
|
||||||
* This file contains an implementation of a virtual DOM, which is a system that
|
|
||||||
* can generate in-memory representations of a DOM tree, compare them, and
|
|
||||||
* eventually change a concrete DOM tree to match its representation, in an
|
|
||||||
* hopefully efficient way.
|
|
||||||
*
|
|
||||||
* Note that this code is a fork of Snabbdom, slightly tweaked/optimized for our
|
|
||||||
* needs (see https://github.com/snabbdom/snabbdom).
|
|
||||||
*
|
|
||||||
* The main exported values are:
|
|
||||||
* - interface VNode
|
|
||||||
* - h function (a helper function to generate a vnode)
|
|
||||||
* - patch function (to apply a vnode to an actual DOM node)
|
|
||||||
*/
|
|
||||||
|
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Props = Record<string, any>;
|
|
||||||
type Attrs = Record<string, string | number | boolean>;
|
|
||||||
type On = { [N in keyof HTMLElementEventMap]?: (ev: HTMLElementEventMap[N]) => void } & {
|
|
||||||
[event: string]: EventListener;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface Module {
|
|
||||||
pre: PreHook;
|
|
||||||
create: CreateHook;
|
|
||||||
update: UpdateHook;
|
|
||||||
destroy: DestroyHook;
|
|
||||||
remove: RemoveHook;
|
|
||||||
post: PostHook;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// vnode.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
type Key = string | number;
|
|
||||||
|
|
||||||
export interface VNode {
|
|
||||||
sel: string | undefined;
|
|
||||||
data: VNodeData | undefined;
|
|
||||||
children: Array<VNode | string> | undefined;
|
|
||||||
elm: Node | undefined;
|
|
||||||
text: string | undefined;
|
|
||||||
key: Key | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface VNodeData {
|
|
||||||
props?: Props;
|
|
||||||
attrs?: Attrs;
|
|
||||||
on?: On;
|
|
||||||
hook?: Hooks;
|
|
||||||
key?: Key;
|
|
||||||
ns?: string; // for SVGs
|
|
||||||
[key: string]: any; // for any other 3rd party module
|
|
||||||
}
|
|
||||||
|
|
||||||
function vnode(
|
|
||||||
sel: string | undefined,
|
|
||||||
data: any | undefined,
|
|
||||||
children: Array<VNode | string> | undefined,
|
|
||||||
text: string | undefined,
|
|
||||||
elm: Element | Text | undefined
|
|
||||||
): VNode {
|
|
||||||
let key = data === undefined ? undefined : data.key;
|
|
||||||
return { sel, data, children, text, elm, key };
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// snabbdom.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
function isUndef(s: any): boolean {
|
|
||||||
return s === undefined;
|
|
||||||
}
|
|
||||||
function isDef(s: any): boolean {
|
|
||||||
return s !== undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
type VNodeQueue = Array<VNode>;
|
|
||||||
|
|
||||||
const emptyNode = vnode("", {}, [], undefined, undefined);
|
|
||||||
|
|
||||||
function sameVnode(vnode1: VNode, vnode2: VNode): boolean {
|
|
||||||
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isVnode(vnode: any): vnode is VNode {
|
|
||||||
return vnode.sel !== undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
type KeyToIndexMap = { [key: string]: number };
|
|
||||||
|
|
||||||
type ArraysOf<T> = { [K in keyof T]: (T[K])[] };
|
|
||||||
|
|
||||||
type ModuleHooks = ArraysOf<Module>;
|
|
||||||
|
|
||||||
function createKeyToOldIdx(
|
|
||||||
children: Array<VNode>,
|
|
||||||
beginIdx: number,
|
|
||||||
endIdx: number
|
|
||||||
): KeyToIndexMap {
|
|
||||||
let i: number,
|
|
||||||
map: KeyToIndexMap = {},
|
|
||||||
key: Key | undefined,
|
|
||||||
ch;
|
|
||||||
for (i = beginIdx; i <= endIdx; ++i) {
|
|
||||||
ch = children[i];
|
|
||||||
if (ch != null) {
|
|
||||||
key = ch.key;
|
|
||||||
if (key !== undefined) map[key] = i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hooks: (keyof Module)[] = ["create", "update", "remove", "destroy", "pre", "post"];
|
|
||||||
|
|
||||||
export function init(modules: Array<Partial<Module>>, domApi?: DOMAPI) {
|
|
||||||
let i: number,
|
|
||||||
j: number,
|
|
||||||
cbs = {} as ModuleHooks;
|
|
||||||
|
|
||||||
const api: DOMAPI = domApi !== undefined ? domApi : htmlDomApi;
|
|
||||||
|
|
||||||
for (i = 0; i < hooks.length; ++i) {
|
|
||||||
cbs[hooks[i]] = [];
|
|
||||||
for (j = 0; j < modules.length; ++j) {
|
|
||||||
const hook = modules[j][hooks[i]];
|
|
||||||
if (hook !== undefined) {
|
|
||||||
(cbs[hooks[i]] as Array<any>).push(hook);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyNodeAt(elm: Element) {
|
|
||||||
const id = elm.id ? "#" + elm.id : "";
|
|
||||||
const c = elm.className ? "." + elm.className.split(" ").join(".") : "";
|
|
||||||
return vnode(api.tagName(elm).toLowerCase() + id + c, {}, [], undefined, elm);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createRmCb(childElm: Node, listeners: number) {
|
|
||||||
return function rmCb() {
|
|
||||||
if (--listeners === 0) {
|
|
||||||
const parent = api.parentNode(childElm);
|
|
||||||
api.removeChild(parent, childElm);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createElm(vnode: VNode, insertedVnodeQueue: VNodeQueue): Node {
|
|
||||||
let i: any,
|
|
||||||
iLen: number,
|
|
||||||
data = vnode.data;
|
|
||||||
if (data !== undefined) {
|
|
||||||
if (isDef((i = data.hook)) && isDef((i = i.init))) {
|
|
||||||
i(vnode);
|
|
||||||
data = vnode.data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let children = vnode.children,
|
|
||||||
sel = vnode.sel;
|
|
||||||
if (sel === "!") {
|
|
||||||
if (isUndef(vnode.text)) {
|
|
||||||
vnode.text = "";
|
|
||||||
}
|
|
||||||
vnode.elm = api.createComment(vnode.text as string);
|
|
||||||
} else if (sel !== undefined) {
|
|
||||||
const elm = (vnode.elm =
|
|
||||||
isDef(data) && isDef((i = (data as VNodeData).ns))
|
|
||||||
? api.createElementNS(i, sel)
|
|
||||||
: api.createElement(sel));
|
|
||||||
for (i = 0, iLen = cbs.create.length; i < iLen; ++i) cbs.create[i](emptyNode, vnode);
|
|
||||||
if (array(children)) {
|
|
||||||
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
|
||||||
const ch = children[i];
|
|
||||||
if (ch != null) {
|
|
||||||
api.appendChild(elm, createElm(ch as VNode, insertedVnodeQueue));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (primitive(vnode.text)) {
|
|
||||||
api.appendChild(elm, api.createTextNode(vnode.text));
|
|
||||||
}
|
|
||||||
i = (vnode.data as VNodeData).hook; // Reuse variable
|
|
||||||
if (isDef(i)) {
|
|
||||||
if (i.create) i.create(emptyNode, vnode);
|
|
||||||
if (i.insert) insertedVnodeQueue.push(vnode);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
vnode.elm = api.createTextNode(vnode.text as string);
|
|
||||||
}
|
|
||||||
return vnode.elm;
|
|
||||||
}
|
|
||||||
|
|
||||||
function addVnodes(
|
|
||||||
parentElm: Node,
|
|
||||||
before: Node | null,
|
|
||||||
vnodes: Array<VNode>,
|
|
||||||
startIdx: number,
|
|
||||||
endIdx: number,
|
|
||||||
insertedVnodeQueue: VNodeQueue
|
|
||||||
) {
|
|
||||||
for (; startIdx <= endIdx; ++startIdx) {
|
|
||||||
const ch = vnodes[startIdx];
|
|
||||||
if (ch != null) {
|
|
||||||
api.insertBefore(parentElm, createElm(ch, insertedVnodeQueue), before);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function invokeDestroyHook(vnode: VNode) {
|
|
||||||
let i: any,
|
|
||||||
iLen: number,
|
|
||||||
j: number,
|
|
||||||
jLen: number,
|
|
||||||
data = vnode.data;
|
|
||||||
if (data !== undefined) {
|
|
||||||
if (isDef((i = data.hook)) && isDef((i = i.destroy))) i(vnode);
|
|
||||||
for (i = 0, iLen = cbs.destroy.length; i < iLen; ++i) cbs.destroy[i](vnode);
|
|
||||||
if (vnode.children !== undefined) {
|
|
||||||
for (j = 0, jLen = vnode.children.length; j < jLen; ++j) {
|
|
||||||
i = vnode.children[j];
|
|
||||||
if (i != null && typeof i !== "string") {
|
|
||||||
invokeDestroyHook(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeVnodes(
|
|
||||||
parentElm: Node,
|
|
||||||
vnodes: Array<VNode>,
|
|
||||||
startIdx: number,
|
|
||||||
endIdx: number
|
|
||||||
): void {
|
|
||||||
for (; startIdx <= endIdx; ++startIdx) {
|
|
||||||
let i: any,
|
|
||||||
iLen: number,
|
|
||||||
listeners: number,
|
|
||||||
rm: () => void,
|
|
||||||
ch = vnodes[startIdx];
|
|
||||||
if (ch != null) {
|
|
||||||
if (isDef(ch.sel)) {
|
|
||||||
invokeDestroyHook(ch);
|
|
||||||
listeners = cbs.remove.length + 1;
|
|
||||||
rm = createRmCb(ch.elm as Node, listeners);
|
|
||||||
for (i = 0, iLen = cbs.remove.length; i < iLen; ++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
|
|
||||||
api.removeChild(parentElm, ch.elm as Node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateChildren(
|
|
||||||
parentElm: Node,
|
|
||||||
oldCh: Array<VNode>,
|
|
||||||
newCh: Array<VNode>,
|
|
||||||
insertedVnodeQueue: VNodeQueue
|
|
||||||
) {
|
|
||||||
let oldStartIdx = 0,
|
|
||||||
newStartIdx = 0;
|
|
||||||
let oldEndIdx = oldCh.length - 1;
|
|
||||||
let oldStartVnode = oldCh[0];
|
|
||||||
let oldEndVnode = oldCh[oldEndIdx];
|
|
||||||
let newEndIdx = newCh.length - 1;
|
|
||||||
let newStartVnode = newCh[0];
|
|
||||||
let newEndVnode = newCh[newEndIdx];
|
|
||||||
let oldKeyToIdx: any;
|
|
||||||
let idxInOld: number;
|
|
||||||
let elmToMove: VNode;
|
|
||||||
let before: any;
|
|
||||||
|
|
||||||
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
|
|
||||||
if (oldStartVnode == null) {
|
|
||||||
oldStartVnode = oldCh[++oldStartIdx]; // Vnode might have been moved left
|
|
||||||
} else if (oldEndVnode == null) {
|
|
||||||
oldEndVnode = oldCh[--oldEndIdx];
|
|
||||||
} else if (newStartVnode == null) {
|
|
||||||
newStartVnode = newCh[++newStartIdx];
|
|
||||||
} else if (newEndVnode == null) {
|
|
||||||
newEndVnode = newCh[--newEndIdx];
|
|
||||||
} 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);
|
|
||||||
api.insertBefore(
|
|
||||||
parentElm,
|
|
||||||
oldStartVnode.elm as Node,
|
|
||||||
api.nextSibling(oldEndVnode.elm as Node)
|
|
||||||
);
|
|
||||||
oldStartVnode = oldCh[++oldStartIdx];
|
|
||||||
newEndVnode = newCh[--newEndIdx];
|
|
||||||
} else if (sameVnode(oldEndVnode, newStartVnode)) {
|
|
||||||
// Vnode moved left
|
|
||||||
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
|
|
||||||
api.insertBefore(parentElm, oldEndVnode.elm as Node, oldStartVnode.elm as Node);
|
|
||||||
oldEndVnode = oldCh[--oldEndIdx];
|
|
||||||
newStartVnode = newCh[++newStartIdx];
|
|
||||||
} else {
|
|
||||||
if (oldKeyToIdx === undefined) {
|
|
||||||
oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
|
|
||||||
}
|
|
||||||
idxInOld = oldKeyToIdx[newStartVnode.key as string];
|
|
||||||
if (isUndef(idxInOld)) {
|
|
||||||
// New element
|
|
||||||
api.insertBefore(
|
|
||||||
parentElm,
|
|
||||||
createElm(newStartVnode, insertedVnodeQueue),
|
|
||||||
oldStartVnode.elm as Node
|
|
||||||
);
|
|
||||||
newStartVnode = newCh[++newStartIdx];
|
|
||||||
} else {
|
|
||||||
elmToMove = oldCh[idxInOld];
|
|
||||||
if (elmToMove.sel !== newStartVnode.sel) {
|
|
||||||
api.insertBefore(
|
|
||||||
parentElm,
|
|
||||||
createElm(newStartVnode, insertedVnodeQueue),
|
|
||||||
oldStartVnode.elm as Node
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
|
|
||||||
oldCh[idxInOld] = undefined as any;
|
|
||||||
api.insertBefore(parentElm, elmToMove.elm as Node, oldStartVnode.elm as Node);
|
|
||||||
}
|
|
||||||
newStartVnode = newCh[++newStartIdx];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
|
|
||||||
if (oldStartIdx > oldEndIdx) {
|
|
||||||
before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
|
|
||||||
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
|
|
||||||
} else {
|
|
||||||
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchVnode(oldVnode: VNode, vnode: VNode, insertedVnodeQueue: VNodeQueue) {
|
|
||||||
let i: any, iLen: number, hook: any;
|
|
||||||
if (isDef((i = vnode.data)) && isDef((hook = i.hook)) && isDef((i = hook.prepatch))) {
|
|
||||||
i(oldVnode, vnode);
|
|
||||||
}
|
|
||||||
const elm = (vnode.elm = oldVnode.elm as Node);
|
|
||||||
let oldCh = oldVnode.children;
|
|
||||||
let ch = vnode.children;
|
|
||||||
if (oldVnode === vnode) return;
|
|
||||||
if (vnode.data !== undefined) {
|
|
||||||
for (i = 0, iLen = cbs.update.length; i < iLen; ++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 as Array<VNode>, ch as Array<VNode>, insertedVnodeQueue);
|
|
||||||
} else if (isDef(ch)) {
|
|
||||||
if (isDef(oldVnode.text)) api.setTextContent(elm, "");
|
|
||||||
addVnodes(
|
|
||||||
elm,
|
|
||||||
null,
|
|
||||||
ch as Array<VNode>,
|
|
||||||
0,
|
|
||||||
(ch as Array<VNode>).length - 1,
|
|
||||||
insertedVnodeQueue
|
|
||||||
);
|
|
||||||
} else if (isDef(oldCh)) {
|
|
||||||
removeVnodes(elm, oldCh as Array<VNode>, 0, (oldCh as Array<VNode>).length - 1);
|
|
||||||
} else if (isDef(oldVnode.text)) {
|
|
||||||
api.setTextContent(elm, "");
|
|
||||||
}
|
|
||||||
} else if (oldVnode.text !== vnode.text) {
|
|
||||||
if (isDef(oldCh)) {
|
|
||||||
removeVnodes(elm, oldCh as Array<VNode>, 0, (oldCh as Array<VNode>).length - 1);
|
|
||||||
}
|
|
||||||
api.setTextContent(elm, vnode.text as string);
|
|
||||||
}
|
|
||||||
if (isDef(hook) && isDef((i = hook.postpatch))) {
|
|
||||||
i(oldVnode, vnode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return function patch(oldVnode: VNode | Element, vnode: VNode): VNode {
|
|
||||||
let i: number, iLen: number, elm: Node, parent: Node;
|
|
||||||
const insertedVnodeQueue: VNodeQueue = [];
|
|
||||||
for (i = 0, iLen = cbs.pre.length; i < iLen; ++i) cbs.pre[i]();
|
|
||||||
|
|
||||||
if (!isVnode(oldVnode)) {
|
|
||||||
oldVnode = emptyNodeAt(oldVnode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sameVnode(oldVnode, vnode)) {
|
|
||||||
patchVnode(oldVnode, vnode, insertedVnodeQueue);
|
|
||||||
} else {
|
|
||||||
elm = oldVnode.elm as Node;
|
|
||||||
parent = api.parentNode(elm);
|
|
||||||
|
|
||||||
createElm(vnode, insertedVnodeQueue);
|
|
||||||
|
|
||||||
if (parent !== null) {
|
|
||||||
api.insertBefore(parent, vnode.elm as Node, api.nextSibling(elm));
|
|
||||||
removeVnodes(parent, [oldVnode], 0, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (i = 0, iLen = insertedVnodeQueue.length; i < iLen; ++i) {
|
|
||||||
(((insertedVnodeQueue[i].data as VNodeData).hook as Hooks).insert as any)(
|
|
||||||
insertedVnodeQueue[i]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (i = 0, iLen = cbs.post.length; i < iLen; ++i) cbs.post[i]();
|
|
||||||
return vnode;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// is.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
const array = Array.isArray;
|
|
||||||
function primitive(s: any): s is string | number {
|
|
||||||
return typeof s === "string" || typeof s === "number";
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// htmldomapi.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const htmlDomApi = {
|
|
||||||
createElement,
|
|
||||||
createElementNS,
|
|
||||||
createTextNode,
|
|
||||||
createComment,
|
|
||||||
insertBefore,
|
|
||||||
removeChild,
|
|
||||||
appendChild,
|
|
||||||
parentNode,
|
|
||||||
nextSibling,
|
|
||||||
tagName,
|
|
||||||
setTextContent
|
|
||||||
} as DOMAPI;
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// hooks.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
type PreHook = () => any;
|
|
||||||
type InitHook = (vNode: VNode) => any;
|
|
||||||
type CreateHook = (emptyVNode: VNode, vNode: VNode) => any;
|
|
||||||
type InsertHook = (vNode: VNode) => any;
|
|
||||||
type PrePatchHook = (oldVNode: VNode, vNode: VNode) => any;
|
|
||||||
type UpdateHook = (oldVNode: VNode, vNode: VNode) => any;
|
|
||||||
type PostPatchHook = (oldVNode: VNode, vNode: VNode) => any;
|
|
||||||
type DestroyHook = (vNode: VNode) => any;
|
|
||||||
type RemoveHook = (vNode: VNode, removeCallback: () => void) => any;
|
|
||||||
type PostHook = () => any;
|
|
||||||
|
|
||||||
interface Hooks {
|
|
||||||
pre?: PreHook;
|
|
||||||
init?: InitHook;
|
|
||||||
create?: CreateHook;
|
|
||||||
insert?: InsertHook;
|
|
||||||
prepatch?: PrePatchHook;
|
|
||||||
update?: UpdateHook;
|
|
||||||
postpatch?: PostPatchHook;
|
|
||||||
destroy?: DestroyHook;
|
|
||||||
remove?: RemoveHook;
|
|
||||||
post?: PostHook;
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// h.ts
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
type VNodes = Array<VNode>;
|
|
||||||
type VNodeChildElement = VNode | string | number | undefined | null;
|
|
||||||
type ArrayOrElement<T> = T | T[];
|
|
||||||
type VNodeChildren = ArrayOrElement<VNodeChildElement>;
|
|
||||||
|
|
||||||
export function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
|
|
||||||
if (sel === "dummy") {
|
|
||||||
// we do not need to add the namespace on dummy elements, they come from a
|
|
||||||
// subcomponent, which will handle the namespace itself
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
data.ns = "http://www.w3.org/2000/svg";
|
|
||||||
if (sel !== "foreignObject" && children !== undefined) {
|
|
||||||
for (let i = 0, iLen = children.length; i < iLen; ++i) {
|
|
||||||
const child = children[i];
|
|
||||||
let childData = child.data;
|
|
||||||
if (childData !== undefined) {
|
|
||||||
addNS(childData, (child as VNode).children as VNodes, child.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,
|
|
||||||
iLen: number;
|
|
||||||
if (c !== undefined) {
|
|
||||||
data = b;
|
|
||||||
if (array(c)) {
|
|
||||||
children = c;
|
|
||||||
} else if (primitive(c)) {
|
|
||||||
text = c;
|
|
||||||
} else if (c && c.sel) {
|
|
||||||
children = [c];
|
|
||||||
}
|
|
||||||
} else if (b !== undefined) {
|
|
||||||
if (array(b)) {
|
|
||||||
children = b;
|
|
||||||
} else if (primitive(b)) {
|
|
||||||
text = b;
|
|
||||||
} else if (b && b.sel) {
|
|
||||||
children = [b];
|
|
||||||
} else {
|
|
||||||
data = b;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (children !== undefined) {
|
|
||||||
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
|
||||||
if (primitive(children[i]))
|
|
||||||
children[i] = vnode(undefined, undefined, undefined, children[i], undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return vnode(sel, data, children, text, undefined);
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
|
||||||
|
|
||||||
exports[`animations t-transition combined with component 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let QWeb = this.constructor;
|
|
||||||
let parent = context;
|
|
||||||
let owner = context;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('div', p1, c1);
|
|
||||||
//COMPONENT
|
|
||||||
let templateId3 = \`__4__\`;
|
|
||||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
|
||||||
let props3 = {};
|
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
|
||||||
w3.destroy();
|
|
||||||
w3 = false;
|
|
||||||
}
|
|
||||||
if (w3) {
|
|
||||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
|
||||||
let pvnode = w3.__owl__.pvnode;
|
|
||||||
c1.push(pvnode);
|
|
||||||
} else {
|
|
||||||
let componentKey3 = \`Child\`;
|
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
|
||||||
w3 = new W3(parent, props3);
|
|
||||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
|
||||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
|
||||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
|
||||||
w3.destroy();
|
|
||||||
};
|
|
||||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
|
||||||
const fiber = w3.__owl__.currentFiber;
|
|
||||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
|
||||||
c1.push(pvnode);
|
|
||||||
w3.__owl__.pvnode = pvnode;
|
|
||||||
}
|
|
||||||
sibling = w3.__owl__.currentFiber || sibling;
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
exports[`animations t-transition combined with t-component and t-if 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let QWeb = this.constructor;
|
|
||||||
let parent = context;
|
|
||||||
let owner = context;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('div', p1, c1);
|
|
||||||
if (context['state'].display) {
|
|
||||||
//COMPONENT
|
|
||||||
let templateId3 = \`__4__\`;
|
|
||||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
|
||||||
let props3 = {};
|
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
|
||||||
w3.destroy();
|
|
||||||
w3 = false;
|
|
||||||
}
|
|
||||||
if (w3) {
|
|
||||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
|
||||||
let pvnode = w3.__owl__.pvnode;
|
|
||||||
c1.push(pvnode);
|
|
||||||
} else {
|
|
||||||
let componentKey3 = \`Child\`;
|
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
|
||||||
w3 = new W3(parent, props3);
|
|
||||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
|
||||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
|
||||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
|
||||||
w3.destroy();
|
|
||||||
};
|
|
||||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
|
||||||
const fiber = w3.__owl__.currentFiber;
|
|
||||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
|
||||||
c1.push(pvnode);
|
|
||||||
w3.__owl__.pvnode = pvnode;
|
|
||||||
}
|
|
||||||
sibling = w3.__owl__.currentFiber || sibling;
|
|
||||||
}
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
exports[`animations t-transition with no delay/duration 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('span', p1, c1);
|
|
||||||
p1.hook = {
|
|
||||||
insert: vn => {
|
|
||||||
utils.transitionInsert(vn, 'jupiler');
|
|
||||||
},
|
|
||||||
remove: (vn, rm) => {
|
|
||||||
utils.transitionRemove(vn, 'jupiler', rm);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
c1.push({text: \`blue\`});
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
exports[`animations t-transition, on a simple node (insert) 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('span', p1, c1);
|
|
||||||
p1.hook = {
|
|
||||||
insert: vn => {
|
|
||||||
utils.transitionInsert(vn, 'chimay');
|
|
||||||
},
|
|
||||||
remove: (vn, rm) => {
|
|
||||||
utils.transitionRemove(vn, 'chimay', rm);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
c1.push({text: \`blue\`});
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
|
||||||
|
|
||||||
exports[`various scenarios scenarios with async store updates and some components events 1`] = `"<div><button>Do stuff</button><div><span>Attachment 100</span><span>Name: text.txt</span></div></div>"`;
|
|
||||||
|
|
||||||
exports[`various scenarios scenarios with async store updates and some components events 2`] = `"<div><button>Do stuff</button></div>"`;
|
|
||||||
@@ -1,379 +0,0 @@
|
|||||||
import { Component, Env } from "../src/component/component";
|
|
||||||
import { QWeb } from "../src/qweb/index";
|
|
||||||
import { useState, useRef } from "../src/hooks";
|
|
||||||
import {
|
|
||||||
makeDeferred,
|
|
||||||
makeTestFixture,
|
|
||||||
makeTestEnv,
|
|
||||||
patchNextFrame,
|
|
||||||
renderToDOM,
|
|
||||||
unpatchNextFrame
|
|
||||||
} from "./helpers";
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Setup and helpers
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
// We create before each test:
|
|
||||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
|
||||||
// manipulations. Note that it is removed after each test.
|
|
||||||
// - qweb: a new QWeb instance
|
|
||||||
// - env: a WEnv, necessary to create new components
|
|
||||||
// - cssEl: a stylesheet injected into the dom
|
|
||||||
|
|
||||||
let fixture: HTMLElement;
|
|
||||||
let qweb: QWeb;
|
|
||||||
let env: Env;
|
|
||||||
let cssEl: HTMLElement;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
fixture = makeTestFixture();
|
|
||||||
env = makeTestEnv();
|
|
||||||
qweb = new QWeb();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
fixture.remove();
|
|
||||||
});
|
|
||||||
|
|
||||||
class Widget extends Component<any, any> {}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Tests
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
describe("animations", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
cssEl = document.createElement("style");
|
|
||||||
let css = `
|
|
||||||
.chimay-enter-active, .chimay-leave-active {
|
|
||||||
transition-property: opacity;
|
|
||||||
transition-duration: 0.1s;
|
|
||||||
}
|
|
||||||
.chimay-enter, .chimay-leave-to {
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
cssEl.textContent = css.trim();
|
|
||||||
document.head.appendChild(cssEl);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
document.head.removeChild(cssEl);
|
|
||||||
unpatchNextFrame();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition, on a simple node (insert)", async () => {
|
|
||||||
expect.assertions(5);
|
|
||||||
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
cb();
|
|
||||||
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
|
||||||
|
|
||||||
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
node.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(node.className).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition with no delay/duration", async () => {
|
|
||||||
expect.assertions(4);
|
|
||||||
qweb.addTemplate("test", `<span t-transition="jupiler">blue</span>`);
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
|
||||||
cb();
|
|
||||||
expect(node.className).toBe("");
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
|
||||||
await def;
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition on a conditional node", async () => {
|
|
||||||
expect.assertions(7);
|
|
||||||
|
|
||||||
env.qweb.addTemplate(
|
|
||||||
"TestWidget",
|
|
||||||
`<div><span t-if="!state.hide" t-transition="chimay">blue</span></div>`
|
|
||||||
);
|
|
||||||
class TestWidget extends Widget {
|
|
||||||
state = useState({ hide: false });
|
|
||||||
}
|
|
||||||
const widget = new TestWidget(env);
|
|
||||||
|
|
||||||
// insert widget into the DOM
|
|
||||||
let def = makeDeferred();
|
|
||||||
var spanNode;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
cb();
|
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await widget.mount(fixture);
|
|
||||||
spanNode = widget.el!.children[0];
|
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(spanNode.className).toBe("");
|
|
||||||
|
|
||||||
// remove span from the DOM
|
|
||||||
def = makeDeferred();
|
|
||||||
widget.state.hide = true;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(spanNode.className).toBe("chimay-leave chimay-leave-active");
|
|
||||||
cb();
|
|
||||||
expect(spanNode.className).toBe("chimay-leave-active chimay-leave-to");
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(spanNode.className).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition combined with t-ref", async () => {
|
|
||||||
expect.assertions(5);
|
|
||||||
|
|
||||||
env.qweb.addTemplate(
|
|
||||||
"TestWidget",
|
|
||||||
`<div><span t-ref="span" t-transition="chimay">blue</span></div>`
|
|
||||||
);
|
|
||||||
class TestWidget extends Widget {
|
|
||||||
state = useState({ hide: false });
|
|
||||||
span = useRef("span");
|
|
||||||
}
|
|
||||||
const widget = new TestWidget(env);
|
|
||||||
|
|
||||||
// insert widget into the DOM
|
|
||||||
let def = makeDeferred();
|
|
||||||
var spanNode;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
cb();
|
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await widget.mount(fixture);
|
|
||||||
spanNode = widget.el!.children[0];
|
|
||||||
expect(widget.span.el).toBe(spanNode);
|
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(spanNode.className).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition combined with component", async () => {
|
|
||||||
expect.assertions(5);
|
|
||||||
|
|
||||||
env.qweb.addTemplate("Parent", `<div><Child t-transition="chimay"/></div>`);
|
|
||||||
env.qweb.addTemplate("Child", `<span>blue</span>`);
|
|
||||||
class Child extends Widget {}
|
|
||||||
class Parent extends Widget {
|
|
||||||
static components = { Child: Child };
|
|
||||||
}
|
|
||||||
const widget = new Parent(env);
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
var spanNode;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
|
||||||
);
|
|
||||||
cb();
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter-active chimay-enter-to">blue</span></div>'
|
|
||||||
);
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await widget.mount(fixture);
|
|
||||||
spanNode = widget.el!.children[0];
|
|
||||||
|
|
||||||
expect(env.qweb.templates.Parent.fn.toString()).toMatchSnapshot();
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
|
||||||
);
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition combined with t-component and t-if", async () => {
|
|
||||||
expect.assertions(8);
|
|
||||||
|
|
||||||
env.qweb.addTemplate(
|
|
||||||
"Parent",
|
|
||||||
`<div><t t-if="state.display" t-component="Child" t-transition="chimay"/></div>`
|
|
||||||
);
|
|
||||||
env.qweb.addTemplate("Child", `<span>blue</span>`);
|
|
||||||
class Child extends Widget {}
|
|
||||||
class Parent extends Widget {
|
|
||||||
static components = { Child: Child };
|
|
||||||
state = useState({ display: true });
|
|
||||||
}
|
|
||||||
const widget = new Parent(env);
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
var spanNode;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
|
||||||
);
|
|
||||||
cb();
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter-active chimay-enter-to">blue</span></div>'
|
|
||||||
);
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await widget.mount(fixture);
|
|
||||||
spanNode = widget.el!.children[0];
|
|
||||||
|
|
||||||
expect(env.qweb.templates.Parent.fn.toString()).toMatchSnapshot();
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
|
||||||
);
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
|
||||||
|
|
||||||
// remove span from the DOM
|
|
||||||
def = makeDeferred();
|
|
||||||
widget.state.display = false;
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__4__">blue</span></div>'
|
|
||||||
);
|
|
||||||
cb();
|
|
||||||
expect(fixture.innerHTML).toBe(
|
|
||||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__4__">blue</span></div>'
|
|
||||||
);
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe("<div></div>");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition, remove and re-add before transitionend", async () => {
|
|
||||||
expect.assertions(11);
|
|
||||||
|
|
||||||
env.qweb.addTemplates(
|
|
||||||
`<templates>
|
|
||||||
<div t-name="Parent">
|
|
||||||
<button t-on-click="toggle">Toggle</button>
|
|
||||||
<span t-if="state.flag" t-transition="chimay">blue</span>
|
|
||||||
</div>
|
|
||||||
</templates>`
|
|
||||||
);
|
|
||||||
class Parent extends Widget {
|
|
||||||
state = useState({ flag: false });
|
|
||||||
|
|
||||||
toggle() {
|
|
||||||
this.state.flag = !this.state.flag;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const widget = new Parent(env);
|
|
||||||
await widget.mount(fixture);
|
|
||||||
let button = widget.el!.querySelector("button");
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
let phase = "enter";
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
let spans = fixture.querySelectorAll("span");
|
|
||||||
expect(spans.length).toBe(1);
|
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
|
||||||
cb();
|
|
||||||
expect(spans[0].className).toBe(`chimay-${phase}-active chimay-${phase}-to`);
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
|
|
||||||
// click display the span
|
|
||||||
button!.click();
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
|
||||||
|
|
||||||
// click to remove the span, and click again to re-add it before transitionend
|
|
||||||
def = makeDeferred();
|
|
||||||
phase = "leave";
|
|
||||||
button!.click();
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
def = makeDeferred();
|
|
||||||
phase = "enter";
|
|
||||||
button!.click();
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("t-transition combined with t-component, remove and re-add before transitionend", async () => {
|
|
||||||
expect.assertions(11);
|
|
||||||
|
|
||||||
env.qweb.addTemplates(
|
|
||||||
`<templates>
|
|
||||||
<div t-name="Parent">
|
|
||||||
<button t-on-click="toggle">Toggle</button>
|
|
||||||
<t t-if="state.flag" t-component="Child" t-transition="chimay"/>
|
|
||||||
</div>
|
|
||||||
<span t-name="Child">blue</span>
|
|
||||||
</templates>`
|
|
||||||
);
|
|
||||||
class Child extends Widget {}
|
|
||||||
class Parent extends Widget {
|
|
||||||
static components = { Child };
|
|
||||||
state = useState({ flag: false });
|
|
||||||
|
|
||||||
toggle() {
|
|
||||||
this.state.flag = !this.state.flag;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const widget = new Parent(env);
|
|
||||||
await widget.mount(fixture);
|
|
||||||
let button = widget.el!.querySelector("button");
|
|
||||||
|
|
||||||
let def = makeDeferred();
|
|
||||||
let phase = "enter";
|
|
||||||
patchNextFrame(cb => {
|
|
||||||
let spans = fixture.querySelectorAll("span");
|
|
||||||
expect(spans.length).toBe(1);
|
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
|
||||||
cb();
|
|
||||||
expect(spans[0].className).toBe(`chimay-${phase}-active chimay-${phase}-to`);
|
|
||||||
def.resolve();
|
|
||||||
});
|
|
||||||
|
|
||||||
// click display the span
|
|
||||||
button!.click();
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
|
||||||
|
|
||||||
// click to remove the span, and click again to re-add it before transitionend
|
|
||||||
def = makeDeferred();
|
|
||||||
phase = "leave";
|
|
||||||
button!.click();
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
def = makeDeferred();
|
|
||||||
phase = "enter";
|
|
||||||
button!.click();
|
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
|
||||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { createBlock, mount, patch, remove, text } from "../../src/blockdom";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("adding/patching blocks", () => {
|
||||||
|
test("simple block", async () => {
|
||||||
|
const block = createBlock("<div>foo</div>");
|
||||||
|
const tree = block();
|
||||||
|
expect(tree.el).toBe(undefined);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(tree.el).not.toBe(undefined);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>foo</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with dynamic content", async () => {
|
||||||
|
const block = createBlock("<div><p><block-text-0/></p></div>");
|
||||||
|
const tree = block(["foo"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>foo</p></div>");
|
||||||
|
patch(tree, block(["bar"]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>bar</p></div>");
|
||||||
|
|
||||||
|
patch(tree, block(["foo"]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>foo</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with 2 dynamic text nodes", async () => {
|
||||||
|
const block = createBlock("<div><p><block-text-0/></p><span><block-text-1/></span></div>");
|
||||||
|
const tree = block(["foo", "bar"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>foo</p><span>bar</span></div>");
|
||||||
|
patch(tree, block(["appa", "yip yip"]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>appa</p><span>yip yip</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with multiple references", async () => {
|
||||||
|
const block1 = createBlock(
|
||||||
|
"<div><block-text-0/><p><block-text-1/><block-text-2/></p><block-text-3/></div>"
|
||||||
|
);
|
||||||
|
const tree = block1(["1", "2", "3", "4"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>1<p>23</p>4</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falsy values in block nodes", () => {
|
||||||
|
const cases = [
|
||||||
|
[false, "false"],
|
||||||
|
[undefined, ""],
|
||||||
|
[null, ""],
|
||||||
|
[0, "0"],
|
||||||
|
["", ""],
|
||||||
|
];
|
||||||
|
const block = createBlock("<p><block-text-0/></p>");
|
||||||
|
|
||||||
|
for (let [value, result] of cases) {
|
||||||
|
const fixture = makeTestFixture();
|
||||||
|
mount(block([value as any]), fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<p>${result}</p>`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sub blocks", () => {
|
||||||
|
test("block with subblock (only child)", async () => {
|
||||||
|
const block1 = createBlock("<div><block-child-0/></div>");
|
||||||
|
const block2 = createBlock("<p>yip yip</p>");
|
||||||
|
const tree = block1([], [block2()]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>yip yip</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with subblock (first child with sibling)", async () => {
|
||||||
|
const block1 = createBlock("<div><block-child-0/><span>something</span></div>");
|
||||||
|
const block2 = createBlock("<p>yip yip</p>");
|
||||||
|
const tree = block1([], [block2()]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>yip yip</p><span>something</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with subblock (last child with sibling)", async () => {
|
||||||
|
const block1 = createBlock("<div><span>something</span><block-child-0/></div>");
|
||||||
|
const block2 = createBlock("<p>yip yip</p>");
|
||||||
|
const tree = block1([], [block2()]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>something</span><p>yip yip</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with 2 subblocks", async () => {
|
||||||
|
const block1 = createBlock("<div><block-child-0/><block-child-1/></div>");
|
||||||
|
const block2 = createBlock("<p>yip yip</p>");
|
||||||
|
const tree = block1([], [block2(), text("appa")]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>yip yip</p>appa</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with subblock with siblings", async () => {
|
||||||
|
const block1 = createBlock("<div><p>1</p><block-child-0/><p>2</p></div>");
|
||||||
|
const block2 = createBlock("<p>yip yip</p>");
|
||||||
|
|
||||||
|
const tree = block1([], [block2()]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>1</p><p>yip yip</p><p>2</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with text, subblock and siblings", async () => {
|
||||||
|
let block1 = createBlock(`<div><p>before<block-child-0/>after</p><block-child-1/></div>`);
|
||||||
|
|
||||||
|
let tree = block1([], [text("water"), text("fire")]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>beforewaterafter</p>fire</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with conditional child", async () => {
|
||||||
|
const block1 = createBlock("<div><p><block-child-0/></p></div>");
|
||||||
|
const block2 = createBlock("<span>foo</span>");
|
||||||
|
|
||||||
|
const tree = block1();
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p></p></div>");
|
||||||
|
|
||||||
|
patch(tree, block1([], [block2()]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p><span>foo</span></p></div>");
|
||||||
|
|
||||||
|
patch(tree, block1());
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p></p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with subblock with dynamic content", async () => {
|
||||||
|
const block1 = createBlock("<div><block-child-0/></div>");
|
||||||
|
const block2 = createBlock("<p><block-text-0/></p>");
|
||||||
|
const tree = block1([], [block2(["yip yip"])]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>yip yip</p></div>");
|
||||||
|
|
||||||
|
patch(tree, block1([], [block2(["foo"])]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>foo</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block with dynamic content and subblock", async () => {
|
||||||
|
const block1 = createBlock("<div><block-child-0/><p><block-text-0/></p></div>");
|
||||||
|
const block2 = createBlock("<p>sub block</p>");
|
||||||
|
const tree = block1(["yip yip"], [block2()]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>sub block</p><p>yip yip</p></div>");
|
||||||
|
|
||||||
|
patch(tree, block1(["foo"], [block2()]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>sub block</p><p>foo</p></div>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("remove elem blocks", () => {
|
||||||
|
test("elem block can be removed", async () => {
|
||||||
|
const block = createBlock("<div>foo</div>");
|
||||||
|
const tree = block();
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>foo</div>");
|
||||||
|
remove(tree);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
expect(fixture.childNodes.length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("misc", () => {
|
||||||
|
test("constructed block as correct number of refs", () => {
|
||||||
|
const block = createBlock("<p><p><block-text-0/></p><block-text-1/></p>");
|
||||||
|
const tree = block(["a", "b"]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p><p>a</p>b</p>");
|
||||||
|
expect((tree as any).refs.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block vnode can be used as text", () => {
|
||||||
|
const block = createBlock("<p>a</p>");
|
||||||
|
mount(text(block() as any), fixture);
|
||||||
|
expect(fixture.textContent).toBe("<p>a</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block vnode can be used to represent a <tr>", () => {
|
||||||
|
const block = createBlock("<tr><td>tomato</td></tr>");
|
||||||
|
const tree = block();
|
||||||
|
const fixture = document.createElement("table");
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.outerHTML).toBe("<table><tr><td>tomato</td></tr></table>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("block vnode with <tr> can be used as text ", () => {
|
||||||
|
const block = createBlock("<tr><td>tomato</td></tr>");
|
||||||
|
mount(text(block() as any), fixture);
|
||||||
|
expect(fixture.textContent).toBe("<tr><td>tomato</td></tr>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("call toString for function/objects if used as inline text in block", () => {
|
||||||
|
const block = createBlock("<p><block-text-0/><block-text-1/></p>");
|
||||||
|
const f = () => 3;
|
||||||
|
const g = () => 4;
|
||||||
|
g.toString = () => "tostring";
|
||||||
|
mount(block([f, g]), fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>() => 3tostring</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
// test.skip("reusing a block skips patching process", async () => {
|
||||||
|
// const block = createBlock('<div><block-text-0/></div>');
|
||||||
|
// const foo = block(["foo"]);
|
||||||
|
// const bar = block(["bar"]);
|
||||||
|
// let fooCounter = 0;
|
||||||
|
// let barCounter = 0;
|
||||||
|
// let fooValue = "foo";
|
||||||
|
// let barValue = "bar";
|
||||||
|
// Object.defineProperty(foo.data, 0, {
|
||||||
|
// get() {
|
||||||
|
// fooCounter++;
|
||||||
|
// return fooValue;
|
||||||
|
// },
|
||||||
|
// });
|
||||||
|
// Object.defineProperty(bar.data, 0, {
|
||||||
|
// get() {
|
||||||
|
// barCounter++;
|
||||||
|
// return barValue;
|
||||||
|
// },
|
||||||
|
// set(val) {
|
||||||
|
// barValue = val;
|
||||||
|
// },
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const bdom = multi([foo, bar]);
|
||||||
|
// mount(bdom, fixture);
|
||||||
|
// expect(fooCounter).toBe(1);
|
||||||
|
// expect(barCounter).toBe(1);
|
||||||
|
// expect(fixture.innerHTML).toBe("<div>foo</div><div>bar</div>");
|
||||||
|
|
||||||
|
// patch(bdom, multi([foo, block(["otherbar"])]));
|
||||||
|
// expect(fixture.innerHTML).toBe("foootherbar");
|
||||||
|
// expect(fooCounter).toBe(1);
|
||||||
|
// expect(barCounter).toBe(2);
|
||||||
|
// });
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { mount, patch, createBlock } from "../../src/blockdom";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple attribute", async () => {
|
||||||
|
const block = createBlock('<div block-attribute-0="hello"></div>');
|
||||||
|
const tree = block(["world"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div hello="world"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block(["owl"]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div hello="owl"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dynamic attribute (pair)", async () => {
|
||||||
|
const block = createBlock('<div block-attributes="0"></div>');
|
||||||
|
const tree = block([["hello", "world"]]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div hello="world"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block([["ola", "mundo"]]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div ola="mundo"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dynamic attribute (object)", async () => {
|
||||||
|
const block = createBlock('<div block-attributes="0"></div>');
|
||||||
|
const tree = block([{ hello: "world" }]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div hello="world"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block([{ ola: "mundo" }]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div ola="mundo"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("class attribute", async () => {
|
||||||
|
const block = createBlock('<div block-attribute-0="class"></div>');
|
||||||
|
const tree = block(["fire"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="fire"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block(["water"]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="water"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block([""]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class=""></div>`);
|
||||||
|
|
||||||
|
patch(tree, block([0]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="0"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("class attribute with undefined value", async () => {
|
||||||
|
const block = createBlock('<div block-attribute-0="class"></div>');
|
||||||
|
const tree = block([undefined]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("class attribute (with a preexisting value", async () => {
|
||||||
|
const block = createBlock('<div class="tomato" block-attribute-0="class"></div>');
|
||||||
|
const tree = block(["potato"]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="tomato potato"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block(["squash"]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="tomato squash"></div>`);
|
||||||
|
|
||||||
|
patch(tree, block([""]));
|
||||||
|
expect(fixture.innerHTML).toBe(`<div class="tomato"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("properties", () => {
|
||||||
|
test("input with value attribute", () => {
|
||||||
|
// render input with initial value
|
||||||
|
const block = createBlock(`<input block-attribute-0="value"/>`);
|
||||||
|
|
||||||
|
const tree = block(["zucchini"]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
// const bnode1 = renderToBdom(template, { v: "zucchini" });
|
||||||
|
// const fixture = makeTestFixture();
|
||||||
|
// mount(bnode1, fixture);
|
||||||
|
const input = fixture.querySelector("input")!;
|
||||||
|
expect(input.value).toBe("zucchini");
|
||||||
|
|
||||||
|
// change value manually in input, to simulate user input
|
||||||
|
input.value = "tomato";
|
||||||
|
expect(input.value).toBe("tomato");
|
||||||
|
|
||||||
|
// rerender with a different value, and patch actual dom, to check that
|
||||||
|
// input value was properly reset by owl
|
||||||
|
patch(tree, block(["potato"]));
|
||||||
|
expect(input.value).toBe("potato");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("input type=checkbox with checked attribute", () => {
|
||||||
|
// render input with initial value
|
||||||
|
const block = createBlock(`<input type="checkbox" block-attribute-0="checked"/>`);
|
||||||
|
|
||||||
|
const tree = block([true]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<input type="checkbox">`);
|
||||||
|
const input = fixture.querySelector("input")!;
|
||||||
|
expect(input.checked).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { mount, createBlock, multi, config, patch } from "../../src/blockdom";
|
||||||
|
// import { defaultHandler, setupMainHandler } from "../../src/bdom/block";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let initialHandler = config.mainEventHandler;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
config.mainEventHandler = initialHandler;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple event handling, with function", async () => {
|
||||||
|
const block = createBlock('<div block-handler-0="click"></div>');
|
||||||
|
let n = 0;
|
||||||
|
const tree = block([() => n++]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
expect(fixture.firstChild).toBeInstanceOf(HTMLDivElement);
|
||||||
|
expect(n).toBe(0);
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
expect(n).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple event handling, with function and argument", async () => {
|
||||||
|
const block = createBlock('<div block-handler-0="click"></div>');
|
||||||
|
let n = 0;
|
||||||
|
const onClick = (arg: number) => {
|
||||||
|
n += arg;
|
||||||
|
};
|
||||||
|
const tree = block([[onClick, 3]]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
expect(fixture.firstChild).toBeInstanceOf(HTMLDivElement);
|
||||||
|
expect(n).toBe(0);
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
expect(n).toBe(3);
|
||||||
|
|
||||||
|
patch(tree, block([[onClick, 5]]));
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
expect(n).toBe(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple event handling ", async () => {
|
||||||
|
config.mainEventHandler = (data, ev) => {
|
||||||
|
if (typeof data === "function") {
|
||||||
|
data();
|
||||||
|
} else {
|
||||||
|
const [owner, method] = data;
|
||||||
|
owner[method]();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const block = createBlock('<div block-handler-0="click"></div>');
|
||||||
|
let n = 0;
|
||||||
|
const obj = { f: () => n++ };
|
||||||
|
const tree = block([[obj, "f"]]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
expect(fixture.firstChild).toBeInstanceOf(HTMLDivElement);
|
||||||
|
expect(n).toBe(0);
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
expect(n).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can bind two handlers on same node", async () => {
|
||||||
|
const block = createBlock('<div block-handler-0="click" block-handler-1="dblclick"></div>');
|
||||||
|
let steps: string[] = [];
|
||||||
|
let handleClick = () => steps.push("click");
|
||||||
|
let handleDblClick = () => steps.push("dblclick");
|
||||||
|
const tree = block([handleClick, handleDblClick]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
(fixture.firstChild as HTMLDivElement).dispatchEvent(new Event("dblclick", { bubbles: true }));
|
||||||
|
expect(steps).toEqual(["click", "dblclick"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("two same block nodes with different handlers", async () => {
|
||||||
|
const block = createBlock('<div block-handler-0="click"></div>');
|
||||||
|
let steps: string[] = [];
|
||||||
|
let handler1 = () => steps.push("1");
|
||||||
|
let handler2 = () => steps.push("2");
|
||||||
|
const tree = multi([block([handler1]), block([handler2])]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><div></div>");
|
||||||
|
|
||||||
|
(fixture.firstChild as HTMLDivElement).click();
|
||||||
|
(fixture.firstChild!.nextSibling as HTMLDivElement).click();
|
||||||
|
expect(steps).toEqual(["1", "2"]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { createBlock, mount, patch, remove } from "../../src/blockdom";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple callback ref", async () => {
|
||||||
|
const block = createBlock('<div><span block-ref="0">hey</span></div>');
|
||||||
|
let arg: any = undefined;
|
||||||
|
let n = 0;
|
||||||
|
const refFn = (_arg: any) => {
|
||||||
|
n++;
|
||||||
|
arg = _arg;
|
||||||
|
};
|
||||||
|
|
||||||
|
const tree = block([refFn]);
|
||||||
|
|
||||||
|
expect(arg).toBeUndefined();
|
||||||
|
expect(n).toBe(0);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>hey</span></div>");
|
||||||
|
expect(n).toBe(1);
|
||||||
|
|
||||||
|
expect(arg).toBeInstanceOf(HTMLSpanElement);
|
||||||
|
expect(arg!.innerHTML).toBe("hey");
|
||||||
|
|
||||||
|
patch(tree, block([refFn]));
|
||||||
|
expect(n).toBe(1);
|
||||||
|
|
||||||
|
remove(tree);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
expect(arg).toBeNull();
|
||||||
|
expect(n).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("is in dom when callback is called", async () => {
|
||||||
|
expect.assertions(1);
|
||||||
|
const block = createBlock('<div><span block-ref="0">hey</span></div>');
|
||||||
|
const refFn = (span: any) => {
|
||||||
|
expect(document.body.contains(span)).toBeTruthy();
|
||||||
|
};
|
||||||
|
|
||||||
|
const tree = block([refFn]);
|
||||||
|
|
||||||
|
mount(tree, fixture);
|
||||||
|
});
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
let lastFixture: any = null;
|
||||||
|
|
||||||
|
export function makeTestFixture() {
|
||||||
|
let fixture = document.createElement("div");
|
||||||
|
document.body.appendChild(fixture);
|
||||||
|
if (lastFixture) {
|
||||||
|
lastFixture.remove();
|
||||||
|
}
|
||||||
|
lastFixture = fixture;
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { html, mount, patch, text } from "../../src/blockdom";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("html block", () => {
|
||||||
|
test("can be mounted and patched", async () => {
|
||||||
|
const tree = html("<span>1</span><span>2</span>");
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<span>1</span><span>2</span>");
|
||||||
|
|
||||||
|
patch(tree, html("<div>coucou</div>"));
|
||||||
|
expect(fixture.innerHTML).toBe("<div>coucou</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("html vnode can be used as text", () => {
|
||||||
|
mount(text(html("<p>a</p>") as any), fixture);
|
||||||
|
expect(fixture.textContent).toBe("<p>a</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("html vnode can represent <tr>", () => {
|
||||||
|
const fixture = document.createElement("table");
|
||||||
|
// const block = createBlock('<table><block-child-0/></table>');
|
||||||
|
// const tree = block([], [html(`<tr><td>tomato</td></tr>`)]);
|
||||||
|
const tree = html(`<tr><td>tomato</td></tr>`);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<tr><td>tomato</td></tr>");
|
||||||
|
|
||||||
|
patch(tree, html(`<tr><td>potato</td></tr>`));
|
||||||
|
expect(fixture.innerHTML).toBe("<tr><td>potato</td></tr>");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
import { list, mount, multi, patch, text, createBlock, VNode, withKey } from "../../src/blockdom";
|
||||||
|
import { makeTestFixture } from "./helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
function kText(str: string, key: any): VNode {
|
||||||
|
return withKey(text(str), key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function n(n: number) {
|
||||||
|
return kText(String(n), n);
|
||||||
|
}
|
||||||
|
|
||||||
|
const span = createBlock("<span><block-text-0/></span>");
|
||||||
|
const p = createBlock("<p><block-text-0/></p>");
|
||||||
|
|
||||||
|
function kSpan(str: string, key: any): VNode {
|
||||||
|
return withKey(span([str]), key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function kPair(n: number): VNode {
|
||||||
|
const bnodes = [p([String(n)]), p([String(n)])];
|
||||||
|
return withKey(multi(bnodes), n);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("list node: misc", () => {
|
||||||
|
test("list node", async () => {
|
||||||
|
const bnodes = [1, 2, 3].map((key) => kText(`text${key}`, key));
|
||||||
|
|
||||||
|
const tree = list(bnodes);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("text1text2text3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("list vnode can be used as text", () => {
|
||||||
|
mount(text(list([text("a"), text("b")]) as any), fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("ab");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a list block can be removed and leaves nothing", async () => {
|
||||||
|
const bnodes = [
|
||||||
|
{ id: 1, name: "sheep" },
|
||||||
|
{ id: 2, name: "cow" },
|
||||||
|
].map((elem) => kText(elem.name, elem.id));
|
||||||
|
|
||||||
|
const tree = list(bnodes);
|
||||||
|
expect(fixture.childNodes.length).toBe(0);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.childNodes.length).toBe(3);
|
||||||
|
expect(fixture.innerHTML).toBe("sheepcow");
|
||||||
|
|
||||||
|
tree.remove();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
expect(fixture.childNodes.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("patching a list block inside an elem block", async () => {
|
||||||
|
const block = createBlock("<div><block-child-0/></div>");
|
||||||
|
const tree = block();
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([1, 2, 3].map(n))]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([])]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([1, 2, 3].map(n))]));
|
||||||
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("list of lists", async () => {
|
||||||
|
const tree = list([
|
||||||
|
withKey(list([kText("a1", "1"), kText("a2", "2")]), "a"),
|
||||||
|
withKey(list([kText("b1", "1"), kText("b2", "2")]), "b"),
|
||||||
|
]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("a1a2b1b2");
|
||||||
|
|
||||||
|
patch(
|
||||||
|
tree,
|
||||||
|
list([
|
||||||
|
withKey(list([kText("b1", "1"), kText("b2", "2")]), "b"),
|
||||||
|
withKey(list([kText("a1", "1"), kText("a2", "2")]), "a"),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("b1b2a1a2");
|
||||||
|
|
||||||
|
patch(
|
||||||
|
tree,
|
||||||
|
list([
|
||||||
|
withKey(list([kText("a2", "2"), kText("a1", "1")]), "a"),
|
||||||
|
withKey(list([kText("b2", "2"), kText("b1", "1")]), "b"),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("a2a1b2b1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("adding/removing elements", () => {
|
||||||
|
test("removing elements", () => {
|
||||||
|
const tree = list([kText("a", "a")]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("a");
|
||||||
|
|
||||||
|
patch(tree, list([]));
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("removing 1 elements from 2", () => {
|
||||||
|
const tree = list([kText("a", "a"), kText("b", "b")]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("ab");
|
||||||
|
|
||||||
|
patch(tree, list([kText("a", "a")]));
|
||||||
|
expect(fixture.innerHTML).toBe("a");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("removing elements", () => {
|
||||||
|
const tree = list([kSpan("a", "a")]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<span>a</span>");
|
||||||
|
|
||||||
|
patch(tree, list([]));
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("removing elements, variation", () => {
|
||||||
|
const f = (i: number) => {
|
||||||
|
const b = multi([span([`a${i}`]), span([`b${i}`])]);
|
||||||
|
b.key = i;
|
||||||
|
return b;
|
||||||
|
};
|
||||||
|
const tree = list([f(1), f(2)]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<span>a1</span><span>b1</span><span>a2</span><span>b2</span>");
|
||||||
|
|
||||||
|
patch(tree, list([]));
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adding one element at the end", () => {
|
||||||
|
const tree = list([n(1), n(2)]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12");
|
||||||
|
|
||||||
|
patch(tree, list([n(1), n(2), n(3)]));
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adding one element at the end", () => {
|
||||||
|
const tree = list([n(1)]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("1");
|
||||||
|
|
||||||
|
patch(tree, list([n(1), n(2), n(3)]));
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prepend elements: 4,5 => 1,2,3,4,5", () => {
|
||||||
|
const tree = list([n(4), n(5)]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("45");
|
||||||
|
|
||||||
|
patch(tree, list([n(1), n(2), n(3), n(4), n(5)]));
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prepend elements: 4,5 => 1,2,3,4,5 (with multi)", () => {
|
||||||
|
const tree = list([kPair(4), kPair(5)]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>4</p><p>4</p><p>5</p><p>5</p>");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3, 4, 5].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("add element in middle: 1,2,4,5 => 1,2,3,4,5", () => {
|
||||||
|
const tree = list([1, 2, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("1245");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3, 4, 5].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("add element in middle: 1,2,4,5 => 1,2,3,4,5 (multi)", () => {
|
||||||
|
const tree = list([1, 2, 4, 5].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3, 4, 5].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("add element at beginning and end: 2,3,4 => 1,2,3,4,5", () => {
|
||||||
|
const tree = list([2, 3, 4].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("234");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3, 4, 5].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("add element at beginning and end: 2,3,4 => 1,2,3,4,5 (multi)", () => {
|
||||||
|
const tree = list([2, 3, 4].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p>");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3, 4, 5].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adds children: [] => [1,2,3]", () => {
|
||||||
|
const tree = list([].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adds children: [] => [1,2,3] (multi)", () => {
|
||||||
|
const tree = list([].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adds children: [] => [1,2,3] (inside elem)", () => {
|
||||||
|
const block = createBlock("<p><block-child-0/></p>");
|
||||||
|
const tree = block([], []);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p></p>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([1, 2, 3].map(n))]));
|
||||||
|
expect(fixture.innerHTML).toBe("<p>123</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adds children: [] => [1,2,3] (inside elem, multi)", () => {
|
||||||
|
const block = createBlock("<p><block-child-0/></p>");
|
||||||
|
const tree = block([], []);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p></p>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([1, 2, 3].map(kPair))]));
|
||||||
|
expect(fixture.innerHTML).toBe("<p><p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p></p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children: [1,2,3] => []", () => {
|
||||||
|
const tree = list([1, 2, 3].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
|
||||||
|
patch(tree, list([].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children: [1,2,3] => [] (multi)", () => {
|
||||||
|
const tree = list([1, 2, 3].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>");
|
||||||
|
|
||||||
|
patch(tree, list([].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children: [1,2,3] => [] (inside elem)", () => {
|
||||||
|
const block = createBlock("<p><block-child-0/></p>");
|
||||||
|
const tree = block([], [list([1, 2, 3].map(n))]);
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>123</p>");
|
||||||
|
|
||||||
|
patch(tree, block([], [list([])]));
|
||||||
|
expect(fixture.innerHTML).toBe("<p></p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children from the beginning: [1,2,3,4,5] => [3,4,5]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
|
||||||
|
patch(tree, list([3, 4, 5].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("345");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children from the beginning: [1,2,3,4,5] => [3,4,5] (multi)", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
patch(tree, list([3, 4, 5].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe("<p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children from the end: [1,2,3,4,5] => [1,2,3]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 3].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remove children from the middle: [1,2,3,4,5] => [1,2,4,5]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
|
||||||
|
patch(tree, list([1, 2, 4, 5].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("1245");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("element reordering", () => {
|
||||||
|
test("move element forward: [1,2,3,4] => [2,3,1,4]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("1234");
|
||||||
|
|
||||||
|
patch(tree, list([2, 3, 1, 4].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("2314");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move element forward: [1,2,3,4] => [2,3,1,4] (multi)", () => {
|
||||||
|
const tree = list([1, 2, 3, 4].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p>"
|
||||||
|
);
|
||||||
|
patch(tree, list([2, 3, 1, 4].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>2</p><p>2</p><p>3</p><p>3</p><p>1</p><p>1</p><p>4</p><p>4</p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move element to end: [1,2,3] => [2,3,1]", () => {
|
||||||
|
const tree = list([1, 2, 3].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("123");
|
||||||
|
|
||||||
|
patch(tree, list([2, 3, 1].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("231");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move element to end: [1,2,3] => [2,3,1] (multi)", () => {
|
||||||
|
const tree = list([1, 2, 3].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>");
|
||||||
|
|
||||||
|
patch(tree, list([2, 3, 1].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe("<p>2</p><p>2</p><p>3</p><p>3</p><p>1</p><p>1</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move element backward: [1,2,3,4] => [1,4,2,3]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("1234");
|
||||||
|
|
||||||
|
patch(tree, list([1, 4, 2, 3].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("1423");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("swaps first and last: [1,2,3,4] => [4,3,2,1]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("1234");
|
||||||
|
|
||||||
|
patch(tree, list([4, 3, 2, 1].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("4321");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("miscellaneous operations", () => {
|
||||||
|
test("move to left and replace: [1,2,3,4,5] => [4,1,2,3,6]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12345");
|
||||||
|
|
||||||
|
patch(tree, list([4, 1, 2, 3, 6].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("41236");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move to left and replace: [1,2,3,4,5] => [4,1,2,3,6] (multi)", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5].map(kPair));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
patch(tree, list([4, 1, 2, 3, 6].map(kPair)));
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p>4</p><p>4</p><p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>6</p><p>6</p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("move to left and leave hole: [1,4,5] => [4,6]", () => {
|
||||||
|
const tree = list([1, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("145");
|
||||||
|
|
||||||
|
patch(tree, list([4, 6].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("46");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("[2,4,5] => [4,5,3]", () => {
|
||||||
|
const tree = list([2, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("245");
|
||||||
|
|
||||||
|
patch(tree, list([4, 5, 3].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("453");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reverse elements [1,2,3,4,5,6,7,8] => [8,7,6,5,4,3,2,1]", () => {
|
||||||
|
const tree = list([1, 2, 3, 4, 5, 6, 7, 8].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("12345678");
|
||||||
|
|
||||||
|
patch(tree, list([8, 7, 6, 5, 4, 3, 2, 1].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("87654321");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("some permutation [0,1,2,3,4,5] => [4,3,2,1,5,0]", () => {
|
||||||
|
const tree = list([0, 1, 2, 3, 4, 5].map(n));
|
||||||
|
mount(tree, fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("012345");
|
||||||
|
|
||||||
|
patch(tree, list([4, 3, 2, 1, 5, 0].map(n)));
|
||||||
|
expect(fixture.innerHTML).toBe("432150");
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user