mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
255 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| de805d0d80 | |||
| 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 | |||
| b0e2ef82f7 | |||
| c9c2b3fa6d | |||
| 62608cbb0d | |||
| 3035a9f009 | |||
| c2adb429bd | |||
| da9dda5eca | |||
| 5614c85b04 | |||
| 5d57a7bf13 | |||
| 4ebe419c56 | |||
| 9779cd196c | |||
| 9cee12d7b4 | |||
| 2c563ee380 | |||
| 2aa705f5c8 | |||
| 5911c8e3f6 | |||
| 2279dafbec | |||
| f07ec21a07 | |||
| b5b6b7342e | |||
| 97b914b9cd | |||
| 9dfcfda365 | |||
| e026f537ae | |||
| f0b5a55ad1 | |||
| 690d8edf67 | |||
| 3c38bbc076 | |||
| 9c5cad15c1 | |||
| 2bed1cfbd1 | |||
| caa9ac5cb2 | |||
| 67349eb0f0 | |||
| 1ca401811f | |||
| 2beb12678e | |||
| 0ea1091692 | |||
| 71827c3ba8 | |||
| c2f42d3b82 | |||
| a3317ab997 | |||
| 403935a41e | |||
| 39af9ec938 | |||
| 13128ed425 | |||
| be556a970e | |||
| da6c24bbca | |||
| f6d6da8393 | |||
| 918945c11e | |||
| 29c2c5b9c9 | |||
| 1bb4577ec1 | |||
| 0aeebd7b6e | |||
| 4bc49e7241 | |||
| 2b5783d9bd | |||
| 1f40f113aa |
+4
-1
@@ -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
|
||||||
@@ -23,4 +24,6 @@ package-lock.json
|
|||||||
node_modules
|
node_modules
|
||||||
|
|
||||||
# Extras temp file
|
# Extras temp file
|
||||||
/tools/owl.js
|
/tools/owl.js
|
||||||
|
|
||||||
|
release-notes.md
|
||||||
@@ -1,44 +1,56 @@
|
|||||||
<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_
|
_Class based components with hooks, reactive state and concurrent mode_
|
||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
The Odoo Web Library (OWL) is a smallish (~17kb 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 stable. Possible future changes are explained in the
|
||||||
|
[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
|
||||||
import { Component, QWeb, useState } from "owl";
|
const { Component, useState } = owl;
|
||||||
import { xml } from "owl/tags";
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<button t-on-click="increment">
|
<button t-on-click="state.value++">
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
Click Me! [<t t-esc="state.value"/>]
|
||||||
</button>`;
|
</button>`;
|
||||||
|
|
||||||
state = useState({ value: 0 });
|
state = useState({ value: 0 });
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class App extends Component {
|
class App extends Component {
|
||||||
@@ -51,12 +63,12 @@ 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);
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the counter component is made reactive with the [`useState`](doc/hooks.md#usestate)
|
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
|
||||||
hook. Also, all examples here uses the `xml` helper to define inline templates.
|
Also, all examples here uses the [`xml` helper](doc/reference/tags.md#xml-tag) to define inline templates.
|
||||||
But this is not mandatory, many applications will load templates separately.
|
But this is not mandatory, many applications will load templates separately.
|
||||||
|
|
||||||
More interesting examples can be found on the
|
More interesting examples can be found on the
|
||||||
@@ -80,10 +92,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
|
||||||
|
|
||||||
@@ -91,172 +102,27 @@ 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)
|
||||||
- [Component](doc/component.md)
|
- [How to start an Owl project](doc/learning/quick_start.md)
|
||||||
- [Hooks](doc/hooks.md)
|
- [QWeb templating language](doc/reference/qweb_templating_language.md)
|
||||||
|
- [Component](doc/reference/component.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.23.0.js](https://github.com/odoo/owl/releases/download/v0.23.0/owl.js)
|
- [owl-1.0.11.js](https://github.com/odoo/owl/releases/download/v1.0.11/owl.js)
|
||||||
- [owl-0.23.0.min.js](https://github.com/odoo/owl/releases/download/v0.23.0/owl.min.js)
|
- [owl-1.0.11.min.js](https://github.com/odoo/owl/releases/download/v1.0.11/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. 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++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**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/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
@@ -3,7 +3,7 @@
|
|||||||
OWL, React and Vue have the same main feature: they allow developers to build
|
OWL, React and Vue have the same main feature: they allow developers to build
|
||||||
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
||||||
|
|
||||||
In this page, we try to highlight some of these differences. Obviously, some
|
In this page, we try to highlight some of these differences. Obviously, a lot of
|
||||||
effort was done to be fair. However, if you disagree with some of the points
|
effort was done to be fair. However, if you disagree with some of the points
|
||||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@ discussed, feel free to open an issue/submit a PR to correct this text.
|
|||||||
- [Asynchronous rendering](#asynchronous-rendering)
|
- [Asynchronous rendering](#asynchronous-rendering)
|
||||||
- [Reactiveness](#reactiveness)
|
- [Reactiveness](#reactiveness)
|
||||||
- [State Management](#state-management)
|
- [State Management](#state-management)
|
||||||
|
- [Hooks](#hooks)
|
||||||
|
|
||||||
## Size
|
## Size
|
||||||
|
|
||||||
@@ -24,11 +25,16 @@ than React and Vue. Also, jQuery is not the same kind of framework, but it is in
|
|||||||
|
|
||||||
| Framework | Size (minified, gzipped) |
|
| Framework | Size (minified, gzipped) |
|
||||||
| ------------------------ | ------------------------ |
|
| ------------------------ | ------------------------ |
|
||||||
| OWL | 16kb |
|
| OWL | 18kb |
|
||||||
| Vue + VueX | 30kb |
|
| Vue + VueX | 30kb |
|
||||||
|
| Vue + VueX + Vue Router | 39kb |
|
||||||
| React + ReactDOM + Redux | 40kb |
|
| React + ReactDOM + Redux | 40kb |
|
||||||
| jQuery | 30kb |
|
| jQuery | 30kb |
|
||||||
|
|
||||||
|
Note that those comparisons are not entirely fair, because we do not compare
|
||||||
|
the same exact set of features. For example, VueX and Vue Router support more
|
||||||
|
advanced use cases.
|
||||||
|
|
||||||
## Class Based
|
## Class Based
|
||||||
|
|
||||||
Both React and Vue moved away from defining components with classes. They prefer
|
Both React and Vue moved away from defining components with classes. They prefer
|
||||||
@@ -40,6 +46,17 @@ contrast, Owl has only one mechanism: class-based components. We believe that Ow
|
|||||||
components are fast enough for all our usecases, and making it as simple as
|
components are fast enough for all our usecases, and making it as simple as
|
||||||
possible for developers is more valuable (for us).
|
possible for developers is more valuable (for us).
|
||||||
|
|
||||||
|
Also, functions or class based components are more than just syntax. Functions
|
||||||
|
comes with a mindset of composition and class are about inheritance. Clearly,
|
||||||
|
both of these are important mechanisms for reusing code. Also, one does not
|
||||||
|
exclude the other.
|
||||||
|
|
||||||
|
It certainly looks like the world of UI frameworks is moving toward composition,
|
||||||
|
for many very good reasons. Owl is still good at composition (for example,
|
||||||
|
Owl supports slots, which is the primary mechanism to make generic reusable
|
||||||
|
components). But it can also use inheritance (and this is very important since
|
||||||
|
templates can also be inherited with `xpaths` transformations).
|
||||||
|
|
||||||
## Tooling/Build step
|
## Tooling/Build step
|
||||||
|
|
||||||
OWL is designed to be easy to use in a standalone way. For various reasons,
|
OWL is designed to be easy to use in a standalone way. For various reasons,
|
||||||
@@ -50,13 +67,23 @@ be used by simply adding a script tag to a page.
|
|||||||
<script src="owl.min.js" />
|
<script src="owl.min.js" />
|
||||||
```
|
```
|
||||||
|
|
||||||
In comparison, React encourages using JSX,
|
In comparison, React encourages using JSX, which necessitate a build step, and
|
||||||
which necessitate a build step, and most Vue applications uses single file
|
most Vue applications uses single file components, which also necessitate a build step.
|
||||||
components, which also necessitate a build step.
|
|
||||||
|
|
||||||
On the flipside, external tooling may make it harder to use in some case, but it
|
On the flipside, external tooling may make it harder to use in some case, but it
|
||||||
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
||||||
|
|
||||||
|
Note that since Owl is not dependant on any external tool nor libraries, it is
|
||||||
|
very easy to integrate into any build toolchain. Also, since we cannot rely on
|
||||||
|
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.
|
||||||
|
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
|
||||||
|
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
|
||||||
|
plugins to have autocompletion inside the template.
|
||||||
|
|
||||||
## Templating
|
## Templating
|
||||||
|
|
||||||
OWL uses its own QWeb engine, which compiles templates on the
|
OWL uses its own QWeb engine, which compiles templates on the
|
||||||
@@ -79,7 +106,8 @@ into javascript functions. Note that Vue has a separate build which includes the
|
|||||||
template compiler.
|
template compiler.
|
||||||
|
|
||||||
In contrast, most React applications do not use a templating language, but write
|
In contrast, most React applications do not use a templating language, but write
|
||||||
some JSX code, which is precompiled into plain JavaScript by a build step.
|
some JSX code, which is precompiled into plain JavaScript by a build step. This
|
||||||
|
example is done with the (kind of outdated) React class system:
|
||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
class Clock extends React.Component {
|
class Clock extends React.Component {
|
||||||
@@ -98,6 +126,20 @@ This has the advantage of having the full power of Javascript, but is less
|
|||||||
structured than a template language. Note that the tooling is quite impressive:
|
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
|
||||||
|
[`xml`](../reference/tags.md#xml-tag) tag helper:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class Clock extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<h1>Hello, world!</h1>
|
||||||
|
<h2>It is {props.date.toLocaleTimeString()}.</h2>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Asynchronous Rendering
|
## Asynchronous Rendering
|
||||||
|
|
||||||
This is actually a big difference between OWL and React/Vue: components in OWL
|
This is actually a big difference between OWL and React/Vue: components in OWL
|
||||||
@@ -127,12 +169,14 @@ This may be dangerous (to stop the rendering waiting for the network), but it is
|
|||||||
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
||||||
|
|
||||||
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
||||||
more convoluted.
|
more convoluted. For example, in Vue, you need to use a dynamic import keyword
|
||||||
|
that needs to be transpiled at build time in order for the component to be loaded
|
||||||
|
asynchronously (see [the documentation](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components)).
|
||||||
|
|
||||||
## Reactiveness
|
## Reactiveness
|
||||||
|
|
||||||
React has a simple model: whenever the state changes, it is
|
React has a simple model: whenever the state changes, it is
|
||||||
replaced with a new state (via the setState method). Then, the DOM is patched.
|
replaced with a new state (via the `setState` method). Then, the DOM is patched.
|
||||||
This is simple, efficient, and a little bit awkward to write.
|
This is simple, efficient, and a little bit awkward to write.
|
||||||
|
|
||||||
Vue is a little bit different: it replace magically the properties in the state
|
Vue is a little bit different: it replace magically the properties in the state
|
||||||
@@ -207,30 +251,95 @@ 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, by inheriting the `ConnectedComponent` class.
|
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 += val;
|
state.counter.value += val;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
counter: 0
|
counter: { value: 0 },
|
||||||
};
|
};
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
|
|
||||||
class Counter extends owl.ConnectedComponent {
|
class Counter extends Component {
|
||||||
static mapStoreToProps(state) {
|
static template = xml`
|
||||||
return {
|
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||||
value: state.counter
|
Click Me! [<t t-esc="counter.value"/>]
|
||||||
};
|
</button>`;
|
||||||
}
|
counter = useStore((state) => state.counter);
|
||||||
increment() {
|
dispatch = useDispatch();
|
||||||
this.env.store.dispatch("increment");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const counter = new Counter({ store, qweb });
|
Counter.env.store = store;
|
||||||
|
const counter = new Counter();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Hooks
|
||||||
|
|
||||||
|
[Hooks](https://reactjs.org/docs/hooks-intro.html#motivation) recently took over
|
||||||
|
the React world. They solve a lot of seemingly unconnected problems: attach
|
||||||
|
reusable behavior to a component, in a composable way, extract stateful logic
|
||||||
|
from a component or reuse stateful logic between component, without changing your
|
||||||
|
component hierarchy.
|
||||||
|
|
||||||
|
Here is an example of the React `useState` hook:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import React, { useState } from "react";
|
||||||
|
|
||||||
|
function Example() {
|
||||||
|
// Declare a new state variable, which we'll call "count"
|
||||||
|
const [count, setCount] = useState(0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>You clicked {count} times</p>
|
||||||
|
<button onClick={() => setCount(count + 1)}>Click me</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Because of the way React designed the hooks API, they only work for functional
|
||||||
|
components. But in that case, they really are powerful. Every major React library
|
||||||
|
is in the process of redesigning their API with hooks (for example,
|
||||||
|
[Redux](https://react-redux.js.org/next/api/hooks)).
|
||||||
|
|
||||||
|
Vue 2 does not have hooks, but the Vue project is working on its next version,
|
||||||
|
which will feature its new [composition API](https://vue-composition-api-rfc.netlify.com/).
|
||||||
|
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
|
||||||
|
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,
|
||||||
|
the `useState` hook is named after React, but its API is closer to the `reactive`
|
||||||
|
Vue hook.
|
||||||
|
|
||||||
|
Here is what the `Counter` example above look like in Owl:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { Component, Owl } from "owl";
|
||||||
|
import { xml } from "owl/tags";
|
||||||
|
|
||||||
|
class Example extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<p>You clicked {count.value} times</p>
|
||||||
|
<button t-on-click="increment">Click me</button>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
count = useState({ value: 0 });
|
||||||
|
|
||||||
|
increment() {
|
||||||
|
this.state.value++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Since the Owl framework had hooks from early in its life, its main APIs
|
||||||
|
are designed to be interacted with hooks from the start. For example, the
|
||||||
|
`Context` and `Store` abstractions.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 🦉 Rendering Pipeline 🦉
|
||||||
|
|
||||||
|
We explain here how Owl is designed, from the perspective of its rendering
|
||||||
|
pipeline.
|
||||||
|
|
||||||
|
Warning: these notes are technical by nature, and intended for people working
|
||||||
|
on Owl (or interested in understanding its design).
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
A rendering occurs in two phases:
|
||||||
|
|
||||||
|
- virtual rendering: this generates the virtual dom in memory, asynchronously
|
||||||
|
- patch: applies a virtual tree to the screen (synchronously)
|
||||||
|
|
||||||
|
There are several classes involved in a rendering:
|
||||||
|
|
||||||
|
- components
|
||||||
|
- a scheduler
|
||||||
|
- fibers: small objects containing some metadata, associated with a rendering of
|
||||||
|
a specific component
|
||||||
|
|
||||||
|
Components are organized in a dynamic component tree, visible in the user
|
||||||
|
interface. Whenever a rendering is initiated in a component `C`:
|
||||||
|
|
||||||
|
- a fiber is created on `C` with the rendering props information
|
||||||
|
- the virtual rendering phase starts on C (will asynchronously render all the
|
||||||
|
child components)
|
||||||
|
- the fiber is added to the scheduler, which will poll continuously, every
|
||||||
|
animation frame, if the fiber is done
|
||||||
|
- once it is done, the scheduler will call the task callback, which will apply
|
||||||
|
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,20 +0,0 @@
|
|||||||
# 🦉 Observer 🦉
|
|
||||||
|
|
||||||
Owl need to be able to react to state changes. For example, whenever the state
|
|
||||||
of a component is changed, we need to rerender it. To help with that, we have
|
|
||||||
an Observer class. Its job is to observe some object state, and react to any
|
|
||||||
change. To do that, it recursively replace all keys of the observed state by
|
|
||||||
getters and setters.
|
|
||||||
|
|
||||||
For example, this code will display `update` in the console:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const observer = new owl.Observer();
|
|
||||||
observer.notifyCB = () => console.log("update");
|
|
||||||
const obj = observer.observe({ a: { b: 1 } });
|
|
||||||
|
|
||||||
obj.a.b = 2;
|
|
||||||
```
|
|
||||||
|
|
||||||
The observer is implemented with the native `Proxy` object. Note that this
|
|
||||||
means that it will not work on older browsers.
|
|
||||||
@@ -1,103 +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 context 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";
|
|
||||||
constructor() {
|
|
||||||
super(...arguments);
|
|
||||||
this.state = useState({ value: 0 });
|
|
||||||
}
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Application initialization
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
async function start() {
|
|
||||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
|
||||||
const env = {
|
|
||||||
qweb: new owl.QWeb(templates)
|
|
||||||
};
|
|
||||||
const counter = new ClickCounter(env);
|
|
||||||
const target = document.getElementById("main");
|
|
||||||
await counter.mount(target);
|
|
||||||
}
|
|
||||||
|
|
||||||
start();
|
|
||||||
```
|
|
||||||
+44
-61
@@ -1,72 +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
|
|
||||||
router
|
|
||||||
Link
|
|
||||||
RouteComponent
|
|
||||||
Router
|
|
||||||
tags
|
|
||||||
xml
|
|
||||||
utils
|
|
||||||
debounce
|
|
||||||
escape
|
|
||||||
loadJS
|
|
||||||
loadTemplates
|
|
||||||
whenReady
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
- [Animations](animations.md)
|
You will find here a complete reference of every feature, class or object
|
||||||
- [Component](component.md)
|
provided by Owl.
|
||||||
- [Context](context.md)
|
|
||||||
- [Event Bus](event_bus.md)
|
|
||||||
- [Hooks](hooks.md)
|
|
||||||
- [Observer](observer.md)
|
|
||||||
- [QWeb](qweb.md)
|
|
||||||
- [Router](router.md)
|
|
||||||
- [Store](store.md)
|
|
||||||
- [Tags](tags.md)
|
|
||||||
- [Utils](utils.md)
|
|
||||||
- [Virtual DOM](vdom.md)
|
|
||||||
|
|
||||||
## Learning Resources
|
- [Animations](reference/animations.md)
|
||||||
|
- [Component](reference/component.md)
|
||||||
|
- [Content](reference/content.md)
|
||||||
|
- [Concurrency Model](reference/concurrency_model.md)
|
||||||
|
- [Configuration](reference/config.md)
|
||||||
|
- [Context](reference/context.md)
|
||||||
|
- [Environment](reference/environment.md)
|
||||||
|
- [Event Bus](reference/event_bus.md)
|
||||||
|
- [Event Handling](reference/event_handling.md)
|
||||||
|
- [Error Handling](reference/error_handling.md)
|
||||||
|
- [Hooks](reference/hooks.md)
|
||||||
|
- [Miscellaneous Components](reference/misc.md)
|
||||||
|
- [Observer](reference/observer.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)
|
||||||
|
- [Store](reference/store.md)
|
||||||
|
- [Slots](reference/slots.md)
|
||||||
|
- [Tags](reference/tags.md)
|
||||||
|
- [Utils](reference/utils.md)
|
||||||
|
|
||||||
- [Quick Start](quick_start.md)
|
## Other Topics
|
||||||
|
|
||||||
## Miscellaneous
|
This section provides miscellaneous document that explains some topics
|
||||||
|
which cannot be considered either a tutorial, or reference documentation.
|
||||||
|
|
||||||
- [Comparison with React/Vue](comparison.md)
|
- [Owl architecture: the Virtual DOM](miscellaneous/vdom.md)
|
||||||
- [Tooling](tooling.md)
|
- [Owl architecture: the rendering pipeline](miscellaneous/rendering.md)
|
||||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
- [Comparison with React/Vue](miscellaneous/comparison.md)
|
||||||
|
- [Why did Odoo built Owl?](miscellaneous/why_owl.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Found an issue in the documentation? A broken link? Some outdated information?
|
||||||
|
Please open an issue or submit a PR!
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ btn {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
will produce a nice flash effect whenever the user click (or activate with the
|
will produce a nice flash effect whenever the user clicks (or activates with the
|
||||||
keyboard) the button.
|
keyboard) the button.
|
||||||
|
|
||||||
## CSS Transitions
|
## CSS Transitions
|
||||||
@@ -47,7 +47,7 @@ the lifetime of a node. Since this is not easy to do by hand, Owl `t-transition`
|
|||||||
directive is there to help.
|
directive is there to help.
|
||||||
|
|
||||||
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
||||||
will happen:
|
sequence of events will happen:
|
||||||
|
|
||||||
At node insertion:
|
At node insertion:
|
||||||
|
|
||||||
@@ -91,6 +91,5 @@ The `t-transition` directive can be applied on a node element or on a component.
|
|||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- more information on animations are available [here](animations.md).
|
Owl does not support more than one transition on a single node, so the
|
||||||
- Owl does not support more than one transition on a single node, so the
|
`t-transition` expression must be a single value (i.e. no space allowed).
|
||||||
`t-transition` expression must be a single value (i.e. no space allowed)
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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,27 @@
|
|||||||
|
# 🦉 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 currently has one key:
|
||||||
|
|
||||||
|
- [`mode`](#mode).
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -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.
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
The `Context` object provides a way to share data between an arbitrary number
|
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,
|
of components. 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
|
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,
|
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.
|
even though some or most of them will not use the information.
|
||||||
@@ -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),
|
|
||||||
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
|
||||||
@@ -56,14 +53,14 @@ fact that we are in a mobile or desktop mode.
|
|||||||
```js
|
```js
|
||||||
class SomeComponent extends Component {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<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,137 @@
|
|||||||
|
# 🦉 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -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)
|
||||||
@@ -35,7 +36,7 @@ Owl hooks serve the same purpose, except that they work for class components
|
|||||||
there seems to be the misconception that hooks are in opposition to class. This
|
there seems to be the misconception that hooks are in opposition to class. This
|
||||||
is clearly not true, as shown by Owl hooks).
|
is clearly not true, as shown by Owl hooks).
|
||||||
|
|
||||||
Hooks works beautifully with Owl components: they solve the problems mentioned
|
Hooks work beautifully with Owl components: they solve the problems mentioned
|
||||||
above, and in particular, they are the perfect way to make your component
|
above, and in particular, they are the perfect way to make your component
|
||||||
reactive.
|
reactive.
|
||||||
|
|
||||||
@@ -127,7 +128,7 @@ class SomeComponent extends Component {
|
|||||||
|
|
||||||
### One rule
|
### One rule
|
||||||
|
|
||||||
There is only one rule: every hook for a component have to be called in the
|
There is only one rule: every hook for a component has to be called in the
|
||||||
constructor (or in class fields):
|
constructor (or in class fields):
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@@ -152,14 +153,20 @@ class SomeComponent extends Component {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Hooks can get a reference to the currently being defined component with the
|
As you can see, the `useState` hook does not need to be given a reference to
|
||||||
`Component.current` static property. This is why they need to be called in the
|
the component. This is possible because there is a way to get a reference to the
|
||||||
constructor.
|
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`
|
||||||
|
|
||||||
The `useState` hook is certainly the most important hooks for Owl components:
|
The `useState` hook is certainly the most important hook for Owl components:
|
||||||
this is what enables component to be reactive, to react to state change.
|
this is what allows a component to be reactive, to react to state change.
|
||||||
|
|
||||||
The `useState` hook has to be given an object or an array, and will return
|
The `useState` hook has to be given an object or an array, and will return
|
||||||
an observed version of it (using a `Proxy`).
|
an observed version of it (using a `Proxy`).
|
||||||
@@ -181,27 +188,30 @@ class Counter extends owl.Component {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
It is important to remember that `useState` only works with objects or arrays. It
|
||||||
|
is necessary, since Owl needs to react to a change in state.
|
||||||
|
|
||||||
### `onMounted`
|
### `onMounted`
|
||||||
|
|
||||||
`onMounted` is not an user hook, but is a building block designed to help make useful
|
`onMounted` is not a user hook, but is a building block designed to help make useful
|
||||||
abstractions. `onMounted` registers a callback, which will be called when the component
|
abstractions. `onMounted` registers a callback, which will be called when the component
|
||||||
is mounted (see example on top of this page).
|
is mounted (see example on top of this page).
|
||||||
|
|
||||||
### `onWillUnmount`
|
### `onWillUnmount`
|
||||||
|
|
||||||
`onWillUnmount` is not an user hook, but is a building block designed to help make useful
|
`onWillUnmount` is not a user hook, but is a building block designed to help make useful
|
||||||
abstractions. `onWillUnmount` registers a callback, which will be called when the component
|
abstractions. `onWillUnmount` registers a callback, which will be called when the component
|
||||||
is unmounted (see example on top of this page).
|
is unmounted (see example on top of this page).
|
||||||
|
|
||||||
### `onWillPatch`
|
### `onWillPatch`
|
||||||
|
|
||||||
`onWillPatch` is not an user hook, but is a building block designed to help make useful
|
`onWillPatch` is not a user hook, but is a building block designed to help make useful
|
||||||
abstractions. `onWillPatch` registers a callback, which will be called just
|
abstractions. `onWillPatch` registers a callback, which will be called just
|
||||||
before the component patched.
|
before the component patched.
|
||||||
|
|
||||||
### `onPatched`
|
### `onPatched`
|
||||||
|
|
||||||
`onPatched` is not an user hook, but is a building block designed to help make useful
|
`onPatched` is not a user hook, but is a building block designed to help make useful
|
||||||
abstractions. `onPatched` registers a callback, which will be called just
|
abstractions. `onPatched` registers a callback, which will be called just
|
||||||
after the component patched.
|
after the component patched.
|
||||||
|
|
||||||
@@ -220,18 +230,18 @@ be ready whenever the component is rendered:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
function useLoader() {
|
function useLoader() {
|
||||||
const component = Component.current;
|
const component = Component.current;
|
||||||
const record = useState({});
|
const record = useState({});
|
||||||
onWillStart(async () => {
|
onWillStart(async () => {
|
||||||
const recordId = component.props.id;
|
const recordId = component.props.id;
|
||||||
Object.assign(record, await fetchSomeRecord(recordId));
|
Object.assign(record, await fetchSomeRecord(recordId));
|
||||||
});
|
});
|
||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that this example does not update the record value whenever props are
|
Note that this example does not update the record value whenever props are
|
||||||
updated. For that situation, we need to use the `onWillUpdateProps` hook.
|
updated. For that situation, we need to use the `onWillUpdateProps` hook.
|
||||||
|
|
||||||
### `onWillUpdateProps`
|
### `onWillUpdateProps`
|
||||||
|
|
||||||
@@ -241,17 +251,17 @@ useful to perform some asynchronous task such as fetching updated data.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
function useLoader() {
|
function useLoader() {
|
||||||
const component = Component.current;
|
const component = Component.current;
|
||||||
const record = useState({});
|
const record = useState({});
|
||||||
|
|
||||||
async function updateRecord(id) {
|
async function updateRecord(id) {
|
||||||
Object.assign(record, await fetchSomeRecord(id));
|
Object.assign(record, await fetchSomeRecord(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
onWillStart(() => updateRecord(component.props.id));
|
onWillStart(() => updateRecord(component.props.id));
|
||||||
onWillUpdateProps(nextProps => updateRecord(nextProps.id));
|
onWillUpdateProps((nextProps) => updateRecord(nextProps.id));
|
||||||
|
|
||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -287,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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -294,18 +305,21 @@ 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
|
||||||
<div t-ref="component_{{someCondition ? '1' : '2'}}"/>
|
<div t-ref="component_{{someCondition ? '1' : '2'}}"/>
|
||||||
```
|
```
|
||||||
|
|
||||||
Here, the references needs to be set like this:
|
Here, the references need to be set like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
this.ref1 = useRef("component_1");
|
this.ref1 = useRef("component_1");
|
||||||
@@ -321,8 +335,8 @@ The environment is sometimes useful to share some common information between
|
|||||||
all components. But sometimes, we want to _scope_ that knowledge to a subtree.
|
all components. But sometimes, we want to _scope_ that knowledge to a subtree.
|
||||||
|
|
||||||
For example, if we have a form view component, maybe we would like to make some
|
For example, if we have a form view component, maybe we would like to make some
|
||||||
`model` object available to all sub component, but not to the whole application.
|
`model` object available to all sub components, but not to the whole application.
|
||||||
This is where the `useSubEnv` hook may be useful: it let a component add some
|
This is where the `useSubEnv` hook may be useful: it lets a component add some
|
||||||
information to the environment in a way that only the component and its children
|
information to the environment in a way that only the component and its children
|
||||||
can access it:
|
can access it:
|
||||||
|
|
||||||
@@ -341,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.
|
||||||
@@ -359,39 +384,39 @@ getters. See the [store documentation](store.md) for more information.
|
|||||||
### Making customized hooks
|
### Making customized hooks
|
||||||
|
|
||||||
Hooks are a wonderful way to organize the code of a complex component by feature
|
Hooks are a wonderful way to organize the code of a complex component by feature
|
||||||
instead of by lifecycle methods. They are like mixins, except that they can be
|
instead of by lifecycle methods. They are like mixins, except that they can be
|
||||||
easily composed together.
|
easily composed together.
|
||||||
|
|
||||||
But, like every good things in life, hooks should be used with moderation. They are
|
But, like every good things in life, hooks should be used with moderation. They are
|
||||||
not the solution to every problem.
|
not the solution to every problem.
|
||||||
|
|
||||||
- they may be overkill: if your component needs to perform some action specific
|
- they may be overkill: if your component needs to perform some action specific
|
||||||
to him (so, the specific code does not need to be shared), there is nothing
|
to itself (so, the specific code does not need to be shared), there is nothing
|
||||||
wrong with a simple class method:
|
wrong with a simple class method:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// maybe overkill
|
// maybe overkill
|
||||||
class A extends Component {
|
class A extends Component {
|
||||||
constructor(...args) {
|
constructor(...args) {
|
||||||
super(...args);
|
super(...args);
|
||||||
useMySpecificHook()
|
useMySpecificHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ok
|
// ok
|
||||||
class B extends Component {
|
class B extends Component {
|
||||||
constructor(...args) {
|
constructor(...args) {
|
||||||
super(...args);
|
super(...args);
|
||||||
this.performSpecificTask()
|
this.performSpecificTask();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the second solution is easier to extend in sub components.
|
Note that the second solution is easier to extend in sub components.
|
||||||
|
|
||||||
- they may be harder to test: if a customized hook inject some external side
|
- they may be harder to test: if a customized hook injects some external side
|
||||||
effect dependency, then it is harder to test without doing some non obvious
|
effect dependency, then it is harder to test without doing some non obvious
|
||||||
manipulation. For example, assume that we want to give a reference to a
|
manipulation. For example, assume that we want to give a reference to a
|
||||||
router in a `useRouter` hook. We could do this:
|
router in a `useRouter` hook. We could do this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@@ -402,7 +427,7 @@ not the solution to every problem.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
As you can see, this does not *hook* into the internal of the component. It
|
As you can see, this does not _hook_ into the internal of the component. It
|
||||||
simply returns a global object, which is difficult to mock.
|
simply returns a global object, which is difficult to mock.
|
||||||
|
|
||||||
A better way would be to do something like this: get the reference from the
|
A better way would be to do something like this: get the reference from the
|
||||||
@@ -410,7 +435,7 @@ not the solution to every problem.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
function useRouter() {
|
function useRouter() {
|
||||||
return Component.current.env.router;
|
return Component.current.env.router;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# 🦉 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`
|
||||||
|
|
||||||
|
When this component is used, 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>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `AsyncRoot` assumes that there is exactly one root node inside it. It can
|
||||||
|
be a dom node or a component.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# 🦉 Observer 🦉
|
||||||
|
|
||||||
|
Owl needs to be able to react to state changes. For example, whenever the state
|
||||||
|
of a component is changed, Owl needs to rerender it. To help with that, there is
|
||||||
|
an Observer class. Its job is to observe the state of an object (or array), and
|
||||||
|
to react to any change. The observer is implemented with the native `Proxy`
|
||||||
|
object. Note that this means that it will not work on older browsers.
|
||||||
|
|
||||||
|
Note that the `Observer` is used by the `useState` and `useContext` hooks. This
|
||||||
|
is the way most Owl applications will create observers. For the majority of
|
||||||
|
use cases, there is no need to directly instantiate an observer.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
For example, this code will display `update` in the console:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const observer = new owl.Observer();
|
||||||
|
observer.notifyCB = () => console.log("update");
|
||||||
|
const obj = observer.observe({ a: { b: 1 } });
|
||||||
|
|
||||||
|
obj.a.b = 2;
|
||||||
|
```
|
||||||
|
|
||||||
|
This example shows that an observer can observe nested properties.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
**observe** An observer can observe multiple values with the `observe` method.
|
||||||
|
This method takes an object or an array as its argument and will return a proxy
|
||||||
|
(which is mapped to the initial object/array). With this proxy, the observer
|
||||||
|
can detect whenever any internal value is changed.
|
||||||
|
|
||||||
|
**Registering a callback** Whenever an observer sees a state change, it will
|
||||||
|
call its `notifyCB` method. No additional information is given to the callback.
|
||||||
|
|
||||||
|
**deepRevNumber** Each observed value has an internal revision number, which
|
||||||
|
is incremented every time the value is observed. Sometimes, it can be useful
|
||||||
|
to obtain that number:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const observer = new owl.Observer();
|
||||||
|
const obj = observer.observe({ a: { b: 1 } });
|
||||||
|
|
||||||
|
observer.deepRevNumber(obj.a); // 1
|
||||||
|
obj.a.b = 2;
|
||||||
|
|
||||||
|
observer.deepRevNumber(obj.a); // 2
|
||||||
|
```
|
||||||
|
|
||||||
|
The `deepRevNumber` can also return 0, which indicates that the value is not
|
||||||
|
observed.
|
||||||
@@ -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,151 @@
|
|||||||
|
# 🦉 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
|
||||||
|
|
||||||
|
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,156 +15,72 @@
|
|||||||
- [Dynamic Attributes](#dynamic-attributes)
|
- [Dynamic Attributes](#dynamic-attributes)
|
||||||
- [Loops](#loops)
|
- [Loops](#loops)
|
||||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||||
|
- [Translations](#translations)
|
||||||
- [Debugging](#debugging)
|
- [Debugging](#debugging)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
[QWeb](https://www.odoo.com/documentation/12.0/reference/qweb.html) is the primary templating engine used by Odoo. It is based on the XML format, and used
|
[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>
|
||||||
</ul>
|
</ul>
|
||||||
</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) |
|
||||||
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
|
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
|
||||||
| `t-foreach`, `t-as` | [Loops](#loops) |
|
| `t-foreach`, `t-as` | [Loops](#loops) |
|
||||||
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
||||||
| `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-name` | [Defining a template (not really a directive)](#qweb-engine) |
|
| `t-translation` | [Disabling the translation of a node](#translations) |
|
||||||
|
| `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();
|
|
||||||
```
|
|
||||||
|
|
||||||
It's API is quite simple:
|
|
||||||
|
|
||||||
- **`constructor(data)`**: constructor. Takes an optional string to add initial
|
|
||||||
templates (see `addTemplates` for more information on format of the string).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template.
|
|
||||||
|
|
||||||
```js
|
|
||||||
qweb.addTemplate("mytemplate", "<div>hello</div>");
|
|
||||||
```
|
|
||||||
|
|
||||||
If the optional `allowDuplicate` is set to `true`, then `QWeb` will simply return whenever a template is added for a second time. Otherwise, `QWeb` will crash.
|
|
||||||
|
|
||||||
- **`addTemplates(xmlStr)`**: add a list of templates (identified by `t-name`
|
|
||||||
attribute).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const TEMPLATES = `
|
|
||||||
<templates>
|
|
||||||
<div t-name="App" class="main">main</div>
|
|
||||||
<div t-name="OtherComponent">other component</div>
|
|
||||||
</templates>`;
|
|
||||||
qweb.addTemplates(TEMPLATES);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
|
||||||
which is a virtual representation of the DOM (see [vdom doc](vdom.md)).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const vnode = qweb.render("App", component);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`renderToString(name, context)`**: renders a template, but returns an html
|
|
||||||
string.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const str = qweb.renderToString("someTemplate", somecontext);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`registerTemplate(name, template)`**: static function to register an global
|
|
||||||
QWeb template. This is useful for commonly used components accross the
|
|
||||||
application, and for making a template available to an application without
|
|
||||||
having a reference to the actual QWeb instance.
|
|
||||||
|
|
||||||
```js
|
|
||||||
QWeb.registerTemplate("mytemplate", `<div>some template`);
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`registerComponent(name, Component)`**: static function to register an OWL Component
|
|
||||||
to QWeb's global registry. Globally registered Components can be used in
|
|
||||||
templates (see the `t-component` directive). This is useful for commonly used
|
|
||||||
components accross the application.
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Dialog extends owl.Component { ... }
|
|
||||||
QWeb.registerComponent("Dialog", Dialog);
|
|
||||||
|
|
||||||
...
|
|
||||||
|
|
||||||
class ParentComponent extends owl.Component { ... }
|
|
||||||
qweb.addTemplate("ParentComponent", "<div><Dialog/></div>");
|
|
||||||
```
|
|
||||||
|
|
||||||
In some way, a `QWeb` instance is the core of an Owl application. It is the only
|
|
||||||
mandatory element of an [environment](component.md#environment). As such, it
|
|
||||||
has an extra responsability: it can act as an event bus for internal communication
|
|
||||||
between Owl classes. This is the reason why `QWeb` actually extends [EventBus](event_bus.md).
|
|
||||||
|
|
||||||
## Reference
|
## 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 templates are handled in a special way:
|
White spaces in a template are handled in a special way:
|
||||||
|
|
||||||
- consecutive whitespaces are always condensed to a single whitespace
|
- consecutive whitespaces are always condensed to a single whitespace
|
||||||
- if a whitespace-only text node contains a linebreak, it is ignored
|
- if a whitespace-only text node contains a linebreak, it is ignored
|
||||||
@@ -186,7 +101,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>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -200,14 +115,14 @@ root nodes.
|
|||||||
### Expression Evaluation
|
### Expression Evaluation
|
||||||
|
|
||||||
QWeb expressions are strings that will be processed at compile time. Each variable in
|
QWeb expressions are strings that will be processed at compile time. Each variable in
|
||||||
the javascript expression will be replaced by a lookup in the context (so, the
|
the javascript expression will be replaced with a lookup in the context (so, the
|
||||||
component). For example, `a + b.c(d)` will be converted into:
|
component). For example, `a + b.c(d)` will be converted into:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
context["a"] + context["b"].c(context["d"]);
|
context["a"] + context["b"].c(context["d"]);
|
||||||
```
|
```
|
||||||
|
|
||||||
It is useful to explain the various rules that applies on these expressions:
|
It is useful to explain the various rules that apply on these expressions:
|
||||||
|
|
||||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||||
|
|
||||||
@@ -233,14 +148,14 @@ It is useful to explain the various rules that applies on these expressions:
|
|||||||
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
||||||
`&` or `|`. This is useful to make sure that we still write valid XML.
|
`&` or `|`. This is useful to make sure that we still write valid XML.
|
||||||
|
|
||||||
| Word | will be replaced by |
|
| Word | replaced with |
|
||||||
| ----- | ------------------- |
|
| ----- | ------------- |
|
||||||
| `and` | `&&` |
|
| `and` | `&&` |
|
||||||
| `or` | `\|\|` |
|
| `or` | `\|\|` |
|
||||||
| `gt` | `>` |
|
| `gt` | `>` |
|
||||||
| `gte` | `>=` |
|
| `gte` | `>=` |
|
||||||
| `lt` | `<` |
|
| `lt` | `<` |
|
||||||
| `lte` | `<=` |
|
| `lte` | `<=` |
|
||||||
|
|
||||||
So, one can write this:
|
So, one can write this:
|
||||||
|
|
||||||
@@ -389,14 +304,25 @@ If an expression evaluates to a falsy value, it will not be set at all:
|
|||||||
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
||||||
```
|
```
|
||||||
|
|
||||||
There is another way to format a string attribute: the `t-attf-` directive. With
|
It is sometimes convenient to format an attribute with string interpolation. In
|
||||||
it, you get string interpolation:
|
that case, the `t-attf-` directive can be used. It is useful when we need to mix
|
||||||
|
literal and dynamic elements, such as css classes.
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
||||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If we need completely dynamic attribute names, then there is an additional
|
||||||
|
directive: `t-att`, which takes either an object (with keys mapping to their
|
||||||
|
values) or a pair `[key, value]`. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-att="{'a': 1, 'b': 2}"/> <!-- result: <div a="1" b="2"></div> -->
|
||||||
|
|
||||||
|
<div t-att="['a', 'b']"/> <!-- <div a="b"></div> -->
|
||||||
|
```
|
||||||
|
|
||||||
### Loops
|
### Loops
|
||||||
|
|
||||||
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
||||||
@@ -431,7 +357,7 @@ is equivalent to the previous example.
|
|||||||
or an object (the current item will be the current key).
|
or an object (the current item will be the current key).
|
||||||
|
|
||||||
In addition to the name passed via t-as, `t-foreach` provides a few other
|
In addition to the name passed via t-as, `t-foreach` provides a few other
|
||||||
variables for various data points (note: `$as` will be replaced by the name
|
variables for various data points (note: `$as` will be replaced with the name
|
||||||
passed to `t-as`):
|
passed to `t-as`):
|
||||||
|
|
||||||
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
||||||
@@ -449,19 +375,83 @@ the context of the `t-foreach`, the value is copied at the end of the foreach
|
|||||||
into the global context.
|
into the global context.
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<t t-set="existing_variable" t-value="False"/>
|
<t t-set="existing_variable" t-value="false"/>
|
||||||
<!-- existing_variable now False -->
|
<!-- existing_variable now False -->
|
||||||
|
|
||||||
<p t-foreach="Array(3)" t-as="i">
|
<p t-foreach="Array(3)" t-as="i">
|
||||||
<t t-set="existing_variable" t-value="True"/>
|
<t t-set="existing_variable" t-value="true"/>
|
||||||
<t t-set="new_variable" t-value="True"/>
|
<t t-set="new_variable" t-value="true"/>
|
||||||
<!-- existing_variable and new_variable now True -->
|
<!-- existing_variable and new_variable now true -->
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<!-- existing_variable always True -->
|
<!-- existing_variable always true -->
|
||||||
<!-- new_variable undefined -->
|
<!-- new_variable undefined -->
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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>
|
||||||
|
```
|
||||||
|
|
||||||
|
If there is no `t-key` directive, Owl will use the index as a default key.
|
||||||
|
|
||||||
### 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
|
||||||
@@ -510,6 +500,30 @@ will result in :
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This can be used to define variables scoped to a sub template:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<t t-call="other-template">
|
||||||
|
<t t-set="var" t-value="1"/>
|
||||||
|
</t>
|
||||||
|
<!-- "var" does not exist here -->
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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 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`.
|
||||||
|
|
||||||
|
See [here](qweb_engine.md#translations) for more information on how to setup a
|
||||||
|
translate function in Owl QWeb.
|
||||||
|
|
||||||
### Debugging
|
### Debugging
|
||||||
|
|
||||||
The javascript QWeb implementation provides two useful debugging directives:
|
The javascript QWeb implementation provides two useful debugging directives:
|
||||||
@@ -518,7 +532,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>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -531,4 +545,4 @@ will stop execution if the browser dev tools are open.
|
|||||||
<t t-log="foo"/>
|
<t t-log="foo"/>
|
||||||
```
|
```
|
||||||
|
|
||||||
will print 42 to the console
|
will print 42 to the console.
|
||||||
@@ -67,6 +67,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
|
||||||
@@ -97,6 +100,13 @@ The `Router` constructor takes three arguments:
|
|||||||
- an optional object (with the only key `mode` which can be `history` (default
|
- an optional object (with the only key `mode` which can be `history` (default
|
||||||
value) or `hash`).
|
value) or `hash`).
|
||||||
|
|
||||||
|
`history` will use the browser [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) as the mechanism to manage URL.\
|
||||||
|
Example: `https://yourdomain.tld/my_custom_route`.\
|
||||||
|
For this mechanism to work, you need a way to configure your web server accordingly.
|
||||||
|
|
||||||
|
`hash` will manipulate the hash of the URL.\
|
||||||
|
Example: `https://yourdomain.tld/index.html#/my_custom_route`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const ROUTES = [...];
|
const ROUTES = [...];
|
||||||
const router = new owl.router.Router(env, ROUTES, {mode: 'history'});
|
const router = new owl.router.Router(env, ROUTES, {mode: 'history'});
|
||||||
@@ -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).
|
||||||
@@ -10,6 +10,8 @@
|
|||||||
- [Getters](#getters)
|
- [Getters](#getters)
|
||||||
- [Connecting a Component](#connecting-a-component)
|
- [Connecting a Component](#connecting-a-component)
|
||||||
- [`useStore`](#usestore)
|
- [`useStore`](#usestore)
|
||||||
|
- [`useDispatch`](#usedispatch)
|
||||||
|
- [`useGetters`](#usegetters)
|
||||||
- [Semantics](#semantics)
|
- [Semantics](#semantics)
|
||||||
- [Good Practices](#good-practices)
|
- [Good Practices](#good-practices)
|
||||||
|
|
||||||
@@ -17,14 +19,14 @@
|
|||||||
|
|
||||||
Managing the state in an application is not an easy task. In some cases, the
|
Managing the state in an application is not an easy task. In some cases, the
|
||||||
state of an application can be part of the component tree, in a natural way.
|
state of an application can be part of the component tree, in a natural way.
|
||||||
However, there are situations where some part of the state need to be displayed
|
However, there are situations where some parts of the state need to be displayed
|
||||||
in various parts of the user interface, and then, it is not obvious which
|
in various parts of the user interface, and then, it is not obvious which
|
||||||
component should own which part of the state.
|
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 let 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.
|
||||||
|
|
||||||
@@ -38,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 });
|
||||||
@@ -88,7 +90,7 @@ const config = {
|
|||||||
state,
|
state,
|
||||||
actions,
|
actions,
|
||||||
getters,
|
getters,
|
||||||
env
|
env,
|
||||||
};
|
};
|
||||||
const store = new Store(config);
|
const store = new Store(config);
|
||||||
```
|
```
|
||||||
@@ -108,14 +110,15 @@ const actions = {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
state.loginState = "error";
|
state.loginState = "error";
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
The first argument to an action method is an object with four keys:
|
The first argument to an action method is an object with four keys:
|
||||||
|
|
||||||
- `state`: the current state of the store content,
|
- `state`: the current state of the store content,
|
||||||
- `dispatch`: a function that can be used to dispatch other actions,
|
- `dispatch`: a function that can be used to dispatch other actions,
|
||||||
- `getters`: an object containing all getters defined in the store
|
- `getters`: an object containing all getters defined in the store,
|
||||||
- `env`: the current environment. This is useful sometimes, in particular if
|
- `env`: the current environment. This is useful sometimes, in particular if
|
||||||
an action needs to apply some side effects (such as performing an rpc), and
|
an action needs to apply some side effects (such as performing an rpc), and
|
||||||
the `rpc` method is located in the environment.
|
the `rpc` method is located in the environment.
|
||||||
@@ -132,7 +135,7 @@ call.
|
|||||||
|
|
||||||
Also, it is important to be aware that we need to be careful with asynchronous
|
Also, it is important to be aware that we need to be careful with asynchronous
|
||||||
logic. Each state change will potentially trigger a rerendering, so we need to
|
logic. Each state change will potentially trigger a rerendering, so we need to
|
||||||
make sure that we do not have a partial corrupted state. Here is an example that
|
make sure that we do not have a partially corrupted state. Here is an example that
|
||||||
is likely not a good idea:
|
is likely not a good idea:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
@@ -141,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;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -156,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;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -184,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
|
||||||
@@ -200,18 +203,20 @@ const post = store.getters.getPost(id);
|
|||||||
|
|
||||||
Getters take _at most_ one argument.
|
Getters take _at most_ one argument.
|
||||||
|
|
||||||
Note that getters are cached if they don't take any argument, or their argument
|
Note that getters are not cached.
|
||||||
is a string or a number.
|
|
||||||
|
|
||||||
### 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.
|
||||||
|
|
||||||
- `useStore` to subscribe a component to some part of the store state,
|
Every component-store interactions are done with the help of the three store hooks:
|
||||||
- `useDispatch` to get a reference to a dispatch function
|
|
||||||
- `useGetters` to get a reference to the getters defined in the store.
|
|
||||||
|
|
||||||
|
- [`useStore`](#usestore) to subscribe a component to some part of the store state,
|
||||||
|
- [`useDispatch`](#usedispatch) to get a reference to a dispatch function,
|
||||||
|
- [`useGetters`](#usegetters) to get a reference to the getters defined in the store.
|
||||||
|
|
||||||
Assume we have this store:
|
Assume we have this store:
|
||||||
|
|
||||||
@@ -219,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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,22 +258,68 @@ const counter = new Counter({ store, qweb });
|
|||||||
</button>
|
</button>
|
||||||
```
|
```
|
||||||
|
|
||||||
### `useStore``
|
### `useStore`
|
||||||
|
|
||||||
The `useStore` hook is used to select some part of the store state. It accepts
|
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` selector returns a sub part of the store state, the component
|
||||||
If the `useStore` callback selects 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 updates 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.
|
||||||
|
|
||||||
|
Note that if the selector function returns a primitive type, the result of
|
||||||
|
`useStore` will be immutable and it will not react to changes. In this case, it
|
||||||
|
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`
|
||||||
|
|
||||||
|
The `useDispatch` hook is useful when a component needs to be able to dispatch
|
||||||
|
actions. It takes an optional argument, which is a store. If not given, it will
|
||||||
|
use the store in the environment.
|
||||||
|
|
||||||
|
Note that a component does not need to be connected in any other way to the store.
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class DoSomethingButton extends Component {
|
||||||
|
static template = xml`<button t-on-click="dispatch('something')">Click</button>`;
|
||||||
|
dispatch = useDispatch();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `useGetters`
|
||||||
|
|
||||||
|
The `useGetters` hook is useful when a component needs to be able to use the
|
||||||
|
getters defined in a store. It takes an optional argument, which is a store. If
|
||||||
|
not given, it will use the store in the environment.
|
||||||
|
|
||||||
|
Note that a component does not need to be connected in any other way to the store.
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class InfoButton extends Component {
|
||||||
|
static template = xml`<span><t t-esc="getters.somevalue()"></span>`;
|
||||||
|
getters = useGetters();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Semantics
|
### Semantics
|
||||||
|
|
||||||
@@ -268,23 +327,23 @@ The `Store` class and the `useStore` hook try to be smart and to optimize as muc
|
|||||||
as possible the rendering and update process. What is important to know is:
|
as possible the rendering and update process. What is important to know is:
|
||||||
|
|
||||||
- components are always updated in the order of their creation (so, parent
|
- components are always updated in the order of their creation (so, parent
|
||||||
before children)
|
before children),
|
||||||
- they are updated only if they are in the DOM
|
- they are updated only if they are in the DOM,
|
||||||
- if a parent is asynchronous, the system will wait for it to complete its
|
- if a parent is asynchronous, the system will wait for it to complete its
|
||||||
update before updating other components.
|
update before updating other components,
|
||||||
- in general, updates are not coordinated. This is not a problem for synchronous
|
- in general, updates are not coordinated. This is not a problem for synchronous
|
||||||
components, but if there are many asynchronous components, this could lead to
|
components, but if there are many asynchronous components, this could lead to
|
||||||
a situation where some part of the UI is updated and other parts of the UI is
|
a situation where some part of the UI is updated and some other part of the UI is
|
||||||
not updated.
|
not updated.
|
||||||
|
|
||||||
### Good Practices
|
### Good Practices
|
||||||
|
|
||||||
- avoid asynchronous components as much as possible. Asynchronous components
|
- avoid asynchronous components as much as possible. Asynchronous components
|
||||||
lead to situations where parts of the UI is not updated immediately.
|
lead to situations where parts of the UI is not updated immediately,
|
||||||
- do not be afraid to connect many components, parent or children if needed. For
|
- do not be afraid to connect many components, parent or children if needed. For
|
||||||
example, a `MessageList` component could get a list of ids in its `useStore`
|
example, a `MessageList` component could get a list of ids in its `useStore`
|
||||||
call and a `Message` component could get the data of its own
|
call and a `Message` component could get the data of its own
|
||||||
message
|
message,
|
||||||
- since the `useStore` function is called for each connected component,
|
- since the `useStore` function is called for each connected component,
|
||||||
for each state update, it is important to make sure that these functions are
|
for each state update, it is important to make sure that these functions are
|
||||||
as fast as possible.
|
as fast as possible.
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
# 🦉 Tags 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [`xml` tag](#xml-tag)
|
||||||
|
- [`css` tag](#css-tag)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Tags are very small helpers intended to make it easy to write inline templates
|
||||||
|
or styles. There are currently two tags: `css` and `xml`. With these functions,
|
||||||
|
it is possible to write [single file components](../learning/how_to_write_sfc.md).
|
||||||
|
|
||||||
|
## XML tag
|
||||||
|
|
||||||
|
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
|
||||||
|
import { Component } from 'owl'
|
||||||
|
|
||||||
|
const name = 'some-unique-name';
|
||||||
|
const template = `
|
||||||
|
<div>
|
||||||
|
<span t-if="somecondition">text</span>
|
||||||
|
<button t-on-click="someMethod">Click</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
QWeb.registerTemplate(name, template);
|
||||||
|
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = name;
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With tags, this process is slightly simplified. The name is uniquely generated,
|
||||||
|
and the template is automatically registered:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { Component } = owl;
|
||||||
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span t-if="somecondition">text</span>
|
||||||
|
<button t-on-click="someMethod">Click</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# 🦉 Utils 🦉
|
||||||
|
|
||||||
|
Owl export a few useful utility functions, to help with common issues. Those
|
||||||
|
functions are all available in the `owl.utils` namespace.
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [`whenReady`](#whenready): executing code when DOM is ready
|
||||||
|
- [`loadJS`](#loadjs): loading script files
|
||||||
|
- [`loadFile`](#loadfile): loading a file (useful for templates)
|
||||||
|
- [`escape`](#escape): sanitizing strings
|
||||||
|
- [`debounce`](#debounce): limiting rate of function calls
|
||||||
|
- [`shallowEqual`](#shallowequal): shallow object comparison
|
||||||
|
|
||||||
|
## `whenReady`
|
||||||
|
|
||||||
|
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
|
||||||
|
not ready yet, resolved directly otherwise). If called with a callback as
|
||||||
|
argument, it executes it as soon as the DOM ready (or directly).
|
||||||
|
|
||||||
|
```js
|
||||||
|
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function ([templates]) {
|
||||||
|
const qweb = new owl.QWeb({ templates });
|
||||||
|
const app = new App({ qweb });
|
||||||
|
app.mount(document.body);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
or alternatively:
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.utils.whenReady(function () {
|
||||||
|
const qweb = new owl.QWeb();
|
||||||
|
const app = new App({ qweb });
|
||||||
|
app.mount(document.body);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `loadJS`
|
||||||
|
|
||||||
|
`loadJS` takes a url (string) for a javascript resource, and loads it (by adding
|
||||||
|
a script tag in the document head). It returns a promise, so the caller can
|
||||||
|
properly reacts when it is ready. Also, it is smart: it maintains a list of urls
|
||||||
|
previously loaded (or currently being loaded), and prevent doing twice the work.
|
||||||
|
|
||||||
|
For example, it is useful for lazy loading external libraries:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class MyComponent extends owl.Component {
|
||||||
|
willStart() {
|
||||||
|
return owl.utils.loadJS("/static/libs/someLib.js");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `loadFile`
|
||||||
|
|
||||||
|
`loadFile` is a helper function to fetch a file. It simply
|
||||||
|
performs a `GET` request and returns the resulting string in a promise. The
|
||||||
|
initial usecase for this function is to load a template file. For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
async function makeEnv() {
|
||||||
|
const templates = await owl.utils.loadFile("templates.xml");
|
||||||
|
const qweb = new owl.QWeb({ templates });
|
||||||
|
return { qweb };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that unlike `loadJS`, this function returns the content of the file as a
|
||||||
|
string. It does not add a `script` tag or any other side effect.
|
||||||
|
|
||||||
|
## `escape`
|
||||||
|
|
||||||
|
Sometimes, we need to display dynamic data (for example user-generated data) in
|
||||||
|
the user interface. If this is done by a `QWeb` template, it is not an issue:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div><t t-esc="user.data"/></div>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `QWeb` engine will create a `div` node and add the content of the `user.data`
|
||||||
|
string as a text node, so the web browser will not parse it as html. However,
|
||||||
|
it may be a problem if this is done with some javascript code like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
class BadComponent extends Component {
|
||||||
|
// some template with a ref to a div
|
||||||
|
// some code ...
|
||||||
|
|
||||||
|
mounted() {
|
||||||
|
this.divRef.el.innerHTML = this.state.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this case, the content of the `div` will be parsed as html, which may inject
|
||||||
|
unwanted behaviour. To fix this, the `escape` function will simply transform a
|
||||||
|
string into an escaped version of the same string, which will be properly displayed
|
||||||
|
by the browser, but which will not be parsed as html (for example, `"<ok>"` is
|
||||||
|
escaped to the string: `"<ok>"`). So, the bad example above can be fixed
|
||||||
|
with the following change:
|
||||||
|
|
||||||
|
```js
|
||||||
|
this.divRef.el.innerHTML = owl.utils.escape(this.state.value);
|
||||||
|
```
|
||||||
|
|
||||||
|
## `debounce`
|
||||||
|
|
||||||
|
The `debounce` function is useful when we want to limit the number of times some
|
||||||
|
function/action is perfomed. For example, this may be useful to prevent issue
|
||||||
|
with people double clicking on a button.
|
||||||
|
|
||||||
|
It takes three arguments:
|
||||||
|
|
||||||
|
- `func` (function): this is the function that will be rate limited
|
||||||
|
- `wait` (number): this is the number of milliseconds that we want to use to
|
||||||
|
rate limit the function `func`
|
||||||
|
- `immediate` (optional, boolean, default=false): if `immediate` is true, the
|
||||||
|
function will be triggered immediately (leading edge of the interval). If false,
|
||||||
|
the function will be triggered at the end (trailing edge).
|
||||||
|
|
||||||
|
It returns a function. For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const debounce = owl.utils.debounce;
|
||||||
|
window.addEventListener("mousemove", debounce(doSomething, 100));
|
||||||
|
```
|
||||||
|
|
||||||
|
As this example shows, it is usualy useful for event handlers which are triggered
|
||||||
|
very quickly, such as `scroll` or `mousemove` events.
|
||||||
|
|
||||||
|
## `shallowEqual`
|
||||||
|
|
||||||
|
This function checks if two objects have the same values assigned to each keys:
|
||||||
|
|
||||||
|
```js
|
||||||
|
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
|
||||||
|
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false
|
||||||
|
```
|
||||||
|
|
||||||
|
However, for performance reasons, it assumes that the two objects have the same
|
||||||
|
keys. If we are in a situation where this is not guaranteed, the following code
|
||||||
|
will work:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const completeShallowEqual = (a, b) => shallowEqual(a, b) && shallowEqual(b, a);
|
||||||
|
```
|
||||||
-47
@@ -1,47 +0,0 @@
|
|||||||
# 🦉 Tags 🦉
|
|
||||||
|
|
||||||
Tags are very small helper to make it easy to write inline templates. There is
|
|
||||||
only one currently available tag: `xml`, but we plan to add other tags later,
|
|
||||||
such as a `css` tag, which will be used to write single file components.
|
|
||||||
|
|
||||||
## XML tag
|
|
||||||
|
|
||||||
Without tags, creating a standalone component would look like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
import { Component } from 'owl'
|
|
||||||
|
|
||||||
const name = 'some-unique-name';
|
|
||||||
const template = `
|
|
||||||
<div>
|
|
||||||
<span t-if="somecondition">text</span>
|
|
||||||
<button t-on-click="someMethod">Click</button>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
QWeb.registerTemplate(name, template);
|
|
||||||
|
|
||||||
class MyComponent extends Component {
|
|
||||||
static template = name;
|
|
||||||
|
|
||||||
...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
With tags, this process is slightly simplified. The name is uniquely generated,
|
|
||||||
and the template is automatically registered:
|
|
||||||
|
|
||||||
```js
|
|
||||||
import { Component } from 'owl'
|
|
||||||
import { xml } from 'owl/tags'
|
|
||||||
|
|
||||||
class MyComponent extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div>
|
|
||||||
<span t-if="somecondition">text</span>
|
|
||||||
<button t-on-click="someMethod">Click</button>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
|
|
||||||
...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -1,87 +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
|
|
||||||
|
|
||||||
If you want to have `xml` syntax highlighting while using the `xml` helper which
|
|
||||||
helps you define inline templates, there is a VS Code addon `Comment tagged template`
|
|
||||||
which, if installed, does exactly that. To enable it, you need to add a comment,
|
|
||||||
like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// 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...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
# 🦉 Utils 🦉
|
|
||||||
|
|
||||||
Owl export a few useful utility functions, to help with common issues. Those
|
|
||||||
functions are all available in the `owl.utils` namespace.
|
|
||||||
|
|
||||||
## Content
|
|
||||||
|
|
||||||
- [`whenReady`](#whenready): executing code when DOM is ready
|
|
||||||
- [`loadJS`](#loadjs): loading script files
|
|
||||||
- [`loadTemplates`](#loadtemplates): loading xml files
|
|
||||||
- [`escape`](#escape): sanitizing strings
|
|
||||||
- [`debounce`](#debounce): limiting rate of function calls
|
|
||||||
|
|
||||||
## `whenReady`
|
|
||||||
|
|
||||||
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
|
|
||||||
not ready yet, resolved directly otherwise). If called with a callback as
|
|
||||||
argument, it executes it as soon as the DOM ready (or directly).
|
|
||||||
|
|
||||||
```js
|
|
||||||
Promise.all([loadTemplates(), owl.utils.whenReady()]).then(function([templates]) {
|
|
||||||
const qweb = new owl.QWeb(templates);
|
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
owl.utils.whenReady(function() {
|
|
||||||
const qweb = new owl.QWeb();
|
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## `loadJS`
|
|
||||||
|
|
||||||
`loadJS` takes a url (string) for a javascript resource, and loads it. It returns
|
|
||||||
a promise, so the caller can properly react when it is ready. Also, it is smart:
|
|
||||||
it maintains a list of urls previously loaded (or currently being loaded), and
|
|
||||||
prevent doing twice the work.
|
|
||||||
|
|
||||||
```js
|
|
||||||
class MyComponent extends owl.Component {
|
|
||||||
willStart() {
|
|
||||||
return owl.utils.loadJS("/static/libs/someLib.js");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## `loadTemplates`
|
|
||||||
|
|
||||||
```js
|
|
||||||
async function makeEnv() {
|
|
||||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
|
||||||
const qweb = new owl.QWeb(templates);
|
|
||||||
return { qweb };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## `escape`
|
|
||||||
|
|
||||||
## `debounce`
|
|
||||||
+23
-7
@@ -1,8 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "owl-framework",
|
"name": "@odoo/owl",
|
||||||
"version": "0.23.0",
|
"version": "1.0.11",
|
||||||
"description": "Odoo Web Library (OWL)",
|
"description": "Odoo Web Library (OWL)",
|
||||||
"main": "src/index.ts",
|
"main": "dist/owl.js",
|
||||||
|
"types": "dist/types/index.d.ts",
|
||||||
|
"files": [
|
||||||
|
"dist/types/",
|
||||||
|
"dist/owl.js",
|
||||||
|
"dist/owl-iife.js"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.15.3"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
||||||
"build:bundle": "rollup -c",
|
"build:bundle": "rollup -c",
|
||||||
@@ -14,14 +23,17 @@
|
|||||||
"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,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write",
|
||||||
|
"publish": "npm run build && mv dist/owl.js dist/owl-iife.js && npm run buildcommonjs && 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"
|
||||||
},
|
},
|
||||||
@@ -29,18 +41,21 @@
|
|||||||
"dependencies": {},
|
"dependencies": {},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^23.3.12",
|
"@types/jest": "^23.3.12",
|
||||||
|
"chalk": "^3.0.0",
|
||||||
"cpx": "^1.5.0",
|
"cpx": "^1.5.0",
|
||||||
"git-rev-sync": "^1.12.0",
|
"git-rev-sync": "^1.12.0",
|
||||||
|
"github-api": "^3.3.0",
|
||||||
"jest": "^23.6.0",
|
"jest": "^23.6.0",
|
||||||
"jest-environment-jsdom": "^24.7.1",
|
"jest-environment-jsdom": "^24.7.1",
|
||||||
"live-server": "^1.2.1",
|
"live-server": "^1.2.1",
|
||||||
"npm-run-all": "^4.1.5",
|
"npm-run-all": "^4.1.5",
|
||||||
|
"prettier": "^2.0.4",
|
||||||
"rollup": "^1.6.0",
|
"rollup": "^1.6.0",
|
||||||
"rollup-plugin-typescript2": "^0.20.1",
|
"rollup-plugin-typescript2": "^0.20.1",
|
||||||
"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": "^23.10.5",
|
||||||
"typescript": "^3.2.2",
|
"typescript": "^3.7.2",
|
||||||
"uglify-es": "^3.3.9"
|
"uglify-es": "^3.3.9"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
@@ -63,6 +78,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"prettier": {
|
"prettier": {
|
||||||
"printWidth": 100
|
"printWidth": 100,
|
||||||
|
"endOfLine": "auto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
# 🦉 OWL Roadmap 🦉
|
||||||
|
|
||||||
|
- Current version: 1.0.11
|
||||||
|
- Status: stable
|
||||||
|
|
||||||
|
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||||
|
change!
|
||||||
|
|
||||||
|
|
||||||
|
### 1.x
|
||||||
|
|
||||||
|
- add chrome and firefox devtools,
|
||||||
|
- fix every bugs,
|
||||||
|
- improve documentation,
|
||||||
|
- small backward compatible improvements.
|
||||||
|
|
||||||
|
### 2.x (2020? 2021? 2022?)
|
||||||
|
|
||||||
|
- stop support for `t-set` directive to define the content of a slot
|
||||||
|
|
||||||
|
Maybe:
|
||||||
|
|
||||||
|
- 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
|
||||||
|
allow additional optimisations.
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
export interface Browser {
|
||||||
|
setTimeout: Window["setTimeout"];
|
||||||
|
clearTimeout: Window["clearTimeout"];
|
||||||
|
setInterval: Window["setInterval"];
|
||||||
|
clearInterval: Window["clearInterval"];
|
||||||
|
requestAnimationFrame: Window["requestAnimationFrame"];
|
||||||
|
random: Math["random"];
|
||||||
|
Date: typeof Date;
|
||||||
|
fetch: Window["fetch"];
|
||||||
|
localStorage: Window["localStorage"];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const browser: Browser = {
|
||||||
|
setTimeout: window.setTimeout.bind(window),
|
||||||
|
clearTimeout: window.clearTimeout.bind(window),
|
||||||
|
setInterval: window.setInterval.bind(window),
|
||||||
|
clearInterval: window.clearInterval.bind(window),
|
||||||
|
requestAnimationFrame: window.requestAnimationFrame.bind(window),
|
||||||
|
random: Math.random,
|
||||||
|
Date: window.Date,
|
||||||
|
fetch: (window.fetch || (() => {})).bind(window),
|
||||||
|
localStorage: window.localStorage,
|
||||||
|
};
|
||||||
+290
-294
@@ -1,8 +1,13 @@
|
|||||||
import { Observer } from "../core/observer";
|
import { Observer } from "../core/observer";
|
||||||
|
import { OwlEvent } from "../core/owl_event";
|
||||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
import { CompiledTemplate, QWeb } from "../qweb/index";
|
||||||
import { h, patch, VNode } from "../vdom/index";
|
import { patch, VNode } from "../vdom/index";
|
||||||
import "./directive";
|
import "./directive";
|
||||||
|
import { Fiber } from "./fiber";
|
||||||
import "./props_validation";
|
import "./props_validation";
|
||||||
|
import { Scheduler, scheduler } from "./scheduler";
|
||||||
|
import { activateSheet } from "./styles";
|
||||||
|
import { Browser, browser } from "../browser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Component System
|
* Owl Component System
|
||||||
@@ -11,7 +16,6 @@ import "./props_validation";
|
|||||||
* contains:
|
* contains:
|
||||||
*
|
*
|
||||||
* - the Env interface (generic type for the environment)
|
* - the Env interface (generic type for the environment)
|
||||||
* - the Fiber interface (owl metadata attached to a rendering)
|
|
||||||
* - the Internal interface (the owl specific metadata attached to a component)
|
* - the Internal interface (the owl specific metadata attached to a component)
|
||||||
* - the Component class
|
* - the Component class
|
||||||
*/
|
*/
|
||||||
@@ -31,28 +35,13 @@ import "./props_validation";
|
|||||||
*/
|
*/
|
||||||
export interface Env {
|
export interface Env {
|
||||||
qweb: QWeb;
|
qweb: QWeb;
|
||||||
[key: string]: any;
|
browser: Browser;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export type MountPosition = "first-child" | "last-child" | "self";
|
||||||
* Fibers are small abstractions designed to contain all the internal state
|
|
||||||
* associated to a "rendering work unit", relative to a specific component.
|
interface MountOptions {
|
||||||
*
|
position?: MountPosition;
|
||||||
* A rendering will cause the creation of a fiber for each impacted components.
|
|
||||||
*/
|
|
||||||
export interface Fiber<Props> {
|
|
||||||
force: boolean;
|
|
||||||
rootFiber: Fiber<any> | null;
|
|
||||||
isCancelled: boolean;
|
|
||||||
scope: any;
|
|
||||||
vars: any;
|
|
||||||
patchQueue: Fiber<any>[];
|
|
||||||
component: Component<any, any>;
|
|
||||||
vnode: VNode | null;
|
|
||||||
props: Props;
|
|
||||||
promise: Promise<VNode> | null;
|
|
||||||
// handlers?: any;
|
|
||||||
// mountedHandlers?: any;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,28 +49,38 @@ export interface Fiber<Props> {
|
|||||||
* useful to typecheck and describe the internal keys used by Owl to manage the
|
* useful to typecheck and describe the internal keys used by Owl to manage the
|
||||||
* component tree.
|
* component tree.
|
||||||
*/
|
*/
|
||||||
interface Internal<T extends Env, Props> {
|
interface Internal<T extends Env> {
|
||||||
// each component has a unique id, useful mostly to handle parent/child
|
// each component has a unique id, useful mostly to handle parent/child
|
||||||
// relationships
|
// relationships
|
||||||
readonly id: number;
|
readonly id: number;
|
||||||
|
depth: number;
|
||||||
vnode: VNode | null;
|
vnode: VNode | null;
|
||||||
|
pvnode: VNode | null;
|
||||||
isMounted: boolean;
|
isMounted: boolean;
|
||||||
isDestroyed: boolean;
|
isDestroyed: boolean;
|
||||||
|
|
||||||
// parent and children keys are obviously useful to setup the parent-children
|
// parent and children keys are obviously useful to setup the parent-children
|
||||||
// relationship.
|
// relationship.
|
||||||
parent: Component<T, any> | null;
|
parent: Component<any, T> | null;
|
||||||
children: { [key: number]: Component<T, any> };
|
children: { [key: number]: Component<any, T> };
|
||||||
// children mapping: from templateID to componentID. templateID identifies a
|
// children mapping: from templateID to componentID. templateID identifies a
|
||||||
// place in a template. The t-component directive needs it to be able to get
|
// place in a template. The t-component directive needs it to be able to get
|
||||||
// the component instance back whenever the template is rerendered.
|
// the component instance back whenever the template is rerendered.
|
||||||
cmap: { [key: number]: number };
|
cmap: { [key: number]: number };
|
||||||
|
|
||||||
currentFiber: Fiber<Props> | null;
|
currentFiber: Fiber | null;
|
||||||
|
// parentLastFiberId is there to help the parent component to detect, among
|
||||||
|
// its children, those that are not used anymore and thus can be destroyed
|
||||||
|
parentLastFiberId: number;
|
||||||
|
|
||||||
|
// when a rendering is initiated by a parent, it may set variables in 'scope'
|
||||||
|
// (typically when the component is rendered in a slot). We need to
|
||||||
|
// store that information in case the component would be re-rendered later on.
|
||||||
|
scope: any;
|
||||||
|
|
||||||
boundHandlers: { [key: number]: any };
|
boundHandlers: { [key: number]: any };
|
||||||
observer: Observer | null;
|
observer: Observer | null;
|
||||||
render: CompiledTemplate;
|
renderFn: CompiledTemplate;
|
||||||
mountedCB: Function | null;
|
mountedCB: Function | null;
|
||||||
willUnmountCB: Function | null;
|
willUnmountCB: Function | null;
|
||||||
willPatchCB: Function | null;
|
willPatchCB: Function | null;
|
||||||
@@ -89,22 +88,27 @@ interface Internal<T extends Env, Props> {
|
|||||||
willStartCB: Function | null;
|
willStartCB: Function | null;
|
||||||
willUpdatePropsCB: Function | null;
|
willUpdatePropsCB: Function | null;
|
||||||
classObj: { [key: string]: boolean } | null;
|
classObj: { [key: string]: boolean } | null;
|
||||||
refs: { [key: string]: Component<T, any> | HTMLElement | undefined } | null;
|
refs: { [key: string]: Component<any, T> | HTMLElement | undefined } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const portalSymbol = Symbol("portal"); // FIXME
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Component
|
// Component
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
let nextId = 1;
|
let nextId = 1;
|
||||||
|
|
||||||
export class Component<T extends Env, Props extends {}> {
|
export class Component<Props extends {} = any, T extends Env = Env> {
|
||||||
readonly __owl__: Internal<Env, Props>;
|
readonly __owl__: Internal<T>;
|
||||||
static template?: string | null = null;
|
static template?: string | null = null;
|
||||||
static _template?: string | null = null;
|
static _template?: string | null = null;
|
||||||
static current: Component<any, any> | null = null;
|
static current: Component | null = null;
|
||||||
static components = {};
|
static components = {};
|
||||||
static props?: any;
|
static props?: any;
|
||||||
static defaultProps?: any;
|
static defaultProps?: any;
|
||||||
|
static env: any = {};
|
||||||
|
// expose scheduler s.t. it can be mocked for testing purposes
|
||||||
|
static scheduler: Scheduler = scheduler;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `el` is the root element of the component. Note that it could be null:
|
* The `el` is the root element of the component. Note that it could be null:
|
||||||
@@ -124,45 +128,39 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* Creates an instance of Component.
|
* 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
|
* 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
|
* hand. Other components should be created automatically by the framework (with
|
||||||
* the t-component directive in a template)
|
* the t-component directive in a template)
|
||||||
*/
|
*/
|
||||||
constructor(parent: Component<T, any> | T, props?: Props) {
|
constructor(parent?: Component<any, T> | null, props?: Props) {
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
|
||||||
Component.current = this;
|
Component.current = this;
|
||||||
|
|
||||||
|
let constr = this.constructor as any;
|
||||||
|
const defaultProps = constr.defaultProps;
|
||||||
if (defaultProps) {
|
if (defaultProps) {
|
||||||
props = this.__applyDefaultProps(props, defaultProps);
|
props = props || ({} as Props);
|
||||||
|
this.__applyDefaultProps(props, defaultProps);
|
||||||
}
|
}
|
||||||
// is this a good idea?
|
this.props = <Props>props;
|
||||||
// Pro: if props is empty, we can create easily a component
|
if (QWeb.dev) {
|
||||||
// Con: this is not really safe
|
QWeb.utils.validateProps(constr, this.props);
|
||||||
// Pro: but creating component (by a template) is always unsafe anyway
|
}
|
||||||
this.props = <Props>props || <Props>{};
|
|
||||||
let id: number = nextId++;
|
const id: number = nextId++;
|
||||||
let p: Component<T, any> | null = null;
|
let depth;
|
||||||
if (parent instanceof Component) {
|
if (parent) {
|
||||||
p = parent;
|
|
||||||
this.env = parent.env;
|
this.env = parent.env;
|
||||||
parent.__owl__.children[id] = this;
|
const __powl__ = parent.__owl__;
|
||||||
|
__powl__.children[id] = this;
|
||||||
|
depth = __powl__.depth + 1;
|
||||||
} else {
|
} else {
|
||||||
this.env = parent;
|
// we are the root component
|
||||||
if (QWeb.dev) {
|
this.env = (this.constructor as any).env;
|
||||||
// we only validate props for root widgets here. "Regular" widget
|
if (!this.env.qweb) {
|
||||||
// props are validated by the t-component directive
|
this.env.qweb = new QWeb();
|
||||||
QWeb.utils.validateProps(this.constructor, this.props);
|
}
|
||||||
|
if (!this.env.browser) {
|
||||||
|
this.env.browser = browser;
|
||||||
}
|
}
|
||||||
this.env.qweb.on("update", this, () => {
|
this.env.qweb.on("update", this, () => {
|
||||||
if (this.__owl__.isMounted) {
|
if (this.__owl__.isMounted) {
|
||||||
@@ -177,18 +175,23 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
this.env.qweb.off("update", this);
|
this.env.qweb.off("update", this);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
depth = 0;
|
||||||
}
|
}
|
||||||
const qweb = this.env.qweb;
|
|
||||||
|
|
||||||
|
const qweb = this.env.qweb;
|
||||||
|
const template = constr.template || this.__getTemplate(qweb);
|
||||||
this.__owl__ = {
|
this.__owl__ = {
|
||||||
id: id,
|
id: id,
|
||||||
|
depth: depth,
|
||||||
vnode: null,
|
vnode: null,
|
||||||
|
pvnode: null,
|
||||||
isMounted: false,
|
isMounted: false,
|
||||||
isDestroyed: false,
|
isDestroyed: false,
|
||||||
parent: p,
|
parent: parent || null,
|
||||||
children: {},
|
children: {},
|
||||||
cmap: {},
|
cmap: {},
|
||||||
currentFiber: null,
|
currentFiber: null,
|
||||||
|
parentLastFiberId: 0,
|
||||||
boundHandlers: {},
|
boundHandlers: {},
|
||||||
mountedCB: null,
|
mountedCB: null,
|
||||||
willUnmountCB: null,
|
willUnmountCB: null,
|
||||||
@@ -197,10 +200,14 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
willStartCB: null,
|
willStartCB: null,
|
||||||
willUpdatePropsCB: null,
|
willUpdatePropsCB: null,
|
||||||
observer: null,
|
observer: null,
|
||||||
render: qweb.render.bind(qweb, this.__getTemplate(qweb)),
|
renderFn: qweb.render.bind(qweb, template),
|
||||||
classObj: null,
|
classObj: null,
|
||||||
refs: null
|
refs: null,
|
||||||
|
scope: null,
|
||||||
};
|
};
|
||||||
|
if (constr.style) {
|
||||||
|
this.__applyStyles(constr);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -278,8 +285,11 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* catchError is a method called whenever some error happens in the rendering or
|
* catchError is a method called whenever some error happens in the rendering or
|
||||||
* lifecycle hooks of a child.
|
* 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 {}
|
catchError?(error?: Error): void;
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
// Public
|
// Public
|
||||||
@@ -293,31 +303,43 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
*
|
*
|
||||||
* Note that a component can be mounted an unmounted several times
|
* Note that a component can be mounted an unmounted several times
|
||||||
*/
|
*/
|
||||||
async mount(target: HTMLElement, renderBeforeRemount: boolean = false): Promise<void> {
|
async mount(target: HTMLElement | DocumentFragment, options: MountOptions = {}): Promise<void> {
|
||||||
|
const position = options.position || "last-child";
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
if (__owl__.isMounted) {
|
if (__owl__.isMounted) {
|
||||||
return;
|
if (position !== "self" && this.el!.parentNode !== target) {
|
||||||
}
|
// in this situation, we are trying to mount a component on a different
|
||||||
const fiber = this.__createFiber(false, undefined, undefined, undefined);
|
// target. In this case, we need to unmount first, otherwise it will
|
||||||
if (!__owl__.vnode) {
|
// not work.
|
||||||
fiber.promise = this.__prepareAndRender(fiber);
|
this.unmount();
|
||||||
const vnode = await fiber.promise;
|
} else {
|
||||||
if (__owl__.isDestroyed) {
|
return Promise.resolve();
|
||||||
// component was destroyed before we get here...
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
this.__patch(vnode);
|
|
||||||
} else if (renderBeforeRemount) {
|
|
||||||
fiber.patchQueue.push(fiber);
|
|
||||||
fiber.promise = this.__render(fiber);
|
|
||||||
await fiber.promise;
|
|
||||||
this.__applyPatchQueue(fiber);
|
|
||||||
}
|
}
|
||||||
target.appendChild(this.el!);
|
if (__owl__.isDestroyed) {
|
||||||
|
throw new Error("Cannot mount a destroyed component");
|
||||||
if (document.body.contains(target)) {
|
|
||||||
this.__callMounted();
|
|
||||||
}
|
}
|
||||||
|
if (__owl__.currentFiber) {
|
||||||
|
const currentFiber = __owl__.currentFiber;
|
||||||
|
if (currentFiber.target === target && currentFiber.position === position) {
|
||||||
|
return scheduler.addFiber(currentFiber);
|
||||||
|
} else {
|
||||||
|
scheduler.rejectFiber(currentFiber, "Mounting operation cancelled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!(target instanceof HTMLElement || target instanceof DocumentFragment)) {
|
||||||
|
let message = `Component '${this.constructor.name}' cannot be mounted: the target is not a valid DOM node.`;
|
||||||
|
message += `\nMaybe the DOM is not ready yet? (in that case, you can use owl.utils.whenReady)`;
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
const fiber = new Fiber(null, this, false, target, position);
|
||||||
|
fiber.shouldPatch = false;
|
||||||
|
if (!__owl__.vnode) {
|
||||||
|
this.__prepareAndRender(fiber, () => {});
|
||||||
|
} else {
|
||||||
|
this.__render(fiber);
|
||||||
|
}
|
||||||
|
return scheduler.addFiber(fiber);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -342,19 +364,38 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
*/
|
*/
|
||||||
async render(force: boolean = false): Promise<void> {
|
async render(force: boolean = false): Promise<void> {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
if (!__owl__.isMounted) {
|
const currentFiber = __owl__.currentFiber;
|
||||||
|
if (!__owl__.isMounted && !currentFiber) {
|
||||||
|
// if we get here, this means that the component was either never mounted,
|
||||||
|
// or was unmounted and some state change triggered a render. Either way,
|
||||||
|
// we do not want to actually render anything in this case.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fiber = this.__createFiber(force, undefined, undefined, undefined);
|
if (currentFiber && !currentFiber.isRendered && !currentFiber.isCompleted) {
|
||||||
fiber.patchQueue.push(fiber);
|
return scheduler.addFiber(currentFiber.root);
|
||||||
fiber.promise = this.__render(fiber);
|
|
||||||
await fiber.promise;
|
|
||||||
|
|
||||||
if (__owl__.isMounted && fiber === __owl__.currentFiber) {
|
|
||||||
// we only update the vnode and the actual DOM if no other rendering
|
|
||||||
// occurred between now and when the render method was initially called.
|
|
||||||
this.__applyPatchQueue(fiber);
|
|
||||||
}
|
}
|
||||||
|
// if we aren't mounted at this point, it implies that there is a
|
||||||
|
// currentFiber that is already rendered (isRendered is true), so we are
|
||||||
|
// about to be mounted
|
||||||
|
const isMounted = __owl__.isMounted;
|
||||||
|
const fiber = new Fiber(null, this, force, null, null);
|
||||||
|
Promise.resolve().then(() => {
|
||||||
|
if (__owl__.isMounted || !isMounted) {
|
||||||
|
if (fiber.isCompleted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// we are mounted (__owl__.isMounted), or if we are currently being
|
||||||
|
// mounted (!isMounted), so we call __render
|
||||||
|
this.__render(fiber);
|
||||||
|
} else {
|
||||||
|
// we were mounted when render was called, but we aren't anymore, so we
|
||||||
|
// were actually about to be unmounted ; we can thus forget about this
|
||||||
|
// fiber
|
||||||
|
fiber.isCompleted = true;
|
||||||
|
__owl__.currentFiber = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return scheduler.addFiber(fiber);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -393,41 +434,13 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* willUnmount().
|
* willUnmount().
|
||||||
*/
|
*/
|
||||||
trigger(eventType: string, payload?: any) {
|
trigger(eventType: string, payload?: any) {
|
||||||
if (this.el) {
|
this.__trigger(this, eventType, payload);
|
||||||
const ev = new CustomEvent(eventType, {
|
|
||||||
bubbles: true,
|
|
||||||
cancelable: true,
|
|
||||||
detail: payload
|
|
||||||
});
|
|
||||||
this.el.dispatchEvent(ev);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
// Private
|
// Private
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
|
||||||
* This method is a helper to create a fiber element.
|
|
||||||
*/
|
|
||||||
__createFiber(force, scope, vars, parent?: Fiber<any>): Fiber<Props> {
|
|
||||||
const fiber: Fiber<Props> = {
|
|
||||||
force,
|
|
||||||
scope,
|
|
||||||
vars,
|
|
||||||
rootFiber: null,
|
|
||||||
isCancelled: false,
|
|
||||||
component: this,
|
|
||||||
vnode: null,
|
|
||||||
patchQueue: parent ? parent.patchQueue : [],
|
|
||||||
props: this.props,
|
|
||||||
promise: null
|
|
||||||
};
|
|
||||||
fiber.rootFiber = parent ? parent.rootFiber : fiber;
|
|
||||||
this.__owl__.currentFiber = fiber;
|
|
||||||
return fiber;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Private helper to perform a full destroy, from the point of view of an Owl
|
* 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
|
* component. It does not remove the el (this is done only once on the top
|
||||||
@@ -439,7 +452,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Note that it does not call the __callWillUnmount method to avoid visiting
|
* Note that it does not call the __callWillUnmount method to avoid visiting
|
||||||
* all children many times.
|
* all children many times.
|
||||||
*/
|
*/
|
||||||
__destroy(parent: Component<any, any> | null) {
|
__destroy(parent: Component | null) {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
const isMounted = __owl__.isMounted;
|
const isMounted = __owl__.isMounted;
|
||||||
if (isMounted) {
|
if (isMounted) {
|
||||||
@@ -460,25 +473,19 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
__owl__.isDestroyed = true;
|
__owl__.isDestroyed = true;
|
||||||
delete __owl__.vnode;
|
delete __owl__.vnode;
|
||||||
|
if (__owl__.currentFiber) {
|
||||||
|
__owl__.currentFiber.isCompleted = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
__callMounted() {
|
__callMounted() {
|
||||||
const __owl__ = this.__owl__;
|
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;
|
__owl__.isMounted = true;
|
||||||
try {
|
__owl__.currentFiber = null;
|
||||||
this.mounted();
|
this.mounted();
|
||||||
if (__owl__.mountedCB) {
|
if (__owl__.mountedCB) {
|
||||||
__owl__.mountedCB();
|
__owl__.mountedCB();
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
errorHandler(e, this);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -489,6 +496,10 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
this.willUnmount();
|
this.willUnmount();
|
||||||
__owl__.isMounted = false;
|
__owl__.isMounted = false;
|
||||||
|
if (__owl__.currentFiber) {
|
||||||
|
__owl__.currentFiber.isCompleted = true;
|
||||||
|
__owl__.currentFiber.root.counter = 0;
|
||||||
|
}
|
||||||
const children = __owl__.children;
|
const children = __owl__.children;
|
||||||
for (let id in children) {
|
for (let id in children) {
|
||||||
const comp = children[id];
|
const comp = children[id];
|
||||||
@@ -497,32 +508,58 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Private trigger method, allows to choose the component which triggered
|
||||||
|
* the event in the first place
|
||||||
|
*/
|
||||||
|
__trigger(component: Component, eventType: string, payload?: any) {
|
||||||
|
if (this.el) {
|
||||||
|
const ev = new OwlEvent(component, eventType, {
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true,
|
||||||
|
detail: payload,
|
||||||
|
});
|
||||||
|
const triggerHook = this.env[portalSymbol as any];
|
||||||
|
if (triggerHook) {
|
||||||
|
triggerHook(ev);
|
||||||
|
}
|
||||||
|
this.el.dispatchEvent(ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* The __updateProps method is called by the t-component directive whenever
|
* The __updateProps method is called by the t-component directive whenever
|
||||||
* it updates a component (so, when the parent template is rerendered).
|
* it updates a component (so, when the parent template is rerendered).
|
||||||
*/
|
*/
|
||||||
async __updateProps(
|
async __updateProps(nextProps: Props, parentFiber: Fiber, scope: any): Promise<void> {
|
||||||
nextProps: Props,
|
this.__owl__.scope = scope;
|
||||||
parentFiber: Fiber<any>,
|
|
||||||
scope?: any,
|
|
||||||
vars?: any
|
|
||||||
): Promise<void> {
|
|
||||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||||
if (shouldUpdate) {
|
if (shouldUpdate) {
|
||||||
|
const __owl__ = this.__owl__;
|
||||||
|
const fiber = new Fiber(parentFiber, this, parentFiber.force, null, null);
|
||||||
|
if (!parentFiber.child) {
|
||||||
|
parentFiber.child = fiber;
|
||||||
|
} else {
|
||||||
|
parentFiber.lastChild!.sibling = fiber;
|
||||||
|
}
|
||||||
|
parentFiber.lastChild = fiber;
|
||||||
|
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
const defaultProps = (<any>this.constructor).defaultProps;
|
||||||
if (defaultProps) {
|
if (defaultProps) {
|
||||||
nextProps = this.__applyDefaultProps(nextProps, defaultProps);
|
this.__applyDefaultProps(nextProps, defaultProps);
|
||||||
|
}
|
||||||
|
if (QWeb.dev) {
|
||||||
|
QWeb.utils.validateProps(this.constructor, nextProps);
|
||||||
}
|
}
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.willUpdateProps(nextProps),
|
this.willUpdateProps(nextProps),
|
||||||
this.__owl__.willUpdatePropsCB && this.__owl__.willUpdatePropsCB(nextProps)
|
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps),
|
||||||
]);
|
]);
|
||||||
|
if (fiber.isCompleted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.props = nextProps;
|
this.props = nextProps;
|
||||||
const fiber = this.__createFiber(parentFiber.force, scope, vars, parentFiber);
|
|
||||||
fiber.patchQueue.push(fiber);
|
|
||||||
|
|
||||||
await this.__render(fiber);
|
this.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -530,112 +567,142 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Main patching method. We call the virtual dom patch method here to convert
|
* Main patching method. We call the virtual dom patch method here to convert
|
||||||
* a virtual dom vnode into some actual dom.
|
* a virtual dom vnode into some actual dom.
|
||||||
*/
|
*/
|
||||||
__patch(vnode) {
|
__patch(target: HTMLElement | VNode | DocumentFragment, vnode: VNode) {
|
||||||
const __owl__ = this.__owl__;
|
this.__owl__.vnode = patch(target as any, vnode);
|
||||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
|
||||||
__owl__.vnode = patch(target, vnode);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The __prepare method is only called by the t-component directive, when a
|
* 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
|
* subcomponent is created. It gets its scope, if any, from the
|
||||||
* parent template.
|
* parent template.
|
||||||
*/
|
*/
|
||||||
__prepare(parentFiber: Fiber<any>, scope: any, vars: any): Promise<VNode> {
|
__prepare(parentFiber: Fiber, scope: any, cb: CallableFunction): Fiber {
|
||||||
const fiber = this.__createFiber(parentFiber.force, scope, vars, parentFiber);
|
this.__owl__.scope = scope;
|
||||||
fiber.promise = this.__prepareAndRender(fiber);
|
const fiber = new Fiber(parentFiber, this, parentFiber.force, null, null);
|
||||||
return fiber.promise;
|
fiber.shouldPatch = false;
|
||||||
|
if (!parentFiber.child) {
|
||||||
|
parentFiber.child = fiber;
|
||||||
|
} else {
|
||||||
|
parentFiber.lastChild!.sibling = fiber;
|
||||||
|
}
|
||||||
|
parentFiber.lastChild = fiber;
|
||||||
|
this.__prepareAndRender(fiber, cb);
|
||||||
|
return fiber;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply the stylesheets defined by the component. Note that we need to make
|
||||||
|
* sure all inherited stylesheets are applied as well. We then delete the
|
||||||
|
* `style` key from the constructor to make sure we do not apply it again.
|
||||||
|
*/
|
||||||
|
private __applyStyles(constr) {
|
||||||
|
while (constr && constr.style) {
|
||||||
|
if (constr.hasOwnProperty("style")) {
|
||||||
|
activateSheet(constr.style, constr.name);
|
||||||
|
delete constr.style;
|
||||||
|
}
|
||||||
|
constr = constr.__proto__;
|
||||||
|
}
|
||||||
|
}
|
||||||
__getTemplate(qweb: QWeb): string {
|
__getTemplate(qweb: QWeb): string {
|
||||||
let p = (<any>this).constructor;
|
let p = (<any>this).constructor;
|
||||||
if (!p.hasOwnProperty("_template")) {
|
if (!p.hasOwnProperty("_template")) {
|
||||||
if (p.template) {
|
// here, the component and none of its superclasses defines a static `template`
|
||||||
p._template = p.template;
|
// key. So we fall back on looking for a template matching its name (or
|
||||||
} else {
|
// one of its subclass).
|
||||||
// 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;
|
let template: string = p.name;
|
||||||
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
while (!(template in qweb.templates) && p !== Component) {
|
||||||
p = p.__proto__;
|
p = p.__proto__;
|
||||||
}
|
template = p.name;
|
||||||
if (p === Component) {
|
}
|
||||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
if (p === Component) {
|
||||||
} else {
|
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
||||||
p._template = template;
|
} else {
|
||||||
}
|
p._template = template;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return p._template;
|
return p._template;
|
||||||
}
|
}
|
||||||
async __prepareAndRender(fiber: Fiber<Props>): Promise<VNode> {
|
async __prepareAndRender(fiber: Fiber, cb: CallableFunction) {
|
||||||
try {
|
try {
|
||||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
errorHandler(e, this);
|
fiber.handleError(e);
|
||||||
return Promise.resolve(h("div"));
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
const __owl__ = this.__owl__;
|
if (this.__owl__.isDestroyed) {
|
||||||
if (__owl__.isDestroyed) {
|
return Promise.resolve();
|
||||||
return Promise.resolve(h("div"));
|
}
|
||||||
|
if (!fiber.isCompleted) {
|
||||||
|
this.__render(fiber);
|
||||||
|
cb();
|
||||||
}
|
}
|
||||||
return this.__render(fiber);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
__render(fiber: Fiber<Props>): Promise<VNode> {
|
__render(fiber: Fiber) {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
const promises: Promise<void>[] = [];
|
|
||||||
if (__owl__.observer) {
|
if (__owl__.observer) {
|
||||||
__owl__.observer.allowMutations = false;
|
__owl__.observer.allowMutations = false;
|
||||||
}
|
}
|
||||||
let vnode;
|
let error;
|
||||||
try {
|
try {
|
||||||
vnode = __owl__.render!(this, {
|
let vnode = __owl__.renderFn!(this, {
|
||||||
promises,
|
|
||||||
handlers: __owl__.boundHandlers,
|
handlers: __owl__.boundHandlers,
|
||||||
fiber: fiber
|
fiber: fiber,
|
||||||
});
|
});
|
||||||
|
// we iterate over the children to detect those that no longer belong to the
|
||||||
|
// current rendering: those ones, if not mounted yet, can (and have to) be
|
||||||
|
// destroyed right now, because they are not in the DOM, and thus we won't
|
||||||
|
// be notified later on (when patching), that they are removed from the DOM
|
||||||
|
for (let childKey in __owl__.children) {
|
||||||
|
const child = __owl__.children[childKey];
|
||||||
|
const childOwl = child.__owl__;
|
||||||
|
if (!childOwl.isMounted && childOwl.parentLastFiberId < fiber.id) {
|
||||||
|
// we only do here a "soft" destroy, meaning that we leave the child
|
||||||
|
// dom node alone, without removing it. Most of the time, it does not
|
||||||
|
// matter, because the child component is already unmounted. However,
|
||||||
|
// if some of its parent have been unmounted, the child could actually
|
||||||
|
// still be attached to its parent, and this may be important if we
|
||||||
|
// want to remount the parent, because the vdom need to match the
|
||||||
|
// actual DOM
|
||||||
|
child.__destroy(childOwl.parent);
|
||||||
|
if (childOwl.pvnode) {
|
||||||
|
// we remove the key here to make sure that the patching algorithm
|
||||||
|
// is able to make the difference between this pvnode and an eventual
|
||||||
|
// other instance of the same component
|
||||||
|
delete childOwl.pvnode.key;
|
||||||
|
// Since the component has been unmounted, we do not want to actually
|
||||||
|
// call a remove hook. This is pretty important, since the t-component
|
||||||
|
// directive actually disabled it, so the vdom algorithm will just
|
||||||
|
// not remove the child elm if we don't remove the hook.
|
||||||
|
delete childOwl.pvnode.data!.hook!.remove;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!vnode) {
|
||||||
|
throw new Error(`Rendering '${this.constructor.name}' did not return anything`);
|
||||||
|
}
|
||||||
|
fiber.vnode = vnode;
|
||||||
|
// 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) {
|
||||||
|
const data = vnode.data!;
|
||||||
|
data.class = Object.assign(data.class || {}, __owl__.classObj);
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
vnode = __owl__.vnode || h("div");
|
error = e;
|
||||||
errorHandler(e, this);
|
|
||||||
}
|
}
|
||||||
fiber.vnode = vnode;
|
|
||||||
if (__owl__.observer) {
|
if (__owl__.observer) {
|
||||||
__owl__.observer.allowMutations = true;
|
__owl__.observer.allowMutations = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// this part is critical for the patching process to be done correctly. The
|
fiber.root.counter--;
|
||||||
// tricky part is that a child component can be rerendered on its own, which
|
fiber.isRendered = true;
|
||||||
// will update its own vnode representation without the knowledge of the
|
if (error) {
|
||||||
// parent component. With this, we make sure that the parent component will be
|
fiber.handleError(error);
|
||||||
// able to patch itself properly after
|
|
||||||
vnode.key = __owl__.id;
|
|
||||||
|
|
||||||
// we applly 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.all(promises).then(() => vnode);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Only called by qweb t-component directive
|
|
||||||
*/
|
|
||||||
__mount(vnode: VNode, elm: HTMLElement): 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);
|
|
||||||
if (__owl__.parent!.__owl__.isMounted && !__owl__.isMounted) {
|
|
||||||
this.__callMounted();
|
|
||||||
}
|
|
||||||
return __owl__.vnode;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -652,84 +719,13 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* Apply default props (only top level).
|
* Apply default props (only top level).
|
||||||
*
|
*
|
||||||
* Note that this method does not modify in place the props, it returns a new
|
* Note that this method does modify in place the props
|
||||||
* prop object
|
|
||||||
*/
|
*/
|
||||||
__applyDefaultProps(props: Object | undefined, defaultProps: Object): Props {
|
__applyDefaultProps(props: Object, defaultProps: Object) {
|
||||||
props = props ? Object.assign({}, props) : {};
|
|
||||||
for (let propName in defaultProps) {
|
for (let propName in defaultProps) {
|
||||||
if (props![propName] === undefined) {
|
if (props![propName] === undefined) {
|
||||||
props![propName] = defaultProps[propName];
|
props![propName] = defaultProps[propName];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return <Props>props;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
*/
|
|
||||||
__applyPatchQueue(fiber: Fiber<Props>) {
|
|
||||||
const patchQueue = fiber.patchQueue;
|
|
||||||
let component: Component<any, any> = this;
|
|
||||||
try {
|
|
||||||
const patchLen = patchQueue.length;
|
|
||||||
for (let i = 0; i < patchLen; i++) {
|
|
||||||
component = patchQueue[i].component;
|
|
||||||
if (component.__owl__.willPatchCB) {
|
|
||||||
component.__owl__.willPatchCB();
|
|
||||||
}
|
|
||||||
component.willPatch();
|
|
||||||
}
|
|
||||||
for (let i = 0; i < patchLen; i++) {
|
|
||||||
const fiber = patchQueue[i];
|
|
||||||
component = fiber.component;
|
|
||||||
component.__patch(fiber.vnode);
|
|
||||||
}
|
|
||||||
for (let i = patchLen - 1; i >= 0; i--) {
|
|
||||||
component = patchQueue[i].component;
|
|
||||||
component.patched();
|
|
||||||
if (component.__owl__.patchedCB) {
|
|
||||||
component.__owl__.patchedCB();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
errorHandler(e, component);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// Error handling
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
function errorHandler(error: Error, component: Component<any, any>) {
|
|
||||||
let canCatch = false;
|
|
||||||
let qweb = component.env.qweb;
|
|
||||||
let root = component;
|
|
||||||
while (component && !(canCatch = component.catchError !== Component.prototype.catchError)) {
|
|
||||||
root = component;
|
|
||||||
component = component.__owl__.parent!;
|
|
||||||
}
|
|
||||||
console.error(error);
|
|
||||||
// we trigger error on QWeb so it can be logged/handled
|
|
||||||
qweb.trigger("error", error);
|
|
||||||
|
|
||||||
if (canCatch) {
|
|
||||||
setTimeout(() => {
|
|
||||||
component.catchError(error);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
root.destroy();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+148
-181
@@ -1,13 +1,13 @@
|
|||||||
import { QWeb } from "../qweb/index";
|
import { QWeb } from "../qweb/index";
|
||||||
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
||||||
import { MODS_CODE } from "../qweb/extensions";
|
import { makeHandlerCode, MODS_CODE } from "../qweb/extensions";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-component
|
// t-component
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
||||||
self: "if (e.target !== vn.elm) {return}"
|
self: "if (e.target !== vn.elm) {return}",
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
||||||
@@ -18,11 +18,31 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
|||||||
},
|
},
|
||||||
set(val) {
|
set(val) {
|
||||||
source[k] = val;
|
source[k] = val;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
QWeb.utils.assignHooks = function assignHooks(dataObj, hooks) {
|
||||||
|
if ("hook" in dataObj) {
|
||||||
|
const hookObject = dataObj.hook;
|
||||||
|
for (let name in hooks) {
|
||||||
|
const current = hookObject[name];
|
||||||
|
const fn = hooks[name];
|
||||||
|
if (current) {
|
||||||
|
hookObject[name] = (...args) => {
|
||||||
|
current(...args);
|
||||||
|
fn(...args);
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
hookObject[name] = fn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dataObj.hook = hooks;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The t-component directive is certainly a complicated and hard to maintain piece
|
* 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
|
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
||||||
@@ -186,20 +206,18 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
|||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "component",
|
name: "component",
|
||||||
extraNames: ["props", "keepalive", "asyncroot"],
|
extraNames: ["props"],
|
||||||
priority: 100,
|
priority: 100,
|
||||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||||
ctx.addLine("//COMPONENT");
|
ctx.addLine(`// Component '${value}'`);
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
ctx.rootContext.shouldDefineQWeb = true;
|
ctx.rootContext.shouldDefineQWeb = true;
|
||||||
ctx.rootContext.shouldDefineParent = true;
|
ctx.rootContext.shouldDefineParent = true;
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||||
let async = node.getAttribute("t-asyncroot") ? true : false;
|
|
||||||
|
|
||||||
// t-on- events and t-transition
|
// t-on- events and t-transition
|
||||||
const events: [string, string[], string, string][] = [];
|
const events: [string, string][] = [];
|
||||||
let transition: string = "";
|
let transition: string = "";
|
||||||
const attributes = (<Element>node).attributes;
|
const attributes = (<Element>node).attributes;
|
||||||
const props: { [key: string]: string } = {};
|
const props: { [key: string]: string } = {};
|
||||||
@@ -207,58 +225,24 @@ QWeb.addDirective({
|
|||||||
const name = attributes[i].name;
|
const name = attributes[i].name;
|
||||||
const value = attributes[i].textContent!;
|
const value = attributes[i].textContent!;
|
||||||
if (name.startsWith("t-on-")) {
|
if (name.startsWith("t-on-")) {
|
||||||
const [eventName, ...mods] = name.slice(5).split(".");
|
events.push([name, value]);
|
||||||
let extraArgs;
|
|
||||||
let handlerName = value.replace(/\(.*\)/, function(args) {
|
|
||||||
extraArgs = args.slice(1, -1);
|
|
||||||
return "";
|
|
||||||
});
|
|
||||||
events.push([eventName, mods, handlerName, extraArgs]);
|
|
||||||
} else if (name === "t-transition") {
|
} else if (name === "t-transition") {
|
||||||
transition = value;
|
transition = value;
|
||||||
} else if (!name.startsWith("t-")) {
|
} else if (!name.startsWith("t-")) {
|
||||||
if (name !== "class" && name !== "style") {
|
if (name !== "class" && name !== "style") {
|
||||||
// this is a prop!
|
// this is a prop!
|
||||||
props[name] = ctx.formatExpression(value);
|
props[name] = ctx.formatExpression(value) || "undefined";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let key = node.getAttribute("t-key");
|
|
||||||
if (key) {
|
|
||||||
key = ctx.formatExpression(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
// computing the props string representing the props object
|
// computing the props string representing the props object
|
||||||
let propStr = Object.keys(props)
|
let propStr = Object.keys(props)
|
||||||
.map(k => k + ":" + props[k])
|
.map((k) => k + ":" + props[k])
|
||||||
.join(",");
|
.join(",");
|
||||||
let dummyID = ctx.generateID();
|
|
||||||
let defID = ctx.generateID();
|
|
||||||
let componentID = ctx.generateID();
|
let componentID = ctx.generateID();
|
||||||
let keyID = key && ctx.generateID();
|
|
||||||
if (key) {
|
|
||||||
// we bind a variable to the key (could be a complex expression, so we
|
|
||||||
// want to evaluate it only once)
|
|
||||||
ctx.addLine(`let key${keyID} = 'key' + ${key};`);
|
|
||||||
}
|
|
||||||
ctx.addLine(`let def${defID};`);
|
|
||||||
let templateID = key
|
|
||||||
? `key${keyID}`
|
|
||||||
: ctx.inLoop
|
|
||||||
? ctx.currentKey
|
|
||||||
? `String(${ctx.currentKey} + '_k_' + i + '_c_' + ${componentID} )`
|
|
||||||
: `String(-${componentID} - i)`
|
|
||||||
: String(componentID);
|
|
||||||
if (ctx.allowMultipleRoots) {
|
|
||||||
templateID = `"_slot_${templateID}"`;
|
|
||||||
}
|
|
||||||
if (key || ctx.inLoop) {
|
|
||||||
let id = ctx.generateID();
|
|
||||||
ctx.addLine(`let templateId${id} = ${templateID};`);
|
|
||||||
templateID = `templateId${id}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const templateKey = ctx.generateTemplateKey();
|
||||||
let ref = node.getAttribute("t-ref");
|
let ref = node.getAttribute("t-ref");
|
||||||
let refExpr = "";
|
let refExpr = "";
|
||||||
let refKey: string = "";
|
let refKey: string = "";
|
||||||
@@ -268,18 +252,15 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
||||||
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
||||||
}
|
}
|
||||||
let transitionsInsertCode = "";
|
let finalizeComponentCode = `w${componentID}.destroy();`;
|
||||||
if (transition) {
|
if (ref) {
|
||||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
|
||||||
}
|
|
||||||
let finalizeComponentCode = `w${componentID}.${keepAlive ? "unmount" : "destroy"}();`;
|
|
||||||
if (ref && !keepAlive) {
|
|
||||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||||
}
|
}
|
||||||
if (transition) {
|
if (transition) {
|
||||||
finalizeComponentCode = `let finalize = () => {
|
finalizeComponentCode = `let finalize = () => {
|
||||||
${finalizeComponentCode}
|
${finalizeComponentCode}
|
||||||
};
|
};
|
||||||
|
delete w${componentID}.__owl__.transitionInserted;
|
||||||
utils.transitionRemove(vn, '${transition}', finalize);`;
|
utils.transitionRemove(vn, '${transition}', finalize);`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,7 +280,7 @@ QWeb.addDirective({
|
|||||||
let classDef = classAttr
|
let classDef = classAttr
|
||||||
.trim()
|
.trim()
|
||||||
.split(/\s+/)
|
.split(/\s+/)
|
||||||
.map(a => `'${a}':true`)
|
.map((a) => `'${a}':true`)
|
||||||
.join(",");
|
.join(",");
|
||||||
classObj = `_${ctx.generateID()}`;
|
classObj = `_${ctx.generateID()}`;
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||||
@@ -317,67 +298,38 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let eventsCode = events
|
let eventsCode = events
|
||||||
.map(function([eventName, mods, handlerName, extraArgs]) {
|
.map(function ([name, value]) {
|
||||||
let params = "owner";
|
const capture = name.match(/\.capture/);
|
||||||
if (extraArgs) {
|
name = capture ? name.replace(/\.capture/, "") : name;
|
||||||
if (ctx.inLoop) {
|
const { event, handler } = makeHandlerCode(
|
||||||
let argId = ctx.generateID();
|
ctx,
|
||||||
// we need to evaluate the arguments now, because the handler will
|
name,
|
||||||
// be set asynchronously later when the widget is ready, and the
|
value,
|
||||||
// context might be different.
|
false,
|
||||||
ctx.addLine(`let arg${argId} = ${ctx.formatExpression(extraArgs)};`);
|
T_COMPONENT_MODS_CODE
|
||||||
params = `owner, arg${argId}`;
|
);
|
||||||
} else {
|
if (capture) {
|
||||||
params = `owner, ${ctx.formatExpression(extraArgs)}`;
|
return `vn.elm.addEventListener('${event}', ${handler}, true);`;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let handler;
|
return `vn.elm.addEventListener('${event}', ${handler});`;
|
||||||
if (mods.length > 0) {
|
|
||||||
handler = `function (e) {`;
|
|
||||||
handler += mods
|
|
||||||
.map(function(mod) {
|
|
||||||
return T_COMPONENT_MODS_CODE[mod];
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
handler += `owner['${handlerName}'].call(${params}, e);}`;
|
|
||||||
} else {
|
|
||||||
handler = `owner['${handlerName}'].bind(${params})`;
|
|
||||||
}
|
|
||||||
return `vn.elm.addEventListener('${eventName}', ${handler});`;
|
|
||||||
})
|
})
|
||||||
.join("");
|
.join("");
|
||||||
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
||||||
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
||||||
createHook = `vnode.data.hook = {create(_, vn){${styleCode}${eventsCode}}};`;
|
createHook = `utils.assignHooks(vnode.data, {create(_, vn){${styleCode}${eventsCode}}});`;
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`let w${componentID} = ${templateID} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateID}]] : false;`
|
`let w${componentID} = ${templateKey} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateKey}]] : false;`
|
||||||
);
|
);
|
||||||
if (ctx.parentNode) {
|
let shouldProxy = !ctx.parentNode;
|
||||||
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
|
if (shouldProxy) {
|
||||||
}
|
let id = ctx.generateID();
|
||||||
let shouldProxy = false;
|
ctx.rootContext.rootNode = id;
|
||||||
if (async || keepAlive) {
|
shouldProxy = true;
|
||||||
ctx.addLine(
|
ctx.rootContext.shouldDefineResult = true;
|
||||||
`const fiber${componentID} = Object.assign(Object.create(extra.fiber), {patchQueue: []});`
|
ctx.addLine(`let vn${id} = {};`);
|
||||||
);
|
ctx.addLine(`result = vn${id};`);
|
||||||
}
|
|
||||||
if (async) {
|
|
||||||
ctx.addLine(
|
|
||||||
`c${ctx.parentNode}.push(w${componentID} && w${componentID}.__owl__.pvnode || null);`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
if (ctx.parentNode) {
|
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(null);`);
|
|
||||||
} else {
|
|
||||||
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) {
|
if (hasDynamicProps) {
|
||||||
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
||||||
@@ -388,17 +340,40 @@ QWeb.addDirective({
|
|||||||
ctx.addIf(
|
ctx.addIf(
|
||||||
`w${componentID} && w${componentID}.__owl__.currentFiber && !w${componentID}.__owl__.vnode`
|
`w${componentID} && w${componentID}.__owl__.currentFiber && !w${componentID}.__owl__.vnode`
|
||||||
);
|
);
|
||||||
ctx.addIf(
|
|
||||||
`utils.shallowEqual(props${componentID}, w${componentID}.__owl__.currentFiber.props)`
|
|
||||||
);
|
|
||||||
ctx.addLine(`def${defID} = w${componentID}.__owl__.currentFiber.promise;`);
|
|
||||||
ctx.addElse();
|
|
||||||
ctx.addLine(`w${componentID}.destroy();`);
|
ctx.addLine(`w${componentID}.destroy();`);
|
||||||
ctx.addLine(`w${componentID} = false;`);
|
ctx.addLine(`w${componentID} = false;`);
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
ctx.closeIf();
|
|
||||||
|
|
||||||
ctx.addIf(`!w${componentID}`);
|
let registerCode = "";
|
||||||
|
if (shouldProxy) {
|
||||||
|
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SLOTS
|
||||||
|
const hasSlots = node.childNodes.length;
|
||||||
|
|
||||||
|
let scope = hasSlots ? `Object.assign(Object.create(context), scope)` : "undefined";
|
||||||
|
|
||||||
|
ctx.addIf(`w${componentID}`);
|
||||||
|
|
||||||
|
// need to update component
|
||||||
|
let styleCode = "";
|
||||||
|
if (tattStyle) {
|
||||||
|
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||||
|
}
|
||||||
|
ctx.addLine(
|
||||||
|
`w${componentID}.__updateProps(props${componentID}, extra.fiber, ${scope})${styleCode};`
|
||||||
|
);
|
||||||
|
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
||||||
|
if (registerCode) {
|
||||||
|
ctx.addLine(registerCode);
|
||||||
|
}
|
||||||
|
if (ctx.parentNode) {
|
||||||
|
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.addElse();
|
||||||
|
|
||||||
// new component
|
// new component
|
||||||
let dynamicFallback = "";
|
let dynamicFallback = "";
|
||||||
if (!value.match(INTERP_REGEXP)) {
|
if (!value.match(INTERP_REGEXP)) {
|
||||||
@@ -414,33 +389,63 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
||||||
);
|
);
|
||||||
if (QWeb.dev) {
|
|
||||||
ctx.addLine(`utils.validateProps(W${componentID}, props${componentID})`);
|
|
||||||
}
|
|
||||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
||||||
ctx.addLine(`parent.__owl__.cmap[${templateID}] = w${componentID}.__owl__.id;`);
|
if (transition) {
|
||||||
|
ctx.addLine(`const __patch${componentID} = w${componentID}.__patch;`);
|
||||||
|
ctx.addLine(
|
||||||
|
`w${componentID}.__patch = (t, vn) => {__patch${componentID}.call(w${componentID}, t, vn); if(!w${componentID}.__owl__.transitionInserted){w${componentID}.__owl__.transitionInserted = true;utils.transitionInsert(w${componentID}.__owl__.vnode, '${transition}');}};`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ctx.addLine(`parent.__owl__.cmap[${templateKey}] = w${componentID}.__owl__.id;`);
|
||||||
|
|
||||||
// SLOTS
|
|
||||||
const varDefs: string[] = [];
|
|
||||||
const hasSlots = node.childNodes.length;
|
|
||||||
if (hasSlots) {
|
if (hasSlots) {
|
||||||
ctx.rootContext.shouldTrackScope = true;
|
const clone = <Element>node.cloneNode(true);
|
||||||
for (let v of Object.values(ctx.variables)) {
|
|
||||||
if (v["id"]) {
|
// The next code is a fallback for compatibility reason. It accepts t-set
|
||||||
varDefs.push(v["id"]);
|
// elements that are direct children with a non empty body as nodes defining
|
||||||
|
// the content of a slot.
|
||||||
|
//
|
||||||
|
// This is wrong, but is necessary to prevent breaking all existing Owl
|
||||||
|
// code using slots. This will be removed in v2.0 someday. Meanwhile,
|
||||||
|
// please use t-set-slot everywhere you need to set the content of a
|
||||||
|
// slot.
|
||||||
|
for (let node of clone.children) {
|
||||||
|
if (node.hasAttribute("t-set") && node.hasChildNodes()) {
|
||||||
|
node.setAttribute("t-set-slot", node.getAttribute("t-set")!);
|
||||||
|
node.removeAttribute("t-set");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
|
||||||
const clone = <Element>node.cloneNode(true);
|
const slotNames = new Set<string>();
|
||||||
const slotNodes = clone.querySelectorAll("[t-set]");
|
|
||||||
const slotId = QWeb.nextSlotId++;
|
const slotId = QWeb.nextSlotId++;
|
||||||
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
||||||
if (slotNodes.length) {
|
if (slotNodes.length) {
|
||||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
||||||
const slotNode = slotNodes[i];
|
const slotNode = slotNodes[i];
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isInSubComponent) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let key = slotNode.getAttribute("t-set-slot")!;
|
||||||
|
if (slotNames.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
slotNames.add(key);
|
||||||
|
slotNode.removeAttribute("t-set-slot");
|
||||||
slotNode.parentElement!.removeChild(slotNode);
|
slotNode.parentElement!.removeChild(slotNode);
|
||||||
const key = slotNode.getAttribute("t-set")!;
|
|
||||||
slotNode.removeAttribute("t-set");
|
|
||||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
||||||
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
||||||
}
|
}
|
||||||
@@ -455,68 +460,30 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let scopeVars;
|
ctx.addLine(
|
||||||
if (hasSlots) {
|
`let fiber = w${componentID}.__prepare(extra.fiber, ${scope}, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||||
let scope = ctx.scopeVars.length ? `Object.assign({}, scope)` : `{}`;
|
);
|
||||||
let vars = varDefs.length ? `{${varDefs.join(",")}}` : "undefined";
|
|
||||||
scopeVars = `${scope}, ${vars}`;
|
|
||||||
} else {
|
|
||||||
scopeVars = "undefined, undefined";
|
|
||||||
}
|
|
||||||
ctx.addLine(`def${defID} = w${componentID}.__prepare(extra.fiber, ${scopeVars});`);
|
|
||||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||||
let registerCode = `c${ctx.parentNode}[_${dummyID}_index]=pvnode;`;
|
const insertHook = refExpr ? `insert(vn) {${refExpr}},` : "";
|
||||||
if (shouldProxy) {
|
|
||||||
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`def${defID} = def${defID}.then(vnode=>{if (w${componentID}.__owl__.isDestroyed){return}${createHook}let pvnode=h(vnode.sel, {key: ${templateID}, hook: {insert(vn) {let nvn=w${componentID}.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeComponentCode}}}});${registerCode}w${componentID}.__owl__.pvnode = pvnode;});`
|
`let pvnode = h('dummy', {key: ${templateKey}, hook: {${insertHook}remove() {},destroy(vn) {${finalizeComponentCode}}}});`
|
||||||
);
|
);
|
||||||
|
if (registerCode) {
|
||||||
|
ctx.addLine(registerCode);
|
||||||
|
}
|
||||||
|
if (ctx.parentNode) {
|
||||||
|
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
||||||
|
}
|
||||||
|
ctx.addLine(`w${componentID}.__owl__.pvnode = pvnode;`);
|
||||||
|
|
||||||
ctx.addElse();
|
|
||||||
// need to update component
|
|
||||||
let patchQueueCode = async || 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}`;
|
|
||||||
}
|
|
||||||
if (QWeb.dev) {
|
|
||||||
ctx.addLine(`utils.validateProps(w${componentID}.constructor, props${componentID})`);
|
|
||||||
}
|
|
||||||
ctx.addLine(
|
|
||||||
`def${defID} = def${defID} || w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
|
|
||||||
", " + scopeVars});`
|
|
||||||
);
|
|
||||||
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(
|
|
||||||
`def${defID} = def${defID}.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};${
|
|
||||||
tattStyle ? `w${componentID}.el.style=${tattStyle};` : ""
|
|
||||||
}let pvnode=w${componentID}.__owl__.pvnode;${keepAliveCode}${registerCode}});`
|
|
||||||
);
|
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
|
|
||||||
if (classObj) {
|
if (classObj) {
|
||||||
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (async) {
|
ctx.addLine(`w${componentID}.__owl__.parentLastFiberId = extra.fiber.id;`);
|
||||||
ctx.addLine(
|
|
||||||
`def${defID}.then(w${componentID}.__applyPatchQueue.bind(w${componentID}, fiber${componentID}));`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ctx.addLine(`extra.promises.push(def${defID});`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.hasAttribute("t-if") || node.hasAttribute("t-else") || node.hasAttribute("t-elif")) {
|
|
||||||
ctx.closeIf();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,332 @@
|
|||||||
|
import { h, VNode } from "../vdom/index";
|
||||||
|
import { Component, MountPosition } from "./component";
|
||||||
|
import { scheduler } from "./scheduler";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
static nextId: number = 1;
|
||||||
|
id: number = Fiber.nextId++;
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
// isCompleted means that the rendering corresponding to this fiber's work is
|
||||||
|
// done, either because the component has been mounted or patched, or because
|
||||||
|
// fiber has been cancelled.
|
||||||
|
isCompleted: 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;
|
||||||
|
|
||||||
|
target: HTMLElement | DocumentFragment | null;
|
||||||
|
position: MountPosition | null;
|
||||||
|
|
||||||
|
scope: any;
|
||||||
|
|
||||||
|
component: Component;
|
||||||
|
vnode: VNode | null = null;
|
||||||
|
|
||||||
|
root: Fiber;
|
||||||
|
child: Fiber | null = null;
|
||||||
|
sibling: Fiber | null = null;
|
||||||
|
lastChild: Fiber | null = null;
|
||||||
|
parent: Fiber | null = null;
|
||||||
|
|
||||||
|
error?: Error;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
parent: Fiber | null,
|
||||||
|
component: Component,
|
||||||
|
force: boolean,
|
||||||
|
target: HTMLElement | DocumentFragment | null,
|
||||||
|
position: MountPosition | null
|
||||||
|
) {
|
||||||
|
this.component = component;
|
||||||
|
this.force = force;
|
||||||
|
this.target = target;
|
||||||
|
this.position = position;
|
||||||
|
|
||||||
|
const __owl__ = component.__owl__;
|
||||||
|
this.scope = __owl__.scope;
|
||||||
|
|
||||||
|
this.root = parent ? parent.root : this;
|
||||||
|
this.parent = parent;
|
||||||
|
|
||||||
|
let oldFiber = __owl__.currentFiber;
|
||||||
|
if (oldFiber && !oldFiber.isCompleted) {
|
||||||
|
if (oldFiber.root === oldFiber && !parent) {
|
||||||
|
// both oldFiber and this fiber are root fibers
|
||||||
|
this._reuseFiber(oldFiber);
|
||||||
|
return oldFiber;
|
||||||
|
} else {
|
||||||
|
this._remapFiber(oldFiber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.root.counter++;
|
||||||
|
|
||||||
|
__owl__.currentFiber = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the oldFiber is not completed yet, and both oldFiber and this fiber
|
||||||
|
* are root fibers, we want to reuse the oldFiber instead of creating a new
|
||||||
|
* one. Doing so will guarantee that the initiator(s) of those renderings will
|
||||||
|
* be notified (the promise will resolve) when the last rendering will be done.
|
||||||
|
*
|
||||||
|
* This function thus assumes that oldFiber is a root fiber.
|
||||||
|
*/
|
||||||
|
_reuseFiber(oldFiber: Fiber) {
|
||||||
|
oldFiber.cancel(); // cancel children fibers
|
||||||
|
oldFiber.isCompleted = false; // keep the root fiber alive
|
||||||
|
oldFiber.isRendered = false; // the fiber has to be re-rendered
|
||||||
|
if (oldFiber.child) {
|
||||||
|
// remove relation to children
|
||||||
|
oldFiber.child.parent = null;
|
||||||
|
oldFiber.child = null;
|
||||||
|
oldFiber.lastChild = null;
|
||||||
|
}
|
||||||
|
oldFiber.counter = 1; // re-initialize counter
|
||||||
|
oldFiber.id = Fiber.nextId++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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();
|
||||||
|
this.shouldPatch = oldFiber.shouldPatch;
|
||||||
|
if (oldFiber === oldFiber.root) {
|
||||||
|
oldFiber.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.lastChild === oldFiber) {
|
||||||
|
this.parent.lastChild = this;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Successfully complete the work of the fiber: call the mount or patch hooks
|
||||||
|
* and patch the DOM. This function is called once the fiber and its children
|
||||||
|
* are ready, and the scheduler decides to process it.
|
||||||
|
*/
|
||||||
|
complete() {
|
||||||
|
let component = this.component;
|
||||||
|
this.isCompleted = true;
|
||||||
|
if (!this.target && !component.__owl__.isMounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// build patchQueue
|
||||||
|
const patchQueue: Fiber[] = [];
|
||||||
|
const doWork: (Fiber) => Fiber | null = function (f) {
|
||||||
|
patchQueue.push(f);
|
||||||
|
return f.child;
|
||||||
|
};
|
||||||
|
this._walk(doWork);
|
||||||
|
const patchLen = patchQueue.length;
|
||||||
|
|
||||||
|
// call willPatch hook on each fiber of patchQueue
|
||||||
|
for (let i = 0; i < patchLen; i++) {
|
||||||
|
const fiber = patchQueue[i];
|
||||||
|
if (fiber.shouldPatch) {
|
||||||
|
component = fiber.component;
|
||||||
|
if (component.__owl__.willPatchCB) {
|
||||||
|
component.__owl__.willPatchCB();
|
||||||
|
}
|
||||||
|
component.willPatch();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// call __patch on each fiber of (reversed) patchQueue
|
||||||
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
|
const fiber = patchQueue[i];
|
||||||
|
component = fiber.component;
|
||||||
|
if (fiber.target && i === 0) {
|
||||||
|
let target;
|
||||||
|
if (fiber.position === "self") {
|
||||||
|
target = fiber.target;
|
||||||
|
if ((target as HTMLElement).tagName.toLowerCase() !== fiber.vnode!.sel) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot attach '${component.constructor.name}' to target node (not same tag name)`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// In self mode, we *know* we are to take possession of the target
|
||||||
|
// Hence we manually create the corresponding VNode and copy the "key" in data
|
||||||
|
const selfVnodeData = fiber.vnode!.data ? { key: fiber.vnode!.data.key } : {};
|
||||||
|
const selfVnode = h(fiber.vnode!.sel, selfVnodeData);
|
||||||
|
selfVnode.elm = target;
|
||||||
|
target = selfVnode;
|
||||||
|
} else {
|
||||||
|
target = component.__owl__.vnode || document.createElement(fiber.vnode!.sel!);
|
||||||
|
}
|
||||||
|
component.__patch(target!, fiber.vnode!);
|
||||||
|
} else {
|
||||||
|
if (fiber.shouldPatch) {
|
||||||
|
component.__patch(component.__owl__.vnode!, fiber.vnode!);
|
||||||
|
// When updating a Component's props (in directive),
|
||||||
|
// the component has a pvnode AND should be patched.
|
||||||
|
// However, its pvnode.elm may have changed if it is a High Order Component
|
||||||
|
if (component.__owl__.pvnode) {
|
||||||
|
component.__owl__.pvnode.elm = component.__owl__.vnode!.elm;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
component.__patch(document.createElement(fiber.vnode!.sel!), fiber.vnode!);
|
||||||
|
component.__owl__.pvnode!.elm = component.__owl__.vnode!.elm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fiber === component.__owl__.currentFiber) {
|
||||||
|
component.__owl__.currentFiber = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert into the DOM (mount case)
|
||||||
|
let inDOM = false;
|
||||||
|
if (this.target) {
|
||||||
|
switch (this.position) {
|
||||||
|
case "first-child":
|
||||||
|
this.target.prepend(this.component.el!);
|
||||||
|
break;
|
||||||
|
case "last-child":
|
||||||
|
this.target.appendChild(this.component.el!);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
inDOM = document.body.contains(this.component.el);
|
||||||
|
this.component.env.qweb.trigger("dom-appended");
|
||||||
|
}
|
||||||
|
|
||||||
|
// call patched/mounted hook on each fiber of (reversed) patchQueue
|
||||||
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
|
const fiber = patchQueue[i];
|
||||||
|
component = fiber.component;
|
||||||
|
if (fiber.shouldPatch && !this.target) {
|
||||||
|
component.patched();
|
||||||
|
if (component.__owl__.patchedCB) {
|
||||||
|
component.__owl__.patchedCB();
|
||||||
|
}
|
||||||
|
} else if (this.target ? inDOM : true) {
|
||||||
|
component.__callMounted();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancel a fiber and all its children.
|
||||||
|
*/
|
||||||
|
cancel() {
|
||||||
|
this._walk((f) => {
|
||||||
|
if (!f.isRendered) {
|
||||||
|
f.root.counter--;
|
||||||
|
}
|
||||||
|
f.isCompleted = 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 component = this.component;
|
||||||
|
this.vnode = component.__owl__.vnode || h("div");
|
||||||
|
|
||||||
|
const qweb = component.env.qweb;
|
||||||
|
let root = component;
|
||||||
|
let canCatch = false;
|
||||||
|
while (component && !(canCatch = !!component.catchError)) {
|
||||||
|
root = component;
|
||||||
|
component = component.__owl__.parent!;
|
||||||
|
}
|
||||||
|
qweb.trigger("error", error);
|
||||||
|
|
||||||
|
if (canCatch) {
|
||||||
|
component.catchError!(error);
|
||||||
|
} else {
|
||||||
|
// the 3 next lines aim to mark the root fiber as being in error, and
|
||||||
|
// to force it to end, without waiting for its children
|
||||||
|
this.root.counter = 0;
|
||||||
|
this.root.error = error;
|
||||||
|
scheduler.flush();
|
||||||
|
root.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ import { QWeb } from "../qweb/index";
|
|||||||
* This is why it is only done in 'dev' mode.
|
* This is why it is only done in 'dev' mode.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
QWeb.utils.validateProps = function(Widget, props: Object) {
|
QWeb.utils.validateProps = function (Widget, props: Object) {
|
||||||
const propsDef = (<any>Widget).props;
|
const propsDef = (<any>Widget).props;
|
||||||
if (propsDef instanceof Array) {
|
if (propsDef instanceof Array) {
|
||||||
// list of strings (prop names)
|
// list of strings (prop names)
|
||||||
@@ -21,7 +21,7 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
|
|||||||
// optional prop
|
// optional prop
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!props[propName]) {
|
if (!(propName in props)) {
|
||||||
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -37,12 +37,18 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
|
|||||||
if (propsDef[propName] && !propsDef[propName].optional) {
|
if (propsDef[propName] && !propsDef[propName].optional) {
|
||||||
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
||||||
} else {
|
} else {
|
||||||
break;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let isValid = isValidProp(props[propName], propsDef[propName]);
|
let isValid;
|
||||||
|
try {
|
||||||
|
isValid = isValidProp(props[propName], propsDef[propName]);
|
||||||
|
} catch (e) {
|
||||||
|
e.message = `Invalid prop '${propName}' in component ${Widget.name} (${e.message})`;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
throw new Error(`Props '${propName}' of invalid type in component '${Widget.name}'`);
|
throw new Error(`Invalid Prop '${propName}' in component '${Widget.name}'`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (let propName in props) {
|
for (let propName in props) {
|
||||||
@@ -80,17 +86,30 @@ function isValidProp(prop, propDef): boolean {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
// propsDef is an object
|
// propsDef is an object
|
||||||
let result = isValidProp(prop, propDef.type);
|
if (propDef.optional && prop === undefined) {
|
||||||
if (propDef.type === Array) {
|
return true;
|
||||||
|
}
|
||||||
|
let result = propDef.type ? isValidProp(prop, propDef.type) : true;
|
||||||
|
if (propDef.validate) {
|
||||||
|
result = result && propDef.validate(prop);
|
||||||
|
}
|
||||||
|
if (propDef.type === Array && propDef.element) {
|
||||||
for (let i = 0, iLen = prop.length; i < iLen; i++) {
|
for (let i = 0, iLen = prop.length; i < iLen; i++) {
|
||||||
result = result && isValidProp(prop[i], propDef.element);
|
result = result && isValidProp(prop[i], propDef.element);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (propDef.type === Object) {
|
if (propDef.type === Object && propDef.shape) {
|
||||||
const shape = propDef.shape;
|
const shape = propDef.shape;
|
||||||
for (let key in shape) {
|
for (let key in shape) {
|
||||||
result = result && isValidProp(prop[key], shape[key]);
|
result = result && isValidProp(prop[key], shape[key]);
|
||||||
}
|
}
|
||||||
|
if (result) {
|
||||||
|
for (let propName in prop) {
|
||||||
|
if (!(propName in shape)) {
|
||||||
|
throw new Error(`unknown prop '${propName}'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { Fiber } from "./fiber";
|
||||||
|
import { browser } from "../browser";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Owl Scheduler Class
|
||||||
|
*
|
||||||
|
* 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 {
|
||||||
|
tasks: Task[] = [];
|
||||||
|
isRunning: boolean = false;
|
||||||
|
requestAnimationFrame: Window["requestAnimationFrame"];
|
||||||
|
|
||||||
|
constructor(requestAnimationFrame: Window["requestAnimationFrame"]) {
|
||||||
|
this.requestAnimationFrame = requestAnimationFrame;
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
this.isRunning = true;
|
||||||
|
this.scheduleTasks();
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.isRunning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
addFiber(fiber: Fiber): Promise<void> {
|
||||||
|
// if the fiber was remapped into a larger rendering fiber, it may not be a
|
||||||
|
// root fiber. But we only want to register root fibers
|
||||||
|
fiber = fiber.root;
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (fiber.error) {
|
||||||
|
return reject(fiber.error);
|
||||||
|
}
|
||||||
|
this.tasks.push({
|
||||||
|
fiber,
|
||||||
|
callback: () => {
|
||||||
|
if (fiber.error) {
|
||||||
|
return reject(fiber.error);
|
||||||
|
}
|
||||||
|
resolve();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!this.isRunning) {
|
||||||
|
this.start();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
rejectFiber(fiber: Fiber, reason: string) {
|
||||||
|
fiber = fiber.root;
|
||||||
|
const index = this.tasks.findIndex((t) => t.fiber === fiber);
|
||||||
|
if (index >= 0) {
|
||||||
|
const [task] = this.tasks.splice(index, 1);
|
||||||
|
fiber.cancel();
|
||||||
|
fiber.error = new Error(reason);
|
||||||
|
task.callback();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process all current tasks. This only applies to the fibers that are ready.
|
||||||
|
* Other tasks are left unchanged.
|
||||||
|
*/
|
||||||
|
flush() {
|
||||||
|
let tasks = this.tasks;
|
||||||
|
this.tasks = [];
|
||||||
|
tasks = tasks.filter((task) => {
|
||||||
|
if (task.fiber.isCompleted) {
|
||||||
|
task.callback();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (task.fiber.counter === 0) {
|
||||||
|
if (!task.fiber.error) {
|
||||||
|
try {
|
||||||
|
task.fiber.complete();
|
||||||
|
} catch (e) {
|
||||||
|
task.fiber.handleError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.callback();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
this.tasks = tasks.concat(this.tasks);
|
||||||
|
if (this.tasks.length === 0) {
|
||||||
|
this.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleTasks() {
|
||||||
|
this.requestAnimationFrame(() => {
|
||||||
|
this.flush();
|
||||||
|
if (this.isRunning) {
|
||||||
|
this.scheduleTasks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const scheduler = new Scheduler(browser.requestAnimationFrame);
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* Owl Style System
|
||||||
|
*
|
||||||
|
* This files contains the Owl code related to processing (extended) css strings
|
||||||
|
* and creating/adding <style> tags to the document head.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const STYLESHEETS: { [id: string]: HTMLStyleElement } = {};
|
||||||
|
|
||||||
|
export function processSheet(str: string): string {
|
||||||
|
const tokens = str.split(/(\{|\}|;)/).map((s) => s.trim());
|
||||||
|
const selectorStack: string[][] = [];
|
||||||
|
const parts: string[] = [];
|
||||||
|
let rules: string[] = [];
|
||||||
|
function generateSelector(stackIndex: number, parentSelector?: string) {
|
||||||
|
const parts: string[] = [];
|
||||||
|
for (const selector of selectorStack[stackIndex]) {
|
||||||
|
let part = (parentSelector && parentSelector + " " + selector) || selector;
|
||||||
|
if (part.includes("&")) {
|
||||||
|
part = selector.replace(/&/g, parentSelector || "");
|
||||||
|
}
|
||||||
|
if (stackIndex < selectorStack.length - 1) {
|
||||||
|
part = generateSelector(stackIndex + 1, part);
|
||||||
|
}
|
||||||
|
parts.push(part);
|
||||||
|
}
|
||||||
|
return parts.join(", ");
|
||||||
|
}
|
||||||
|
function generateRules() {
|
||||||
|
if (rules.length) {
|
||||||
|
parts.push(generateSelector(0) + " {");
|
||||||
|
parts.push(...rules);
|
||||||
|
parts.push("}");
|
||||||
|
rules = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (tokens.length) {
|
||||||
|
let token = tokens.shift()!;
|
||||||
|
if (token === "}") {
|
||||||
|
generateRules();
|
||||||
|
selectorStack.pop();
|
||||||
|
} else {
|
||||||
|
if (tokens[0] === "{") {
|
||||||
|
generateRules();
|
||||||
|
selectorStack.push(token.split(/\s*,\s*/));
|
||||||
|
tokens.shift();
|
||||||
|
}
|
||||||
|
if (tokens[0] === ";") {
|
||||||
|
rules.push(" " + token + ";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts.join("\n");
|
||||||
|
}
|
||||||
|
export function registerSheet(id: string, css: string) {
|
||||||
|
const sheet = document.createElement("style");
|
||||||
|
sheet.innerHTML = processSheet(css);
|
||||||
|
STYLESHEETS[id] = sheet;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function activateSheet(id, name) {
|
||||||
|
const sheet = STYLESHEETS[id];
|
||||||
|
if (!sheet) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid css stylesheet for component '${name}'. Did you forget to use the 'css' tag helper?`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
sheet.setAttribute("component", name);
|
||||||
|
document.head.appendChild(sheet);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { QWeb } from "./qweb/index";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This file creates and exports the OWL 'config' object, with keys:
|
||||||
|
* - 'mode': 'prod' or 'dev',
|
||||||
|
* - 'env': the environment to use in root components.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Config {
|
||||||
|
mode: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {} as Config;
|
||||||
|
|
||||||
|
Object.defineProperty(config, "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/reference/config.md#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.`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
+87
-34
@@ -1,7 +1,7 @@
|
|||||||
import { Component } from "./component/component";
|
import { Component } from "./component/component";
|
||||||
import { Observer } from "./core/observer";
|
import { scheduler } from "./component/scheduler";
|
||||||
import { EventBus } from "./core/event_bus";
|
import { EventBus } from "./core/event_bus";
|
||||||
import { onWillUnmount } from "./hooks";
|
import { Observer } from "./core/observer";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `Context` object provides a way to share data between an arbitrary number
|
* The `Context` object provides a way to share data between an arbitrary number
|
||||||
@@ -13,48 +13,84 @@ import { onWillUnmount } from "./hooks";
|
|||||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
* 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.
|
* hook) to its state, and will be updated whenever the context state is updated.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
function partitionBy<T>(arr: T[], fn: (t: T) => boolean) {
|
||||||
|
let lastGroup: T[] | false = false;
|
||||||
|
let lastValue;
|
||||||
|
return arr.reduce((acc: T[][], cur) => {
|
||||||
|
let curVal = fn(cur);
|
||||||
|
if (lastGroup) {
|
||||||
|
if (curVal === lastValue) {
|
||||||
|
lastGroup.push(cur);
|
||||||
|
} else {
|
||||||
|
lastGroup = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lastGroup) {
|
||||||
|
lastGroup = [cur];
|
||||||
|
acc.push(lastGroup);
|
||||||
|
}
|
||||||
|
lastValue = curVal;
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
|
||||||
export class Context extends EventBus {
|
export class Context extends EventBus {
|
||||||
state: any;
|
state: any;
|
||||||
observer: Observer;
|
observer: Observer;
|
||||||
id: number = 1;
|
rev: number = 1;
|
||||||
// mapping from component id to last observed context id
|
// mapping from component id to last observed context id
|
||||||
mapping: { [componentId: number]: number } = {};
|
mapping: { [componentId: number]: number } = {};
|
||||||
|
|
||||||
constructor(state: Object = {}) {
|
constructor(state: Object = {}) {
|
||||||
super();
|
super();
|
||||||
this.observer = new Observer();
|
this.observer = new Observer();
|
||||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
this.observer.notifyCB = () => {
|
||||||
|
// notify components in the next microtask tick to ensure that subscribers
|
||||||
|
// are notified only once for all changes that occur in the same micro tick
|
||||||
|
let rev = this.rev;
|
||||||
|
return Promise.resolve().then(() => {
|
||||||
|
if (rev === this.rev) {
|
||||||
|
this.__notifyComponents();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
this.state = this.observer.observe(state);
|
this.state = this.observer.observe(state);
|
||||||
|
this.subscriptions.update = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instead of using trigger to emit an update event, we actually implement
|
* 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
|
* 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
|
* 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
|
* done before doing children components. More precisely, if an update
|
||||||
* as an effect of destroying a children, we do not want to call the
|
* as an effect of destroying a children, we do not want to call any code
|
||||||
* mapStoreToProps function of the child, nor rendering it.
|
* from the child, and certainly not render it.
|
||||||
*
|
*
|
||||||
* This method is not optimal if we have a bunch of asynchronous components:
|
* This method implements a simple grouping algorithm by depth. If we have
|
||||||
* we wait sequentially for each component to be completed before updating the
|
* connected components of depths [2, 4,4,4,4, 3,8,8], the Context will notify
|
||||||
* next. However, the only things that matters is that children are updated
|
* them in the following groups: [2], [4,4,4,4], [3], [8,8]. Each group will
|
||||||
* after their parents. So, this could be optimized by being smarter, and
|
* be updated sequentially, but each components in a given group will be done in
|
||||||
* updating all widgets concurrently, except for parents/children.
|
* parallel.
|
||||||
*
|
*
|
||||||
* A potential cheap way to improve this situation is to keep track of the
|
* This is a very simple algorithm, but it avoids checking if a given
|
||||||
* depth of a component in the component tree. A root component has a depth of
|
* component is a child of another.
|
||||||
* 1, then its children of 2 and so on... Then, we can update all components
|
|
||||||
* with the same depth in parallel.
|
|
||||||
*/
|
*/
|
||||||
async __notifyComponents() {
|
async __notifyComponents() {
|
||||||
const id = ++this.id;
|
const rev = ++this.rev;
|
||||||
const subs = this.subscriptions.update || [];
|
const subscriptions = this.subscriptions.update;
|
||||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
const groups = partitionBy(subscriptions, (s) => (s.owner ? s.owner.__owl__.depth : -1));
|
||||||
const sub = subs[i];
|
for (let group of groups) {
|
||||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
const proms = group.map((sub) => sub.callback.call(sub.owner, rev));
|
||||||
if (shouldCallback) {
|
// at this point, each component in the current group has registered a
|
||||||
await sub.callback.call(sub.owner, id);
|
// top level fiber in the scheduler. It could happen that rendering these
|
||||||
}
|
// components is done (if they have no children). This is why we manually
|
||||||
|
// flush the scheduler. This will force the scheduler to check
|
||||||
|
// immediately if they are done, which will cause their rendering
|
||||||
|
// promise to resolve earlier, which means that there is a chance of
|
||||||
|
// processing the next group in the same frame.
|
||||||
|
scheduler.flush();
|
||||||
|
await Promise.all(proms);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,32 +100,49 @@ export class Context extends EventBus {
|
|||||||
* to context state changes. The `useContext` method returns the context state
|
* to context state changes. The `useContext` method returns the context state
|
||||||
*/
|
*/
|
||||||
export function useContext(ctx: Context): any {
|
export function useContext(ctx: Context): any {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
return useContextWithCB(ctx, component, component.render.bind(component));
|
return useContextWithCB(ctx, component, component.render.bind(component));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useContextWithCB(ctx: Context, component, method): any {
|
export function useContextWithCB(ctx: Context, component: Component, method): any {
|
||||||
const __owl__ = component.__owl__;
|
const __owl__ = component.__owl__;
|
||||||
const id = __owl__.id;
|
const id = __owl__.id;
|
||||||
const mapping = ctx.mapping;
|
const mapping = ctx.mapping;
|
||||||
if (id in mapping) {
|
if (id in mapping) {
|
||||||
return ctx.state;
|
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;
|
mapping[id] = 0;
|
||||||
const renderFn = __owl__.render;
|
const renderFn = __owl__.renderFn;
|
||||||
__owl__.render = function(comp, params) {
|
__owl__.renderFn = function (comp, params) {
|
||||||
mapping[id] = ctx.id;
|
mapping[id] = ctx.rev;
|
||||||
return renderFn(comp, params);
|
return renderFn(comp, params);
|
||||||
};
|
};
|
||||||
ctx.on("update", component, async contextId => {
|
ctx.on("update", component, async (contextRev) => {
|
||||||
if (mapping[id] < contextId) {
|
if (mapping[id] < contextRev) {
|
||||||
mapping[id] = contextId;
|
mapping[id] = contextRev;
|
||||||
await method();
|
await method();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
onWillUnmount(() => {
|
const __destroy = component.__destroy;
|
||||||
|
component.__destroy = (parent) => {
|
||||||
ctx.off("update", component);
|
ctx.off("update", component);
|
||||||
delete mapping[id];
|
delete mapping[id];
|
||||||
});
|
__destroy.call(component, parent);
|
||||||
|
};
|
||||||
return ctx.state;
|
return ctx.state;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export class EventBus {
|
|||||||
}
|
}
|
||||||
this.subscriptions[eventType].push({
|
this.subscriptions[eventType].push({
|
||||||
owner,
|
owner,
|
||||||
callback
|
callback,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ export class EventBus {
|
|||||||
off(eventType: string, owner: any) {
|
off(eventType: string, owner: any) {
|
||||||
const subs = this.subscriptions[eventType];
|
const subs = this.subscriptions[eventType];
|
||||||
if (subs) {
|
if (subs) {
|
||||||
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
|
this.subscriptions[eventType] = subs.filter((s) => s.owner !== owner);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+11
-21
@@ -20,21 +20,17 @@
|
|||||||
export class Observer {
|
export class Observer {
|
||||||
rev: number = 1;
|
rev: number = 1;
|
||||||
allowMutations: boolean = true;
|
allowMutations: boolean = true;
|
||||||
dirty: boolean = false;
|
|
||||||
weakMap: WeakMap<any, any> = new WeakMap();
|
weakMap: WeakMap<any, any> = new WeakMap();
|
||||||
|
|
||||||
notifyCB() {}
|
notifyCB() {}
|
||||||
async notifyChange() {
|
|
||||||
this.dirty = true;
|
|
||||||
await Promise.resolve();
|
|
||||||
if (this.dirty) {
|
|
||||||
this.dirty = false;
|
|
||||||
this.notifyCB();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
observe<T>(value: T, parent?: any): T {
|
observe<T>(value: T, parent?: any): T {
|
||||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
if (
|
||||||
|
value === null ||
|
||||||
|
typeof value !== "object" ||
|
||||||
|
value instanceof Date ||
|
||||||
|
value instanceof Promise
|
||||||
|
) {
|
||||||
// fun fact: typeof null === 'object'
|
// fun fact: typeof null === 'object'
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
@@ -46,10 +42,6 @@ export class Observer {
|
|||||||
const metadata = this.weakMap.get(value);
|
const metadata = this.weakMap.get(value);
|
||||||
return metadata ? metadata.rev : 0;
|
return metadata ? metadata.rev : 0;
|
||||||
}
|
}
|
||||||
deepRevNumber(value): number {
|
|
||||||
const metadata = this.weakMap.get(value);
|
|
||||||
return metadata ? metadata.deepRev : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
_observe(value, parent) {
|
_observe(value, parent) {
|
||||||
var self = this;
|
var self = this;
|
||||||
@@ -69,7 +61,7 @@ export class Observer {
|
|||||||
}
|
}
|
||||||
self._updateRevNumber(target);
|
self._updateRevNumber(target);
|
||||||
target[key] = newVal;
|
target[key] = newVal;
|
||||||
self.notifyChange();
|
self.notifyCB();
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
@@ -77,18 +69,17 @@ export class Observer {
|
|||||||
if (key in target) {
|
if (key in target) {
|
||||||
delete target[key];
|
delete target[key];
|
||||||
self._updateRevNumber(target);
|
self._updateRevNumber(target);
|
||||||
self.notifyChange();
|
self.notifyCB();
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const metadata = {
|
const metadata = {
|
||||||
value,
|
value,
|
||||||
proxy,
|
proxy,
|
||||||
rev: this.rev,
|
rev: this.rev,
|
||||||
deepRev: this.rev,
|
parent,
|
||||||
parent
|
|
||||||
};
|
};
|
||||||
|
|
||||||
this.weakMap.set(value, metadata);
|
this.weakMap.set(value, metadata);
|
||||||
@@ -99,11 +90,10 @@ export class Observer {
|
|||||||
_updateRevNumber(target: any) {
|
_updateRevNumber(target: any) {
|
||||||
this.rev++;
|
this.rev++;
|
||||||
let metadata = this.weakMap.get(target);
|
let metadata = this.weakMap.get(target);
|
||||||
metadata.rev!++;
|
|
||||||
let parent = target;
|
let parent = target;
|
||||||
do {
|
do {
|
||||||
metadata = this.weakMap.get(parent);
|
metadata = this.weakMap.get(parent);
|
||||||
metadata.deepRev++;
|
metadata.rev++;
|
||||||
} while ((parent = metadata.parent) && parent !== target);
|
} while ((parent = metadata.parent) && parent !== target);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Component } from "../component/component";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We define here OwlEvent, a subclass of CustomEvent, with an additional
|
||||||
|
* attribute:
|
||||||
|
* - originalComponent: the component that triggered the event
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class OwlEvent<T> extends CustomEvent<T> {
|
||||||
|
originalComponent: Component;
|
||||||
|
constructor(component, eventType, options) {
|
||||||
|
super(eventType, options);
|
||||||
|
this.originalComponent = component;
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
-18
@@ -22,7 +22,7 @@ import { Observer } from "./core/observer";
|
|||||||
* trigger a rerendering of the current component.
|
* trigger a rerendering of the current component.
|
||||||
*/
|
*/
|
||||||
export function useState<T>(state: T): T {
|
export function useState<T>(state: T): T {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
const __owl__ = component.__owl__;
|
const __owl__ = component.__owl__;
|
||||||
if (!__owl__.observer) {
|
if (!__owl__.observer) {
|
||||||
__owl__.observer = new Observer();
|
__owl__.observer = new Observer();
|
||||||
@@ -36,11 +36,11 @@ export function useState<T>(state: T): T {
|
|||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
||||||
if (reverse) {
|
if (reverse) {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function() {
|
component.__owl__[method] = function () {
|
||||||
current.call(component);
|
current.call(component);
|
||||||
cb.call(component);
|
cb.call(component);
|
||||||
};
|
};
|
||||||
@@ -49,11 +49,11 @@ function makeLifecycleHook(method: string, reverse: boolean = false) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function() {
|
component.__owl__[method] = function () {
|
||||||
cb.call(component);
|
cb.call(component);
|
||||||
current.call(component);
|
current.call(component);
|
||||||
};
|
};
|
||||||
@@ -65,12 +65,12 @@ function makeLifecycleHook(method: string, reverse: boolean = false) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function makeAsyncHook(method: string) {
|
function makeAsyncHook(method: string) {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function(...args) {
|
component.__owl__[method] = function (...args) {
|
||||||
return Promise.all[(current.call(component, ...args), cb.call(component, ...args))];
|
return Promise.all([current.call(component, ...args), cb.call(component, ...args)]);
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
component.__owl__[method] = cb;
|
component.__owl__[method] = cb;
|
||||||
@@ -94,22 +94,27 @@ export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
|
|||||||
* The purpose of this hook is to allow components to get a reference to a sub
|
* The purpose of this hook is to allow components to get a reference to a sub
|
||||||
* html node or component.
|
* html node or component.
|
||||||
*/
|
*/
|
||||||
interface Ref {
|
interface Ref<C extends Component = Component> {
|
||||||
el: HTMLElement | null;
|
el: HTMLElement | null;
|
||||||
comp: Component<any, any> | null;
|
comp: C | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useRef(name: string): Ref {
|
export function useRef<C extends Component = Component>(name: string): Ref<C> {
|
||||||
const __owl__ = Component.current!.__owl__;
|
const __owl__ = Component.current!.__owl__;
|
||||||
return {
|
return {
|
||||||
get el(): HTMLElement | null {
|
get el(): HTMLElement | null {
|
||||||
const val = __owl__.refs && __owl__.refs[name];
|
const val = __owl__.refs && __owl__.refs[name];
|
||||||
return val instanceof HTMLElement ? val : null;
|
if (val instanceof HTMLElement) {
|
||||||
|
return val;
|
||||||
|
} else if (val instanceof Component) {
|
||||||
|
return val.el;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
},
|
},
|
||||||
get comp(): Component<any, any> | null {
|
get comp(): C | null {
|
||||||
const val = __owl__.refs && __owl__.refs[name];
|
const val = __owl__.refs && __owl__.refs[name];
|
||||||
return val instanceof Component ? val : null;
|
return val instanceof Component ? (val as C) : null;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,3 +131,32 @@ export function useSubEnv(nextEnv) {
|
|||||||
const component = Component.current!;
|
const component = Component.current!;
|
||||||
component.env = Object.assign(Object.create(component.env), nextEnv);
|
component.env = Object.assign(Object.create(component.env), nextEnv);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// useExternalListener
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When a component needs to listen to DOM Events on element(s) that are not
|
||||||
|
* part of his hierarchy, we can use the `useExternalListener` hook.
|
||||||
|
* It will correctly add and remove the event listener, whenever the
|
||||||
|
* component is mounted and unmounted.
|
||||||
|
*
|
||||||
|
* Example:
|
||||||
|
* a menu needs to listen to the click on window to be closed automatically
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* in the constructor of the OWL component that needs to be notified,
|
||||||
|
* `useExternalListener(window, 'click', this._doSomething);`
|
||||||
|
* */
|
||||||
|
export function useExternalListener(
|
||||||
|
target: HTMLElement | typeof window,
|
||||||
|
eventName: string,
|
||||||
|
handler,
|
||||||
|
eventParams?
|
||||||
|
) {
|
||||||
|
const boundHandler = handler.bind(Component.current);
|
||||||
|
|
||||||
|
onMounted(() => target.addEventListener(eventName, boundHandler, eventParams));
|
||||||
|
onWillUnmount(() => target.removeEventListener(eventName, boundHandler, eventParams));
|
||||||
|
}
|
||||||
|
|||||||
+6
-18
@@ -7,9 +7,12 @@
|
|||||||
import { EventBus } from "./core/event_bus";
|
import { EventBus } from "./core/event_bus";
|
||||||
import { Observer } from "./core/observer";
|
import { Observer } from "./core/observer";
|
||||||
import { QWeb } from "./qweb/index";
|
import { QWeb } from "./qweb/index";
|
||||||
|
import { config } from "./config";
|
||||||
import * as _store from "./store";
|
import * as _store from "./store";
|
||||||
import * as _utils from "./utils";
|
import * as _utils from "./utils";
|
||||||
import * as _tags from "./tags";
|
import * as _tags from "./tags";
|
||||||
|
import { AsyncRoot } from "./misc/async_root";
|
||||||
|
import { Portal } from "./misc/portal";
|
||||||
import * as _hooks from "./hooks";
|
import * as _hooks from "./hooks";
|
||||||
import * as _context from "./context";
|
import * as _context from "./context";
|
||||||
import { Link } from "./router/link";
|
import { Link } from "./router/link";
|
||||||
@@ -18,6 +21,7 @@ import { Router } from "./router/router";
|
|||||||
|
|
||||||
export { Component } from "./component/component";
|
export { Component } from "./component/component";
|
||||||
export { QWeb };
|
export { QWeb };
|
||||||
|
export { config };
|
||||||
|
|
||||||
export const Context = _context.Context;
|
export const Context = _context.Context;
|
||||||
export const useState = _hooks.useState;
|
export const useState = _hooks.useState;
|
||||||
@@ -26,27 +30,11 @@ export const router = { Router, RouteComponent, Link };
|
|||||||
export const Store = _store.Store;
|
export const Store = _store.Store;
|
||||||
export const utils = _utils;
|
export const utils = _utils;
|
||||||
export const tags = _tags;
|
export const tags = _tags;
|
||||||
|
export const misc = { AsyncRoot, Portal };
|
||||||
export const hooks = Object.assign({}, _hooks, {
|
export const hooks = Object.assign({}, _hooks, {
|
||||||
useContext: _context.useContext,
|
useContext: _context.useContext,
|
||||||
useDispatch: _store.useDispatch,
|
useDispatch: _store.useDispatch,
|
||||||
useGetters: _store.useGetters,
|
useGetters: _store.useGetters,
|
||||||
useStore: _store.useStore
|
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,19 @@
|
|||||||
|
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 {
|
||||||
|
static template = xml`<t t-slot="default"/>`;
|
||||||
|
|
||||||
|
async __updateProps(nextProps, parentFiber) {
|
||||||
|
this.render(parentFiber.force);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { Component, portalSymbol } from "../component/component";
|
||||||
|
import { VNode, patch } from "../vdom/index";
|
||||||
|
import { xml } from "../tags";
|
||||||
|
import { OwlEvent } from "../core/owl_event";
|
||||||
|
import { useSubEnv } from "../hooks";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Portal
|
||||||
|
*
|
||||||
|
* The Portal component allows to render a part of a component outside it's DOM.
|
||||||
|
* It is for example useful for dialogs: for css reasons, dialogs are in general
|
||||||
|
* placed in a specific spot of the DOM (e.g. directly in the body). With the
|
||||||
|
* Portal, a component can conditionally specify in its tempate that it contains
|
||||||
|
* a dialog, and where this dialog should be inserted in the DOM.
|
||||||
|
*
|
||||||
|
* The Portal component ensures that the communication between the content of
|
||||||
|
* the Portal and its parent properly works: business events reaching the Portal
|
||||||
|
* are re-triggered on an empty <portal> node located in the parent's DOM.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
target: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Portal extends Component<Props> {
|
||||||
|
static template = xml`<portal><t t-slot="default"/></portal>`;
|
||||||
|
static props = {
|
||||||
|
target: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// boolean to indicate whether or not we must listen to 'dom-appended' event
|
||||||
|
// to hook on the moment when the target is inserted into the DOM (because it
|
||||||
|
// is not when the portal is rendered)
|
||||||
|
doTargetLookUp: boolean = true;
|
||||||
|
// set of encountered events that need to be redirected
|
||||||
|
_handledEvents: Set<string> = new Set();
|
||||||
|
// function that will be the event's tunnel (needs to be an arrow function to
|
||||||
|
// avoid having to rebind `this`)
|
||||||
|
_handlerTunnel: (f: OwlEvent<any>) => void = (ev: OwlEvent<any>) => {
|
||||||
|
ev.stopPropagation();
|
||||||
|
this.__trigger(ev.originalComponent, ev.type, ev.detail);
|
||||||
|
};
|
||||||
|
// Storing the parent's env
|
||||||
|
parentEnv: any = null;
|
||||||
|
// represents the element that is moved somewhere else
|
||||||
|
portal: VNode | null = null;
|
||||||
|
// the target where we will move `portal`
|
||||||
|
target: Element | null = null;
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
this.parentEnv = parent ? parent.env : {};
|
||||||
|
// put a callback in the env that is propagated to children s.t. portal can
|
||||||
|
// register an handler to those events just before children will trigger them
|
||||||
|
useSubEnv({
|
||||||
|
[portalSymbol]: (ev) => {
|
||||||
|
if (!this._handledEvents.has(ev.type)) {
|
||||||
|
this.portal!.elm!.addEventListener(ev.type, this._handlerTunnel);
|
||||||
|
this._handledEvents.add(ev.type);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Override to revert back to a classic Component's structure
|
||||||
|
*
|
||||||
|
* @override
|
||||||
|
*/
|
||||||
|
__callWillUnmount() {
|
||||||
|
super.__callWillUnmount();
|
||||||
|
this.el!.appendChild(this.portal!.elm!);
|
||||||
|
this.doTargetLookUp = true;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* At each DOM change, we must ensure that the portal contains exactly one
|
||||||
|
* child
|
||||||
|
*/
|
||||||
|
__checkVNodeStructure(vnode: VNode) {
|
||||||
|
const children = vnode.children!;
|
||||||
|
let countRealNodes = 0;
|
||||||
|
for (let child of children) {
|
||||||
|
if ((child as VNode).sel) {
|
||||||
|
countRealNodes++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (countRealNodes !== 1) {
|
||||||
|
throw new Error(`Portal must have exactly one non-text child (has ${countRealNodes})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Ensure the target is still there at whichever time we render
|
||||||
|
*/
|
||||||
|
__checkTargetPresence() {
|
||||||
|
if (!this.target || !document.contains(this.target)) {
|
||||||
|
throw new Error(`Could not find any match for "${this.props.target}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Move the portal's element to the target
|
||||||
|
*/
|
||||||
|
__deployPortal() {
|
||||||
|
this.__checkTargetPresence();
|
||||||
|
this.target!.appendChild(this.portal!.elm!);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Override to remove from the DOM the element we have teleported
|
||||||
|
*
|
||||||
|
* @override
|
||||||
|
*/
|
||||||
|
__destroy(parent) {
|
||||||
|
if (this.portal && this.portal.elm) {
|
||||||
|
const displacedElm = this.portal.elm!;
|
||||||
|
const parent = displacedElm.parentNode;
|
||||||
|
if (parent) {
|
||||||
|
parent.removeChild(displacedElm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
super.__destroy(parent);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Override to patch the element that has been teleported
|
||||||
|
*
|
||||||
|
* @override
|
||||||
|
*/
|
||||||
|
__patch(target, vnode) {
|
||||||
|
if (this.doTargetLookUp) {
|
||||||
|
const target = document.querySelector(this.props.target);
|
||||||
|
if (!target) {
|
||||||
|
this.env.qweb.on("dom-appended", this, () => {
|
||||||
|
this.doTargetLookUp = false;
|
||||||
|
this.env.qweb.off("dom-appended", this);
|
||||||
|
this.target = document.querySelector(this.props.target);
|
||||||
|
this.__deployPortal();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.doTargetLookUp = false;
|
||||||
|
this.target = target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.__checkVNodeStructure(vnode);
|
||||||
|
const shouldDeploy =
|
||||||
|
(!this.portal || this.el!.contains(this.portal.elm!)) && !this.doTargetLookUp;
|
||||||
|
|
||||||
|
if (!this.doTargetLookUp && !shouldDeploy) {
|
||||||
|
// Only on pure patching, provided the
|
||||||
|
// this.target's parent has not been unmounted
|
||||||
|
this.__checkTargetPresence();
|
||||||
|
}
|
||||||
|
|
||||||
|
const portalPatch = this.portal ? this.portal : document.createElement(vnode.children[0].sel);
|
||||||
|
this.portal = patch(portalPatch, vnode.children![0] as VNode);
|
||||||
|
vnode.children = [];
|
||||||
|
|
||||||
|
super.__patch(target, vnode);
|
||||||
|
|
||||||
|
if (shouldDeploy) {
|
||||||
|
this.__deployPortal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Override to set the env
|
||||||
|
*/
|
||||||
|
__trigger(component: Component, eventType: string, payload?: any) {
|
||||||
|
const env = this.env;
|
||||||
|
this.env = this.parentEnv;
|
||||||
|
super.__trigger(component, eventType, payload);
|
||||||
|
this.env = env;
|
||||||
|
}
|
||||||
|
}
|
||||||
+177
-143
@@ -1,7 +1,7 @@
|
|||||||
import { CompilationContext } from "./compilation_context";
|
import { CompilationContext } from "./compilation_context";
|
||||||
import { QWebExprVar } from "./expression_parser";
|
|
||||||
import { QWeb } from "./qweb";
|
import { QWeb } from "./qweb";
|
||||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||||
|
import { QWebVar } from "./expression_parser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl QWeb Directives
|
* Owl QWeb Directives
|
||||||
@@ -20,35 +20,41 @@ import { htmlToVDOM } from "../vdom/html_to_vdom";
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-esc and t-raw
|
// 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;
|
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
||||||
|
|
||||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
||||||
if (value === "0" && ctx.caller) {
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
qweb._compileNode(ctx.caller, ctx);
|
if (value === "0") {
|
||||||
return;
|
if (ctx.parentNode) {
|
||||||
}
|
// the 'zero' magical symbol is where we can find the result of the rendering
|
||||||
|
// of the body of the t-call.
|
||||||
if (value.xml instanceof NodeList) {
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
for (let node of Array.from(value.xml)) {
|
const zeroArgs = ctx.escaping
|
||||||
qweb._compileNode(<ChildNode>node, ctx);
|
? `{text: utils.vDomToString(scope[utils.zero])}`
|
||||||
|
: `...scope[utils.zero]`;
|
||||||
|
ctx.addLine(`c${ctx.parentNode}.push(${zeroArgs});`);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let exprID: string;
|
let exprID: string;
|
||||||
if (typeof value === "string") {
|
if (typeof value === "string") {
|
||||||
exprID = `_${ctx.generateID()}`;
|
exprID = `_${ctx.generateID()}`;
|
||||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
ctx.addLine(`let ${exprID} = ${ctx.formatExpression(value)};`);
|
||||||
} else {
|
} else {
|
||||||
exprID = value.id;
|
exprID = `scope.${value.id}`;
|
||||||
}
|
}
|
||||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
ctx.addIf(`${exprID} != null`);
|
||||||
|
|
||||||
if (ctx.escaping) {
|
if (ctx.escaping) {
|
||||||
|
let protectID;
|
||||||
|
if (value.hasBody) {
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
|
protectID = ctx.startProtectScope();
|
||||||
|
ctx.addLine(
|
||||||
|
`${exprID} = ${exprID} instanceof utils.VDomArray ? utils.vDomToString(${exprID}) : ${exprID};`
|
||||||
|
);
|
||||||
|
}
|
||||||
if (ctx.parentTextNode) {
|
if (ctx.parentTextNode) {
|
||||||
ctx.addLine(`vn${ctx.parentTextNode}.text += ${exprID};`);
|
ctx.addLine(`vn${ctx.parentTextNode}.text += ${exprID};`);
|
||||||
} else if (ctx.parentNode) {
|
} else if (ctx.parentNode) {
|
||||||
@@ -57,14 +63,24 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Compilatio
|
|||||||
let nodeID = ctx.generateID();
|
let nodeID = ctx.generateID();
|
||||||
ctx.rootContext.rootNode = nodeID;
|
ctx.rootContext.rootNode = nodeID;
|
||||||
ctx.rootContext.parentTextNode = nodeID;
|
ctx.rootContext.parentTextNode = nodeID;
|
||||||
ctx.addLine(`var vn${nodeID} = {text: ${exprID}};`);
|
ctx.addLine(`let vn${nodeID} = {text: ${exprID}};`);
|
||||||
if (ctx.rootContext.shouldDefineResult) {
|
if (ctx.rootContext.shouldDefineResult) {
|
||||||
ctx.addLine(`result = vn${nodeID}`);
|
ctx.addLine(`result = vn${nodeID}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (value.hasBody) {
|
||||||
|
ctx.stopProtectScope(protectID);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(...utils.htmlToVDOM(${exprID}));`);
|
if (value.hasBody) {
|
||||||
|
ctx.addLine(
|
||||||
|
`const vnodeArray = ${exprID} instanceof utils.VDomArray ? ${exprID} : utils.htmlToVDOM(${exprID});`
|
||||||
|
);
|
||||||
|
ctx.addLine(`c${ctx.parentNode}.push(...vnodeArray);`);
|
||||||
|
} else {
|
||||||
|
ctx.addLine(`c${ctx.parentNode}.push(...utils.htmlToVDOM(${exprID}));`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (node.childNodes.length) {
|
if (node.childNodes.length) {
|
||||||
ctx.addElse();
|
ctx.addElse();
|
||||||
@@ -81,7 +97,7 @@ QWeb.addDirective({
|
|||||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
||||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -91,7 +107,7 @@ QWeb.addDirective({
|
|||||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
||||||
compileValueNode(value, node, qweb, ctx);
|
compileValueNode(value, node, qweb, ctx);
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -101,28 +117,54 @@ QWeb.addDirective({
|
|||||||
name: "set",
|
name: "set",
|
||||||
extraNames: ["value"],
|
extraNames: ["value"],
|
||||||
priority: 60,
|
priority: 60,
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||||
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
const variable = node.getAttribute("t-set")!;
|
const variable = node.getAttribute("t-set")!;
|
||||||
let value = node.getAttribute("t-value")!;
|
let value = node.getAttribute("t-value")!;
|
||||||
|
ctx.variables[variable] = ctx.variables[variable] || ({} as QWebVar);
|
||||||
|
let qwebvar = ctx.variables[variable];
|
||||||
|
const hasBody = node.hasChildNodes();
|
||||||
|
|
||||||
|
qwebvar.id = variable;
|
||||||
|
qwebvar.expr = `scope.${variable}`;
|
||||||
if (value) {
|
if (value) {
|
||||||
const formattedValue = ctx.formatExpression(value);
|
const formattedValue = ctx.formatExpression(value);
|
||||||
if (ctx.variables.hasOwnProperty(variable)) {
|
let scopeExpr = `scope`;
|
||||||
ctx.addLine(`${(<QWebExprVar>ctx.variables[variable]).id} = ${formattedValue}`);
|
if (ctx.protectedScopeNumber) {
|
||||||
} else {
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
const varName = `_${ctx.generateID()}`;
|
scopeExpr = `utils.getScope(scope, '${variable}')`;
|
||||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
}
|
||||||
ctx.variables[variable] = {
|
ctx.addLine(`${scopeExpr}.${variable} = ${formattedValue};`);
|
||||||
id: varName,
|
qwebvar.value = formattedValue;
|
||||||
expr: formattedValue
|
}
|
||||||
};
|
|
||||||
|
if (hasBody) {
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
|
if (value) {
|
||||||
|
ctx.addIf(`!(${qwebvar.expr})`);
|
||||||
|
}
|
||||||
|
const tempParentNodeID = ctx.generateID();
|
||||||
|
const _parentNode = ctx.parentNode;
|
||||||
|
ctx.parentNode = tempParentNodeID;
|
||||||
|
|
||||||
|
ctx.addLine(`let c${tempParentNodeID} = new utils.VDomArray();`);
|
||||||
|
const nodeCopy = node.cloneNode(true) as Element;
|
||||||
|
for (let attr of ["t-set", "t-value", "t-if", "t-else", "t-elif"]) {
|
||||||
|
nodeCopy.removeAttribute(attr);
|
||||||
|
}
|
||||||
|
qweb._compileNode(nodeCopy, ctx);
|
||||||
|
|
||||||
|
ctx.addLine(`${qwebvar.expr} = c${tempParentNodeID}`);
|
||||||
|
qwebvar.value = `c${tempParentNodeID}`;
|
||||||
|
qwebvar.hasBody = true;
|
||||||
|
|
||||||
|
ctx.parentNode = _parentNode;
|
||||||
|
if (value) {
|
||||||
|
ctx.closeIf();
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
ctx.variables[variable] = {
|
|
||||||
xml: node.childNodes
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -133,12 +175,12 @@ QWeb.addDirective({
|
|||||||
priority: 20,
|
priority: 20,
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
atNodeEncounter({ node, ctx }): boolean {
|
||||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||||
ctx.addIf(`${ctx.formatExpression(cond)}`);
|
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id!}`);
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -146,13 +188,15 @@ QWeb.addDirective({
|
|||||||
priority: 30,
|
priority: 30,
|
||||||
atNodeEncounter({ node, ctx }): boolean {
|
atNodeEncounter({ node, ctx }): boolean {
|
||||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
||||||
ctx.addLine(`else if (${ctx.formatExpression(cond)}) {`);
|
ctx.addLine(
|
||||||
|
`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id}`}) {`
|
||||||
|
);
|
||||||
ctx.indent();
|
ctx.indent();
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -165,7 +209,7 @@ QWeb.addDirective({
|
|||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -175,95 +219,78 @@ QWeb.addDirective({
|
|||||||
name: "call",
|
name: "call",
|
||||||
priority: 50,
|
priority: 50,
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||||
if (node.nodeName !== "t") {
|
// Step 1: sanity checks
|
||||||
throw new Error("Invalid tag for t-call directive (should be 't')");
|
// ------------------------------------------------
|
||||||
}
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
const subTemplate = node.getAttribute("t-call")!;
|
const subTemplate = node.getAttribute("t-call")!;
|
||||||
const nodeTemplate = qweb.templates[subTemplate];
|
const nodeTemplate = qweb.templates[subTemplate];
|
||||||
if (!nodeTemplate) {
|
if (!nodeTemplate) {
|
||||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
||||||
}
|
}
|
||||||
const nodeCopy = node.cloneNode(true) as Element;
|
|
||||||
nodeCopy.removeAttribute("t-call");
|
|
||||||
|
|
||||||
// extract variables from nodecopy
|
// Step 2: compile target template in sub templates
|
||||||
const tempCtx = new CompilationContext();
|
// ------------------------------------------------
|
||||||
tempCtx.nextID = ctx.rootContext.nextID;
|
let subId = qweb.subTemplates[subTemplate];
|
||||||
tempCtx.allowMultipleRoots = true;
|
if (!subId) {
|
||||||
qweb._compileNode(nodeCopy, tempCtx);
|
subId = QWeb.nextId++;
|
||||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
qweb.subTemplates[subTemplate] = subId;
|
||||||
ctx.rootContext.nextID = tempCtx.nextID;
|
const subTemplateFn = qweb._compile(subTemplate, nodeTemplate.elem, ctx, true);
|
||||||
|
QWeb.subTemplates[subId] = subTemplateFn;
|
||||||
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) {
|
// Step 3: compile t-call body if necessary
|
||||||
ctx.addLine("{");
|
// ------------------------------------------------
|
||||||
|
let hasBody = node.hasChildNodes();
|
||||||
|
const protectID = ctx.startProtectScope();
|
||||||
|
if (hasBody) {
|
||||||
|
// we add a sub scope to protect the ambient scope
|
||||||
|
ctx.addLine(`{`);
|
||||||
ctx.indent();
|
ctx.indent();
|
||||||
// add new variables, if any
|
const nodeCopy = node.cloneNode(true) as Element;
|
||||||
for (let key in tempCtx.variables) {
|
for (let attr of ["t-if", "t-else", "t-elif", "t-call"]) {
|
||||||
const v = tempCtx.variables[key];
|
nodeCopy.removeAttribute(attr);
|
||||||
if ((<QWebExprVar>v).expr) {
|
|
||||||
ctx.addLine(`let ${(<QWebExprVar>v).id} = ${(<QWebExprVar>v).expr};`);
|
|
||||||
}
|
|
||||||
// todo: handle XML variables...
|
|
||||||
}
|
}
|
||||||
}
|
const parentNode = ctx.parentNode;
|
||||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
ctx.parentNode = "__0";
|
||||||
|
// this local scope is intended to trap c__0
|
||||||
// close new scope
|
ctx.addLine(`{`);
|
||||||
if (hasNewVariables) {
|
ctx.indent();
|
||||||
|
ctx.addLine("let c__0 = [];");
|
||||||
|
qweb._compileNode(nodeCopy, ctx);
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
|
ctx.addLine("scope[utils.zero] = c__0;");
|
||||||
|
ctx.parentNode = parentNode;
|
||||||
ctx.dedent();
|
ctx.dedent();
|
||||||
ctx.addLine("}");
|
ctx.addLine(`}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.hasAttribute("t-if") || node.hasAttribute("t-else") || node.hasAttribute("t-elif")) {
|
// Step 4: add the appropriate function call to current component
|
||||||
ctx.closeIf();
|
// ------------------------------------------------
|
||||||
|
const parentComponent = `utils.getComponent(context)`;
|
||||||
|
const key = ctx.generateTemplateKey();
|
||||||
|
const parentNode = ctx.parentNode ? `c${ctx.parentNode}` : "result";
|
||||||
|
const extra = `Object.assign({}, extra, {parentNode: ${parentNode}, parent: ${parentComponent}, key: ${key}})`;
|
||||||
|
if (ctx.parentNode) {
|
||||||
|
ctx.addLine(`this.constructor.subTemplates['${subId}'].call(this, scope, ${extra});`);
|
||||||
|
} else {
|
||||||
|
// this is a t-call with no parentnode, we need to extract the result
|
||||||
|
ctx.rootContext.shouldDefineResult = true;
|
||||||
|
ctx.addLine(`result = []`);
|
||||||
|
ctx.addLine(`this.constructor.subTemplates['${subId}'].call(this, scope, ${extra});`);
|
||||||
|
ctx.addLine(`result = result[0]`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Step 5: restore previous scope
|
||||||
|
// ------------------------------------------------
|
||||||
|
if (hasBody) {
|
||||||
|
ctx.dedent();
|
||||||
|
ctx.addLine(`}`);
|
||||||
|
}
|
||||||
|
ctx.stopProtectScope(protectID);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -274,54 +301,61 @@ QWeb.addDirective({
|
|||||||
extraNames: ["as"],
|
extraNames: ["as"],
|
||||||
priority: 10,
|
priority: 10,
|
||||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||||
ctx.rootContext.shouldProtectContext = true;
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
ctx = ctx.subContext("inLoop", true);
|
ctx = ctx.subContext("loopNumber", ctx.loopNumber + 1);
|
||||||
const elems = node.getAttribute("t-foreach")!;
|
const elems = node.getAttribute("t-foreach")!;
|
||||||
const name = node.getAttribute("t-as")!;
|
const name = node.getAttribute("t-as")!;
|
||||||
let arrayID = ctx.generateID();
|
let arrayID = ctx.generateID();
|
||||||
ctx.addLine(`var _${arrayID} = ${ctx.formatExpression(elems)};`);
|
ctx.addLine(`let _${arrayID} = ${ctx.formatExpression(elems)};`);
|
||||||
ctx.addLine(`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`);
|
ctx.addLine(`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`);
|
||||||
let keysID = ctx.generateID();
|
let keysID = ctx.generateID();
|
||||||
let valuesID = ctx.generateID();
|
let valuesID = ctx.generateID();
|
||||||
ctx.addLine(`var _${keysID} = _${valuesID} = _${arrayID};`);
|
ctx.addLine(`let _${keysID} = _${valuesID} = _${arrayID};`);
|
||||||
ctx.addIf(`!(_${arrayID} instanceof Array)`);
|
ctx.addIf(`!(_${arrayID} instanceof Array)`);
|
||||||
|
ctx.addIf(`typeof _${arrayID}[Symbol.iterator] === 'function'`);
|
||||||
|
ctx.addLine(`_${keysID} = [..._${arrayID}];`)
|
||||||
|
ctx.addElse();
|
||||||
ctx.addLine(`_${keysID} = Object.keys(_${arrayID});`);
|
ctx.addLine(`_${keysID} = Object.keys(_${arrayID});`);
|
||||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
ctx.closeIf();
|
||||||
ctx.addLine(`for (let i = 0; i < _length${keysID}; i++) {`);
|
ctx.addLine(`let _length${keysID} = _${keysID}.length;`);
|
||||||
|
let varsID = ctx.startProtectScope(true);
|
||||||
|
const loopVar = `i${ctx.loopNumber}`;
|
||||||
|
ctx.addLine(`for (let ${loopVar} = 0; ${loopVar} < _length${keysID}; ${loopVar}++) {`);
|
||||||
ctx.indent();
|
ctx.indent();
|
||||||
ctx.addToScope(name + "_first", "i === 0");
|
|
||||||
ctx.addToScope(name + "_last", `i === _length${keysID} - 1`);
|
ctx.addLine(`scope.${name}_first = ${loopVar} === 0`);
|
||||||
ctx.addToScope(name + "_index", "i");
|
ctx.addLine(`scope.${name}_last = ${loopVar} === _length${keysID} - 1`);
|
||||||
ctx.addToScope(name, `_${keysID}[i]`);
|
ctx.addLine(`scope.${name}_index = ${loopVar}`);
|
||||||
ctx.addToScope(name + "_value", `_${valuesID}[i]`);
|
ctx.addLine(`scope.${name} = _${keysID}[${loopVar}]`);
|
||||||
|
ctx.addLine(`scope.${name}_value = _${valuesID}[${loopVar}]`);
|
||||||
const nodeCopy = <Element>node.cloneNode(true);
|
const nodeCopy = <Element>node.cloneNode(true);
|
||||||
let shouldWarn = nodeCopy.tagName !== "t" && !nodeCopy.hasAttribute("t-key");
|
let shouldWarn =
|
||||||
if (!shouldWarn && node.tagName === "t") {
|
!nodeCopy.hasAttribute("t-key") &&
|
||||||
if (node.hasAttribute("t-component") && !node.hasAttribute("t-key")) {
|
node.children.length === 1 &&
|
||||||
shouldWarn = true;
|
node.children[0].tagName !== "t" &&
|
||||||
}
|
!node.children[0].hasAttribute("t-key");
|
||||||
if (
|
|
||||||
!shouldWarn &&
|
|
||||||
node.children.length === 1 &&
|
|
||||||
node.children[0].tagName !== "t" &&
|
|
||||||
!node.children[0].hasAttribute("t-key")
|
|
||||||
) {
|
|
||||||
shouldWarn = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (shouldWarn) {
|
if (shouldWarn) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (nodeCopy.hasAttribute("t-key")) {
|
||||||
|
const expr = ctx.formatExpression(nodeCopy.getAttribute("t-key")!);
|
||||||
|
ctx.addLine(`let key${ctx.loopNumber} = ${expr};`);
|
||||||
|
nodeCopy.removeAttribute("t-key");
|
||||||
|
} else {
|
||||||
|
ctx.addLine(`let key${ctx.loopNumber} = i${ctx.loopNumber};`);
|
||||||
|
}
|
||||||
|
|
||||||
nodeCopy.removeAttribute("t-foreach");
|
nodeCopy.removeAttribute("t-foreach");
|
||||||
qweb._compileNode(nodeCopy, ctx);
|
qweb._compileNode(nodeCopy, ctx);
|
||||||
ctx.dedent();
|
ctx.dedent();
|
||||||
ctx.addLine("}");
|
ctx.addLine("}");
|
||||||
|
ctx.stopProtectScope(varsID);
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -332,7 +366,7 @@ QWeb.addDirective({
|
|||||||
priority: 1,
|
priority: 1,
|
||||||
atNodeEncounter({ ctx }) {
|
atNodeEncounter({ ctx }) {
|
||||||
ctx.addLine("debugger;");
|
ctx.addLine("debugger;");
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -344,5 +378,5 @@ QWeb.addDirective({
|
|||||||
atNodeEncounter({ ctx, value }) {
|
atNodeEncounter({ ctx, value }) {
|
||||||
const expr = ctx.formatExpression(value);
|
const expr = ctx.formatExpression(value);
|
||||||
ctx.addLine(`console.log(${expr})`);
|
ctx.addLine(`console.log(${expr})`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { compileExpr, QWebVar } from "./expression_parser";
|
import { compileExpr, compileExprToArray, QWebVar } from "./expression_parser";
|
||||||
|
|
||||||
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -6,71 +6,73 @@ export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
export class CompilationContext {
|
export class CompilationContext {
|
||||||
nextID: number = 1;
|
static nextID: number = 1;
|
||||||
code: string[] = [];
|
code: string[] = [];
|
||||||
variables: { [key: string]: QWebVar } = {};
|
variables: { [key: string]: QWebVar } = {};
|
||||||
escaping: boolean = false;
|
escaping: boolean = false;
|
||||||
parentNode: number | null = null;
|
parentNode: number | null | string = null;
|
||||||
parentTextNode: number | null = null;
|
parentTextNode: number | null = null;
|
||||||
rootNode: number | null = null;
|
rootNode: number | null = null;
|
||||||
indentLevel: number = 0;
|
indentLevel: number = 0;
|
||||||
rootContext: CompilationContext;
|
rootContext: CompilationContext;
|
||||||
caller: Element | undefined;
|
|
||||||
shouldDefineOwner: boolean = false;
|
|
||||||
shouldDefineParent: boolean = false;
|
shouldDefineParent: boolean = false;
|
||||||
|
shouldDefineScope: boolean = false;
|
||||||
|
protectedScopeNumber: number = 0;
|
||||||
shouldDefineQWeb: boolean = false;
|
shouldDefineQWeb: boolean = false;
|
||||||
shouldDefineUtils: boolean = false;
|
shouldDefineUtils: boolean = false;
|
||||||
shouldDefineRefs: boolean = false;
|
shouldDefineRefs: boolean = false;
|
||||||
shouldDefineResult: boolean = true;
|
shouldDefineResult: boolean = true;
|
||||||
shouldProtectContext: boolean = false;
|
loopNumber: number = 0;
|
||||||
shouldTrackScope: boolean = false;
|
|
||||||
inLoop: boolean = false;
|
|
||||||
inPreTag: boolean = false;
|
inPreTag: boolean = false;
|
||||||
templateName: string;
|
templateName: string;
|
||||||
allowMultipleRoots: boolean = false;
|
allowMultipleRoots: boolean = false;
|
||||||
hasParentWidget: boolean = false;
|
hasParentWidget: boolean = false;
|
||||||
scopeVars: any[] = [];
|
hasKey0: boolean = false;
|
||||||
currentKey: string = "";
|
keyStack: boolean[] = [];
|
||||||
lastNodeKey: string = ""; // temp variable to communicate to previous caller
|
|
||||||
templates: { [key: string]: boolean } = {};
|
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.rootContext = this;
|
this.rootContext = this;
|
||||||
this.templateName = name || "noname";
|
this.templateName = name || "noname";
|
||||||
this.templates[this.templateName] = true;
|
this.addLine("let h = this.h;");
|
||||||
this.addLine("var h = this.h;");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
generateID(): number {
|
generateID(): number {
|
||||||
const id = this.rootContext.nextID++;
|
return CompilationContext.nextID++;
|
||||||
return id;
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method generates a "template key", which is basically a unique key
|
||||||
|
* which depends on the currently set keys, and on the iteration numbers (if
|
||||||
|
* we are in a loop).
|
||||||
|
*
|
||||||
|
* Such a key is necessary when we need to associate an id to some element
|
||||||
|
* generated by a template (for example, a component)
|
||||||
|
*/
|
||||||
|
generateTemplateKey(prefix: string = ""): string {
|
||||||
|
const id = this.generateID();
|
||||||
|
if (this.loopNumber === 0 && !this.hasKey0) {
|
||||||
|
return `'${prefix}__${id}__'`;
|
||||||
|
}
|
||||||
|
let key = `\`${prefix}__${id}__`;
|
||||||
|
let start = this.hasKey0 ? 0 : 1;
|
||||||
|
for (let i = start; i < this.loopNumber + 1; i++) {
|
||||||
|
key += `\${key${i}}__`;
|
||||||
|
}
|
||||||
|
this.addLine(`let k${id} = ${key}\`;`);
|
||||||
|
return `k${id}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
generateCode(): string[] {
|
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) {
|
if (this.shouldDefineResult) {
|
||||||
this.code.unshift(" let result;");
|
this.code.unshift(" let result;");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.shouldDefineScope) {
|
||||||
|
this.code.unshift(" let scope = Object.create(context);");
|
||||||
|
}
|
||||||
if (this.shouldDefineRefs) {
|
if (this.shouldDefineRefs) {
|
||||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
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.shouldDefineParent) {
|
||||||
if (this.hasParentWidget) {
|
if (this.hasParentWidget) {
|
||||||
this.code.unshift(" let parent = extra.parent;");
|
this.code.unshift(" let parent = extra.parent;");
|
||||||
@@ -111,11 +113,11 @@ export class CompilationContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
indent() {
|
indent() {
|
||||||
this.indentLevel++;
|
this.rootContext.indentLevel++;
|
||||||
}
|
}
|
||||||
|
|
||||||
dedent() {
|
dedent() {
|
||||||
this.indentLevel--;
|
this.rootContext.indentLevel--;
|
||||||
}
|
}
|
||||||
|
|
||||||
addLine(line: string): number {
|
addLine(line: string): number {
|
||||||
@@ -124,11 +126,6 @@ export class CompilationContext {
|
|||||||
return this.code.length - 1;
|
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) {
|
addIf(condition: string) {
|
||||||
this.addLine(`if (${condition}) {`);
|
this.addLine(`if (${condition}) {`);
|
||||||
this.indent();
|
this.indent();
|
||||||
@@ -145,7 +142,7 @@ export class CompilationContext {
|
|||||||
this.addLine("}");
|
this.addLine("}");
|
||||||
}
|
}
|
||||||
|
|
||||||
getValue(val: any): any {
|
getValue(val: any): QWebVar | string {
|
||||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,8 +153,27 @@ export class CompilationContext {
|
|||||||
* - replace already defined variables by their internal name
|
* - replace already defined variables by their internal name
|
||||||
*/
|
*/
|
||||||
formatExpression(expr: string): string {
|
formatExpression(expr: string): string {
|
||||||
|
this.rootContext.shouldDefineScope = true;
|
||||||
return compileExpr(expr, this.variables);
|
return compileExpr(expr, this.variables);
|
||||||
}
|
}
|
||||||
|
captureExpression(expr: string): string {
|
||||||
|
this.rootContext.shouldDefineScope = true;
|
||||||
|
const argId = this.generateID();
|
||||||
|
const tokens = compileExprToArray(expr, this.variables);
|
||||||
|
const done = new Set();
|
||||||
|
return tokens
|
||||||
|
.map((tok) => {
|
||||||
|
if (tok.varName) {
|
||||||
|
if (!done.has(tok.varName)) {
|
||||||
|
done.add(tok.varName);
|
||||||
|
this.addLine(`const ${tok.varName}_${argId} = ${tok.value};`);
|
||||||
|
}
|
||||||
|
tok.value = `${tok.varName}_${argId}`;
|
||||||
|
}
|
||||||
|
return tok.value;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Perform string interpolation on the given string. Note that if the whole
|
* Perform string interpolation on the given string. Note that if the whole
|
||||||
@@ -173,7 +189,23 @@ export class CompilationContext {
|
|||||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
return `(${this.formatExpression(s.slice(2, -2))})`;
|
||||||
}
|
}
|
||||||
|
|
||||||
let r = s.replace(/\{\{.*?\}\}/g, s => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
let r = s.replace(/\{\{.*?\}\}/g, (s) => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
||||||
return "`" + r + "`";
|
return "`" + r + "`";
|
||||||
}
|
}
|
||||||
|
startProtectScope(codeBlock?: boolean): number {
|
||||||
|
const protectID = this.generateID();
|
||||||
|
this.rootContext.protectedScopeNumber++;
|
||||||
|
this.rootContext.shouldDefineScope = true;
|
||||||
|
const scopeExpr = `Object.create(scope);`;
|
||||||
|
this.addLine(`let _origScope${protectID} = scope;`);
|
||||||
|
this.addLine(`scope = ${scopeExpr}`);
|
||||||
|
if (!codeBlock) {
|
||||||
|
this.addLine(`scope.__access_mode__ = 'ro';`);
|
||||||
|
}
|
||||||
|
return protectID;
|
||||||
|
}
|
||||||
|
stopProtectScope(protectID: number) {
|
||||||
|
this.rootContext.protectedScopeNumber--;
|
||||||
|
this.addLine(`scope = _origScope${protectID};`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
// 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(
|
||||||
","
|
","
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -35,20 +35,16 @@ const WORD_REPLACEMENT = {
|
|||||||
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
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -68,7 +64,9 @@ type TKind =
|
|||||||
interface Token {
|
interface Token {
|
||||||
type: TKind;
|
type: TKind;
|
||||||
value: string;
|
value: string;
|
||||||
|
originalValue?: string;
|
||||||
size?: number;
|
size?: number;
|
||||||
|
varName?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
||||||
@@ -79,14 +77,16 @@ 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 !== '"') {
|
||||||
@@ -114,7 +114,7 @@ let tokenizeString: Tokenizer = function(expr) {
|
|||||||
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 +128,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 +145,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 +153,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 +165,9 @@ const tokenizeOperator: Tokenizer = function(expr) {
|
|||||||
const TOKENIZERS = [
|
const TOKENIZERS = [
|
||||||
tokenizeString,
|
tokenizeString,
|
||||||
tokenizeNumber,
|
tokenizeNumber,
|
||||||
|
tokenizeOperator,
|
||||||
tokenizeSymbol,
|
tokenizeSymbol,
|
||||||
tokenizeStatic,
|
tokenizeStatic,
|
||||||
tokenizeOperator
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -230,35 +230,60 @@ 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, scope: { [key: string]: QWebVar }): Token[] {
|
||||||
|
scope = Object.create(scope);
|
||||||
const tokens = tokenize(expr);
|
const tokens = tokenize(expr);
|
||||||
let result = "";
|
|
||||||
for (let i = 0; i < tokens.length; i++) {
|
for (let i = 0; i < tokens.length; i++) {
|
||||||
let token = tokens[i];
|
let token = tokens[i];
|
||||||
|
let prevToken = tokens[i - 1];
|
||||||
|
let nextToken = tokens[i + 1];
|
||||||
|
let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value);
|
||||||
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
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];
|
|
||||||
if (prevToken) {
|
if (prevToken) {
|
||||||
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 (nextToken && nextToken.type === "OPERATOR" && nextToken.value === "=>") {
|
||||||
token.value = (<QWebExprVar>vars[token.value]).id;
|
if (token.type === "RIGHT_PAREN") {
|
||||||
} else {
|
let j = i - 1;
|
||||||
token.value = `context['${token.value}']`;
|
while (j > 0 && tokens[j].type !== "LEFT_PAREN") {
|
||||||
|
if (tokens[j].type === "SYMBOL" && tokens[j].originalValue) {
|
||||||
|
tokens[j].value = tokens[j].originalValue!;
|
||||||
|
scope[tokens[j].value] = { id: tokens[j].value, expr: tokens[j].value };
|
||||||
|
}
|
||||||
|
j--;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
scope[token.value] = { id: token.value, expr: token.value };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isVar) {
|
||||||
|
token.varName = token.value;
|
||||||
|
if (token.value in scope && "id" in scope[token.value]) {
|
||||||
|
token.value = scope[token.value].expr!;
|
||||||
|
} else {
|
||||||
|
token.originalValue = token.value;
|
||||||
|
token.value = `scope['${token.value}']`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result += token.value;
|
|
||||||
}
|
}
|
||||||
return result;
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compileExpr(expr: string, scope: { [key: string]: QWebVar }): string {
|
||||||
|
return compileExprToArray(expr, scope)
|
||||||
|
.map((t) => t.value)
|
||||||
|
.join("");
|
||||||
}
|
}
|
||||||
|
|||||||
+163
-74
@@ -23,63 +23,74 @@ import { QWeb } from "./qweb";
|
|||||||
export const MODS_CODE = {
|
export const MODS_CODE = {
|
||||||
prevent: "e.preventDefault();",
|
prevent: "e.preventDefault();",
|
||||||
self: "if (e.target !== this.elm) {return}",
|
self: "if (e.target !== this.elm) {return}",
|
||||||
stop: "e.stopPropagation();"
|
stop: "e.stopPropagation();",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface HandlerInfo {
|
||||||
|
event: string;
|
||||||
|
handler: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FNAMEREGEXP = /^[$A-Z_][0-9A-Z_$]*$/i;
|
||||||
|
|
||||||
|
export function makeHandlerCode(
|
||||||
|
ctx,
|
||||||
|
fullName,
|
||||||
|
value,
|
||||||
|
putInCache: boolean,
|
||||||
|
modcodes = MODS_CODE
|
||||||
|
): HandlerInfo {
|
||||||
|
let [event, ...mods] = fullName.slice(5).split(".");
|
||||||
|
if (mods.includes("capture")) {
|
||||||
|
event = "!" + event;
|
||||||
|
}
|
||||||
|
if (!event) {
|
||||||
|
throw new Error("Missing event name with t-on directive");
|
||||||
|
}
|
||||||
|
let code: string;
|
||||||
|
// check if it is a method with no args, a method with args or an expression
|
||||||
|
let args: string = "";
|
||||||
|
const name: string = value.replace(/\(.*\)/, function (_args) {
|
||||||
|
args = _args.slice(1, -1);
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
const isMethodCall = name.match(FNAMEREGEXP);
|
||||||
|
|
||||||
|
// then generate code
|
||||||
|
if (isMethodCall) {
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
|
const comp = `utils.getComponent(context)`;
|
||||||
|
if (args) {
|
||||||
|
const argId = ctx.generateID();
|
||||||
|
ctx.addLine(`let args${argId} = [${ctx.formatExpression(args)}];`);
|
||||||
|
code = `${comp}['${name}'](...args${argId}, e);`;
|
||||||
|
putInCache = false;
|
||||||
|
} else {
|
||||||
|
code = `${comp}['${name}'](e);`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// if we get here, then it is an expression
|
||||||
|
// we need to capture every variable in it
|
||||||
|
putInCache = false;
|
||||||
|
code = ctx.captureExpression(value);
|
||||||
|
}
|
||||||
|
const modCode = mods.map((mod) => modcodes[mod]).join("");
|
||||||
|
let handler = `function (e) {if (!context.__owl__.isMounted){return}${modCode}${code}}`;
|
||||||
|
if (putInCache) {
|
||||||
|
const key = ctx.generateTemplateKey(event);
|
||||||
|
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || ${handler};`);
|
||||||
|
handler = `extra.handlers[${key}]`;
|
||||||
|
}
|
||||||
|
return { event, handler };
|
||||||
|
}
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "on",
|
name: "on",
|
||||||
priority: 90,
|
priority: 90,
|
||||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
const { event, handler } = makeHandlerCode(ctx, fullName, value, true);
|
||||||
const [eventName, ...mods] = fullName.slice(5).split(".");
|
ctx.addLine(`p${nodeID}.on['${event}'] = ${handler};`);
|
||||||
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 "";
|
|
||||||
});
|
|
||||||
ctx.addIf(`!context['${handlerName}']`);
|
|
||||||
ctx.addLine(
|
|
||||||
`throw new Error('Missing handler \\'' + '${handlerName}' + \`\\' when evaluating template '${ctx.templateName.replace(
|
|
||||||
/`/g,
|
|
||||||
"'"
|
|
||||||
)}'\`)`
|
|
||||||
);
|
|
||||||
ctx.closeIf();
|
|
||||||
let params = extraArgs ? `owner, ${ctx.formatExpression(extraArgs)}` : "owner";
|
|
||||||
if (mods.length > 0) {
|
|
||||||
let handler = `function (e) {`;
|
|
||||||
handler += mods
|
|
||||||
.map(function(mod) {
|
|
||||||
return MODS_CODE[mod];
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
if (!extraArgs) {
|
|
||||||
handler += `context['${handlerName}'].call(${params}, e);}`;
|
|
||||||
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}'].bind(${params});`);
|
|
||||||
handler += `${handlerKey}(e);}`;
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const handler = `context['${handlerName}'].bind(${params})`;
|
|
||||||
if (extraArgs) {
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
|
||||||
} else {
|
|
||||||
ctx.addLine(
|
|
||||||
`extra.handlers['${eventName}' + ${nodeID}] = extra.handlers['${eventName}' + ${nodeID}] || ${handler};`
|
|
||||||
);
|
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -94,17 +105,17 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
||||||
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
||||||
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-transition
|
// t-transition
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
QWeb.utils.nextFrame = function(cb: () => void) {
|
QWeb.utils.nextFrame = function (cb: () => void) {
|
||||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
requestAnimationFrame(() => requestAnimationFrame(cb));
|
||||||
};
|
};
|
||||||
|
|
||||||
QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
QWeb.utils.transitionInsert = function (vn: VNode, name: string) {
|
||||||
const elm = <HTMLElement>vn.elm;
|
const elm = <HTMLElement>vn.elm;
|
||||||
// remove potential duplicated vnode that is currently being removed, to
|
// remove potential duplicated vnode that is currently being removed, to
|
||||||
// prevent from having twice the same node in the DOM during an animation
|
// prevent from having twice the same node in the DOM during an animation
|
||||||
@@ -115,6 +126,8 @@ QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
|||||||
|
|
||||||
elm.classList.add(name + "-enter");
|
elm.classList.add(name + "-enter");
|
||||||
elm.classList.add(name + "-enter-active");
|
elm.classList.add(name + "-enter-active");
|
||||||
|
elm.classList.remove(name + "-leave-active");
|
||||||
|
elm.classList.remove(name + "-leave-to");
|
||||||
const finalize = () => {
|
const finalize = () => {
|
||||||
elm.classList.remove(name + "-enter-active");
|
elm.classList.remove(name + "-enter-active");
|
||||||
elm.classList.remove(name + "-enter-to");
|
elm.classList.remove(name + "-enter-to");
|
||||||
@@ -126,13 +139,16 @@ QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
QWeb.utils.transitionRemove = function(vn: VNode, name: string, rm: () => void) {
|
QWeb.utils.transitionRemove = function (vn: VNode, name: string, rm: () => void) {
|
||||||
const elm = <HTMLElement>vn.elm;
|
const elm = <HTMLElement>vn.elm;
|
||||||
elm.setAttribute("data-owl-key", vn.key!);
|
elm.setAttribute("data-owl-key", vn.key!);
|
||||||
|
|
||||||
elm.classList.add(name + "-leave");
|
elm.classList.add(name + "-leave");
|
||||||
elm.classList.add(name + "-leave-active");
|
elm.classList.add(name + "-leave-active");
|
||||||
const finalize = () => {
|
const finalize = () => {
|
||||||
|
if (!elm.classList.contains(name + "-leave-active")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
elm.classList.remove(name + "-leave-active");
|
elm.classList.remove(name + "-leave-active");
|
||||||
elm.classList.remove(name + "-leave-to");
|
elm.classList.remove(name + "-leave-to");
|
||||||
rm();
|
rm();
|
||||||
@@ -167,6 +183,13 @@ function toMs(s: string): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function whenTransitionEnd(elm: HTMLElement, cb) {
|
function whenTransitionEnd(elm: HTMLElement, cb) {
|
||||||
|
if (!elm.parentNode) {
|
||||||
|
// if we get here, this means that the element was removed for some other
|
||||||
|
// reasons, and in that case, we don't want to work on animation since nothing
|
||||||
|
// will be displayed anyway.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const styles = window.getComputedStyle(elm);
|
const styles = window.getComputedStyle(elm);
|
||||||
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
||||||
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
||||||
@@ -186,12 +209,12 @@ QWeb.addDirective({
|
|||||||
let name = value;
|
let name = value;
|
||||||
const hooks = {
|
const hooks = {
|
||||||
insert: `utils.transitionInsert(vn, '${name}');`,
|
insert: `utils.transitionInsert(vn, '${name}');`,
|
||||||
remove: `utils.transitionRemove(vn, '${name}', rm);`
|
remove: `utils.transitionRemove(vn, '${name}', rm);`,
|
||||||
};
|
};
|
||||||
for (let hookName in hooks) {
|
for (let hookName in hooks) {
|
||||||
addNodeHook(hookName, hooks[hookName]);
|
addNodeHook(hookName, hooks[hookName]);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -200,40 +223,48 @@ QWeb.addDirective({
|
|||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "slot",
|
name: "slot",
|
||||||
priority: 80,
|
priority: 80,
|
||||||
atNodeEncounter({ ctx, value }): boolean {
|
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||||
const slotKey = ctx.generateID();
|
const slotKey = ctx.generateID();
|
||||||
ctx.rootContext.shouldDefineOwner = true;
|
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
||||||
);
|
);
|
||||||
ctx.addIf(`slot${slotKey}`);
|
ctx.addIf(`slot${slotKey}`);
|
||||||
let parentNode = `c${ctx.parentNode}`;
|
let parentNode = `c${ctx.parentNode}`;
|
||||||
if (!ctx.parentNode) {
|
if (!ctx.parentNode) {
|
||||||
ctx.rootContext.shouldDefineResult = true;
|
ctx.rootContext.shouldDefineResult = true;
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
parentNode = `children${ctx.nextID++}`;
|
parentNode = `children${ctx.generateID()}`;
|
||||||
ctx.addLine(`let ${parentNode}= []`);
|
ctx.addLine(`let ${parentNode}= []`);
|
||||||
ctx.addLine(`result = {}`);
|
ctx.addLine(`result = {}`);
|
||||||
}
|
}
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, vars: extra.vars, parent: owner}));`
|
`slot${slotKey}.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: ${parentNode}, parent: extra.parent || context}));`
|
||||||
);
|
);
|
||||||
if (!ctx.parentNode) {
|
if (!ctx.parentNode) {
|
||||||
ctx.addLine(`Promise.all(extra.promises).then(() => utils.defineProxy(result, ${parentNode}[0]))`);
|
ctx.addLine(`utils.defineProxy(result, ${parentNode}[0]);`);
|
||||||
|
}
|
||||||
|
if (node.hasChildNodes()) {
|
||||||
|
ctx.addElse();
|
||||||
|
const nodeCopy = <Element>node.cloneNode(true);
|
||||||
|
nodeCopy.removeAttribute("t-slot");
|
||||||
|
qweb._compileNode(nodeCopy, ctx);
|
||||||
}
|
}
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-model
|
// t-model
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
QWeb.utils.toNumber = function(val: string): number | string {
|
QWeb.utils.toNumber = function (val: string): number | string {
|
||||||
const n = parseFloat(val);
|
const n = parseFloat(val);
|
||||||
return isNaN(n) ? val : n;
|
return isNaN(n) ? val : n;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const hasDotAtTheEnd = /\.[\w_]+\s*$/;
|
||||||
|
const hasBracketsAtTheEnd = /\[[^\[]+\]\s*$/;
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "model",
|
name: "model",
|
||||||
priority: 42,
|
priority: 42,
|
||||||
@@ -241,7 +272,43 @@ QWeb.addDirective({
|
|||||||
const type = node.getAttribute("type");
|
const type = node.getAttribute("type");
|
||||||
let handler;
|
let handler;
|
||||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
let event = fullName.includes(".lazy") ? "change" : "input";
|
||||||
const expr = ctx.formatExpression(value);
|
|
||||||
|
// First step: we need to understand the structure of the expression, and
|
||||||
|
// from it, extract a base expression (that we can capture, which is
|
||||||
|
// important because it will be used in a handler later) and a formatted
|
||||||
|
// expression (which uses the captured base expression)
|
||||||
|
//
|
||||||
|
// Also, we support 2 kinds of values: some.expr.value or some.expr[value]
|
||||||
|
// For the first one, we have:
|
||||||
|
// - base expression = scope[some].expr
|
||||||
|
// - expression = exprX.value (where exprX is the var that captures the base expr)
|
||||||
|
// and for the expression with brackets:
|
||||||
|
// - base expression = scope[some].expr
|
||||||
|
// - expression = exprX[keyX] (where exprX is the var that captures the base expr
|
||||||
|
// and keyX captures scope[value])
|
||||||
|
let expr: string;
|
||||||
|
let baseExpr: string;
|
||||||
|
|
||||||
|
if (hasDotAtTheEnd.test(value)) {
|
||||||
|
// we manage the case where the expr has a dot: some.expr.value
|
||||||
|
const index = value.lastIndexOf(".");
|
||||||
|
baseExpr = value.slice(0, index);
|
||||||
|
ctx.addLine(`let expr${nodeID} = ${ctx.formatExpression(baseExpr)};`);
|
||||||
|
expr = `expr${nodeID}${value.slice(index)}`;
|
||||||
|
} else if (hasBracketsAtTheEnd.test(value)) {
|
||||||
|
// we manage here the case where the expr ends in a bracket expression:
|
||||||
|
// some.expr[value]
|
||||||
|
const index = value.lastIndexOf("[");
|
||||||
|
baseExpr = value.slice(0, index);
|
||||||
|
ctx.addLine(`let expr${nodeID} = ${ctx.formatExpression(baseExpr)};`);
|
||||||
|
let exprKey = value.trimRight().slice(index + 1, -1);
|
||||||
|
ctx.addLine(`let exprKey${nodeID} = ${ctx.formatExpression(exprKey)};`);
|
||||||
|
expr = `expr${nodeID}[exprKey${nodeID}]`;
|
||||||
|
} else {
|
||||||
|
throw new Error(`Invalid t-model expression: "${value}" (it should be assignable)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = ctx.generateTemplateKey();
|
||||||
if (node.tagName === "select") {
|
if (node.tagName === "select") {
|
||||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||||
addNodeHook("create", `n.elm.value=${expr};`);
|
addNodeHook("create", `n.elm.value=${expr};`);
|
||||||
@@ -265,9 +332,31 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
handler = `(ev) => {${expr} = ${valueCode}}`;
|
handler = `(ev) => {${expr} = ${valueCode}}`;
|
||||||
}
|
}
|
||||||
ctx.addLine(
|
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || (${handler});`);
|
||||||
`extra.handlers['${event}' + ${nodeID}] = extra.handlers['${event}' + ${nodeID}] || (${handler});`
|
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers[${key}];`);
|
||||||
);
|
},
|
||||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
|
});
|
||||||
}
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// t-key
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
QWeb.addDirective({
|
||||||
|
name: "key",
|
||||||
|
priority: 45,
|
||||||
|
atNodeEncounter({ ctx, value, node }) {
|
||||||
|
if (ctx.loopNumber === 0) {
|
||||||
|
ctx.keyStack.push(ctx.rootContext.hasKey0);
|
||||||
|
ctx.rootContext.hasKey0 = true;
|
||||||
|
}
|
||||||
|
ctx.addLine("{");
|
||||||
|
ctx.indent();
|
||||||
|
ctx.addLine(`let key${ctx.loopNumber} = ${ctx.formatExpression(value)};`);
|
||||||
|
},
|
||||||
|
finalize({ ctx }) {
|
||||||
|
ctx.dedent();
|
||||||
|
ctx.addLine("}");
|
||||||
|
if (ctx.loopNumber === 0) {
|
||||||
|
ctx.rootContext.hasKey0 = ctx.keyStack.pop() as boolean;
|
||||||
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
+198
-90
@@ -1,7 +1,7 @@
|
|||||||
import { EventBus } from "../core/event_bus";
|
import { EventBus } from "../core/event_bus";
|
||||||
import { h, patch, VNode } from "../vdom/index";
|
import { h, patch, VNode } from "../vdom/index";
|
||||||
import { CompilationContext } from "./compilation_context";
|
import { CompilationContext } from "./compilation_context";
|
||||||
import { shallowEqual } from "../utils";
|
import { shallowEqual, escape } from "../utils";
|
||||||
import { addNS } from "../vdom/vdom";
|
import { addNS } from "../vdom/vdom";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -57,11 +57,16 @@ export interface Directive {
|
|||||||
finalize?(info: CompilationInfo): void;
|
finalize?(info: CompilationInfo): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface QWebConfig {
|
||||||
|
templates?: string;
|
||||||
|
translateFn?(text: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Const/global stuff/helpers
|
// 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 lineBreakRE = /[\r\n]/;
|
||||||
const whitespaceRE = /\s+/g;
|
const whitespaceRE = /\s+/g;
|
||||||
@@ -70,7 +75,7 @@ const NODE_HOOKS_PARAMS = {
|
|||||||
create: "(_, n)",
|
create: "(_, n)",
|
||||||
insert: "vn",
|
insert: "vn",
|
||||||
remove: "(vn, rm)",
|
remove: "(vn, rm)",
|
||||||
destroy: "()"
|
destroy: "()",
|
||||||
};
|
};
|
||||||
|
|
||||||
interface Utils {
|
interface Utils {
|
||||||
@@ -79,7 +84,32 @@ interface Utils {
|
|||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isComponent(obj): boolean {
|
||||||
|
return obj && obj.hasOwnProperty("__owl__");
|
||||||
|
}
|
||||||
|
|
||||||
|
class VDomArray extends Array {
|
||||||
|
toString() {
|
||||||
|
return vDomToString(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function vDomToString(vdom: VNode[]): string {
|
||||||
|
return vdom
|
||||||
|
.map((vnode) => {
|
||||||
|
if (vnode.sel) {
|
||||||
|
const node = document.createElement(vnode.sel);
|
||||||
|
const result = patch(node, vnode);
|
||||||
|
return (<HTMLElement>result.elm).outerHTML;
|
||||||
|
} else {
|
||||||
|
return vnode.text;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
const UTILS: Utils = {
|
const UTILS: Utils = {
|
||||||
|
zero: Symbol("zero"),
|
||||||
toObj(expr) {
|
toObj(expr) {
|
||||||
if (typeof expr === "string") {
|
if (typeof expr === "string") {
|
||||||
expr = expr.trim();
|
expr = expr.trim();
|
||||||
@@ -98,7 +128,30 @@ const UTILS: Utils = {
|
|||||||
shallowEqual,
|
shallowEqual,
|
||||||
addNameSpace(vnode) {
|
addNameSpace(vnode) {
|
||||||
addNS(vnode.data, vnode.children, vnode.sel);
|
addNS(vnode.data, vnode.children, vnode.sel);
|
||||||
}
|
},
|
||||||
|
VDomArray,
|
||||||
|
vDomToString,
|
||||||
|
getComponent(obj) {
|
||||||
|
while (obj && !isComponent(obj)) {
|
||||||
|
obj = obj.__proto__;
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
},
|
||||||
|
getScope(obj, property: string) {
|
||||||
|
const obj0 = obj;
|
||||||
|
while (
|
||||||
|
obj &&
|
||||||
|
!obj.hasOwnProperty(property) &&
|
||||||
|
!(obj.hasOwnProperty("__access_mode__") && obj.__access_mode__ === "ro")
|
||||||
|
) {
|
||||||
|
const newObj = obj.__proto__;
|
||||||
|
if (!newObj || isComponent(newObj)) {
|
||||||
|
return obj0;
|
||||||
|
}
|
||||||
|
obj = newObj;
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseXML(xml: string): Document {
|
function parseXML(xml: string): Document {
|
||||||
@@ -131,9 +184,14 @@ function parseXML(xml: string): Document {
|
|||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escapeQuotes(str: string): string {
|
||||||
|
return str.replace(/\'/g, "\\'");
|
||||||
|
}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// QWeb rendering engine
|
// QWeb rendering engine
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
export class QWeb extends EventBus {
|
export class QWeb extends EventBus {
|
||||||
templates: { [name: string]: Template };
|
templates: { [name: string]: Template };
|
||||||
static utils = UTILS;
|
static utils = UTILS;
|
||||||
@@ -143,7 +201,7 @@ export class QWeb extends EventBus {
|
|||||||
name: 1,
|
name: 1,
|
||||||
att: 1,
|
att: 1,
|
||||||
attf: 1,
|
attf: 1,
|
||||||
key: 1
|
translation: 1,
|
||||||
};
|
};
|
||||||
static DIRECTIVES: Directive[] = [];
|
static DIRECTIVES: Directive[] = [];
|
||||||
|
|
||||||
@@ -160,18 +218,24 @@ export class QWeb extends EventBus {
|
|||||||
static slots = {};
|
static slots = {};
|
||||||
static nextSlotId = 1;
|
static nextSlotId = 1;
|
||||||
|
|
||||||
// recursiveTemplates contains sub templates called with t-call, but which
|
// subTemplates are stored in two objects: a (local) mapping from a name to an
|
||||||
// ends up in recursive situations. This is very similar to the slot situation,
|
// id, and a (global) mapping from an id to the compiled function. This is
|
||||||
// as in we need to propagate the scope.
|
// necessary to ensure that global templates can be called with more than one
|
||||||
recursiveFns = {};
|
// QWeb instance.
|
||||||
|
subTemplates: { [key: string]: number } = {};
|
||||||
|
static subTemplates: { [id: number]: Function } = {};
|
||||||
|
|
||||||
isUpdating: boolean = false;
|
isUpdating: boolean = false;
|
||||||
|
translateFn?: QWebConfig["translateFn"];
|
||||||
|
|
||||||
constructor(data?: string) {
|
constructor(config: QWebConfig = {}) {
|
||||||
super();
|
super();
|
||||||
this.templates = Object.create(QWeb.TEMPLATES);
|
this.templates = Object.create(QWeb.TEMPLATES);
|
||||||
if (data) {
|
if (config.templates) {
|
||||||
this.addTemplates(data);
|
this.addTemplates(config.templates);
|
||||||
|
}
|
||||||
|
if (config.translateFn) {
|
||||||
|
this.translateFn = config.translateFn;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,7 +247,7 @@ export class QWeb extends EventBus {
|
|||||||
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
||||||
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
||||||
if (directive.extraNames) {
|
if (directive.extraNames) {
|
||||||
directive.extraNames.forEach(n => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
directive.extraNames.forEach((n) => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,11 +311,11 @@ export class QWeb extends EventBus {
|
|||||||
this._processTemplate(elem);
|
this._processTemplate(elem);
|
||||||
const template = {
|
const template = {
|
||||||
elem,
|
elem,
|
||||||
fn: function(this: QWeb, context, extra) {
|
fn: function (this: QWeb, context, extra) {
|
||||||
const compiledFunction = this._compile(name, elem);
|
const compiledFunction = this._compile(name, elem);
|
||||||
template.fn = compiledFunction;
|
template.fn = compiledFunction;
|
||||||
return compiledFunction.call(this, context, extra);
|
return compiledFunction.call(this, context, extra);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
this.templates[name] = template;
|
this.templates[name] = template;
|
||||||
}
|
}
|
||||||
@@ -261,10 +325,10 @@ export class QWeb extends EventBus {
|
|||||||
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
||||||
let node = tbranch[i];
|
let node = tbranch[i];
|
||||||
let prevElem = node.previousElementSibling!;
|
let prevElem = node.previousElementSibling!;
|
||||||
let pattr = function(name) {
|
let pattr = function (name) {
|
||||||
return prevElem.getAttribute(name);
|
return prevElem.getAttribute(name);
|
||||||
};
|
};
|
||||||
let nattr = function(name) {
|
let nattr = function (name) {
|
||||||
return +!!node.getAttribute(name);
|
return +!!node.getAttribute(name);
|
||||||
};
|
};
|
||||||
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
||||||
@@ -274,16 +338,17 @@ export class QWeb extends EventBus {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
["t-if", "t-elif", "t-else"].map(nattr).reduce(function(a, b) {
|
["t-if", "t-elif", "t-else"].map(nattr).reduce(function (a, b) {
|
||||||
return a + b;
|
return a + b;
|
||||||
}) > 1
|
}) > 1
|
||||||
) {
|
) {
|
||||||
throw new Error("Only one conditional branching directive is allowed per node");
|
throw new Error("Only one conditional branching directive is allowed per node");
|
||||||
}
|
}
|
||||||
// All text nodes between branch nodes are removed
|
// All text (with only spaces) and comment nodes (nodeType 8) between
|
||||||
|
// branch nodes are removed
|
||||||
let textNode;
|
let textNode;
|
||||||
while ((textNode = node.previousSibling) !== prevElem) {
|
while ((textNode = node.previousSibling) !== prevElem) {
|
||||||
if (textNode.nodeValue.trim().length) {
|
if (textNode.nodeValue.trim().length && textNode.nodeType !== 8) {
|
||||||
throw new Error("text is not allowed between branching directives");
|
throw new Error("text is not allowed between branching directives");
|
||||||
}
|
}
|
||||||
textNode.remove();
|
textNode.remove();
|
||||||
@@ -321,8 +386,17 @@ export class QWeb extends EventBus {
|
|||||||
return vnode.text!;
|
return vnode.text!;
|
||||||
}
|
}
|
||||||
const node = document.createElement(vnode.sel);
|
const node = document.createElement(vnode.sel);
|
||||||
const result = patch(node, vnode);
|
const elem = patch(node, vnode).elm as HTMLElement;
|
||||||
return (<HTMLElement>result.elm).outerHTML;
|
function escapeTextNodes(node) {
|
||||||
|
if (node.nodeType === 3) {
|
||||||
|
node.textContent = escape(node.textContent);
|
||||||
|
}
|
||||||
|
for (let n of node.childNodes) {
|
||||||
|
escapeTextNodes(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
escapeTextNodes(elem);
|
||||||
|
return elem.outerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -341,32 +415,29 @@ export class QWeb extends EventBus {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_compile(name: string, elem: Element, parentContext?: CompilationContext): CompiledTemplate {
|
_compile(
|
||||||
|
name: string,
|
||||||
|
elem: Element,
|
||||||
|
parentContext?: CompilationContext,
|
||||||
|
defineKey?: boolean
|
||||||
|
): CompiledTemplate {
|
||||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
||||||
const ctx = new CompilationContext(name);
|
const ctx = new CompilationContext(name);
|
||||||
if (elem.tagName !== "t") {
|
if (elem.tagName !== "t") {
|
||||||
ctx.shouldDefineResult = false;
|
ctx.shouldDefineResult = false;
|
||||||
}
|
}
|
||||||
if (parentContext) {
|
if (parentContext) {
|
||||||
ctx.templates = Object.create(parentContext.templates);
|
|
||||||
ctx.variables = Object.create(parentContext.variables);
|
ctx.variables = Object.create(parentContext.variables);
|
||||||
ctx.nextID = parentContext.nextID + 1;
|
ctx.parentNode = parentContext.parentNode || ctx.generateID();
|
||||||
ctx.parentNode = parentContext.parentNode || ctx.nextID++;
|
|
||||||
ctx.allowMultipleRoots = true;
|
ctx.allowMultipleRoots = true;
|
||||||
ctx.hasParentWidget = true;
|
ctx.hasParentWidget = true;
|
||||||
ctx.shouldDefineResult = false;
|
ctx.shouldDefineResult = false;
|
||||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
||||||
|
if (defineKey) {
|
||||||
for (let v in parentContext.variables) {
|
ctx.addLine(`let key0 = extra.key || "";`);
|
||||||
let variable = <any>parentContext.variables[v];
|
ctx.hasKey0 = true;
|
||||||
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);
|
this._compileNode(elem, ctx);
|
||||||
|
|
||||||
if (!parentContext) {
|
if (!parentContext) {
|
||||||
@@ -381,12 +452,13 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let code = ctx.generateCode();
|
let code = ctx.generateCode();
|
||||||
|
const templateName = ctx.templateName.replace(/`/g, "'").slice(0, 200);
|
||||||
|
code.unshift(` // Template name: "${templateName}"`);
|
||||||
|
|
||||||
let template;
|
let template;
|
||||||
try {
|
try {
|
||||||
template = new Function("context", "extra", code.join("\n")) as CompiledTemplate;
|
template = new Function("context, extra", code.join("\n")) as CompiledTemplate;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const templateName = ctx.templateName.replace(/`/g, "'");
|
|
||||||
console.groupCollapsed(`Invalid Code generated by ${templateName}`);
|
console.groupCollapsed(`Invalid Code generated by ${templateName}`);
|
||||||
console.warn(code.join("\n"));
|
console.warn(code.join("\n"));
|
||||||
console.groupEnd();
|
console.groupEnd();
|
||||||
@@ -418,6 +490,11 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
text = text.replace(whitespaceRE, " ");
|
text = text.replace(whitespaceRE, " ");
|
||||||
}
|
}
|
||||||
|
if (this.translateFn) {
|
||||||
|
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
||||||
|
text = this.translateFn(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
if (node.nodeType === 3) {
|
if (node.nodeType === 3) {
|
||||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||||
@@ -430,7 +507,7 @@ export class QWeb extends EventBus {
|
|||||||
// this is an unusual situation: this text node is the result of the
|
// this is an unusual situation: this text node is the result of the
|
||||||
// template rendering.
|
// template rendering.
|
||||||
let nodeID = ctx.generateID();
|
let nodeID = ctx.generateID();
|
||||||
ctx.addLine(`var vn${nodeID} = {text: \`${text}\`};`);
|
ctx.addLine(`let vn${nodeID} = {text: \`${text}\`};`);
|
||||||
ctx.addLine(`result = vn${nodeID};`);
|
ctx.addLine(`result = vn${nodeID};`);
|
||||||
ctx.rootContext.rootNode = nodeID;
|
ctx.rootContext.rootNode = nodeID;
|
||||||
ctx.rootContext.parentTextNode = nodeID;
|
ctx.rootContext.parentTextNode = nodeID;
|
||||||
@@ -438,11 +515,22 @@ export class QWeb extends EventBus {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (node.tagName !== "t" && node.hasAttribute("t-call")) {
|
||||||
|
const tCallNode = document.createElement("t");
|
||||||
|
tCallNode.setAttribute("t-call", node.getAttribute("t-call")!);
|
||||||
|
node.removeAttribute("t-call");
|
||||||
|
node.prepend(tCallNode);
|
||||||
|
}
|
||||||
|
|
||||||
const firstLetter = node.tagName[0];
|
const firstLetter = node.tagName[0];
|
||||||
if (firstLetter === firstLetter.toUpperCase()) {
|
if (firstLetter === firstLetter.toUpperCase()) {
|
||||||
// this is a component, we modify in place the xml document to change
|
// this is a component, we modify in place the xml document to change
|
||||||
// <SomeComponent ... /> to <t t-component="SomeComponent" ... />
|
// <SomeComponent ... /> to <SomeComponent t-component="SomeComponent" ... />
|
||||||
node.setAttribute("t-component", node.tagName);
|
node.setAttribute("t-component", node.tagName);
|
||||||
|
} else if (node.tagName !== "t" && node.hasAttribute("t-component")) {
|
||||||
|
throw new Error(
|
||||||
|
`Directive 't-component' can only be used on <t> nodes (used on a <${node.tagName}>)`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const attributes = (<Element>node).attributes;
|
const attributes = (<Element>node).attributes;
|
||||||
|
|
||||||
@@ -452,6 +540,8 @@ export class QWeb extends EventBus {
|
|||||||
fullName: string;
|
fullName: string;
|
||||||
}[] = [];
|
}[] = [];
|
||||||
|
|
||||||
|
const finalizers: typeof validDirectives = [];
|
||||||
|
|
||||||
// maybe this is not optimal: we iterate on all attributes here, and again
|
// maybe this is not optimal: we iterate on all attributes here, and again
|
||||||
// just after for each directive.
|
// just after for each directive.
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
for (let i = 0; i < attributes.length; i++) {
|
||||||
@@ -496,16 +586,23 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let { directive, value, fullName } of validDirectives) {
|
for (let { directive, value, fullName } of validDirectives) {
|
||||||
|
if (directive.finalize) {
|
||||||
|
finalizers.push({ directive, value, fullName });
|
||||||
|
}
|
||||||
if (directive.atNodeEncounter) {
|
if (directive.atNodeEncounter) {
|
||||||
const isDone = directive.atNodeEncounter({
|
const isDone = directive.atNodeEncounter({
|
||||||
node,
|
node,
|
||||||
qweb: this,
|
qweb: this,
|
||||||
ctx,
|
ctx,
|
||||||
fullName,
|
fullName,
|
||||||
value
|
value,
|
||||||
});
|
});
|
||||||
if (isDone) {
|
if (isDone) {
|
||||||
|
for (let { directive, value, fullName } of finalizers) {
|
||||||
|
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -514,9 +611,8 @@ export class QWeb extends EventBus {
|
|||||||
if (node.nodeName !== "t") {
|
if (node.nodeName !== "t") {
|
||||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||||
ctx = ctx.withParent(nodeID);
|
ctx = ctx.withParent(nodeID);
|
||||||
ctx = ctx.subContext("currentKey", ctx.lastNodeKey);
|
|
||||||
let nodeHooks = {};
|
let nodeHooks = {};
|
||||||
let addNodeHook = function(hook, handler) {
|
let addNodeHook = function (hook, handler) {
|
||||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||||
nodeHooks[hook].push(handler);
|
nodeHooks[hook].push(handler);
|
||||||
};
|
};
|
||||||
@@ -530,7 +626,7 @@ export class QWeb extends EventBus {
|
|||||||
fullName,
|
fullName,
|
||||||
value,
|
value,
|
||||||
nodeID,
|
nodeID,
|
||||||
addNodeHook
|
addNodeHook,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -564,10 +660,8 @@ export class QWeb extends EventBus {
|
|||||||
ctx.addLine(`utils.addNameSpace(vn${ctx.parentNode});`);
|
ctx.addLine(`utils.addNameSpace(vn${ctx.parentNode});`);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let { directive, value, fullName } of validDirectives) {
|
for (let { directive, value, fullName } of finalizers) {
|
||||||
if (directive.finalize) {
|
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||||
directive.finalize({ node, qweb: this, ctx, fullName, value });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -585,22 +679,31 @@ export class QWeb extends EventBus {
|
|||||||
const props: string[] = [];
|
const props: string[] = [];
|
||||||
const tattrs: number[] = [];
|
const tattrs: number[] = [];
|
||||||
|
|
||||||
function handleBooleanProps(key, val) {
|
function handleProperties(key, val) {
|
||||||
let isProp = false;
|
let isProp = false;
|
||||||
if (node.nodeName === "input" && key === "checked") {
|
switch (node.nodeName) {
|
||||||
let type = (<Element>node).getAttribute("type");
|
case "input":
|
||||||
if (type === "checkbox" || type === "radio") {
|
let type = (<Element>node).getAttribute("type");
|
||||||
isProp = true;
|
if (type === "checkbox" || type === "radio") {
|
||||||
}
|
if (key === "checked" || key === "indeterminate") {
|
||||||
}
|
isProp = true;
|
||||||
if (node.nodeName === "option" && key === "selected") {
|
}
|
||||||
isProp = true;
|
}
|
||||||
}
|
if (key === "value" || key === "readonly" || key === "disabled") {
|
||||||
if (key === "disabled" && DISABLED_TAGS.indexOf(node.nodeName) > -1) {
|
isProp = true;
|
||||||
isProp = true;
|
}
|
||||||
}
|
break;
|
||||||
if ((key === "readonly" && node.nodeName === "input") || node.nodeName === "textarea") {
|
case "option":
|
||||||
isProp = true;
|
isProp = key === "selected" || key === "disabled";
|
||||||
|
break;
|
||||||
|
case "textarea":
|
||||||
|
isProp = key === "readonly" || key === "disabled";
|
||||||
|
break;
|
||||||
|
case "button":
|
||||||
|
case "select":
|
||||||
|
case "optgroup":
|
||||||
|
isProp = key === "disabled";
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
if (isProp) {
|
if (isProp) {
|
||||||
props.push(`${key}: _${val}`);
|
props.push(`${key}: _${val}`);
|
||||||
@@ -610,27 +713,36 @@ export class QWeb extends EventBus {
|
|||||||
|
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
for (let i = 0; i < attributes.length; i++) {
|
||||||
let name = attributes[i].name;
|
let name = attributes[i].name;
|
||||||
const value = attributes[i].textContent!;
|
let value = attributes[i].textContent!;
|
||||||
|
|
||||||
|
if (this.translateFn && TRANSLATABLE_ATTRS.includes(name)) {
|
||||||
|
value = this.translateFn(value);
|
||||||
|
}
|
||||||
|
|
||||||
// regular attributes
|
// regular attributes
|
||||||
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
||||||
const attID = ctx.generateID();
|
const attID = ctx.generateID();
|
||||||
if (name === "class") {
|
if (name === "class") {
|
||||||
let classDef = value
|
if ((value = value.trim())) {
|
||||||
.trim()
|
let classDef = value
|
||||||
.split(/\s+/)
|
.split(/\s+/)
|
||||||
.map(a => `'${a}':true`)
|
.map((a) => `'${escapeQuotes(a)}':true`)
|
||||||
.join(",");
|
.join(",");
|
||||||
classObj = `_${ctx.generateID()}`;
|
if (classObj) {
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
ctx.addLine(`Object.assign(${classObj}, {${classDef}})`);
|
||||||
|
} else {
|
||||||
|
classObj = `_${ctx.generateID()}`;
|
||||||
|
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
ctx.addLine(`var _${attID} = '${value}';`);
|
ctx.addLine(`let _${attID} = '${escapeQuotes(value)}';`);
|
||||||
if (!name.match(/^[a-zA-Z]+$/)) {
|
if (!name.match(/^[a-zA-Z]+$/)) {
|
||||||
// attribute contains 'non letters' => we want to quote it
|
// attribute contains 'non letters' => we want to quote it
|
||||||
name = '"' + name + '"';
|
name = '"' + name + '"';
|
||||||
}
|
}
|
||||||
attrs.push(`${name}: _${attID}`);
|
attrs.push(`${name}: _${attID}`);
|
||||||
handleBooleanProps(name, attID);
|
handleProperties(name, attID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,7 +750,7 @@ export class QWeb extends EventBus {
|
|||||||
if (name.startsWith("t-att-")) {
|
if (name.startsWith("t-att-")) {
|
||||||
let attName = name.slice(6);
|
let attName = name.slice(6);
|
||||||
const v = ctx.getValue(value);
|
const v = ctx.getValue(value);
|
||||||
let formattedValue = v.id || ctx.formatExpression(v);
|
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : `scope.${v.id}`;
|
||||||
|
|
||||||
if (attName === "class") {
|
if (attName === "class") {
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
@@ -660,14 +772,14 @@ export class QWeb extends EventBus {
|
|||||||
const attValue = (<Element>node).getAttribute(attName);
|
const attValue = (<Element>node).getAttribute(attName);
|
||||||
if (attValue) {
|
if (attValue) {
|
||||||
const attValueID = ctx.generateID();
|
const attValueID = ctx.generateID();
|
||||||
ctx.addLine(`var _${attValueID} = ${formattedValue};`);
|
ctx.addLine(`let _${attValueID} = ${formattedValue};`);
|
||||||
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
||||||
const attrIndex = attrs.findIndex(att => att.startsWith(attName + ":"));
|
const attrIndex = attrs.findIndex((att) => att.startsWith(attName + ":"));
|
||||||
attrs.splice(attrIndex, 1);
|
attrs.splice(attrIndex, 1);
|
||||||
}
|
}
|
||||||
ctx.addLine(`var _${attID} = ${formattedValue};`);
|
ctx.addLine(`let _${attID} = ${formattedValue};`);
|
||||||
attrs.push(`${attName}: _${attID}`);
|
attrs.push(`${attName}: _${attID}`);
|
||||||
handleBooleanProps(attName, attID);
|
handleProperties(attName, attID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -681,9 +793,9 @@ export class QWeb extends EventBus {
|
|||||||
const attID = ctx.generateID();
|
const attID = ctx.generateID();
|
||||||
let staticVal = (<Element>node).getAttribute(attName);
|
let staticVal = (<Element>node).getAttribute(attName);
|
||||||
if (staticVal) {
|
if (staticVal) {
|
||||||
ctx.addLine(`var _${attID} = '${staticVal} ' + ${formattedExpr};`);
|
ctx.addLine(`let _${attID} = '${staticVal} ' + ${formattedExpr};`);
|
||||||
} else {
|
} else {
|
||||||
ctx.addLine(`var _${attID} = ${formattedExpr};`);
|
ctx.addLine(`let _${attID} = ${formattedExpr};`);
|
||||||
}
|
}
|
||||||
attrs.push(`${attName}: _${attID}`);
|
attrs.push(`${attName}: _${attID}`);
|
||||||
}
|
}
|
||||||
@@ -691,20 +803,13 @@ export class QWeb extends EventBus {
|
|||||||
// t-att= attributes
|
// t-att= attributes
|
||||||
if (name === "t-att") {
|
if (name === "t-att") {
|
||||||
let id = ctx.generateID();
|
let id = ctx.generateID();
|
||||||
ctx.addLine(`var _${id} = ${ctx.formatExpression(value!)};`);
|
ctx.addLine(`let _${id} = ${ctx.formatExpression(value!)};`);
|
||||||
tattrs.push(id);
|
tattrs.push(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let nodeID = ctx.generateID();
|
let nodeID = ctx.generateID();
|
||||||
let nodeKey: any = (<Element>node).getAttribute("t-key");
|
let key = ctx.loopNumber || ctx.hasKey0 ? `\`\${key${ctx.loopNumber}}_${nodeID}\`` : nodeID;
|
||||||
if (nodeKey) {
|
const parts = [`key:${key}`];
|
||||||
ctx.addLine(`const nodeKey${nodeID} = ${ctx.formatExpression(nodeKey)}`);
|
|
||||||
nodeKey = `nodeKey${nodeID}`;
|
|
||||||
ctx.lastNodeKey = nodeKey;
|
|
||||||
} else {
|
|
||||||
nodeKey = nodeID;
|
|
||||||
}
|
|
||||||
const parts = [`key:${nodeKey}`];
|
|
||||||
if (attrs.length + tattrs.length > 0) {
|
if (attrs.length + tattrs.length > 0) {
|
||||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
parts.push(`attrs:{${attrs.join(",")}}`);
|
||||||
}
|
}
|
||||||
@@ -730,9 +835,12 @@ export class QWeb extends EventBus {
|
|||||||
ctx.addLine(`}`);
|
ctx.addLine(`}`);
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
}
|
||||||
ctx.addLine(`var vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`);
|
ctx.addLine(`let vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`);
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
||||||
|
} else if (ctx.loopNumber || ctx.hasKey0) {
|
||||||
|
ctx.rootContext.shouldDefineResult = true;
|
||||||
|
ctx.addLine(`result = vn${nodeID};`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nodeID;
|
return nodeID;
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ import { Destination, RouterEnv } from "./router";
|
|||||||
|
|
||||||
type Props = Destination;
|
type Props = Destination;
|
||||||
|
|
||||||
export class Link<Env extends RouterEnv> extends Component<Env, Props> {
|
export class Link<Env extends RouterEnv> extends Component<Props, Env> {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<a t-att-class="{'router-link-active': isActive }"
|
<a t-att-class="{'router-link-active': isActive }"
|
||||||
t-att-href="href"
|
t-att-href="href"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Component } from "../component/component";
|
import { Component } from "../component/component";
|
||||||
import { xml } from "../tags";
|
import { xml } from "../tags";
|
||||||
|
import { EnvWithRouter } from "./router";
|
||||||
|
|
||||||
export class RouteComponent extends Component<any, {}> {
|
export class RouteComponent extends Component<{}, EnvWithRouter> {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<t>
|
<t>
|
||||||
<t
|
<t
|
||||||
|
|||||||
+13
-5
@@ -49,6 +49,10 @@ interface Options {
|
|||||||
mode: Router["mode"];
|
mode: Router["mode"];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface EnvWithRouter extends Env {
|
||||||
|
router: Router;
|
||||||
|
}
|
||||||
|
|
||||||
const paramRegexp = /\{\{(.*?)\}\}/;
|
const paramRegexp = /\{\{(.*?)\}\}/;
|
||||||
|
|
||||||
export class Router {
|
export class Router {
|
||||||
@@ -60,7 +64,11 @@ export class Router {
|
|||||||
routeIds: string[];
|
routeIds: string[];
|
||||||
env: RouterEnv;
|
env: RouterEnv;
|
||||||
|
|
||||||
constructor(env: Env, routes: Partial<Route>[], options: Options = { mode: "history" }) {
|
constructor(
|
||||||
|
env: Partial<EnvWithRouter>,
|
||||||
|
routes: Partial<Route>[],
|
||||||
|
options: Options = { mode: "history" }
|
||||||
|
) {
|
||||||
env.router = this;
|
env.router = this;
|
||||||
this.mode = options.mode;
|
this.mode = options.mode;
|
||||||
this.env = env as RouterEnv;
|
this.env = env as RouterEnv;
|
||||||
@@ -89,7 +97,7 @@ export class Router {
|
|||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
(this as any)._listener = ev => this._navigate(this.currentPath(), ev);
|
(this as any)._listener = (ev) => this._navigate(this.currentPath(), ev);
|
||||||
window.addEventListener("popstate", (this as any)._listener);
|
window.addEventListener("popstate", (this as any)._listener);
|
||||||
if (this.mode === "hash") {
|
if (this.mode === "hash") {
|
||||||
window.addEventListener("hashchange", (this as any)._listener);
|
window.addEventListener("hashchange", (this as any)._listener);
|
||||||
@@ -148,7 +156,7 @@ export class Router {
|
|||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
private setUrlFromPath(path: string) {
|
private setUrlFromPath(path: string) {
|
||||||
const separator = this.mode === "hash" ? "/" : "";
|
const separator = this.mode === "hash" ? location.pathname : "";
|
||||||
const url = location.origin + separator + path;
|
const url = location.origin + separator + path;
|
||||||
if (url !== window.location.href) {
|
if (url !== window.location.href) {
|
||||||
window.history.pushState({}, path, url);
|
window.history.pushState({}, path, url);
|
||||||
@@ -190,7 +198,7 @@ export class Router {
|
|||||||
return {
|
return {
|
||||||
type: "match",
|
type: "match",
|
||||||
route: route,
|
route: route,
|
||||||
params: params
|
params: params,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,7 +223,7 @@ export class Router {
|
|||||||
const result = await route.beforeRouteEnter({
|
const result = await route.beforeRouteEnter({
|
||||||
env: this.env,
|
env: this.env,
|
||||||
from: this.currentRoute,
|
from: this.currentRoute,
|
||||||
to: route
|
to: route,
|
||||||
});
|
});
|
||||||
if (result === false) {
|
if (result === false) {
|
||||||
return { type: "cancelled" };
|
return { type: "cancelled" };
|
||||||
|
|||||||
+51
-30
@@ -24,6 +24,10 @@ import { onWillUpdateProps } from "./hooks";
|
|||||||
// Store Definition
|
// Store Definition
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export interface EnvWithStore extends Env {
|
||||||
|
store: Store;
|
||||||
|
}
|
||||||
|
|
||||||
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
||||||
export type Getter = ({ state: any, getters }, payload?) => any;
|
export type Getter = ({ state: any, getters }, payload?) => any;
|
||||||
|
|
||||||
@@ -49,7 +53,7 @@ export class Store extends Context {
|
|||||||
if (config.getters) {
|
if (config.getters) {
|
||||||
const firstArg = {
|
const firstArg = {
|
||||||
state: this.state,
|
state: this.state,
|
||||||
getters: this.getters
|
getters: this.getters,
|
||||||
};
|
};
|
||||||
for (let g in config.getters) {
|
for (let g in config.getters) {
|
||||||
this.getters[g] = config.getters[g].bind(this, firstArg);
|
this.getters[g] = config.getters[g].bind(this, firstArg);
|
||||||
@@ -66,7 +70,7 @@ export class Store extends Context {
|
|||||||
dispatch: this.dispatch.bind(this),
|
dispatch: this.dispatch.bind(this),
|
||||||
env: this.env,
|
env: this.env,
|
||||||
state: this.state,
|
state: this.state,
|
||||||
getters: this.getters
|
getters: this.getters,
|
||||||
},
|
},
|
||||||
...payload
|
...payload
|
||||||
);
|
);
|
||||||
@@ -77,66 +81,83 @@ export class Store extends Context {
|
|||||||
interface SelectorOptions {
|
interface SelectorOptions {
|
||||||
store?: Store;
|
store?: Store;
|
||||||
isEqual?: (a: any, b: any) => boolean;
|
isEqual?: (a: any, b: any) => boolean;
|
||||||
|
onUpdate?: (result: any) => any;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isStrictEqual = (a, b) => a === b;
|
const isStrictEqual = (a, b) => a === b;
|
||||||
|
|
||||||
export function useStore(selector, options: SelectorOptions = {}): any {
|
export function useStore(selector, options: SelectorOptions = {}): any {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component = Component.current as Component<any, EnvWithStore>;
|
||||||
|
const componentId = component.__owl__.id;
|
||||||
const store = options.store || (component.env.store as Store);
|
const store = options.store || (component.env.store as Store);
|
||||||
let result = selector(store.state, component.props);
|
if (!(store instanceof Store)) {
|
||||||
const hashFn = store.observer.deepRevNumber.bind(store.observer);
|
throw new Error(`No store found when connecting '${component.constructor.name}'`);
|
||||||
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];
|
let result = selector(store.state, component.props);
|
||||||
updateFunctions.push(function(): boolean {
|
const hashFn = store.observer.revNumber.bind(store.observer);
|
||||||
|
let revNumber = hashFn(result);
|
||||||
|
const isEqual = options.isEqual || isStrictEqual;
|
||||||
|
if (!store.updateFunctions[componentId]) {
|
||||||
|
store.updateFunctions[componentId] = [];
|
||||||
|
}
|
||||||
|
function selectCompareUpdate(state, props): boolean {
|
||||||
const oldResult = result;
|
const oldResult = result;
|
||||||
result = selector(store!.state, component.props);
|
result = selector(state, props);
|
||||||
const newRevNumber = hashFn(result);
|
const newRevNumber = hashFn(result);
|
||||||
if (
|
if ((newRevNumber > 0 && revNumber !== newRevNumber) || !isEqual(oldResult, result)) {
|
||||||
(newRevNumber > 0 && revNumber !== newRevNumber) ||
|
|
||||||
(newRevNumber === 0 && !isEqual(oldResult, result))
|
|
||||||
) {
|
|
||||||
revNumber = newRevNumber;
|
revNumber = newRevNumber;
|
||||||
|
if (options.onUpdate) {
|
||||||
|
options.onUpdate(result);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
})
|
}
|
||||||
|
store.updateFunctions[componentId].push(function (): boolean {
|
||||||
|
return selectCompareUpdate(store!.state, component.props);
|
||||||
|
});
|
||||||
|
|
||||||
useContextWithCB(store, component, function(): Promise<void> | void {
|
useContextWithCB(store, component, function (): Promise<void> | void {
|
||||||
let shouldRender = false;
|
let shouldRender = false;
|
||||||
updateFunctions.forEach(function (updateFn) {
|
for (let fn of store.updateFunctions[componentId]) {
|
||||||
shouldRender = updateFn() || shouldRender;
|
shouldRender = fn() || shouldRender;
|
||||||
});
|
}
|
||||||
if (shouldRender) {
|
if (shouldRender) {
|
||||||
return component.render();
|
return component.render();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
onWillUpdateProps(props => {
|
onWillUpdateProps((props) => {
|
||||||
// FIXME: only do that if not keepalive + do it in destroy in that case
|
selectCompareUpdate(store.state, props);
|
||||||
delete store.updateFunctions[component.__owl__.id];
|
|
||||||
result = selector(store.state, props);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const __destroy = component.__destroy;
|
||||||
|
component.__destroy = (parent) => {
|
||||||
|
delete store.updateFunctions[componentId];
|
||||||
|
__destroy.call(component, parent);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof result !== "object" || result === null) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
return new Proxy(result, {
|
return new Proxy(result, {
|
||||||
get(target, k) {
|
get(target, k) {
|
||||||
return result[k];
|
return result[k];
|
||||||
},
|
},
|
||||||
set(target, k, v) {
|
set(target, k, v) {
|
||||||
result[k] = v;
|
throw new Error("Store state should only be modified through actions");
|
||||||
return true;
|
},
|
||||||
}
|
has(target, k) {
|
||||||
|
return k in result;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDispatch(store?: Store): Store["dispatch"] {
|
export function useDispatch(store?: Store): Store["dispatch"] {
|
||||||
store = store || (Component.current!.env.store as Store);
|
store = store || (Component.current!.env as EnvWithStore).store;
|
||||||
return store.dispatch.bind(store);
|
return store.dispatch.bind(store);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGetters(store?: Store): Store["getters"] {
|
export function useGetters(store?: Store): Store["getters"] {
|
||||||
store = store || (Component.current!.env.store as Store);
|
store = store || (Component.current!.env as EnvWithStore).store;
|
||||||
return store.getters;
|
return store.getters;
|
||||||
}
|
}
|
||||||
|
|||||||
+17
@@ -1,4 +1,5 @@
|
|||||||
import { QWeb } from "./qweb/index";
|
import { QWeb } from "./qweb/index";
|
||||||
|
import { registerSheet } from "./component/styles";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Tags
|
* Owl Tags
|
||||||
@@ -25,3 +26,19 @@ export function xml(strings, ...args) {
|
|||||||
QWeb.registerTemplate(name, value);
|
QWeb.registerTemplate(name, value);
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSS tag helper for defining inline stylesheets. With this, one can simply define
|
||||||
|
* an inline stylesheet with just the following code:
|
||||||
|
* ```js
|
||||||
|
* class A extends Component {
|
||||||
|
* static style = css`.component-a { color: red; }`;
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function css(strings, ...args) {
|
||||||
|
const name = `__sheet__${QWeb.nextId++}`;
|
||||||
|
const value = String.raw(strings, ...args);
|
||||||
|
registerSheet(name, value);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|||||||
+16
-17
@@ -5,19 +5,21 @@
|
|||||||
*
|
*
|
||||||
* - whenReady
|
* - whenReady
|
||||||
* - loadJS
|
* - loadJS
|
||||||
* - loadTemplates
|
* - loadFile
|
||||||
* - escape
|
* - escape
|
||||||
* - debounce
|
* - debounce
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { browser } from "./browser";
|
||||||
|
|
||||||
export function whenReady(fn?: any) {
|
export function whenReady(fn?: any) {
|
||||||
return new Promise(function(resolve) {
|
return new Promise(function (resolve) {
|
||||||
if (document.readyState !== "loading") {
|
if (document.readyState !== "loading") {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
document.addEventListener("DOMContentLoaded", resolve, false);
|
document.addEventListener("DOMContentLoaded", resolve, false);
|
||||||
}
|
}
|
||||||
}).then(fn || function() {});
|
}).then(fn || function () {});
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadedScripts: { [key: string]: Promise<void> } = {};
|
const loadedScripts: { [key: string]: Promise<void> } = {};
|
||||||
@@ -26,14 +28,14 @@ export function loadJS(url: string): Promise<void> {
|
|||||||
if (url in loadedScripts) {
|
if (url in loadedScripts) {
|
||||||
return loadedScripts[url];
|
return loadedScripts[url];
|
||||||
}
|
}
|
||||||
const promise: Promise<void> = new Promise(function(resolve, reject) {
|
const promise: Promise<void> = new Promise(function (resolve, reject) {
|
||||||
const script = document.createElement("script");
|
const script = document.createElement("script");
|
||||||
script.type = "text/javascript";
|
script.type = "text/javascript";
|
||||||
script.src = url;
|
script.src = url;
|
||||||
script.onload = function() {
|
script.onload = function () {
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
script.onerror = function() {
|
script.onerror = function () {
|
||||||
reject(`Error loading file '${url}'`);
|
reject(`Error loading file '${url}'`);
|
||||||
};
|
};
|
||||||
const head = document.head || document.getElementsByTagName("head")[0];
|
const head = document.head || document.getElementsByTagName("head")[0];
|
||||||
@@ -43,8 +45,8 @@ export function loadJS(url: string): Promise<void> {
|
|||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadTemplates(url: string): Promise<string> {
|
export async function loadFile(url: string): Promise<string> {
|
||||||
const result = await fetch(url);
|
const result = await browser.fetch(url);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
throw new Error("Error while fetching xml templates");
|
throw new Error("Error while fetching xml templates");
|
||||||
}
|
}
|
||||||
@@ -58,12 +60,9 @@ export function escape(str: string | number | undefined): string {
|
|||||||
if (typeof str === "number") {
|
if (typeof str === "number") {
|
||||||
return String(str);
|
return String(str);
|
||||||
}
|
}
|
||||||
return str
|
const p = document.createElement("p");
|
||||||
.replace(/&/g, "&")
|
p.textContent = str;
|
||||||
.replace(/</g, "<")
|
return p.innerHTML;
|
||||||
.replace(/>/g, ">")
|
|
||||||
.replace(/"/g, "'")
|
|
||||||
.replace(/`/g, "`");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,7 +75,7 @@ export function escape(str: string | number | undefined): string {
|
|||||||
*/
|
*/
|
||||||
export function debounce(func: Function, wait: number, immediate?: boolean): Function {
|
export function debounce(func: Function, wait: number, immediate?: boolean): Function {
|
||||||
let timeout;
|
let timeout;
|
||||||
return function(this: any) {
|
return function (this: any) {
|
||||||
const context = this;
|
const context = this;
|
||||||
const args = arguments;
|
const args = arguments;
|
||||||
function later() {
|
function later() {
|
||||||
@@ -86,8 +85,8 @@ export function debounce(func: Function, wait: number, immediate?: boolean): Fun
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const callNow = immediate && !timeout;
|
const callNow = immediate && !timeout;
|
||||||
clearTimeout(timeout);
|
browser.clearTimeout(timeout);
|
||||||
timeout = setTimeout(later, wait);
|
timeout = browser.setTimeout(later, wait);
|
||||||
if (callNow) {
|
if (callNow) {
|
||||||
func.apply(context, args);
|
func.apply(context, args);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { VNode, h } from "./vdom";
|
import { VNode, h, addNS } from "./vdom";
|
||||||
|
|
||||||
const parser = new DOMParser();
|
const parser = new DOMParser();
|
||||||
|
|
||||||
@@ -20,10 +20,12 @@ function htmlToVNode(node: ChildNode): VNode {
|
|||||||
attrs[attr.name] = attr.textContent;
|
attrs[attr.name] = attr.textContent;
|
||||||
}
|
}
|
||||||
const children: VNode[] = [];
|
const children: VNode[] = [];
|
||||||
if (node.hasChildNodes) {
|
for (let c of node.childNodes) {
|
||||||
for (let c of node.childNodes) {
|
children.push(htmlToVNode(c));
|
||||||
children.push(htmlToVNode(c));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return h((node as Element).tagName, { attrs }, children);
|
const vnode = h((node as Element).tagName, { attrs }, children);
|
||||||
|
if (vnode.sel === "svg") {
|
||||||
|
addNS(vnode.data, (vnode as any).children, vnode.sel);
|
||||||
|
}
|
||||||
|
return vnode;
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-10
@@ -33,7 +33,7 @@ function updateProps(oldVnode: VNode, vnode: VNode): void {
|
|||||||
|
|
||||||
export const propsModule = {
|
export const propsModule = {
|
||||||
create: updateProps,
|
create: updateProps,
|
||||||
update: updateProps
|
update: updateProps,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -70,8 +70,12 @@ function handleEvent(event: Event, vnode: VNode) {
|
|||||||
on = (vnode.data as VNodeData).on;
|
on = (vnode.data as VNodeData).on;
|
||||||
|
|
||||||
// call event handler(s) if exists
|
// call event handler(s) if exists
|
||||||
if (on && on[name]) {
|
if (on) {
|
||||||
invokeHandler(on[name], vnode, event);
|
if (on[name]) {
|
||||||
|
invokeHandler(on[name], vnode, event);
|
||||||
|
} else if (on["!" + name]) {
|
||||||
|
invokeHandler(on["!" + name], vnode, event);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,13 +104,17 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
if (!on) {
|
if (!on) {
|
||||||
for (name in oldOn) {
|
for (name in oldOn) {
|
||||||
// remove listener if element was changed or existing listeners removed
|
// remove listener if element was changed or existing listeners removed
|
||||||
oldElm.removeEventListener(name, oldListener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
oldElm.removeEventListener(name, oldListener, capture);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (name in oldOn) {
|
for (name in oldOn) {
|
||||||
// remove listener if existing listener removed
|
// remove listener if existing listener removed
|
||||||
if (!on[name]) {
|
if (!on[name]) {
|
||||||
oldElm.removeEventListener(name, oldListener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
oldElm.removeEventListener(name, oldListener, capture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -123,13 +131,17 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
if (!oldOn) {
|
if (!oldOn) {
|
||||||
for (name in on) {
|
for (name in on) {
|
||||||
// add listener if element was changed or new listeners added
|
// add listener if element was changed or new listeners added
|
||||||
elm.addEventListener(name, listener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
elm.addEventListener(name, listener, capture);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (name in on) {
|
for (name in on) {
|
||||||
// add listener if new listener added
|
// add listener if new listener added
|
||||||
if (!oldOn[name]) {
|
if (!oldOn[name]) {
|
||||||
elm.addEventListener(name, listener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
elm.addEventListener(name, listener, capture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,7 +151,7 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
export const eventListenersModule = {
|
export const eventListenersModule = {
|
||||||
create: updateEventListeners,
|
create: updateEventListeners,
|
||||||
update: updateEventListeners,
|
update: updateEventListeners,
|
||||||
destroy: updateEventListeners
|
destroy: updateEventListeners,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -198,7 +210,7 @@ function updateAttrs(oldVnode: VNode, vnode: VNode): void {
|
|||||||
|
|
||||||
export const attrsModule = {
|
export const attrsModule = {
|
||||||
create: updateAttrs,
|
create: updateAttrs,
|
||||||
update: updateAttrs
|
update: updateAttrs,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -219,7 +231,7 @@ function updateClass(oldVnode: VNode, vnode: VNode): void {
|
|||||||
elm = vnode.elm as Element;
|
elm = vnode.elm as Element;
|
||||||
|
|
||||||
for (name in oldClass) {
|
for (name in oldClass) {
|
||||||
if (!klass[name]) {
|
if (name && !klass[name]) {
|
||||||
elm.classList.remove(name);
|
elm.classList.remove(name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-17
@@ -101,7 +101,7 @@ function isVnode(vnode: any): vnode is VNode {
|
|||||||
|
|
||||||
type KeyToIndexMap = { [key: string]: number };
|
type KeyToIndexMap = { [key: string]: number };
|
||||||
|
|
||||||
type ArraysOf<T> = { [K in keyof T]: (T[K])[] };
|
type ArraysOf<T> = { [K in keyof T]: T[K][] };
|
||||||
|
|
||||||
type ModuleHooks = ArraysOf<Module>;
|
type ModuleHooks = ArraysOf<Module>;
|
||||||
|
|
||||||
@@ -176,18 +176,12 @@ export function init(modules: Array<Partial<Module>>, domApi?: DOMAPI) {
|
|||||||
}
|
}
|
||||||
vnode.elm = api.createComment(vnode.text as string);
|
vnode.elm = api.createComment(vnode.text as string);
|
||||||
} else if (sel !== undefined) {
|
} else if (sel !== undefined) {
|
||||||
// Parse selector
|
const elm =
|
||||||
const hashIdx = sel.indexOf("#");
|
vnode.elm ||
|
||||||
const dotIdx = sel.indexOf(".", hashIdx);
|
(vnode.elm =
|
||||||
const hash = hashIdx > 0 ? hashIdx : sel.length;
|
isDef(data) && isDef((i = (data as VNodeData).ns))
|
||||||
const dot = dotIdx > 0 ? dotIdx : sel.length;
|
? api.createElementNS(i, sel)
|
||||||
const tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
: api.createElement(sel));
|
||||||
const elm = (vnode.elm =
|
|
||||||
isDef(data) && isDef((i = (data as VNodeData).ns))
|
|
||||||
? api.createElementNS(i, tag)
|
|
||||||
: api.createElement(tag));
|
|
||||||
if (hash < dot) elm.setAttribute("id", sel.slice(hash + 1, dot));
|
|
||||||
if (dotIdx > 0) elm.setAttribute("class", sel.slice(dot + 1).replace(/\./g, " "));
|
|
||||||
for (i = 0, iLen = cbs.create.length; i < iLen; ++i) cbs.create[i](emptyNode, vnode);
|
for (i = 0, iLen = cbs.create.length; i < iLen; ++i) cbs.create[i](emptyNode, vnode);
|
||||||
if (array(children)) {
|
if (array(children)) {
|
||||||
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
||||||
@@ -526,7 +520,7 @@ const htmlDomApi = {
|
|||||||
parentNode,
|
parentNode,
|
||||||
nextSibling,
|
nextSibling,
|
||||||
tagName,
|
tagName,
|
||||||
setTextContent
|
setTextContent,
|
||||||
} as DOMAPI;
|
} as DOMAPI;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -565,13 +559,15 @@ type ArrayOrElement<T> = T | T[];
|
|||||||
type VNodeChildren = ArrayOrElement<VNodeChildElement>;
|
type VNodeChildren = ArrayOrElement<VNodeChildElement>;
|
||||||
|
|
||||||
export function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
|
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";
|
data.ns = "http://www.w3.org/2000/svg";
|
||||||
if (sel !== "foreignObject" && children !== undefined) {
|
if (sel !== "foreignObject" && children !== undefined) {
|
||||||
for (let i = 0, iLen = children.length; i < iLen; ++i) {
|
for (let i = 0, iLen = children.length; i < iLen; ++i) {
|
||||||
const child = children[i];
|
const child = children[i];
|
||||||
if (child === null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let childData = child.data;
|
let childData = child.data;
|
||||||
if (childData !== undefined) {
|
if (childData !== undefined) {
|
||||||
addNS(childData, (child as VNode).children as VNodes, child.sel);
|
addNS(childData, (child as VNode).children as VNodes, child.sel);
|
||||||
|
|||||||
@@ -1,102 +1,149 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
exports[`animations t-transition combined with component 1`] = `
|
exports[`animations t-transition combined with component 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"Parent\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let QWeb = this.constructor;
|
let QWeb = this.constructor;
|
||||||
let parent = context;
|
let parent = context;
|
||||||
let owner = context;
|
let scope = Object.create(context);
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
//COMPONENT
|
// Component 'Child'
|
||||||
let def3;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
let props2 = {};
|
||||||
let _2_index = c1.length;
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
c1.push(null);
|
w2.destroy();
|
||||||
let props4 = {};
|
w2 = false;
|
||||||
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
|
||||||
if (utils.shallowEqual(props4, w4.__owl__.currentFiber.props)) {
|
|
||||||
def3 = w4.__owl__.currentFiber.promise;
|
|
||||||
} else {
|
|
||||||
w4.destroy();
|
|
||||||
w4 = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!w4) {
|
if (w2) {
|
||||||
let componentKey4 = \`Child\`;
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| context['Child'];
|
let pvnode = w2.__owl__.pvnode;
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
c1.push(pvnode);
|
||||||
w4 = new W4(parent, props4);
|
|
||||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
|
||||||
def3 = w4.__prepare(extra.fiber, undefined, undefined);
|
|
||||||
def3 = def3.then(vnode=>{if (w4.__owl__.isDestroyed){return}let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
|
||||||
w4.destroy();
|
|
||||||
};
|
|
||||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
|
||||||
} else {
|
} else {
|
||||||
def3 = def3 || w4.__updateProps(props4, extra.fiber, undefined, undefined);
|
let componentKey2 = \`Child\`;
|
||||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
const __patch2 = w2.__patch;
|
||||||
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
|
w2.destroy();
|
||||||
|
};
|
||||||
|
delete w2.__owl__.transitionInserted;
|
||||||
|
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
extra.promises.push(def3);
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`animations t-transition combined with t-component and t-if 1`] = `
|
exports[`animations t-transition combined with t-component and t-if 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"Parent\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let QWeb = this.constructor;
|
let QWeb = this.constructor;
|
||||||
let parent = context;
|
let parent = context;
|
||||||
let owner = context;
|
let scope = Object.create(context);
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
if (context['state'].display) {
|
if (scope['state'].display) {
|
||||||
//COMPONENT
|
// Component 'Child'
|
||||||
let def3;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
let props2 = {};
|
||||||
let _2_index = c1.length;
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
c1.push(null);
|
w2.destroy();
|
||||||
let props4 = {};
|
w2 = false;
|
||||||
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
|
||||||
if (utils.shallowEqual(props4, w4.__owl__.currentFiber.props)) {
|
|
||||||
def3 = w4.__owl__.currentFiber.promise;
|
|
||||||
} else {
|
|
||||||
w4.destroy();
|
|
||||||
w4 = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!w4) {
|
if (w2) {
|
||||||
let componentKey4 = \`Child\`;
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| context['Child'];
|
let pvnode = w2.__owl__.pvnode;
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
c1.push(pvnode);
|
||||||
w4 = new W4(parent, props4);
|
|
||||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
|
||||||
def3 = w4.__prepare(extra.fiber, undefined, undefined);
|
|
||||||
def3 = def3.then(vnode=>{if (w4.__owl__.isDestroyed){return}let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
|
||||||
w4.destroy();
|
|
||||||
};
|
|
||||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
|
||||||
} else {
|
} else {
|
||||||
def3 = def3 || w4.__updateProps(props4, extra.fiber, undefined, undefined);
|
let componentKey2 = \`Child\`;
|
||||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
const __patch2 = w2.__patch;
|
||||||
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
|
w2.destroy();
|
||||||
|
};
|
||||||
|
delete w2.__owl__.transitionInserted;
|
||||||
|
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
extra.promises.push(def3);
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
}
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`animations t-transition combined with t-component, remove and re-add before transitionend 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
if (scope['state'].flag) {
|
||||||
|
// Component 'Child'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Child\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
const __patch2 = w2.__patch;
|
||||||
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
|
w2.destroy();
|
||||||
|
};
|
||||||
|
delete w2.__owl__.transitionInserted;
|
||||||
|
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`animations t-transition with no delay/duration 1`] = `
|
exports[`animations t-transition with no delay/duration 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('span', p1, c1);
|
let vn1 = h('span', p1, c1);
|
||||||
p1.hook = {
|
p1.hook = {
|
||||||
insert: vn => {
|
insert: vn => {
|
||||||
utils.transitionInsert(vn, 'jupiler');
|
utils.transitionInsert(vn, 'jupiler');
|
||||||
@@ -111,12 +158,34 @@ exports[`animations t-transition with no delay/duration 1`] = `
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`animations t-transition, on a simple node (insert) 1`] = `
|
exports[`animations t-transition, on a simple node (insert) 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('span', p1, c1);
|
let 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;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`animations t-transition, on a simple node, not in the DOM 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('span', p1, c1);
|
||||||
p1.hook = {
|
p1.hook = {
|
||||||
insert: vn => {
|
insert: vn => {
|
||||||
utils.transitionInsert(vn, 'chimay');
|
utils.transitionInsert(vn, 'chimay');
|
||||||
|
|||||||
+116
-43
@@ -1,13 +1,15 @@
|
|||||||
import { Component, Env } from "../src/component/component";
|
import { Component, Env } from "../src/component/component";
|
||||||
import { QWeb } from "../src/qweb/index";
|
import { QWeb } from "../src/qweb/index";
|
||||||
import { useState, useRef } from "../src/hooks";
|
import { useState, useRef } from "../src/hooks";
|
||||||
|
import { xml } from "../src/tags";
|
||||||
import {
|
import {
|
||||||
makeDeferred,
|
makeDeferred,
|
||||||
makeTestFixture,
|
makeTestFixture,
|
||||||
makeTestEnv,
|
makeTestEnv,
|
||||||
patchNextFrame,
|
patchNextFrame,
|
||||||
renderToDOM,
|
renderToDOM,
|
||||||
unpatchNextFrame
|
unpatchNextFrame,
|
||||||
|
nextTick,
|
||||||
} from "./helpers";
|
} from "./helpers";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -29,6 +31,7 @@ let cssEl: HTMLElement;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
qweb = new QWeb();
|
qweb = new QWeb();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -68,7 +71,27 @@ describe("animations", () => {
|
|||||||
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
patchNextFrame(cb => {
|
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");
|
||||||
|
fixture.appendChild(node);
|
||||||
|
|
||||||
|
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, on a simple node, not in the DOM", 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");
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -78,8 +101,10 @@ describe("animations", () => {
|
|||||||
|
|
||||||
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
await def; // wait for the mocked repaint to be done
|
await def; // wait for the mocked repaint to be done
|
||||||
node.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
node.dispatchEvent(new Event("transitionend"));
|
||||||
expect(node.className).toBe("");
|
// we check here that the css classes have not been removed, since the
|
||||||
|
// element is not in the dom, we actually do not want to do anything.
|
||||||
|
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("t-transition with no delay/duration", async () => {
|
test("t-transition with no delay/duration", async () => {
|
||||||
@@ -87,13 +112,14 @@ describe("animations", () => {
|
|||||||
qweb.addTemplate("test", `<span t-transition="jupiler">blue</span>`);
|
qweb.addTemplate("test", `<span t-transition="jupiler">blue</span>`);
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(node.className).toBe("");
|
expect(node.className).toBe("");
|
||||||
def.resolve();
|
def.resolve();
|
||||||
});
|
});
|
||||||
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
||||||
|
fixture.appendChild(node);
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
||||||
await def;
|
await def;
|
||||||
});
|
});
|
||||||
@@ -108,12 +134,12 @@ describe("animations", () => {
|
|||||||
class TestWidget extends Widget {
|
class TestWidget extends Widget {
|
||||||
state = useState({ hide: false });
|
state = useState({ hide: false });
|
||||||
}
|
}
|
||||||
const widget = new TestWidget(env);
|
const widget = new TestWidget();
|
||||||
|
|
||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -129,7 +155,7 @@ describe("animations", () => {
|
|||||||
// remove span from the DOM
|
// remove span from the DOM
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
widget.state.hide = true;
|
widget.state.hide = true;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-leave chimay-leave-active");
|
expect(spanNode.className).toBe("chimay-leave chimay-leave-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-leave-active chimay-leave-to");
|
expect(spanNode.className).toBe("chimay-leave-active chimay-leave-to");
|
||||||
@@ -151,12 +177,12 @@ describe("animations", () => {
|
|||||||
state = useState({ hide: false });
|
state = useState({ hide: false });
|
||||||
span = useRef("span");
|
span = useRef("span");
|
||||||
}
|
}
|
||||||
const widget = new TestWidget(env);
|
const widget = new TestWidget();
|
||||||
|
|
||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -180,11 +206,11 @@ describe("animations", () => {
|
|||||||
class Parent extends Widget {
|
class Parent extends Widget {
|
||||||
static components = { Child: Child };
|
static components = { Child: Child };
|
||||||
}
|
}
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
||||||
);
|
);
|
||||||
@@ -220,11 +246,11 @@ describe("animations", () => {
|
|||||||
static components = { Child: Child };
|
static components = { Child: Child };
|
||||||
state = useState({ display: true });
|
state = useState({ display: true });
|
||||||
}
|
}
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
||||||
);
|
);
|
||||||
@@ -249,13 +275,13 @@ describe("animations", () => {
|
|||||||
// remove span from the DOM
|
// remove span from the DOM
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
widget.state.display = false;
|
widget.state.display = false;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="4">blue</span></div>'
|
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__3__">blue</span></div>'
|
||||||
);
|
);
|
||||||
cb();
|
cb();
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="4">blue</span></div>'
|
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__3__">blue</span></div>'
|
||||||
);
|
);
|
||||||
def.resolve();
|
def.resolve();
|
||||||
});
|
});
|
||||||
@@ -283,13 +309,13 @@ describe("animations", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
await widget.mount(fixture);
|
await widget.mount(fixture);
|
||||||
let button = widget.el!.querySelector("button");
|
let button = widget.el!.querySelector("button");
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
let phase = "enter";
|
let phase = "enter";
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
let spans = fixture.querySelectorAll("span");
|
let spans = fixture.querySelectorAll("span");
|
||||||
expect(spans.length).toBe(1);
|
expect(spans.length).toBe(1);
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||||
@@ -320,34 +346,27 @@ describe("animations", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("t-transition combined with t-component, remove and re-add before transitionend", async () => {
|
test("t-transition combined with t-component, remove and re-add before transitionend", async () => {
|
||||||
expect.assertions(11);
|
expect.assertions(12);
|
||||||
|
|
||||||
env.qweb.addTemplates(
|
class Child extends Widget {
|
||||||
`<templates>
|
static template = xml`<span>blue</span>`;
|
||||||
<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 {
|
class Parent extends Widget {
|
||||||
|
static template = xml`
|
||||||
|
<div t-name="Parent">
|
||||||
|
<t t-if="state.flag" t-component="Child" t-transition="chimay"/>
|
||||||
|
</div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
|
|
||||||
toggle() {
|
|
||||||
this.state.flag = !this.state.flag;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
await widget.mount(fixture);
|
await widget.mount(fixture);
|
||||||
let button = widget.el!.querySelector("button");
|
expect(env.qweb.templates[Parent.template].fn.toString()).toMatchSnapshot();
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
let phase = "enter";
|
let phase = "enter";
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
let spans = fixture.querySelectorAll("span");
|
let spans = fixture.querySelectorAll("span");
|
||||||
expect(spans.length).toBe(1);
|
expect(spans.length).toBe(1);
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||||
@@ -356,24 +375,78 @@ describe("animations", () => {
|
|||||||
def.resolve();
|
def.resolve();
|
||||||
});
|
});
|
||||||
|
|
||||||
// click display the span
|
// display the span
|
||||||
button!.click();
|
widget.state.flag = true;
|
||||||
await def; // wait for the mocked repaint to be done
|
await def; // wait for the mocked repaint to be done
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
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>');
|
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
||||||
|
|
||||||
// click to remove the span, and click again to re-add it before transitionend
|
// click to remove the span, and click again to re-add it before transitionend
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
phase = "leave";
|
phase = "leave";
|
||||||
button!.click();
|
|
||||||
|
widget.state.flag = false;
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
await def; // wait for the mocked repaint to be done
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
phase = "enter";
|
phase = "enter";
|
||||||
button!.click();
|
widget.state.flag = true;
|
||||||
|
|
||||||
await def; // wait for the mocked repaint to be done
|
await def; // wait for the mocked repaint to be done
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
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>');
|
expect(fixture.innerHTML).toBe('<div><span class="" data-owl-key="__3__">blue</span></div>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("transitionInsert is called the correct amount of times", async () => {
|
||||||
|
const oldTransitionInsert = QWeb.utils.transitionInsert;
|
||||||
|
QWeb.utils.transitionInsert = jest.fn(oldTransitionInsert);
|
||||||
|
|
||||||
|
class Child extends Widget {
|
||||||
|
static template = xml`<span>blue</span>`;
|
||||||
|
}
|
||||||
|
class Parent extends Widget {
|
||||||
|
static template = xml`
|
||||||
|
<div t-name="Parent">
|
||||||
|
<Child t-if="state.flag" t-transition="chimay"/>
|
||||||
|
</div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ flag: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
patchNextFrame((cb) => cb());
|
||||||
|
|
||||||
|
const widget = new Parent();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
|
||||||
|
widget.state.flag = true;
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||||
|
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
||||||
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||||
|
|
||||||
|
widget.state.flag = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__3__">blue</span></div>'
|
||||||
|
);
|
||||||
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||||
|
|
||||||
|
widget.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
'<div><span class="chimay-enter-active chimay-enter-to" data-owl-key="__3__">blue</span></div>'
|
||||||
|
);
|
||||||
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(2);
|
||||||
|
|
||||||
|
widget.state.flag = false;
|
||||||
|
await nextTick();
|
||||||
|
widget.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(3);
|
||||||
|
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||||
|
expect(fixture.innerHTML).toBe('<div><span class="" data-owl-key="__3__">blue</span></div>');
|
||||||
|
QWeb.utils.transitionInsert = oldTransitionInsert;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
|
exports[`class and style attributes with t-component dynamic t-att-style is properly added and updated on widget root el 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"ParentWidget\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'child'
|
||||||
|
const _4 = scope['state'].style;
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined).then(()=>{if (w2.__owl__.isDestroyed) {return};w2.el.style=_4;});;
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`child\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.style = _4;}});});
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`class and style attributes with t-component t-att-class is properly added/removed on widget root el (v2) 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"ParentWidget\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
context.__owl__.refs = context.__owl__.refs || {};
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Child'
|
||||||
|
const ref4 = \`child\`;
|
||||||
|
let _5 = {'a':true};
|
||||||
|
Object.assign(_5, {b:scope['state'].b})
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Child\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){}});});
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.classObj=_5;
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`class and style attributes with t-component t-att-class is properly added/removed on widget root el (v2) 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Child\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _7 = {'c':true};
|
||||||
|
Object.assign(_7, utils.toObj({d:scope['state'].d}))
|
||||||
|
let c8 = [], p8 = {key:8,class:_7};
|
||||||
|
let vn8 = h('span', p8, c8);
|
||||||
|
return vn8;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`class and style attributes with t-component t-att-class is properly added/removed on widget root el (v3) 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"ParentWidget\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
context.__owl__.refs = context.__owl__.refs || {};
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Child'
|
||||||
|
const ref4 = \`child\`;
|
||||||
|
let _5 = {'a':true};
|
||||||
|
Object.assign(_5, utils.toObj(scope['state'].b?'b':''))
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Child\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){}});});
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.classObj=_5;
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`class and style attributes with t-component t-att-class is properly added/removed on widget root el (v3) 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Child\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _7 = {'c':true};
|
||||||
|
Object.assign(_7, utils.toObj(scope['state'].d?'d':''))
|
||||||
|
let c8 = [], p8 = {key:8,class:_7};
|
||||||
|
let vn8 = h('span', p8, c8);
|
||||||
|
return vn8;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,48 +1,39 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
exports[`default props default values are also set whenever component is updated 1`] = `"<div>1</div>"`;
|
|
||||||
|
|
||||||
exports[`default props default values are also set whenever component is updated 2`] = `"<div>4</div>"`;
|
|
||||||
|
|
||||||
exports[`props validation props are validated in dev mode (code snapshot) 1`] = `
|
exports[`props validation props are validated in dev mode (code snapshot) 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"App\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let QWeb = this.constructor;
|
let QWeb = this.constructor;
|
||||||
let parent = context;
|
let parent = context;
|
||||||
let owner = context;
|
let scope = Object.create(context);
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
//COMPONENT
|
// Component 'Child'
|
||||||
let def3;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
let props2 = {message:1};
|
||||||
let _2_index = c1.length;
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
c1.push(null);
|
w2.destroy();
|
||||||
let props4 = {message:1};
|
w2 = false;
|
||||||
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
|
||||||
if (utils.shallowEqual(props4, w4.__owl__.currentFiber.props)) {
|
|
||||||
def3 = w4.__owl__.currentFiber.promise;
|
|
||||||
} else {
|
|
||||||
w4.destroy();
|
|
||||||
w4 = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!w4) {
|
if (w2) {
|
||||||
let componentKey4 = \`Child\`;
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| context['Child'];
|
let pvnode = w2.__owl__.pvnode;
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
c1.push(pvnode);
|
||||||
utils.validateProps(W4, props4)
|
|
||||||
w4 = new W4(parent, props4);
|
|
||||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
|
||||||
def3 = w4.__prepare(extra.fiber, undefined, undefined);
|
|
||||||
def3 = def3.then(vnode=>{if (w4.__owl__.isDestroyed){return}let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
|
||||||
} else {
|
} else {
|
||||||
utils.validateProps(w4.constructor, props4)
|
let componentKey2 = \`Child\`;
|
||||||
def3 = def3 || w4.__updateProps(props4, extra.fiber, undefined, undefined);
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
||||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
extra.promises.push(def3);
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|||||||
@@ -0,0 +1,601 @@
|
|||||||
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Parent\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Dialog'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, Object.assign(Object.create(context), scope));
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Dialog\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Dialog'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
w2.__owl__.slotId = 1;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Dialog\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c6 = [], p6 = {key:6};
|
||||||
|
let vn6 = h('div', p6, c6);
|
||||||
|
let c7 = [], p7 = {key:7};
|
||||||
|
let vn7 = h('div', p7, c7);
|
||||||
|
c6.push(vn7);
|
||||||
|
const slot8 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
||||||
|
if (slot8) {
|
||||||
|
slot8.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c7, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
let c9 = [], p9 = {key:9};
|
||||||
|
let vn9 = h('div', p9, c9);
|
||||||
|
c6.push(vn9);
|
||||||
|
const slot10 = this.constructor.slots[context.__owl__.slotId + '_' + 'footer'];
|
||||||
|
if (slot10) {
|
||||||
|
slot10.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn6;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots 3`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_header_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
c4.push({text: \`header\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots 4`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c5 = [], p5 = {key:5};
|
||||||
|
let vn5 = h('span', p5, c5);
|
||||||
|
c1.push(vn5);
|
||||||
|
c5.push({text: \`footer\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Dialog'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, Object.assign(Object.create(context), scope));
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Dialog\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Dialog'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
w2.__owl__.slotId = 1;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c6 = [], p6 = {key:6};
|
||||||
|
let vn6 = h('div', p6, c6);
|
||||||
|
let c7 = [], p7 = {key:7};
|
||||||
|
let vn7 = h('div', p7, c7);
|
||||||
|
c6.push(vn7);
|
||||||
|
const slot8 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
||||||
|
if (slot8) {
|
||||||
|
slot8.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c7, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
let c9 = [], p9 = {key:9};
|
||||||
|
let vn9 = h('div', p9, c9);
|
||||||
|
c6.push(vn9);
|
||||||
|
const slot10 = this.constructor.slots[context.__owl__.slotId + '_' + 'footer'];
|
||||||
|
if (slot10) {
|
||||||
|
slot10.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn6;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 3`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_header_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
c4.push({text: \`header\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 4`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c5 = [], p5 = {key:5};
|
||||||
|
let vn5 = h('span', p5, c5);
|
||||||
|
c1.push(vn5);
|
||||||
|
c5.push({text: \`footer\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive content is the default slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
c4.push({text: \`sts rocks\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive dafault slots can define a default content 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
const slot5 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot5) {
|
||||||
|
slot5.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c4, parent: extra.parent || context}));
|
||||||
|
} else {
|
||||||
|
c4.push({text: \`default content\`});
|
||||||
|
}
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive default slot work with text nodes 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
c1.push({text: \`sts rocks\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive multiple roots are allowed in a default slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
c4.push({text: \`sts\`});
|
||||||
|
let c5 = [], p5 = {key:5};
|
||||||
|
let vn5 = h('span', p5, c5);
|
||||||
|
c1.push(vn5);
|
||||||
|
c5.push({text: \`rocks\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive multiple roots are allowed in a named slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_content_template\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
c4.push({text: \`sts\`});
|
||||||
|
let c5 = [], p5 = {key:5};
|
||||||
|
let vn5 = h('span', p5, c5);
|
||||||
|
c1.push(vn5);
|
||||||
|
c5.push({text: \`rocks\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive named slots can define a default content 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
const slot5 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
||||||
|
if (slot5) {
|
||||||
|
slot5.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c4, parent: extra.parent || context}));
|
||||||
|
} else {
|
||||||
|
c4.push({text: \`default content\`});
|
||||||
|
}
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive refs are properly bound in slots 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
context.__owl__.refs = context.__owl__.refs || {};
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c8 = [], p8 = {key:8,on:{}};
|
||||||
|
let vn8 = h('button', p8, c8);
|
||||||
|
c1.push(vn8);
|
||||||
|
extra.handlers['click__9__'] = extra.handlers['click__9__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['doSomething'](e);};
|
||||||
|
p8.on['click'] = extra.handlers['click__9__'];
|
||||||
|
const ref10 = \`myButton\`;
|
||||||
|
p8.hook = {
|
||||||
|
create: (_, n) => {
|
||||||
|
context.__owl__.refs[ref10] = n.elm;
|
||||||
|
},
|
||||||
|
destroy: () => {
|
||||||
|
delete context.__owl__.refs[ref10];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
c8.push({text: \`do something\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
let c8 = [], p8 = {key:8,on:{}};
|
||||||
|
let vn8 = h('button', p8, c8);
|
||||||
|
c1.push(vn8);
|
||||||
|
extra.handlers['click__9__'] = extra.handlers['click__9__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['doSomething'](e);};
|
||||||
|
p8.on['click'] = extra.handlers['click__9__'];
|
||||||
|
c8.push({text: \`do something\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 2 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Link\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _11 = scope['props'].to;
|
||||||
|
let c12 = [], p12 = {key:12,attrs:{href: _11}};
|
||||||
|
let vn12 = h('a', p12, c12);
|
||||||
|
const slot13 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot13) {
|
||||||
|
slot13.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c12, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn12;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 2 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"App\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let c2 = [], p2 = {key:2};
|
||||||
|
let vn2 = h('u', p2, c2);
|
||||||
|
c1.push(vn2);
|
||||||
|
let _3 = scope['state'].users;
|
||||||
|
if (!_3) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
|
let _4 = _5 = _3;
|
||||||
|
if (!(_3 instanceof Array)) {
|
||||||
|
if (typeof _3[Symbol.iterator] === 'function') {
|
||||||
|
_4 = [..._3];
|
||||||
|
} else {
|
||||||
|
_4 = Object.keys(_3);
|
||||||
|
_5 = Object.values(_3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _length4 = _4.length;
|
||||||
|
let _origScope6 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
for (let i1 = 0; i1 < _length4; i1++) {
|
||||||
|
scope.user_first = i1 === 0
|
||||||
|
scope.user_last = i1 === _length4 - 1
|
||||||
|
scope.user_index = i1
|
||||||
|
scope.user = _4[i1]
|
||||||
|
scope.user_value = _5[i1]
|
||||||
|
let key1 = scope['user'].id;
|
||||||
|
let c7 = [], p7 = {key:\`\${key1}_7\`};
|
||||||
|
let vn7 = h('li', p7, c7);
|
||||||
|
c2.push(vn7);
|
||||||
|
// Component 'Link'
|
||||||
|
let k9 = \`__9__\${key1}__\`;
|
||||||
|
let w8 = k9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k9]] : false;
|
||||||
|
let props8 = {to:'/user/'+scope['user'].id};
|
||||||
|
if (w8 && w8.__owl__.currentFiber && !w8.__owl__.vnode) {
|
||||||
|
w8.destroy();
|
||||||
|
w8 = false;
|
||||||
|
}
|
||||||
|
if (w8) {
|
||||||
|
w8.__updateProps(props8, extra.fiber, Object.assign(Object.create(context), scope));
|
||||||
|
let pvnode = w8.__owl__.pvnode;
|
||||||
|
c7.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey8 = \`Link\`;
|
||||||
|
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| scope['Link'];
|
||||||
|
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
||||||
|
w8 = new W8(parent, props8);
|
||||||
|
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
||||||
|
w8.__owl__.slotId = 1;
|
||||||
|
let fiber = w8.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
||||||
|
c7.push(pvnode);
|
||||||
|
w8.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w8.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
}
|
||||||
|
scope = _origScope6;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 2 3`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c7 = extra.parentNode;
|
||||||
|
c7.push({text: \`User \`});
|
||||||
|
let _10 = scope['user'].name;
|
||||||
|
if (_10 != null) {
|
||||||
|
c7.push({text: _10});
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 3 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"Link\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _10 = scope['props'].to;
|
||||||
|
let c11 = [], p11 = {key:11,attrs:{href: _10}};
|
||||||
|
let vn11 = h('a', p11, c11);
|
||||||
|
const slot12 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot12) {
|
||||||
|
slot12.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c11, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn11;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 3 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"App\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let c2 = [], p2 = {key:2};
|
||||||
|
let vn2 = h('u', p2, c2);
|
||||||
|
c1.push(vn2);
|
||||||
|
let _3 = scope['state'].users;
|
||||||
|
if (!_3) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
|
let _4 = _5 = _3;
|
||||||
|
if (!(_3 instanceof Array)) {
|
||||||
|
if (typeof _3[Symbol.iterator] === 'function') {
|
||||||
|
_4 = [..._3];
|
||||||
|
} else {
|
||||||
|
_4 = Object.keys(_3);
|
||||||
|
_5 = Object.values(_3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _length4 = _4.length;
|
||||||
|
let _origScope6 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
for (let i1 = 0; i1 < _length4; i1++) {
|
||||||
|
scope.user_first = i1 === 0
|
||||||
|
scope.user_last = i1 === _length4 - 1
|
||||||
|
scope.user_index = i1
|
||||||
|
scope.user = _4[i1]
|
||||||
|
scope.user_value = _5[i1]
|
||||||
|
let key1 = scope['user'].id;
|
||||||
|
let c7 = [], p7 = {key:\`\${key1}_7\`};
|
||||||
|
let vn7 = h('li', p7, c7);
|
||||||
|
c2.push(vn7);
|
||||||
|
utils.getScope(scope, 'userdescr').userdescr = 'User '+scope['user'].name;
|
||||||
|
// Component 'Link'
|
||||||
|
let k9 = \`__9__\${key1}__\`;
|
||||||
|
let w8 = k9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k9]] : false;
|
||||||
|
let props8 = {to:'/user/'+scope['user'].id};
|
||||||
|
if (w8 && w8.__owl__.currentFiber && !w8.__owl__.vnode) {
|
||||||
|
w8.destroy();
|
||||||
|
w8 = false;
|
||||||
|
}
|
||||||
|
if (w8) {
|
||||||
|
w8.__updateProps(props8, extra.fiber, Object.assign(Object.create(context), scope));
|
||||||
|
let pvnode = w8.__owl__.pvnode;
|
||||||
|
c7.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey8 = \`Link\`;
|
||||||
|
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| scope['Link'];
|
||||||
|
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
||||||
|
w8 = new W8(parent, props8);
|
||||||
|
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
||||||
|
w8.__owl__.slotId = 1;
|
||||||
|
let fiber = w8.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
||||||
|
c7.push(pvnode);
|
||||||
|
w8.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w8.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
}
|
||||||
|
scope = _origScope6;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 3 3`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c7 = extra.parentNode;
|
||||||
|
if (scope.userdescr != null) {
|
||||||
|
c7.push({text: scope.userdescr});
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 4 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"App\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
scope.userdescr = 'User '+scope['state'].user.name;
|
||||||
|
// Component 'Link'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {to:'/user/'+scope['state'].user.id};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, Object.assign(Object.create(context), scope));
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Link\`;
|
||||||
|
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Link'];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
w2.__owl__.slotId = 1;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots are rendered with proper context, part 4 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = extra.parentNode;
|
||||||
|
if (scope.userdescr != null) {
|
||||||
|
c1.push({text: scope.userdescr});
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive t-set t-value in a slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
const slot5 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot5) {
|
||||||
|
slot5.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c4, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive template can just return a slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let result;
|
||||||
|
let h = this.h;
|
||||||
|
const slot6 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot6) {
|
||||||
|
let children7= []
|
||||||
|
result = {}
|
||||||
|
slot6.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: children7, parent: extra.parent || context}));
|
||||||
|
utils.defineProxy(result, children7[0]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,271 @@
|
|||||||
|
import { Component, Env } from "../../src/component/component";
|
||||||
|
import { QWeb } from "../../src/qweb/qweb";
|
||||||
|
import { xml } from "../../src/tags";
|
||||||
|
import { useState, useRef } from "../../src/hooks";
|
||||||
|
import { makeTestFixture, makeTestEnv, nextTick } 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.
|
||||||
|
// - env: a WEnv, necessary to create new components
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let env: Env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("class and style attributes with t-component", () => {
|
||||||
|
test("class is properly added on widget root el", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div class="c"/>`;
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static template = xml`<div><Child class="a b"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div class="c a b"></div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("empty class attribute is not added on widget root el", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span/>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child class=""/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
const widget = new Parent();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><span></span></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-att-class is properly added/removed on widget root el", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div class="c"/>`;
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static template = xml`<div><Child t-att-class="{a:state.a, b:state.b}"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ a: true, b: false });
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div class="c a"></div></div>`);
|
||||||
|
expect(QWeb.TEMPLATES[ParentWidget.template].fn.toString());
|
||||||
|
|
||||||
|
widget.state.a = false;
|
||||||
|
widget.state.b = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div class="c b"></div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("class with extra whitespaces", async () => {
|
||||||
|
env.qweb.addTemplate(
|
||||||
|
"ParentWidget",
|
||||||
|
`<div>
|
||||||
|
<Child class="a b c d"/>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
class Child extends Component {}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
env.qweb.addTemplate("Child", `<div/>`);
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div class="a b c d"></div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-att-class is properly added/removed on widget root el (v2)", async () => {
|
||||||
|
env.qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="ParentWidget">
|
||||||
|
<Child class="a" t-att-class="{ b: state.b }" t-ref="child"/>
|
||||||
|
</div>
|
||||||
|
<span t-name="Child" class="c" t-att-class="{ d: state.d }"/>
|
||||||
|
</templates>`);
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
state = useState({ d: true });
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ b: true });
|
||||||
|
child = useRef("child");
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
|
||||||
|
const span = fixture.querySelector("span")!;
|
||||||
|
expect(span.className).toBe("c d a b");
|
||||||
|
|
||||||
|
widget.state.b = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c d a");
|
||||||
|
|
||||||
|
(widget.child.comp as Child).state.d = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a");
|
||||||
|
|
||||||
|
widget.state.b = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a b");
|
||||||
|
|
||||||
|
(widget.child.comp as Child).state.d = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a b d");
|
||||||
|
expect(env.qweb.templates.ParentWidget.fn.toString()).toMatchSnapshot();
|
||||||
|
expect(env.qweb.templates.Child.fn.toString()).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-att-class is properly added/removed on widget root el (v3)", async () => {
|
||||||
|
env.qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="ParentWidget">
|
||||||
|
<Child class="a" t-att-class="state.b ? 'b' : ''" t-ref="child"/>
|
||||||
|
</div>
|
||||||
|
<span t-name="Child" class="c" t-att-class="state.d ? 'd' : ''"/>
|
||||||
|
</templates>`);
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
state = useState({ d: true });
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ b: true });
|
||||||
|
child = useRef("child");
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
|
||||||
|
const span = fixture.querySelector("span")!;
|
||||||
|
expect(span.className).toBe("c d a b");
|
||||||
|
|
||||||
|
widget.state.b = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c d a");
|
||||||
|
|
||||||
|
(widget.child.comp as Child).state.d = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a");
|
||||||
|
|
||||||
|
widget.state.b = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a b");
|
||||||
|
|
||||||
|
(widget.child.comp as Child).state.d = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(span.className).toBe("c a b d");
|
||||||
|
expect(env.qweb.templates.ParentWidget.fn.toString()).toMatchSnapshot();
|
||||||
|
expect(env.qweb.templates.Child.fn.toString()).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("class on components do not interfere with user defined classes", async () => {
|
||||||
|
env.qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="App" t-att-class="{ c: state.c }" />
|
||||||
|
</templates>`);
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
state = useState({ c: true });
|
||||||
|
mounted() {
|
||||||
|
this.el!.classList.add("user");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const widget = new App();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe('<div class="c user"></div>');
|
||||||
|
|
||||||
|
widget.state.c = false;
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe('<div class="user"></div>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("style is properly added on widget root el", async () => {
|
||||||
|
env.qweb.addTemplate(
|
||||||
|
"ParentWidget",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<t t-component="child" style="font-weight: bold;"/>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
|
||||||
|
class SomeComponent extends Component {
|
||||||
|
static template = xml`<div/>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static components = { child: SomeComponent };
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div style="font-weight: bold;"></div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dynamic t-att-style is properly added and updated on widget root el", async () => {
|
||||||
|
env.qweb.addTemplate(
|
||||||
|
"ParentWidget",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<t t-component="child" t-att-style="state.style"/>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
|
||||||
|
class SomeComponent extends Component {
|
||||||
|
static template = xml`<div/>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static components = { child: SomeComponent };
|
||||||
|
state = useState({ style: "font-size: 20px" });
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
|
||||||
|
expect(env.qweb.templates.ParentWidget.fn.toString()).toMatchSnapshot();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div style="font-size: 20px;"></div></div>`);
|
||||||
|
|
||||||
|
widget.state.style = "font-size: 30px";
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe(`<div><div style="font-size: 30px;"></div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("error in subcomponent with class", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div t-esc="this.will.crash"/>`;
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static template = xml`<div><Child class="a"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
const widget = new ParentWidget();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await widget.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
+1894
-2125
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,523 @@
|
|||||||
|
import { Component, Env } from "../../src/component/component";
|
||||||
|
import { useState } from "../../src/hooks";
|
||||||
|
import { xml } from "../../src/tags";
|
||||||
|
import { makeTestEnv, makeTestFixture, nextTick } 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.
|
||||||
|
// - env: a WEnv, necessary to create new components
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let env: Env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("component error handling (catchError)", () => {
|
||||||
|
/**
|
||||||
|
* This test suite requires often to wait for 3 ticks. Here is why:
|
||||||
|
* - First tick is to let the app render and crash.
|
||||||
|
* - When we crash, we call the catchError handler in a setTimeout (because we
|
||||||
|
* need to wait for the previous rendering to be completely stopped). So, we
|
||||||
|
* need to wait for the second tick.
|
||||||
|
* - Then, when the handler changes the state, we need to wait for the interface
|
||||||
|
* to be rerendered.
|
||||||
|
* */
|
||||||
|
|
||||||
|
test("can catch an error in a component render function", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
const handler = jest.fn();
|
||||||
|
env.qweb.on("error", null, handler);
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<ErrorBoundary><ErrorComponent flag="state.flag"/></ErrorBoundary>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ flag: false });
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div><div>heyfalse</div></div></div>");
|
||||||
|
app.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
expect(handler).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no component catching error lead to full app destruction", async () => {
|
||||||
|
expect.assertions(6);
|
||||||
|
const handler = jest.fn();
|
||||||
|
env.qweb.on("error", null, handler);
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><ErrorComponent flag="state.flag"/></div>`;
|
||||||
|
static components = { ErrorComponent };
|
||||||
|
state = useState({ flag: false });
|
||||||
|
async render() {
|
||||||
|
try {
|
||||||
|
await super.render();
|
||||||
|
} catch (e) {
|
||||||
|
expect(e.message).toBe("Cannot read property 'this' of undefined");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>heyfalse</div></div>");
|
||||||
|
app.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
expect(app.__owl__.isDestroyed).toBe(true);
|
||||||
|
expect(handler).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can catch an error in the initial call of a component render function (parent mounted)", async () => {
|
||||||
|
const handler = jest.fn();
|
||||||
|
env.qweb.on("error", null, handler);
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
|
</div>`;
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
expect(handler).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can catch an error in the initial call of a component render function (parent updated)", async () => {
|
||||||
|
const handler = jest.fn();
|
||||||
|
env.qweb.on("error", null, handler);
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<ErrorBoundary t-if="state.flag"><ErrorComponent /></ErrorBoundary>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ flag: false });
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
app.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
expect(handler).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can catch an error in the constructor call of a component render function", async () => {
|
||||||
|
const handler = jest.fn();
|
||||||
|
env.qweb.on("error", null, handler);
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
env.qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="ErrorBoundary">
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>
|
||||||
|
<div t-name="ErrorComponent">Some text</div>
|
||||||
|
<div t-name="App">
|
||||||
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
|
</div>
|
||||||
|
</templates>`);
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
constructor(parent) {
|
||||||
|
super(parent);
|
||||||
|
throw new Error("NOOOOO");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
expect(handler).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can catch an error in the willStart call", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div t-name="ErrorComponent">Some text</div>`;
|
||||||
|
async willStart() {
|
||||||
|
// we wait a little bit to be in a different stack frame
|
||||||
|
await nextTick();
|
||||||
|
throw new Error("NOOOOO");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><ErrorBoundary><ErrorComponent /></ErrorBoundary></div>`;
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test.skip("can catch an error in the mounted call", async () => {
|
||||||
|
// we do not catch error in mounted anymore
|
||||||
|
console.error = jest.fn();
|
||||||
|
env.qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="ErrorBoundary">
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>
|
||||||
|
<div t-name="ErrorComponent">Some text</div>
|
||||||
|
<div t-name="App">
|
||||||
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
|
</div>
|
||||||
|
</templates>`);
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
mounted() {
|
||||||
|
throw new Error("NOOOOO");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
await nextTick();
|
||||||
|
await nextTick();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test.skip("can catch an error in the willPatch call", async () => {
|
||||||
|
// we do not catch error in willPatch anymore
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn();
|
||||||
|
class ErrorComponent extends Component {
|
||||||
|
static template = xml`<div><t t-esc="props.message"/></div>`;
|
||||||
|
willPatch() {
|
||||||
|
throw new Error("NOOOOO");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.error">Error handled</t>
|
||||||
|
<t t-else=""><t t-slot="default" /></t>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span><t t-esc="state.message"/></span>
|
||||||
|
<ErrorBoundary><ErrorComponent message="state.message" /></ErrorBoundary>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ message: "abc" });
|
||||||
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
|
}
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>abc</span><div><div>abc</div></div></div>");
|
||||||
|
app.state.message = "def";
|
||||||
|
await nextTick();
|
||||||
|
await nextTick();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>def</span><div>Error handled</div></div>");
|
||||||
|
expect(console.error).toHaveBeenCalledTimes(1);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a rendering error will reject the mount promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
// we do not catch error in willPatch anymore
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an error in mounted call will reject the mount promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>abc</div>`;
|
||||||
|
mounted() {
|
||||||
|
throw new Error("boom");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("boom");
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an error in willPatch call will reject the render promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="val"/></div>`;
|
||||||
|
val = 3;
|
||||||
|
willPatch() {
|
||||||
|
throw new Error("boom");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
app.val = 4;
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.render();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("boom");
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an error in patched call will reject the render promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="val"/></div>`;
|
||||||
|
val = 3;
|
||||||
|
patched() {
|
||||||
|
throw new Error("boom");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
app.val = 4;
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.render();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("boom");
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a rendering error in a sub component will reject the mount promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
// we do not catch error in willPatch anymore
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><Child/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a rendering error will reject the render promise", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
// we do not catch error in willPatch anymore
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-if="flag" t-esc="this.will.crash"/></div>`;
|
||||||
|
flag = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
app.flag = true;
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.render();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a rendering error will reject the render promise (with sub components)", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span></span>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child/><t t-esc="x.y"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'y' of undefined");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, Env } from "../../src/component/component";
|
import { Component, Env } from "../../src/component/component";
|
||||||
import { makeTestFixture, makeTestEnv } from "../helpers";
|
import { makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||||
|
import { useState } from "../../src/hooks";
|
||||||
import { QWeb } from "../../src/qweb";
|
import { QWeb } from "../../src/qweb";
|
||||||
import { xml } from "../../src/tags";
|
import { xml } from "../../src/tags";
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@ let dev: boolean = false;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
dev = QWeb.dev;
|
dev = QWeb.dev;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
});
|
});
|
||||||
@@ -23,7 +25,7 @@ afterEach(() => {
|
|||||||
QWeb.dev = dev;
|
QWeb.dev = dev;
|
||||||
});
|
});
|
||||||
|
|
||||||
class Widget extends Component<any, any> {}
|
class Widget extends Component {}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Tests
|
// Tests
|
||||||
@@ -34,17 +36,32 @@ describe("props validation", () => {
|
|||||||
static props = ["message"];
|
static props = ["message"];
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
}
|
}
|
||||||
|
class Parent extends Widget {
|
||||||
|
static components = { TestWidget };
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let error;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env);
|
const p = new Parent();
|
||||||
}).toThrow();
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
|
||||||
QWeb.dev = false;
|
QWeb.dev = false;
|
||||||
|
try {
|
||||||
expect(() => {
|
const p = new Parent();
|
||||||
new TestWidget(env);
|
await p.mount(fixture);
|
||||||
}).not.toThrow();
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("props: list of strings", async () => {
|
test("props: list of strings", async () => {
|
||||||
@@ -52,10 +69,20 @@ describe("props validation", () => {
|
|||||||
static props = ["message"];
|
static props = ["message"];
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
}
|
}
|
||||||
|
class Parent extends Widget {
|
||||||
|
static components = { TestWidget };
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
try {
|
||||||
}).toThrow("Missing props 'message' (component 'TestWidget')");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("validate simple types", async () => {
|
test("validate simple types", async () => {
|
||||||
@@ -65,26 +92,53 @@ describe("props validation", () => {
|
|||||||
{ type: String, ok: "1", ko: 1 },
|
{ type: String, ok: "1", ko: 1 },
|
||||||
{ type: Object, ok: {}, ko: "1" },
|
{ type: Object, ok: {}, ko: "1" },
|
||||||
{ type: Date, ok: new Date(), ko: "1" },
|
{ type: Date, ok: new Date(), ko: "1" },
|
||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let props;
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
for (let test of Tests) {
|
for (let test of Tests) {
|
||||||
let TestWidget = class extends Widget {
|
let TestWidget = class extends Widget {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: test.type };
|
static props = { p: test.type };
|
||||||
};
|
};
|
||||||
|
Parent.components = { TestWidget };
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
props = {};
|
||||||
}).toThrow("Missing props 'p'");
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||||
|
|
||||||
expect(() => {
|
error = undefined;
|
||||||
new TestWidget(env, { p: test.ok });
|
props = { p: test.ok };
|
||||||
}).not.toThrow();
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
props = { p: test.ko };
|
||||||
new TestWidget(env, { p: test.ko });
|
try {
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component '_a'");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -95,142 +149,454 @@ describe("props validation", () => {
|
|||||||
{ type: String, ok: "1", ko: 1 },
|
{ type: String, ok: "1", ko: 1 },
|
||||||
{ type: Object, ok: {}, ko: "1" },
|
{ type: Object, ok: {}, ko: "1" },
|
||||||
{ type: Date, ok: new Date(), ko: "1" },
|
{ type: Date, ok: new Date(), ko: "1" },
|
||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let props;
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
for (let test of Tests) {
|
for (let test of Tests) {
|
||||||
let TestWidget = class extends Widget {
|
let TestWidget = class extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
|
||||||
static props = { p: { type: test.type } };
|
static props = { p: { type: test.type } };
|
||||||
|
static template = xml`<div>hey</div>`;
|
||||||
};
|
};
|
||||||
|
Parent.components = { TestWidget };
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
props = {};
|
||||||
}).toThrow("Missing props 'p'");
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||||
|
|
||||||
expect(() => {
|
error = undefined;
|
||||||
new TestWidget(env, { p: test.ok });
|
props = { p: test.ok };
|
||||||
}).not.toThrow();
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
props = { p: test.ko };
|
||||||
new TestWidget(env, { p: test.ko });
|
try {
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component '_a'");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate a prop with multiple types", async () => {
|
test("can validate a prop with multiple types", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: [String, Boolean] };
|
static props = { p: [String, Boolean] };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: "string" });
|
let props;
|
||||||
new TestWidget(env, { p: true });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: "string" };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: 1 });
|
props = { p: true };
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: 1 };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an optional props", async () => {
|
test("can validate an optional props", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: String, optional: true } };
|
static props = { p: { type: String, optional: true } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: "hey" });
|
let props;
|
||||||
new TestWidget(env, {});
|
try {
|
||||||
}).not.toThrow();
|
props = { p: "key" };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: 1 });
|
props = {};
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: 1 };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with given primitive type", async () => {
|
test("can validate an array with given primitive type", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: String } };
|
static props = { p: { type: Array, element: String } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: [] });
|
let props;
|
||||||
new TestWidget(env, { p: ["string"] });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: [] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: [1] });
|
props = { p: ["string"] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: ["string", 1] });
|
props = { p: [1] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
try {
|
||||||
|
props = { p: ["string", 1] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with multiple sub element types", async () => {
|
test("can validate an array with multiple sub element types", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: [String, Boolean] } };
|
static props = { p: { type: Array, element: [String, Boolean] } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: [] });
|
let props;
|
||||||
new TestWidget(env, { p: ["string"] });
|
try {
|
||||||
new TestWidget(env, { p: [false, true, "string"] });
|
props = { p: [] };
|
||||||
}).not.toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: [true, 1] });
|
props = { p: ["string"] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: [false, true, "string"] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: [true, 1] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an object with simple shape", async () => {
|
test("can validate an object with simple shape", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: { type: Object, shape: { id: Number, url: String } }
|
p: { type: Object, shape: { id: Number, url: String } },
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: { id: 1, url: "url" } });
|
let props;
|
||||||
new TestWidget(env, { p: { id: 1, url: "url", extra: true } });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: { id: 1, url: "url" } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: "1", url: "url" } });
|
props = { p: { id: 1, url: "url", extra: true } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid prop 'p' in component TestWidget (unknown prop 'extra')");
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: 1 } });
|
props = { p: { id: "1", url: "url" } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
try {
|
||||||
|
props = { p: { id: 1 } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate recursively complicated prop def", async () => {
|
test("can validate recursively complicated prop def", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: {
|
p: {
|
||||||
type: Object,
|
type: Object,
|
||||||
shape: {
|
shape: {
|
||||||
id: Number,
|
id: Number,
|
||||||
url: [Boolean, { type: Array, element: Number }]
|
url: [Boolean, { type: Array, element: Number }],
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: { id: 1, url: true } });
|
let props;
|
||||||
new TestWidget(env, { p: { id: 1, url: [12] } });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: { id: 1, url: true } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: 1, url: [12, true] } });
|
props = { p: { id: 1, url: [12] } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: { id: 1, url: [12, true] } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can validate optional attributes in nested sub props", () => {
|
||||||
|
class TestComponent extends Component {
|
||||||
|
static props = {
|
||||||
|
myprop: {
|
||||||
|
type: Array,
|
||||||
|
element: {
|
||||||
|
type: Object,
|
||||||
|
shape: {
|
||||||
|
num: { type: Number, optional: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { myprop: [{}] });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { myprop: [{ a: 1 }] });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(
|
||||||
|
"Invalid prop 'myprop' in component TestComponent (unknown prop 'a')"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can validate with a custom validator", () => {
|
||||||
|
class TestComponent extends Component {
|
||||||
|
static props = {
|
||||||
|
size: {
|
||||||
|
validate: (e) => ["small", "medium", "large"].includes(e),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { size: "small" });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { size: "abcdef" });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'size' in component 'TestComponent'");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can validate with a custom validator, and a type", () => {
|
||||||
|
const validator = jest.fn((n) => 0 <= n && n <= 10);
|
||||||
|
class TestComponent extends Component {
|
||||||
|
static props = {
|
||||||
|
n: {
|
||||||
|
type: Number,
|
||||||
|
validate: validator,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { n: 3 });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
expect(validator).toBeCalledTimes(1);
|
||||||
|
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { n: "str" });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'n' in component 'TestComponent'");
|
||||||
|
expect(validator).toBeCalledTimes(1);
|
||||||
|
|
||||||
|
error = null;
|
||||||
|
try {
|
||||||
|
QWeb.utils.validateProps(TestComponent, { n: 100 });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Invalid Prop 'n' in component 'TestComponent'");
|
||||||
|
expect(validator).toBeCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("props are validated in dev mode (code snapshot)", async () => {
|
test("props are validated in dev mode (code snapshot)", async () => {
|
||||||
@@ -248,7 +614,7 @@ describe("props validation", () => {
|
|||||||
class App extends Widget {
|
class App extends Widget {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
// need to make sure there are 2 call to update props. one at component
|
// need to make sure there are 2 call to update props. one at component
|
||||||
@@ -279,6 +645,32 @@ describe("props validation", () => {
|
|||||||
}).toThrow();
|
}).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("props with type array, and no element", async () => {
|
||||||
|
class TestWidget extends Widget {
|
||||||
|
static props = { myprop: { type: Array } };
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
QWeb.utils.validateProps(TestWidget, { myprop: [1] });
|
||||||
|
}).not.toThrow();
|
||||||
|
expect(() => {
|
||||||
|
QWeb.utils.validateProps(TestWidget, { myprop: 1 });
|
||||||
|
}).toThrow(`Invalid Prop 'myprop' in component 'TestWidget'`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("props with type object, and no shape", async () => {
|
||||||
|
class TestWidget extends Widget {
|
||||||
|
static props = { myprop: { type: Object } };
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
QWeb.utils.validateProps(TestWidget, { myprop: { a: 3 } });
|
||||||
|
}).not.toThrow();
|
||||||
|
expect(() => {
|
||||||
|
QWeb.utils.validateProps(TestWidget, { myprop: false });
|
||||||
|
}).toThrow(`Invalid Prop 'myprop' in component 'TestWidget'`);
|
||||||
|
});
|
||||||
|
|
||||||
test("props: extra props cause an error", async () => {
|
test("props: extra props cause an error", async () => {
|
||||||
class TestWidget extends Widget {
|
class TestWidget extends Widget {
|
||||||
static props = ["message"];
|
static props = ["message"];
|
||||||
@@ -321,35 +713,156 @@ describe("props validation", () => {
|
|||||||
QWeb.utils.validateProps(TestWidget, { message: null });
|
QWeb.utils.validateProps(TestWidget, { message: null });
|
||||||
}).toThrow();
|
}).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("missing required boolean prop causes an error", async () => {
|
||||||
|
class TestWidget extends Widget {
|
||||||
|
static props = ["p"];
|
||||||
|
static template = xml`<span><t t-if="props.p">hey</t></span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Widget {
|
||||||
|
static template = xml`<div><TestWidget/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new App(undefined, {});
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("props are validated whenever component is updated", async () => {
|
||||||
|
let error;
|
||||||
|
class TestWidget extends Component {
|
||||||
|
static props = { p: { type: Number } };
|
||||||
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
|
||||||
|
async __updateProps() {
|
||||||
|
try {
|
||||||
|
await Component.prototype.__updateProps.apply(this, arguments);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
state: any = useState({ p: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new Parent();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
|
|
||||||
|
w.state.p = undefined;
|
||||||
|
await nextTick();
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("default values are applied before validating props at update", async () => {
|
||||||
|
class TestWidget extends Component {
|
||||||
|
static props = { p: { type: Number } };
|
||||||
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
static defaultProps = { p: 4 };
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
state: any = useState({ p: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new Parent();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
|
|
||||||
|
w.state.p = undefined;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("mix of optional and mandatory", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static props = {
|
||||||
|
optional: { type: String, optional: true },
|
||||||
|
mandatory: Number,
|
||||||
|
};
|
||||||
|
static template = xml` <div><t t-esc="props.mandatory"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`<div><Child/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new App(undefined, {});
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'mandatory' (component 'Child')");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("default props", () => {
|
describe("default props", () => {
|
||||||
test("can set default values", async () => {
|
test("can set default values", async () => {
|
||||||
class TestWidget extends Widget {
|
class TestWidget extends Component {
|
||||||
static defaultProps = { p: 4 };
|
static defaultProps = { p: 4 };
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new TestWidget(env, {});
|
const w = new Parent();
|
||||||
expect(w.props.p).toBe(4);
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("default values are also set whenever component is updated", async () => {
|
test("default values are also set whenever component is updated", async () => {
|
||||||
class TestWidget extends Widget {
|
class TestWidget extends Widget {
|
||||||
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
static defaultProps = { p: 4 };
|
static defaultProps = { p: 4 };
|
||||||
}
|
}
|
||||||
env.qweb.addTemplates(`
|
class Parent extends Widget {
|
||||||
<templates>
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
<div t-name="TestWidget"><t t-esc="props.p"/></div>
|
static components = { TestWidget };
|
||||||
</templates>`);
|
state: any = useState({ p: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
const w = new TestWidget(env, { p: 1 });
|
const w = new Parent();
|
||||||
await w.mount(fixture);
|
await w.mount(fixture);
|
||||||
expect(fixture.innerHTML).toMatchSnapshot();
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
const fiber = w.__createFiber(false, undefined, undefined, undefined);
|
|
||||||
await w.__updateProps({}, fiber);
|
w.state.p = undefined;
|
||||||
await w.render();
|
await nextTick();
|
||||||
expect(w.props.p).toBe(4);
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
expect(fixture.innerHTML).toMatchSnapshot();
|
});
|
||||||
|
|
||||||
|
test("can set default required boolean values", async () => {
|
||||||
|
class TestWidget extends Widget {
|
||||||
|
static props = ["p", "q"];
|
||||||
|
static defaultProps = { p: true, q: false };
|
||||||
|
static template = xml`<span><t t-if="props.p">hey</t><t t-if="!props.q">hey</t></span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Widget {
|
||||||
|
static template = xml`<div><TestWidget/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new App(undefined, {});
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>heyhey</span></div>");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,170 @@
|
|||||||
|
import { Component, Env } from "../../src/component/component";
|
||||||
|
import { processSheet } from "../../src/component/styles";
|
||||||
|
import { xml, css } from "../../src/tags";
|
||||||
|
import { makeTestFixture, makeTestEnv } 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.
|
||||||
|
// - env: an Env, necessary to create new components
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let env: Env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
|
document.head.innerHTML = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("styles and component", () => {
|
||||||
|
test("can define an inline stylesheet", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div class="app">text</div>`;
|
||||||
|
static style = css`
|
||||||
|
.app {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
expect(document.head.innerHTML).toBe("");
|
||||||
|
const app = new App();
|
||||||
|
|
||||||
|
expect(document.head.innerHTML).toBe(`<style component=\"App\">.app {
|
||||||
|
color: red;
|
||||||
|
}</style>`);
|
||||||
|
|
||||||
|
await app.mount(fixture);
|
||||||
|
const style = getComputedStyle(app.el!);
|
||||||
|
expect(style.color).toBe("red");
|
||||||
|
expect(fixture.innerHTML).toBe('<div class="app">text</div>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("inherited components properly apply css", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div class="app">text</div>`;
|
||||||
|
static style = css`
|
||||||
|
.app {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
class SubApp extends App {
|
||||||
|
static style = css`
|
||||||
|
.app {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
expect(document.head.innerHTML).toBe("");
|
||||||
|
const app = new SubApp();
|
||||||
|
|
||||||
|
expect(document.head.innerHTML).toBe(`<style component=\"SubApp\">.app {
|
||||||
|
font-weight: bold;
|
||||||
|
}</style><style component=\"App\">.app {
|
||||||
|
color: red;
|
||||||
|
}</style>`);
|
||||||
|
|
||||||
|
await app.mount(fixture);
|
||||||
|
const style = getComputedStyle(app.el!);
|
||||||
|
expect(style.color).toBe("red");
|
||||||
|
expect(style.fontWeight).toBe("bold");
|
||||||
|
expect(fixture.innerHTML).toBe('<div class="app">text</div>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("get a meaningful error message if css helper is missing", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div class="app">text</div>`;
|
||||||
|
static style = `.app {color: red;}`;
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
new App();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(
|
||||||
|
"Invalid css stylesheet for component 'App'. Did you forget to use the 'css' tag helper?"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("inline stylesheets are processed", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div class="app">text</div>`;
|
||||||
|
static style = css`
|
||||||
|
.app {
|
||||||
|
color: red;
|
||||||
|
.some-class {
|
||||||
|
font-weight: bold;
|
||||||
|
width: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
new App();
|
||||||
|
|
||||||
|
expect(document.head.querySelector("style")!.innerHTML).toBe(`.app {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
.app .some-class {
|
||||||
|
font-weight: bold;
|
||||||
|
width: 40px;
|
||||||
|
}
|
||||||
|
.app {
|
||||||
|
display: block;
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("properly handle rules with commas", async () => {
|
||||||
|
const sheet = processSheet(`.parent-a, .parent-b {
|
||||||
|
.child-a, .child-b {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}`);
|
||||||
|
|
||||||
|
expect(sheet)
|
||||||
|
.toBe(`.parent-a .child-a, .parent-a .child-b, .parent-b .child-a, .parent-b .child-b {
|
||||||
|
color: red;
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handle & selector", async () => {
|
||||||
|
let sheet = processSheet(`.btn {
|
||||||
|
&.danger {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}`);
|
||||||
|
|
||||||
|
expect(sheet).toBe(`.btn.danger {
|
||||||
|
color: red;
|
||||||
|
}`);
|
||||||
|
|
||||||
|
sheet = processSheet(`.some-class {
|
||||||
|
&.btn {
|
||||||
|
.other-class ~ & {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`);
|
||||||
|
|
||||||
|
expect(sheet).toBe(`.other-class ~ .some-class.btn {
|
||||||
|
color: red;
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,611 @@
|
|||||||
|
import { Component, Env } from "../../src/component/component";
|
||||||
|
import { useState } from "../../src/hooks";
|
||||||
|
import { xml } from "../../src/tags";
|
||||||
|
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick, nextMicroTick } from "../helpers";
|
||||||
|
import { scheduler } from "../../src/component/scheduler";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// 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.
|
||||||
|
// - env: a WEnv, necessary to create new components
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let env: Env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("mount targets", () => {
|
||||||
|
test("can attach a component to an existing node (if same tagname)", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div t-att-class="state.customClass">app<p>another tag</p></div>`;
|
||||||
|
state = useState({ customClass: "custom" });
|
||||||
|
}
|
||||||
|
const div = document.createElement("div");
|
||||||
|
div.classList.add("arbitrary");
|
||||||
|
div.innerHTML = `<p>pre-existing</p>`;
|
||||||
|
fixture.appendChild(div);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(div, { position: "self" });
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
`<div class="arbitrary custom"><p>pre-existing</p>app<p>another tag</p></div>`
|
||||||
|
);
|
||||||
|
expect(div).toBe(app.el);
|
||||||
|
|
||||||
|
app.state.customClass = "custom2";
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
`<div class="arbitrary custom2"><p>pre-existing</p>app<p>another tag</p></div>`
|
||||||
|
);
|
||||||
|
expect(div).toBe(app.el);
|
||||||
|
|
||||||
|
app.unmount();
|
||||||
|
// This assert is a best guess
|
||||||
|
// The use case it covers was not really thought through
|
||||||
|
// and may change in the future
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cannot attach a component to an existing node (if not same tagname)", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<span>app</span>`;
|
||||||
|
}
|
||||||
|
const div = document.createElement("div");
|
||||||
|
fixture.appendChild(div);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await app.mount(div, { position: "self" });
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot attach 'App' to target node (not same tag name)");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can mount a component (with position='first-child')", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>app</div>`;
|
||||||
|
}
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(span);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture, { position: "first-child" });
|
||||||
|
expect(fixture.innerHTML).toBe("<div>app</div><span></span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("can mount a component (with position='last-child')", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>app</div>`;
|
||||||
|
}
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(span);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture, { position: "last-child" });
|
||||||
|
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("default mount option is 'last-child'", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>app</div>`;
|
||||||
|
}
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(span);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("unmounting and remounting", () => {
|
||||||
|
test("widget can be unmounted and remounted", async () => {
|
||||||
|
const steps: string[] = [];
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
steps.push("willstart");
|
||||||
|
}
|
||||||
|
mounted() {
|
||||||
|
steps.push("mounted");
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("willunmount");
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new MyWidget();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
|
expect(steps).toEqual(["willstart", "mounted"]);
|
||||||
|
|
||||||
|
w.unmount();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
expect(steps).toEqual(["willstart", "mounted", "willunmount"]);
|
||||||
|
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
|
expect(steps).toEqual(["willstart", "mounted", "willunmount", "mounted"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("widget can be mounted twice without ill effect", async () => {
|
||||||
|
const steps: string[] = [];
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
steps.push("willstart");
|
||||||
|
}
|
||||||
|
mounted() {
|
||||||
|
steps.push("mounted");
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("willunmount");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new MyWidget();
|
||||||
|
await w.mount(fixture);
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
|
expect(steps).toEqual(["willstart", "mounted"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("state changes in willUnmount do not trigger rerender", async () => {
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<span><t t-esc="props.val"/><t t-esc="state.n"/></span>
|
||||||
|
`;
|
||||||
|
state = useState({ n: 2 });
|
||||||
|
__render(f) {
|
||||||
|
steps.push("render");
|
||||||
|
return super.__render(f);
|
||||||
|
}
|
||||||
|
willPatch() {
|
||||||
|
steps.push("willPatch");
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
steps.push("patched");
|
||||||
|
}
|
||||||
|
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("willUnmount");
|
||||||
|
this.state.n = 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Child t-if="state.flag" val="state.val"/>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ val: 1, flag: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const widget = new Parent();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(steps).toEqual(["render"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||||
|
widget.state.flag = false;
|
||||||
|
await nextTick();
|
||||||
|
// we make sure here that no call to __render is done
|
||||||
|
expect(steps).toEqual(["render", "willUnmount"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("state changes in willUnmount will be applied on remount", async () => {
|
||||||
|
class TestWidget extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div><t t-esc="state.val"/></div>
|
||||||
|
`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
willUnmount() {
|
||||||
|
this.state.val = 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const widget = new TestWidget();
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||||
|
widget.unmount();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
await nextTick(); // wait for changes to be detected before remounting
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||||
|
// we want to make sure that there are no remaining tasks left at this point.
|
||||||
|
expect(Component.scheduler.tasks.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sub component is still active after being unmounted and remounted", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<p t-on-click="state.value++">
|
||||||
|
<t t-esc="state.value"/>
|
||||||
|
</p>`;
|
||||||
|
|
||||||
|
state = useState({ value: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`<div><Child/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new Parent();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>1</p></div>");
|
||||||
|
|
||||||
|
fixture.querySelector("p")!.click();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>2</p></div>");
|
||||||
|
w.unmount();
|
||||||
|
await nextTick();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>2</p></div>");
|
||||||
|
fixture.querySelector("p")!.click();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p>3</p></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("change state just before mounting component", async () => {
|
||||||
|
const steps: number[] = [];
|
||||||
|
class TestWidget extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div><t t-esc="state.val"/></div>
|
||||||
|
`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
__render(f) {
|
||||||
|
steps.push(this.state.val);
|
||||||
|
return super.__render(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TestWidget.prototype.__render = jest.fn(TestWidget.prototype.__render);
|
||||||
|
|
||||||
|
const widget = new TestWidget();
|
||||||
|
widget.state.val = 2;
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(TestWidget.prototype.__render).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// unmount and re-mount, as in this case, willStart won't be called, so it's
|
||||||
|
// slightly different
|
||||||
|
widget.unmount();
|
||||||
|
widget.state.val = 3;
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||||
|
expect(TestWidget.prototype.__render).toHaveBeenCalledTimes(2);
|
||||||
|
expect(steps).toEqual([2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("change state while mounting component", async () => {
|
||||||
|
const steps: number[] = [];
|
||||||
|
class TestWidget extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div><t t-esc="state.val"/></div>
|
||||||
|
`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
__render(f) {
|
||||||
|
steps.push(this.state.val);
|
||||||
|
return super.__render(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TestWidget.prototype.__render = jest.fn(TestWidget.prototype.__render);
|
||||||
|
TestWidget.prototype.__patch = jest.fn(TestWidget.prototype.__patch);
|
||||||
|
|
||||||
|
const widget = new TestWidget();
|
||||||
|
let prom = widget.mount(fixture);
|
||||||
|
widget.state.val = 2;
|
||||||
|
await prom;
|
||||||
|
expect(fixture.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(TestWidget.prototype.__render).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// unmount and re-mount, as in this case, willStart won't be called, so it's
|
||||||
|
// slightly different
|
||||||
|
widget.unmount();
|
||||||
|
prom = widget.mount(fixture);
|
||||||
|
widget.state.val = 3;
|
||||||
|
await prom;
|
||||||
|
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||||
|
expect(TestWidget.prototype.__render).toHaveBeenCalledTimes(3);
|
||||||
|
expect(TestWidget.prototype.__patch).toHaveBeenCalledTimes(2);
|
||||||
|
expect(steps).toEqual([2, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("change state while component is unmounted", async () => {
|
||||||
|
let child;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span t-esc="state.val"/>`;
|
||||||
|
state = useState({
|
||||||
|
val: "C1",
|
||||||
|
});
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
child = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`<div><t t-esc="state.val"/><Child/></div>`;
|
||||||
|
state = useState({ val: "P1" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>P1<span>C1</span></div>");
|
||||||
|
|
||||||
|
parent.unmount();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
parent.state.val = "P2";
|
||||||
|
child.state.val = "C2";
|
||||||
|
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>P2<span>C2</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("unmount component during a re-rendering", async () => {
|
||||||
|
const def = makeDeferred();
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Child.prototype.__render = jest.fn(Child.prototype.__render);
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child val="state.val"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
expect(Child.prototype.__render).toBeCalledTimes(1);
|
||||||
|
|
||||||
|
parent.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.unmount();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
expect(Child.prototype.__render).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("widget can be mounted on different target", async () => {
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const div = document.createElement("div");
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(div);
|
||||||
|
fixture.appendChild(span);
|
||||||
|
const w = new MyWidget();
|
||||||
|
await w.mount(div);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>Hey</div></div><span></span>");
|
||||||
|
|
||||||
|
await w.mount(span);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span><div>Hey</div></span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("widget can be mounted on different target, another situation", async () => {
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const div = document.createElement("div");
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(div);
|
||||||
|
fixture.appendChild(span);
|
||||||
|
const w = new MyWidget();
|
||||||
|
|
||||||
|
w.mount(div).catch(() => steps.push("1 catch"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span></span>");
|
||||||
|
|
||||||
|
w.mount(span).then(() => steps.push("2 resolved"));
|
||||||
|
|
||||||
|
// we wait two microticks because this is the number of internal promises
|
||||||
|
// that need to be resolved/rejected, and because we want to prove here
|
||||||
|
// that the first mount operation is cancelled immediately, and not after
|
||||||
|
// one full tick.
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
expect(steps).toEqual(["1 catch"]);
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span></span>");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["1 catch", "2 resolved"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span><div>Hey</div></span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("widget can be mounted on same target, another situation", async () => {
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const w = new MyWidget();
|
||||||
|
|
||||||
|
w.mount(fixture).then(() => steps.push("1 resolved"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
w.mount(fixture).then(() => steps.push("2 resolved"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual([]);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["1 resolved", "2 resolved"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("mounting a destroyed widget", async () => {
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
}
|
||||||
|
const w = new MyWidget();
|
||||||
|
w.destroy(); // because, why not
|
||||||
|
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(scheduler.tasks.length).toBe(0);
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot mount a destroyed component");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C1 };
|
||||||
|
static template = xml`<div><div><C1 t-props="state" t-if="state.a"/></div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("first");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 2", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C1 };
|
||||||
|
static template = xml`<div><div><C1 t-props="state" t-if="state.a"/>some text</div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("firstsome text");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixedsome text");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 3", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class C2 extends Component {
|
||||||
|
static template = xml`<C1 a="props.a"/>`;
|
||||||
|
static components = { C1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C2 };
|
||||||
|
static template = xml`<div><div><C2 t-props="state" t-if="state.a"/></div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("first");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 4", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class C2 extends Component {
|
||||||
|
static template = xml`<C1 a="props.a"/>`;
|
||||||
|
static components = { C1 };
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C2 };
|
||||||
|
static template = xml`<div><div><C2 t-props="state" t-if="state.a"/>some text</div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("firstsome text");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixedsome text");
|
||||||
|
});
|
||||||
|
});
|
||||||
+184
-21
@@ -1,5 +1,5 @@
|
|||||||
import { makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||||
import { Component, Env } from "../src/component/component";
|
import { Component } from "../src/component/component";
|
||||||
import { Context, useContext } from "../src/context";
|
import { Context, useContext } from "../src/context";
|
||||||
import { xml } from "../src/tags";
|
import { xml } from "../src/tags";
|
||||||
import { useState } from "../src/hooks";
|
import { useState } from "../src/hooks";
|
||||||
@@ -11,14 +11,13 @@ import { useState } from "../src/hooks";
|
|||||||
// We create before each test:
|
// We create before each test:
|
||||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||||
// manipulations. Note that it is removed after each test.
|
// manipulations. Note that it is removed after each test.
|
||||||
// - env: a WEnv, necessary to create new components
|
// - a test env, necessary to create components, that is set as env
|
||||||
|
|
||||||
let fixture: HTMLElement;
|
let fixture: HTMLElement;
|
||||||
let env: Env;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
Component.env = makeTestEnv();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -33,11 +32,11 @@ describe("Context", () => {
|
|||||||
test("very simple use, with initial value", async () => {
|
test("very simple use, with initial value", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Test extends Component<any, any> {
|
class Test extends Component {
|
||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
const test = new Test(env);
|
const test = new Test();
|
||||||
await test.mount(fixture);
|
await test.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
});
|
});
|
||||||
@@ -45,11 +44,11 @@ describe("Context", () => {
|
|||||||
test("useContext hook is reactive, for one component", async () => {
|
test("useContext hook is reactive, for one component", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Test extends Component<any, any> {
|
class Test extends Component {
|
||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
const test = new Test(env);
|
const test = new Test();
|
||||||
await test.mount(fixture);
|
await test.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
test.contextObj.value = 321;
|
test.contextObj.value = 321;
|
||||||
@@ -60,15 +59,15 @@ describe("Context", () => {
|
|||||||
test("two components can subscribe to same context", async () => {
|
test("two components can subscribe to same context", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><Child /></div>`;
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
testContext.state.value = 321;
|
testContext.state.value = 321;
|
||||||
@@ -76,11 +75,98 @@ describe("Context", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("two async components are updated in parallel", async () => {
|
||||||
|
const testContext = new Context({ value: 123 });
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||||
|
contextObj = useContext(testContext);
|
||||||
|
async render() {
|
||||||
|
steps.push("render");
|
||||||
|
await def;
|
||||||
|
return super.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
|
testContext.state.value = 321;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render", "render"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("two async components on two levels are updated (mostly) in parallel", async () => {
|
||||||
|
const testContext = new Context({ value: 123 });
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class SlowComp extends Component {
|
||||||
|
static template = xml`<p><t t-esc="props.value"/></p>`;
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><SlowComp value="contextObj.value"/></span>`;
|
||||||
|
static components = { SlowComp };
|
||||||
|
contextObj = useContext(testContext);
|
||||||
|
|
||||||
|
render() {
|
||||||
|
steps.push("render");
|
||||||
|
return super.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><Child /><Parent /></div>`;
|
||||||
|
static components = { Child, Parent };
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||||
|
);
|
||||||
|
testContext.state.value = 321;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render"]);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||||
|
);
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
// we need to wait for an extra tick because it could happen (even though it
|
||||||
|
// is rare) that the second batch of renderings is not done yet, because
|
||||||
|
// the initial promise has been given to the macrotask queue, so a small
|
||||||
|
// delay happens.
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render", "render", "render"]);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>321</p></span><div><span><p>321</p></span><span><p>321</p></span></div></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("one components can subscribe twice to same context", async () => {
|
test("one components can subscribe twice to same context", async () => {
|
||||||
const testContext = new Context({ a: 1, b: 2 });
|
const testContext = new Context({ a: 1, b: 2 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj1.a"/><t t-esc="contextObj2.b"/></span>`;
|
static template = xml`<span><t t-esc="contextObj1.a"/><t t-esc="contextObj2.b"/></span>`;
|
||||||
contextObj1 = useContext(testContext);
|
contextObj1 = useContext(testContext);
|
||||||
contextObj2 = useContext(testContext);
|
contextObj2 = useContext(testContext);
|
||||||
@@ -89,11 +175,11 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /></div>`;
|
static template = xml`<div><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||||
expect(steps).toEqual(["child"]);
|
expect(steps).toEqual(["child"]);
|
||||||
@@ -107,7 +193,7 @@ describe("Context", () => {
|
|||||||
const testContext = new Context({ a: 123, b: 321 });
|
const testContext = new Context({ a: 123, b: 321 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
__render(fiber) {
|
__render(fiber) {
|
||||||
@@ -115,7 +201,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><t t-esc="contextObj.b"/></div>`;
|
static template = xml`<div><Child /><t t-esc="contextObj.b"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
@@ -124,7 +210,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
||||||
expect(steps).toEqual(["parent", "child"]);
|
expect(steps).toEqual(["parent", "child"]);
|
||||||
@@ -141,7 +227,7 @@ describe("Context", () => {
|
|||||||
const testContext = new Context({ a: 123 });
|
const testContext = new Context({ a: 123 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
__render(fiber) {
|
__render(fiber) {
|
||||||
@@ -149,7 +235,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -158,7 +244,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
||||||
expect(steps).toEqual(["parent", "child"]);
|
expect(steps).toEqual(["parent", "child"]);
|
||||||
@@ -173,4 +259,81 @@ describe("Context", () => {
|
|||||||
// event
|
// event
|
||||||
expect(testContext.subscriptions.update.length).toBe(0);
|
expect(testContext.subscriptions.update.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("destroyed component before being mounted is inactive", async () => {
|
||||||
|
const testContext = new Context({ a: 123 });
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
|
contextObj = useContext(testContext);
|
||||||
|
willStart() {
|
||||||
|
return makeDeferred();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ flag: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
const prom = parent.mount(fixture);
|
||||||
|
await nextTick(); // wait for Child to be instantiated
|
||||||
|
expect(testContext.subscriptions.update.length).toBe(1);
|
||||||
|
parent.state.flag = false;
|
||||||
|
await prom;
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
|
// kind of whitebox...
|
||||||
|
// we make sure we do not have any pending subscriptions to the 'update'
|
||||||
|
// event
|
||||||
|
expect(testContext.subscriptions.update.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("concurrent renderings", async () => {
|
||||||
|
const testContext = new Context({ x: { n: 1 }, key: "x" });
|
||||||
|
const def = makeDeferred();
|
||||||
|
let stateC;
|
||||||
|
class ComponentC extends Component {
|
||||||
|
static template = xml`<span><t t-esc="context[props.key].n"/><t t-esc="state.x"/></span>`;
|
||||||
|
context = useContext(testContext);
|
||||||
|
state = useState({ x: "a" });
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
stateC = this.state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ComponentB extends Component {
|
||||||
|
static components = { ComponentC };
|
||||||
|
static template = xml`<p><ComponentC key="props.key"/></p>`;
|
||||||
|
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ComponentA extends Component {
|
||||||
|
static components = { ComponentB };
|
||||||
|
static template = xml`<div><ComponentB key="context.key"/></div>`;
|
||||||
|
context = useContext(testContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
const component = new ComponentA();
|
||||||
|
await component.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||||
|
testContext.state.key = "y";
|
||||||
|
testContext.state.y = { n: 2 };
|
||||||
|
delete testContext.state.x;
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||||
|
stateC.x = "b";
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><p><span>2b</span></p></div>");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ describe("event bus behaviour", () => {
|
|||||||
expect.assertions(1);
|
expect.assertions(1);
|
||||||
const bus = new EventBus();
|
const bus = new EventBus();
|
||||||
const owner = {};
|
const owner = {};
|
||||||
bus.on("event", owner, function(this: any) {
|
bus.on("event", owner, function (this: any) {
|
||||||
expect(this).toBe(owner);
|
expect(this).toBe(owner);
|
||||||
});
|
});
|
||||||
bus.trigger("event");
|
bus.trigger("event");
|
||||||
|
|||||||
+29
-46
@@ -8,13 +8,11 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(typeof obj).toBe("object");
|
expect(typeof obj).toBe("object");
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
const obj2: any = observer.observe({ a: 1 });
|
const obj2: any = observer.observe({ a: 1 });
|
||||||
expect(observer.revNumber(obj2)).toBe(1);
|
expect(observer.revNumber(obj2)).toBe(1);
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj2.a = 2;
|
obj2.a = 2;
|
||||||
@@ -24,7 +22,7 @@ describe("observer", () => {
|
|||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
expect(obj2).toEqual({
|
expect(obj2).toEqual({
|
||||||
a: 2
|
a: 2,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -33,27 +31,23 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ a: null, b: undefined });
|
const obj: any = observer.observe({ a: null, b: undefined });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.a = 3;
|
obj.a = 3;
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.b = 5;
|
obj.b = 5;
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
|
|
||||||
obj.a = null;
|
obj.a = null;
|
||||||
obj.b = undefined;
|
obj.b = undefined;
|
||||||
expect(observer.revNumber(obj)).toBe(5);
|
expect(observer.revNumber(obj)).toBe(5);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(5);
|
|
||||||
expect(observer.rev).toBe(5);
|
expect(observer.rev).toBe(5);
|
||||||
expect(obj).toEqual({
|
expect(obj).toEqual({
|
||||||
a: null,
|
a: null,
|
||||||
b: undefined
|
b: undefined,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -63,7 +57,6 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ date });
|
const obj: any = observer.observe({ date });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(typeof obj.date.getFullYear()).toBe("number");
|
expect(typeof obj.date.getFullYear()).toBe("number");
|
||||||
expect(obj.date).toBe(date);
|
expect(obj.date).toBe(date);
|
||||||
@@ -71,25 +64,38 @@ describe("observer", () => {
|
|||||||
obj.date = new Date();
|
obj.date = new Date();
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(obj.date).not.toBe(date);
|
expect(obj.date).not.toBe(date);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("properly handle promises (i.e.: treat them like primitive values", async () => {
|
||||||
|
const observer = new Observer();
|
||||||
|
let resolved = false;
|
||||||
|
const prom = new Promise((r) => r());
|
||||||
|
const obj: any = observer.observe({ prom });
|
||||||
|
expect(obj.prom).toBeInstanceOf(Promise);
|
||||||
|
|
||||||
|
obj.prom.then(() => (resolved = true));
|
||||||
|
|
||||||
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
|
|
||||||
|
expect(resolved).toBe(false);
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(resolved).toBe(true);
|
||||||
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
test("can change values in array", () => {
|
test("can change values in array", () => {
|
||||||
const observer = new Observer();
|
const observer = new Observer();
|
||||||
const obj: any = observer.observe({ arr: [1, 2] });
|
const obj: any = observer.observe({ arr: [1, 2] });
|
||||||
|
|
||||||
expect(Array.isArray(obj.arr)).toBe(true);
|
expect(Array.isArray(obj.arr)).toBe(true);
|
||||||
expect(observer.revNumber(obj.arr)).toBe(1);
|
expect(observer.revNumber(obj.arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj.arr)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.arr[0] = "nope";
|
obj.arr[0] = "nope";
|
||||||
expect(observer.revNumber(obj.arr)).toBe(2);
|
expect(observer.revNumber(obj.arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj.arr)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,24 +104,20 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ a: 1 });
|
const obj: any = observer.observe({ a: 1 });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.a = 2;
|
obj.a = 2;
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
// same value again
|
// same value again
|
||||||
obj.a = 2;
|
obj.a = 2;
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.a = 3;
|
obj.a = 3;
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -126,19 +128,16 @@ describe("observer", () => {
|
|||||||
expect(Array.isArray(arr)).toBe(true);
|
expect(Array.isArray(arr)).toBe(true);
|
||||||
expect(arr.length).toBe(0);
|
expect(arr.length).toBe(0);
|
||||||
expect(observer.revNumber(arr)).toBe(1);
|
expect(observer.revNumber(arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
arr.push(1);
|
arr.push(1);
|
||||||
expect(observer.revNumber(arr)).toBe(2);
|
expect(observer.revNumber(arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(arr.length).toBe(1);
|
expect(arr.length).toBe(1);
|
||||||
expect(arr).toEqual([1]);
|
expect(arr).toEqual([1]);
|
||||||
|
|
||||||
arr.splice(1, 0, "hey");
|
arr.splice(1, 0, "hey");
|
||||||
expect(observer.revNumber(arr)).toBe(3);
|
expect(observer.revNumber(arr)).toBe(3);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(arr).toEqual([1, "hey"]);
|
expect(arr).toEqual([1, "hey"]);
|
||||||
expect(arr.length).toBe(2);
|
expect(arr.length).toBe(2);
|
||||||
@@ -146,7 +145,6 @@ describe("observer", () => {
|
|||||||
arr.unshift("lindemans");
|
arr.unshift("lindemans");
|
||||||
//it generates 3 primitive operations
|
//it generates 3 primitive operations
|
||||||
expect(observer.revNumber(arr)).toBe(6);
|
expect(observer.revNumber(arr)).toBe(6);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(6);
|
|
||||||
expect(observer.rev).toBe(6);
|
expect(observer.rev).toBe(6);
|
||||||
expect(arr).toEqual(["lindemans", 1, "hey"]);
|
expect(arr).toEqual(["lindemans", 1, "hey"]);
|
||||||
expect(arr.length).toBe(3);
|
expect(arr.length).toBe(3);
|
||||||
@@ -154,21 +152,18 @@ describe("observer", () => {
|
|||||||
arr.reverse();
|
arr.reverse();
|
||||||
//it generates 2 primitive operations
|
//it generates 2 primitive operations
|
||||||
expect(observer.revNumber(arr)).toBe(8);
|
expect(observer.revNumber(arr)).toBe(8);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(8);
|
|
||||||
expect(observer.rev).toBe(8);
|
expect(observer.rev).toBe(8);
|
||||||
expect(arr).toEqual(["hey", 1, "lindemans"]);
|
expect(arr).toEqual(["hey", 1, "lindemans"]);
|
||||||
expect(arr.length).toBe(3);
|
expect(arr.length).toBe(3);
|
||||||
|
|
||||||
arr.pop(); // one set, one delete
|
arr.pop(); // one set, one delete
|
||||||
expect(observer.revNumber(arr)).toBe(10);
|
expect(observer.revNumber(arr)).toBe(10);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(10);
|
|
||||||
expect(observer.rev).toBe(10);
|
expect(observer.rev).toBe(10);
|
||||||
expect(arr).toEqual(["hey", 1]);
|
expect(arr).toEqual(["hey", 1]);
|
||||||
expect(arr.length).toBe(2);
|
expect(arr.length).toBe(2);
|
||||||
|
|
||||||
arr.shift(); // 2 sets, 1 delete
|
arr.shift(); // 2 sets, 1 delete
|
||||||
expect(observer.revNumber(arr)).toBe(13);
|
expect(observer.revNumber(arr)).toBe(13);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(13);
|
|
||||||
expect(observer.rev).toBe(13);
|
expect(observer.rev).toBe(13);
|
||||||
expect(arr).toEqual([1]);
|
expect(arr).toEqual([1]);
|
||||||
expect(arr.length).toBe(1);
|
expect(arr.length).toBe(1);
|
||||||
@@ -187,8 +182,7 @@ describe("observer", () => {
|
|||||||
arr[0].kriek = 6;
|
arr[0].kriek = 6;
|
||||||
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(arr)).toBe(2);
|
expect(observer.revNumber(arr)).toBe(3);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
|
||||||
expect(observer.revNumber(arr[0])).toBe(3);
|
expect(observer.revNumber(arr[0])).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -238,7 +232,6 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state)).toBe(1);
|
|
||||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||||
|
|
||||||
state[1] = "b";
|
state[1] = "b";
|
||||||
@@ -247,7 +240,6 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(2);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state)).toBe(2);
|
|
||||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||||
|
|
||||||
expect(state).toEqual(["a", "b"]);
|
expect(state).toEqual(["a", "b"]);
|
||||||
@@ -259,13 +251,11 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(observer.revNumber(state.arr)).toBe(1);
|
expect(observer.revNumber(state.arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state.arr)).toBe(1);
|
|
||||||
expect(state.arr.length).toBe(0);
|
expect(state.arr.length).toBe(0);
|
||||||
|
|
||||||
state.arr.push(1);
|
state.arr.push(1);
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state.arr)).toBe(2);
|
expect(observer.revNumber(state.arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state.arr)).toBe(2);
|
|
||||||
expect(state.arr.length).toBe(1);
|
expect(state.arr.length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -280,7 +270,7 @@ describe("observer", () => {
|
|||||||
|
|
||||||
state.arr[0].something = 2;
|
state.arr[0].something = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state.arr)).toBe(1);
|
expect(observer.revNumber(state.arr)).toBe(2);
|
||||||
expect(observer.revNumber(state.arr[0])).toBe(2);
|
expect(observer.revNumber(state.arr[0])).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -294,7 +284,7 @@ describe("observer", () => {
|
|||||||
|
|
||||||
state.a.b = 2;
|
state.a.b = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.revNumber(state.a)).toBe(2);
|
expect(observer.revNumber(state.a)).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -312,7 +302,7 @@ describe("observer", () => {
|
|||||||
expect(observer.revNumber(obj.a)).toBe(2);
|
expect(observer.revNumber(obj.a)).toBe(2);
|
||||||
obj.a.b = 3;
|
obj.a.b = 3;
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.revNumber(obj.a)).toBe(3);
|
expect(observer.revNumber(obj.a)).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -320,22 +310,18 @@ describe("observer", () => {
|
|||||||
const observer = new Observer();
|
const observer = new Observer();
|
||||||
const state: any = observer.observe({ o: { a: 1 }, arr: [1], n: 13 });
|
const state: any = observer.observe({ o: { a: 1 }, arr: [1], n: 13 });
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state)).toBe(1);
|
|
||||||
|
|
||||||
state.o.a = 2;
|
state.o.a = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state)).toBe(2);
|
|
||||||
|
|
||||||
state.arr.push(2);
|
state.arr.push(2);
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(3);
|
||||||
expect(observer.deepRevNumber(state)).toBe(3);
|
|
||||||
|
|
||||||
state.n = 155;
|
state.n = 155;
|
||||||
expect(observer.rev).toBe(4);
|
expect(observer.rev).toBe(4);
|
||||||
expect(observer.revNumber(state)).toBe(2);
|
expect(observer.revNumber(state)).toBe(4);
|
||||||
expect(observer.deepRevNumber(state)).toBe(4);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("properly handle already observed state", () => {
|
test("properly handle already observed state", () => {
|
||||||
@@ -361,18 +347,15 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({});
|
const obj: any = observer.observe({});
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.aku = "always finds annoying problems";
|
obj.aku = "always finds annoying problems";
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.aku = "always finds good problems";
|
obj.aku = "always finds good problems";
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -416,7 +399,7 @@ describe("observer", () => {
|
|||||||
expect(observer.revNumber(obj2)).toBe(1);
|
expect(observer.revNumber(obj2)).toBe(1);
|
||||||
|
|
||||||
obj2.key = 3;
|
obj2.key = 3;
|
||||||
expect(observer.revNumber(obj1)).toBe(1);
|
expect(observer.revNumber(obj1)).toBe(2);
|
||||||
expect(observer.revNumber(obj2)).toBe(2);
|
expect(observer.revNumber(obj2)).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -442,7 +425,7 @@ describe("observer", () => {
|
|||||||
obj.a = 111;
|
obj.a = 111;
|
||||||
obj.f = 222;
|
obj.f = 222;
|
||||||
await nextMicroTick();
|
await nextMicroTick();
|
||||||
expect(observer.notifyCB).toBeCalledTimes(4);
|
expect(observer.notifyCB).toBeCalledTimes(5);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("throw error when state is mutated in object if allowMutation=false", async () => {
|
test("throw error when state is mutated in object if allowMutation=false", async () => {
|
||||||
|
|||||||
@@ -1,126 +0,0 @@
|
|||||||
/**
|
|
||||||
* Doc Link Checker
|
|
||||||
*
|
|
||||||
* We define here a test to make sure that there are no dead link in the Owl
|
|
||||||
* documentation.
|
|
||||||
*/
|
|
||||||
import * as fs from "fs";
|
|
||||||
|
|
||||||
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
|
|
||||||
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
|
|
||||||
|
|
||||||
// files to be checked
|
|
||||||
function getFiles(): string[] {
|
|
||||||
const DOCFILES = fs.readdirSync("doc").map(f => `doc/${f}`);
|
|
||||||
const MAINREADME = "README.md";
|
|
||||||
return DOCFILES.concat(MAINREADME);
|
|
||||||
}
|
|
||||||
|
|
||||||
test("All markdown links work", () => {
|
|
||||||
let linkNumber = 0;
|
|
||||||
let invalidLinkNumber = 0;
|
|
||||||
const files = getFiles();
|
|
||||||
const data = readDocData(files);
|
|
||||||
for (let file of data) {
|
|
||||||
for (let link of file.links) {
|
|
||||||
// DEBUG: uncomment next line
|
|
||||||
// console.warn(`Checking "${link.name}" in "${file.name}"`);
|
|
||||||
linkNumber++;
|
|
||||||
if (!isLinkValid(link, file, data)) {
|
|
||||||
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
|
||||||
invalidLinkNumber++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(invalidLinkNumber).toBe(0);
|
|
||||||
expect(linkNumber).toBeGreaterThan(10);
|
|
||||||
});
|
|
||||||
|
|
||||||
interface MarkDownLink {
|
|
||||||
name: string;
|
|
||||||
link: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MarkDownSection {
|
|
||||||
name: string;
|
|
||||||
slug: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FileData {
|
|
||||||
name: string;
|
|
||||||
links: MarkDownLink[];
|
|
||||||
sections: MarkDownSection[];
|
|
||||||
}
|
|
||||||
|
|
||||||
function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
|
|
||||||
const parts = link.link.split("#");
|
|
||||||
const currentParts = current.name.split("/");
|
|
||||||
const path = currentParts.length > 1 ? currentParts[0] + "/" : "";
|
|
||||||
const fullName = path + parts[0];
|
|
||||||
if (parts.length === 1) {
|
|
||||||
// no # in url
|
|
||||||
if (parts[0].endsWith(".md")) {
|
|
||||||
// it is a local md file
|
|
||||||
if (!files.find(f => f.name === fullName)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const file = parts[0] === "" ? current : files.find(f => f.name === fullName);
|
|
||||||
if (!file) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!file.sections.find(s => s.slug === parts[1])) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
|
|
||||||
function slugify(str) {
|
|
||||||
const a = "àáäâãåăæçèéëêǵḧìíïîḿńǹñòóöôœøṕŕßśșțùúüûǘẃẍÿź·_,:;";
|
|
||||||
const b = "aaaaaaaaceeeeghiiiimnnnooooooprssstuuuuuwxyz-----";
|
|
||||||
const p = new RegExp(a.split("").join("|"), "g");
|
|
||||||
return str
|
|
||||||
.toString()
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/\//g, "") // remove /
|
|
||||||
.replace(/\s+/g, "-") // Replace spaces with -
|
|
||||||
.replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
|
|
||||||
.replace(/&/g, "-and-") // Replace & with ‘and’
|
|
||||||
.replace(/[^\w\-]+/g, "") // Remove all non-word characters
|
|
||||||
.replace(/\-\-+/g, "-") // Replace multiple - with single -
|
|
||||||
.replace(/^-+/, "") // Trim - from start of text
|
|
||||||
.replace(/-+$/, ""); // Trim - from end of text
|
|
||||||
}
|
|
||||||
|
|
||||||
function readDocData(files: string[]): FileData[] {
|
|
||||||
const result: FileData[] = [];
|
|
||||||
|
|
||||||
for (let file of files) {
|
|
||||||
const fileData: FileData = {
|
|
||||||
name: file,
|
|
||||||
links: [],
|
|
||||||
sections: []
|
|
||||||
};
|
|
||||||
const content = fs.readFileSync(file, { encoding: "utf8" });
|
|
||||||
let m;
|
|
||||||
// get links info
|
|
||||||
do {
|
|
||||||
m = LINK_REGEXP.exec(content);
|
|
||||||
if (m) {
|
|
||||||
fileData.links.push({ name: m[0], link: m[2] });
|
|
||||||
}
|
|
||||||
} while (m);
|
|
||||||
// get sections info
|
|
||||||
do {
|
|
||||||
m = HEADING_REGEXP.exec(content);
|
|
||||||
if (m) {
|
|
||||||
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
|
|
||||||
}
|
|
||||||
} while (m);
|
|
||||||
|
|
||||||
result.push(fileData);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
+19
-9
@@ -1,9 +1,12 @@
|
|||||||
import { Env } from "../src/component/component";
|
import { Env, Component } from "../src/component/component";
|
||||||
|
import { scheduler } from "../src/component/scheduler";
|
||||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||||
|
import { CompilationContext } from "../src/qweb/compilation_context";
|
||||||
import { patch } from "../src/vdom";
|
import { patch } from "../src/vdom";
|
||||||
import "../src/qweb/base_directives";
|
import "../src/qweb/base_directives";
|
||||||
import "../src/qweb/extensions";
|
import "../src/qweb/extensions";
|
||||||
import "../src/component/directive";
|
import "../src/component/directive";
|
||||||
|
import { browser } from "../src/browser";
|
||||||
|
|
||||||
// Some static cleanup
|
// Some static cleanup
|
||||||
let nextSlotId;
|
let nextSlotId;
|
||||||
@@ -13,9 +16,11 @@ let TEMPLATES;
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
nextSlotId = QWeb.nextSlotId;
|
nextSlotId = QWeb.nextSlotId;
|
||||||
|
CompilationContext.nextID = 1;
|
||||||
slots = Object.assign({}, QWeb.slots);
|
slots = Object.assign({}, QWeb.slots);
|
||||||
nextId = QWeb.nextId;
|
nextId = QWeb.nextId;
|
||||||
TEMPLATES = Object.assign({}, QWeb.TEMPLATES);
|
TEMPLATES = Object.assign({}, QWeb.TEMPLATES);
|
||||||
|
Component.scheduler.tasks = [];
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -23,6 +28,7 @@ afterEach(() => {
|
|||||||
QWeb.slots = slots;
|
QWeb.slots = slots;
|
||||||
QWeb.nextId = nextId;
|
QWeb.nextId = nextId;
|
||||||
QWeb.TEMPLATES = TEMPLATES;
|
QWeb.TEMPLATES = TEMPLATES;
|
||||||
|
Component.scheduler.tasks = [];
|
||||||
});
|
});
|
||||||
|
|
||||||
// helpers
|
// helpers
|
||||||
@@ -30,8 +36,9 @@ export function nextMicroTick(): Promise<void> {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nextTick(): Promise<void> {
|
export async function nextTick(): Promise<void> {
|
||||||
return new Promise(resolve => setTimeout(resolve));
|
await new Promise((resolve) => scheduler.requestAnimationFrame(resolve));
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeTestFixture() {
|
export function makeTestFixture() {
|
||||||
@@ -62,7 +69,8 @@ export function makeDeferred(): Deferred {
|
|||||||
|
|
||||||
export function makeTestEnv(): Env {
|
export function makeTestEnv(): Env {
|
||||||
return {
|
return {
|
||||||
qweb: new QWeb()
|
qweb: new QWeb(),
|
||||||
|
browser: browser,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +84,11 @@ export function renderToDOM(
|
|||||||
context: EvalContext = {},
|
context: EvalContext = {},
|
||||||
extra?: any
|
extra?: any
|
||||||
): HTMLElement | Text {
|
): HTMLElement | Text {
|
||||||
|
if (!context.__owl__) {
|
||||||
|
// we add `__owl__` to better simulate a component as context. This is
|
||||||
|
// particularly important for event handlers added with the `t-on` directive.
|
||||||
|
context.__owl__ = { isMounted: true };
|
||||||
|
}
|
||||||
const vnode = qweb.render(template, context, extra);
|
const vnode = qweb.render(template, context, extra);
|
||||||
|
|
||||||
// we snapshot here the compiled code. This is useful to prevent unwanted code
|
// we snapshot here the compiled code. This is useful to prevent unwanted code
|
||||||
@@ -105,11 +118,8 @@ export function renderToString(
|
|||||||
context: EvalContext = {},
|
context: EvalContext = {},
|
||||||
extra?: any
|
extra?: any
|
||||||
): string {
|
): string {
|
||||||
const node = renderToDOM(qweb, t, context, extra);
|
const result = qweb.renderToString(t, context, extra);
|
||||||
const result = node instanceof Text ? node.textContent! : node.outerHTML;
|
expect(qweb.templates[t].fn.toString()).toMatchSnapshot();
|
||||||
if (result !== qweb.renderToString(t, context, extra)) {
|
|
||||||
throw new Error("HTML string returned by renderToString helper does not match QWeb render");
|
|
||||||
}
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+239
-68
@@ -9,7 +9,8 @@ import {
|
|||||||
onWillPatch,
|
onWillPatch,
|
||||||
onWillStart,
|
onWillStart,
|
||||||
onWillUpdateProps,
|
onWillUpdateProps,
|
||||||
useSubEnv
|
useSubEnv,
|
||||||
|
useExternalListener,
|
||||||
} from "../src/hooks";
|
} from "../src/hooks";
|
||||||
import { xml } from "../src/tags";
|
import { xml } from "../src/tags";
|
||||||
|
|
||||||
@@ -28,6 +29,7 @@ let env: Env;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -40,11 +42,11 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("hooks", () => {
|
describe("hooks", () => {
|
||||||
test("can use a state hook", async () => {
|
test("can use a state hook", async () => {
|
||||||
class Counter extends Component<any, any> {
|
class Counter extends Component {
|
||||||
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
||||||
counter = useState({ value: 42 });
|
counter = useState({ value: 42 });
|
||||||
}
|
}
|
||||||
const counter = new Counter(env);
|
const counter = new Counter();
|
||||||
await counter.mount(fixture);
|
await counter.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>42</div>");
|
expect(fixture.innerHTML).toBe("<div>42</div>");
|
||||||
counter.counter.value = 3;
|
counter.counter.value = 3;
|
||||||
@@ -62,14 +64,14 @@ describe("hooks", () => {
|
|||||||
steps.push("willunmount");
|
steps.push("willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("mounted");
|
expect(component).not.toHaveProperty("mounted");
|
||||||
expect(component).not.toHaveProperty("willUnmount");
|
expect(component).not.toHaveProperty("willUnmount");
|
||||||
@@ -90,20 +92,20 @@ describe("hooks", () => {
|
|||||||
steps.push("willunmount");
|
steps.push("willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||||
expect(steps).toEqual(["mounted"]);
|
expect(steps).toEqual(["mounted"]);
|
||||||
@@ -124,10 +126,10 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount");
|
steps.push("hook:willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -137,7 +139,7 @@ describe("hooks", () => {
|
|||||||
steps.push("comp:willunmount");
|
steps.push("comp:willunmount");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.unmount();
|
component.unmount();
|
||||||
@@ -155,10 +157,10 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount");
|
steps.push("hook:willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -169,13 +171,13 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||||
parent.state.flag = false;
|
parent.state.flag = false;
|
||||||
@@ -195,15 +197,15 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount" + i);
|
steps.push("hook:willunmount" + i);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook(1);
|
useMyHook(1);
|
||||||
useMyHook(2);
|
useMyHook(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.unmount();
|
component.unmount();
|
||||||
@@ -212,12 +214,12 @@ describe("hooks", () => {
|
|||||||
"hook:mounted1",
|
"hook:mounted1",
|
||||||
"hook:mounted2",
|
"hook:mounted2",
|
||||||
"hook:willunmount2",
|
"hook:willunmount2",
|
||||||
"hook:willunmount1"
|
"hook:willunmount1",
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("useRef hook", async () => {
|
test("useRef hook", async () => {
|
||||||
class Counter extends Component<any, any> {
|
class Counter extends Component {
|
||||||
static template = xml`<div><button t-ref="button"><t t-esc="value"/></button></div>`;
|
static template = xml`<div><button t-ref="button"><t t-esc="value"/></button></div>`;
|
||||||
button = useRef("button");
|
button = useRef("button");
|
||||||
value = 0;
|
value = 0;
|
||||||
@@ -226,9 +228,12 @@ describe("hooks", () => {
|
|||||||
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const counter = new Counter(env);
|
const counter = new Counter();
|
||||||
|
expect(counter.button.el).toBe(null);
|
||||||
await counter.mount(fixture);
|
await counter.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
||||||
|
expect(counter.button.el).not.toBe(null);
|
||||||
|
expect(counter.button.el).toBe(fixture.querySelector("button"));
|
||||||
counter.increment();
|
counter.increment();
|
||||||
await nextTick();
|
await nextTick();
|
||||||
expect(fixture.innerHTML).toBe("<div><button>1</button></div>");
|
expect(fixture.innerHTML).toBe("<div><button>1</button></div>");
|
||||||
@@ -236,7 +241,7 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
test("useRef hook is null if ref is removed ", async () => {
|
test("useRef hook is null if ref is removed ", async () => {
|
||||||
expect.assertions(4);
|
expect.assertions(4);
|
||||||
class TestRef extends Component<any, any> {
|
class TestRef extends Component {
|
||||||
static template = xml`<div><span t-if="state.flag" t-ref="span">owl</span></div>`;
|
static template = xml`<div><span t-if="state.flag" t-ref="span">owl</span></div>`;
|
||||||
spanRef = useRef("span");
|
spanRef = useRef("span");
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -247,7 +252,7 @@ describe("hooks", () => {
|
|||||||
expect(this.spanRef.el).toBeNull();
|
expect(this.spanRef.el).toBeNull();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new TestRef(env);
|
const component = new TestRef();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
||||||
component.state.flag = false;
|
component.state.flag = false;
|
||||||
@@ -255,6 +260,104 @@ describe("hooks", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div></div>");
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("t-refs on widget are components", async () => {
|
||||||
|
class WidgetB extends Component {
|
||||||
|
static template = xml`<div>b</div>`;
|
||||||
|
}
|
||||||
|
class WidgetC extends Component {
|
||||||
|
static template = xml`<div class="outer-div">Hello<WidgetB t-ref="mywidgetb" /></div>`;
|
||||||
|
static components = { WidgetB };
|
||||||
|
ref = useRef<WidgetB>("mywidgetb");
|
||||||
|
}
|
||||||
|
|
||||||
|
const widget = new WidgetC();
|
||||||
|
expect(widget.ref.comp).toBe(null);
|
||||||
|
expect(widget.ref.el).toBe(null);
|
||||||
|
await widget.mount(fixture);
|
||||||
|
expect(widget.ref.comp).toBeInstanceOf(WidgetB);
|
||||||
|
expect(widget.ref.el).toEqual(fixture.querySelector(".outer-div > div"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-refs are bound at proper timing", async () => {
|
||||||
|
expect.assertions(2);
|
||||||
|
class Widget extends Component {
|
||||||
|
static template = xml`<div>widget</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-foreach="state.list" t-as="elem" t-ref="child" t-key="elem" t-component="Widget"/>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
static components = { Widget };
|
||||||
|
state = useState({ list: <any>[] });
|
||||||
|
child = useRef("child");
|
||||||
|
willPatch() {
|
||||||
|
expect(this.child.comp).toBeNull();
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
expect(this.child.comp).not.toBeNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new ParentWidget();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
parent.state.list.push(1);
|
||||||
|
await nextTick();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-refs are bound at proper timing (2)", async () => {
|
||||||
|
expect.assertions(10);
|
||||||
|
class Widget extends Component {
|
||||||
|
static template = xml`<div>widget</div>`;
|
||||||
|
}
|
||||||
|
class ParentWidget extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="state.child1" t-ref="child1" t-component="Widget"/>
|
||||||
|
<t t-if="state.child2" t-ref="child2" t-component="Widget"/>
|
||||||
|
</div>`;
|
||||||
|
static components = { Widget };
|
||||||
|
state = useState({ child1: true, child2: false });
|
||||||
|
child1 = useRef("child1");
|
||||||
|
child2 = useRef("child2");
|
||||||
|
count = 0;
|
||||||
|
mounted() {
|
||||||
|
expect(this.child1.comp).toBeDefined();
|
||||||
|
expect(this.child2.comp).toBeNull();
|
||||||
|
}
|
||||||
|
willPatch() {
|
||||||
|
if (this.count === 0) {
|
||||||
|
expect(this.child1.comp).toBeDefined();
|
||||||
|
expect(this.child2.comp).toBeNull();
|
||||||
|
}
|
||||||
|
if (this.count === 1) {
|
||||||
|
expect(this.child1.comp).toBeDefined();
|
||||||
|
expect(this.child2.comp).toBeDefined();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
if (this.count === 0) {
|
||||||
|
expect(this.child1.comp).toBeDefined();
|
||||||
|
expect(this.child2.comp).toBeDefined();
|
||||||
|
}
|
||||||
|
if (this.count === 1) {
|
||||||
|
expect(this.child1.comp).toBeNull();
|
||||||
|
expect(this.child2.comp).toBeDefined();
|
||||||
|
}
|
||||||
|
this.count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new ParentWidget();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
parent.state.child2 = true;
|
||||||
|
await nextTick();
|
||||||
|
parent.state.child1 = false;
|
||||||
|
await nextTick();
|
||||||
|
});
|
||||||
|
|
||||||
test("can use onPatched, onWillPatch", async () => {
|
test("can use onPatched, onWillPatch", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
function useMyHook() {
|
function useMyHook() {
|
||||||
@@ -266,17 +369,17 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("patched");
|
expect(component).not.toHaveProperty("patched");
|
||||||
expect(component).not.toHaveProperty("willPatch");
|
expect(component).not.toHaveProperty("willPatch");
|
||||||
@@ -300,12 +403,12 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willPatch");
|
steps.push("hook:willPatch");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
willPatch() {
|
willPatch() {
|
||||||
@@ -315,7 +418,7 @@ describe("hooks", () => {
|
|||||||
steps.push("comp:patched");
|
steps.push("comp:patched");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.state.flag = false;
|
component.state.flag = false;
|
||||||
@@ -334,16 +437,16 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willPatch" + i);
|
steps.push("hook:willPatch" + i);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook(1);
|
useMyHook(1);
|
||||||
useMyHook(2);
|
useMyHook(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
||||||
component.state.value++;
|
component.state.value++;
|
||||||
@@ -370,20 +473,20 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test("simple input", async () => {
|
test("simple input", async () => {
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<input t-ref="input1"/>
|
<input t-ref="input1"/>
|
||||||
<input t-ref="input2"/>
|
<input t-ref="input2"/>
|
||||||
</div>`;
|
</div>`;
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useAutofocus("input2");
|
useAutofocus("input2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new SomeComponent(env);
|
const component = new SomeComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
||||||
const input2 = fixture.querySelectorAll("input")[1];
|
const input2 = fixture.querySelectorAll("input")[1];
|
||||||
@@ -391,7 +494,7 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("input in a t-if", async () => {
|
test("input in a t-if", async () => {
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<input t-ref="input1"/>
|
<input t-ref="input1"/>
|
||||||
@@ -399,13 +502,13 @@ describe("hooks", () => {
|
|||||||
</div>`;
|
</div>`;
|
||||||
|
|
||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useAutofocus("input2");
|
useAutofocus("input2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new SomeComponent(env);
|
const component = new SomeComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><input></div>");
|
expect(fixture.innerHTML).toBe("<div><input></div>");
|
||||||
expect(document.activeElement).toBe(document.body);
|
expect(document.activeElement).toBe(document.body);
|
||||||
@@ -418,14 +521,14 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can use sub env", async () => {
|
test("can use sub env", async () => {
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useSubEnv({ val: 3 });
|
useSubEnv({ val: 3 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new TestComponent(env);
|
const component = new TestComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>3</div>");
|
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||||
expect(env).not.toHaveProperty("val");
|
expect(env).not.toHaveProperty("val");
|
||||||
@@ -433,61 +536,129 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("parent and child env", async () => {
|
test("parent and child env", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useSubEnv({ val: 5 });
|
useSubEnv({ val: 5 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useSubEnv({ val: 3 });
|
useSubEnv({ val: 3 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new Parent(env);
|
const component = new Parent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can use onWillStart, onWillUpdateProps", async () => {
|
test("can use onWillStart, onWillUpdateProps", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
async function slow(): Promise<string> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
resolve("slow");
|
||||||
|
}, 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
function useMyHook() {
|
function useMyHook() {
|
||||||
onWillStart(() => {
|
onWillStart(async () => {
|
||||||
|
steps.push(await slow());
|
||||||
steps.push("onWillStart");
|
steps.push("onWillStart");
|
||||||
});
|
});
|
||||||
onWillUpdateProps(nextProps => {
|
onWillUpdateProps(async (nextProps) => {
|
||||||
expect(nextProps).toEqual({ value: 2 });
|
expect(nextProps).toEqual({ value: 2 });
|
||||||
|
steps.push(await slow());
|
||||||
steps.push("onWillUpdateProps");
|
steps.push("onWillUpdateProps");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
function use2ndHook() {
|
||||||
|
onWillStart(() => {
|
||||||
|
steps.push("on2ndStart");
|
||||||
|
});
|
||||||
|
onWillUpdateProps((nextProps) => {
|
||||||
|
expect(nextProps).toEqual({ value: 2 });
|
||||||
|
steps.push("on2ndUpdate");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
class MyComponent extends Component {
|
||||||
static template = xml`<span><t t-esc="props.value"/></span>`;
|
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
|
use2ndHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><MyComponent value="state.value"/></div>`;
|
static template = xml`<div><MyComponent value="state.value"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(app).not.toHaveProperty("willStart");
|
expect(app).not.toHaveProperty("willStart");
|
||||||
expect(app).not.toHaveProperty("willUpdateProps");
|
expect(app).not.toHaveProperty("willUpdateProps");
|
||||||
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
||||||
expect(steps).toEqual(["onWillStart"]);
|
|
||||||
|
// NOTE: 'on2ndStart' appears first in the list even though
|
||||||
|
// the 'use2ndHook' is declared after 'useMyHook'. This is
|
||||||
|
// because Promise.all is used to call the callbacks specified
|
||||||
|
// in the hooks, which runs them simultaneously.
|
||||||
|
// Additionally, 'slow' should be listed before 'onWillStart'
|
||||||
|
// because call to `slow` is awaited.
|
||||||
|
expect(steps).toEqual(["on2ndStart", "slow", "onWillStart"]);
|
||||||
|
|
||||||
app.state.value = 2;
|
app.state.value = 2;
|
||||||
await nextTick();
|
await nextTick();
|
||||||
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
|
||||||
expect(steps).toEqual(["onWillStart", "onWillUpdateProps"]);
|
expect(steps).toEqual([
|
||||||
|
"on2ndStart",
|
||||||
|
"slow",
|
||||||
|
"onWillStart",
|
||||||
|
"on2ndUpdate",
|
||||||
|
"slow",
|
||||||
|
"onWillUpdateProps",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("useExternalListener", async () => {
|
||||||
|
let n = 0;
|
||||||
|
|
||||||
|
class MyComponent extends Component {
|
||||||
|
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
useExternalListener(window as any, "click", this.increment);
|
||||||
|
}
|
||||||
|
increment() {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
|
static components = { MyComponent };
|
||||||
|
state = useState({ flag: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
|
||||||
|
expect(n).toBe(0);
|
||||||
|
window.dispatchEvent(new Event("click"));
|
||||||
|
expect(n).toBe(0);
|
||||||
|
app.state.flag = true;
|
||||||
|
await nextTick();
|
||||||
|
window.dispatchEvent(new Event("click"));
|
||||||
|
expect(n).toBe(1);
|
||||||
|
app.state.flag = false;
|
||||||
|
await nextTick();
|
||||||
|
window.dispatchEvent(new Event("click"));
|
||||||
|
expect(n).toBe(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import { AsyncRoot } from "../../src/misc/async_root";
|
||||||
|
import { useState } from "../../src/hooks";
|
||||||
|
import { xml } from "../../src/tags";
|
||||||
|
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||||
|
import { Component } from "../../src/component/component";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// 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.
|
||||||
|
// - a test env, necessary to create components, that is set as env
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
Component.env = makeTestEnv();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Asyncroot", () => {
|
||||||
|
test("delayed component with AsyncRoot component", async () => {
|
||||||
|
let def;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
|
}
|
||||||
|
class AsyncChild extends Child {
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
|
<div class="children">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
<AsyncRoot>
|
||||||
|
<AsyncChild val="state.val"/>
|
||||||
|
</AsyncRoot>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
static components = { Child, AsyncChild, AsyncRoot };
|
||||||
|
state = useState({ val: 0 });
|
||||||
|
|
||||||
|
updateApp() {
|
||||||
|
this.state.val++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||||
|
|
||||||
|
// click on button to increment Parent counter
|
||||||
|
def = makeDeferred();
|
||||||
|
fixture.querySelector("button")!.click();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>0</span>");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>1</span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("fast component with AsyncRoot", async () => {
|
||||||
|
let def;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
|
}
|
||||||
|
class AsyncChild extends Child {
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
|
<div class="children">
|
||||||
|
<AsyncRoot>
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</AsyncRoot>
|
||||||
|
<AsyncChild val="state.val"/>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
static components = { Child, AsyncChild, AsyncRoot };
|
||||||
|
state = useState({ val: 0 });
|
||||||
|
|
||||||
|
updateApp() {
|
||||||
|
this.state.val++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||||
|
|
||||||
|
// click on button to increment Parent counter
|
||||||
|
def = makeDeferred();
|
||||||
|
fixture.querySelector("button")!.click();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>0</span>");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>1</span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("asyncroot component: mixed re-renderings", async () => {
|
||||||
|
let def;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<span t-on-click="increment">
|
||||||
|
<t t-esc="state.val"/>/<t t-esc="props.val"/>
|
||||||
|
</span>`;
|
||||||
|
state = useState({ val: 0 });
|
||||||
|
|
||||||
|
increment() {
|
||||||
|
this.state.val++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class AsyncChild extends Child {
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
|
<div class="children">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
<AsyncRoot>
|
||||||
|
<AsyncChild val="state.val"/>
|
||||||
|
</AsyncRoot>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
static components = { Child, AsyncChild, AsyncRoot };
|
||||||
|
state = useState({ val: 0 });
|
||||||
|
|
||||||
|
updateApp() {
|
||||||
|
this.state.val++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/0</span><span>0/0</span>");
|
||||||
|
|
||||||
|
// click on button to increment Parent counter
|
||||||
|
def = makeDeferred();
|
||||||
|
fixture.querySelector("button")!.click();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/1</span><span>0/0</span>");
|
||||||
|
|
||||||
|
// click on each Child to increment their local counter
|
||||||
|
const children = parent.el!.querySelectorAll("span");
|
||||||
|
children[0]!.click();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>0/0</span>");
|
||||||
|
|
||||||
|
children[1]!.click();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>0/0</span>");
|
||||||
|
|
||||||
|
// finalize first re-rendering (coming from the props update)
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>1/1</span>");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,890 @@
|
|||||||
|
import { Portal } from "../../src/misc/portal";
|
||||||
|
import { xml } from "../../src/tags";
|
||||||
|
import { makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||||
|
import { Component } from "../../src/component/component";
|
||||||
|
import { useState } from "../../src/hooks";
|
||||||
|
import { QWeb } from "../../src/qweb";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// 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.
|
||||||
|
// - outside: a div with id #outside appended into fixture, meant to be used as
|
||||||
|
// target by Portal component
|
||||||
|
// - a test env, necessary to create components, that is set on Component
|
||||||
|
|
||||||
|
let fixture: HTMLElement;
|
||||||
|
let outside: HTMLElement;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
outside = document.createElement("div");
|
||||||
|
outside.setAttribute("id", "outside");
|
||||||
|
fixture.appendChild(outside);
|
||||||
|
|
||||||
|
Component.env = makeTestEnv();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Portal: Props validation", () => {
|
||||||
|
test("target is mandatory", async () => {
|
||||||
|
const dev = QWeb.dev;
|
||||||
|
QWeb.dev = true;
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal>
|
||||||
|
<div>2</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'target' (component 'Portal')`);
|
||||||
|
|
||||||
|
QWeb.dev = dev;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("target is not list", async () => {
|
||||||
|
const dev = QWeb.dev;
|
||||||
|
QWeb.dev = true;
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="['body']">
|
||||||
|
<div>2</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Invalid Prop 'target' in component 'Portal'`);
|
||||||
|
|
||||||
|
QWeb.dev = dev;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Portal: Basic use and DOM placement", () => {
|
||||||
|
test("basic use of portal", async () => {
|
||||||
|
const dev = QWeb.dev;
|
||||||
|
QWeb.dev = true;
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span>1</span>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<div>2</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
let error;
|
||||||
|
let parent;
|
||||||
|
try {
|
||||||
|
parent = new Parent();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span><portal></portal></div>");
|
||||||
|
QWeb.dev = dev;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("conditional use of Portal", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span>1</span>
|
||||||
|
<Portal target="'#outside'" t-if="state.hasPortal">
|
||||||
|
<div>2</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
state = useState({ hasPortal: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span><portal></portal></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span><portal></portal></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("conditional use of Portal (with sub Component)", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div><t t-esc="props.val"/></div>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span>1</span>
|
||||||
|
<Portal t-if="state.hasPortal" target="'#outside'">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ hasPortal: false, val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("<div>1</div>");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span><portal></portal></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span></div>");
|
||||||
|
|
||||||
|
parent.state.hasPortal = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("<div>2</div>");
|
||||||
|
expect(parent.el!.outerHTML).toBe("<div><span>1</span><portal></portal></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with target in template (before portal)", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<div id="local-target"></div>
|
||||||
|
<span>1</span>
|
||||||
|
<Portal target="'#local-target'">
|
||||||
|
<p>2</p>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(parent.el!.innerHTML).toBe(
|
||||||
|
'<div id="local-target"><p>2</p></div><span>1</span><portal></portal>'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with target in template (after portal)", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<span>1</span>
|
||||||
|
<Portal target="'#local-target'">
|
||||||
|
<p>2</p>
|
||||||
|
</Portal>
|
||||||
|
<div id="local-target"></div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(parent.el!.innerHTML).toBe(
|
||||||
|
'<span>1</span><portal></portal><div id="local-target"><p>2</p></div>'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with target not in dom", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#does-not-exist'">
|
||||||
|
<div>2</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe('Could not find any match for "#does-not-exist"');
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div id="outside"></div>`);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with child and props", async () => {
|
||||||
|
const steps: string[] = [];
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
|
mounted() {
|
||||||
|
steps.push("mounted");
|
||||||
|
expect(outside.innerHTML).toBe("<span>1</span>");
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
steps.push("patched");
|
||||||
|
expect(outside.innerHTML).toBe("<span>2</span>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("<span>1</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
|
||||||
|
parent.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe("<span>2</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
expect(steps).toEqual(["mounted", "patched"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with only text as content", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<t t-esc="'only text'"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Portal must have exactly one non-text child (has 0)");
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div id="outside"></div>`);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with no content", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<t t-if="false" t-esc="'ABC'"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Portal must have exactly one non-text child (has 0)");
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div id="outside"></div>`);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with many children", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<div>1</div>
|
||||||
|
<p>2</p>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await parent.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Portal must have exactly one non-text child (has 2)");
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
expect(fixture.innerHTML).toBe(`<div id="outside"></div>`);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal with dynamic body", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<span t-if="state.val" t-esc="state.val"/>
|
||||||
|
<div t-else=""/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ val: "ab" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe(`<span>ab</span>`);
|
||||||
|
|
||||||
|
parent.state.val = "";
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe(`<div></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal could have dynamically no content", async () => {
|
||||||
|
const consoleError = console.error;
|
||||||
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<span t-if="state.val" t-esc="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = { val: "ab" };
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe(`<span>ab</span>`);
|
||||||
|
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
parent.state.val = "";
|
||||||
|
await parent.render();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(outside.innerHTML).toBe(``);
|
||||||
|
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Portal must have exactly one non-text child (has 0)");
|
||||||
|
|
||||||
|
expect(console.error).toBeCalledTimes(0);
|
||||||
|
console.error = consoleError;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("lifecycle hooks of portal sub component are properly called", async () => {
|
||||||
|
const steps: any[] = [];
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span t-esc="props.val"/>`;
|
||||||
|
mounted() {
|
||||||
|
steps.push("child:mounted");
|
||||||
|
}
|
||||||
|
willPatch() {
|
||||||
|
steps.push("child:willPatch");
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
steps.push("child:patched");
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("child:willUnmount");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal t-if="state.hasChild" target="'#outside'">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ hasChild: false, val: 1 });
|
||||||
|
mounted() {
|
||||||
|
steps.push("parent:mounted");
|
||||||
|
}
|
||||||
|
willPatch() {
|
||||||
|
steps.push("parent:willPatch");
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
steps.push("parent:patched");
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("parent:willUnmount");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(steps).toEqual(["parent:mounted"]);
|
||||||
|
|
||||||
|
parent.state.hasChild = true;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual([
|
||||||
|
"parent:mounted",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:mounted",
|
||||||
|
"parent:patched",
|
||||||
|
]);
|
||||||
|
|
||||||
|
parent.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual([
|
||||||
|
"parent:mounted",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:mounted",
|
||||||
|
"parent:patched",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:willPatch",
|
||||||
|
"child:patched",
|
||||||
|
"parent:patched",
|
||||||
|
]);
|
||||||
|
|
||||||
|
parent.state.hasChild = false;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual([
|
||||||
|
"parent:mounted",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:mounted",
|
||||||
|
"parent:patched",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:willPatch",
|
||||||
|
"child:patched",
|
||||||
|
"parent:patched",
|
||||||
|
"parent:willPatch",
|
||||||
|
"child:willUnmount",
|
||||||
|
"parent:patched",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal destroys on crash", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span t-esc="props.error and this.will.crash" />`;
|
||||||
|
state = {};
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'" >
|
||||||
|
<Child error="state.error"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = { error: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
parent.state.error = true;
|
||||||
|
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await parent.render();
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal manual unmount", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<span>gloria</span>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe("<span>gloria</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
|
||||||
|
parent.unmount();
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal><span>gloria</span></portal>");
|
||||||
|
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("<span>gloria</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal manual unmount with subcomponent", async () => {
|
||||||
|
expect.assertions(9);
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<span>gloria</span>`;
|
||||||
|
mounted() {
|
||||||
|
expect(outside.contains(this.el)).toBeTruthy();
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
expect(outside.contains(this.el)).toBeTruthy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child />
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe("<span>gloria</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
|
||||||
|
parent.unmount();
|
||||||
|
expect(outside.innerHTML).toBe("");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal><span>gloria</span></portal>");
|
||||||
|
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(outside.innerHTML).toBe("<span>gloria</span>");
|
||||||
|
expect(parent.el!.innerHTML).toBe("<portal></portal>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Portal: Events handling", () => {
|
||||||
|
test("events triggered on movable pure node are handled", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<span id="trigger-me" t-on-custom="_onCustom" t-esc="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ val: "ab" });
|
||||||
|
|
||||||
|
_onCustom() {
|
||||||
|
this.state.val = "triggered";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe(`<span id="trigger-me">ab</span>`);
|
||||||
|
outside.querySelector("#trigger-me")!.dispatchEvent(new Event("custom"));
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe(`<span id="trigger-me">triggered</span>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("events triggered on movable owl components are redirected", async () => {
|
||||||
|
let childInst: Component | null = null;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<span t-on-custom="_onCustom" t-esc="props.val"/>`;
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
childInst = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
_onCustom() {
|
||||||
|
this.trigger("custom-portal");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-custom-portal="_onCustomPortal">
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ val: "ab" });
|
||||||
|
|
||||||
|
_onCustomPortal() {
|
||||||
|
this.state.val = "triggered";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(outside.innerHTML).toBe(`<span>ab</span>`);
|
||||||
|
childInst!.trigger("custom");
|
||||||
|
await nextTick();
|
||||||
|
expect(outside.innerHTML).toBe(`<span>triggered</span>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("events triggered on contained movable owl components are redirected", async () => {
|
||||||
|
const steps: string[] = [];
|
||||||
|
let childInst: Component | null = null;
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<span t-on-custom="_onCustom"/>`;
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
childInst = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
_onCustom() {
|
||||||
|
this.trigger("custom-portal");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-custom="_handled" t-on-custom-portal="_handled">
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<div>
|
||||||
|
<Child/>
|
||||||
|
</div>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
_handled(ev) {
|
||||||
|
steps.push(ev.type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
childInst!.trigger("custom");
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
// This is expected because trigger is synchronous
|
||||||
|
expect(steps).toMatchObject(["custom-portal", "custom"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Dom events are not mapped", async () => {
|
||||||
|
let childInst: Component | null = null;
|
||||||
|
const steps: string[] = [];
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<button>child</button>`;
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
childInst = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-click="_handled">
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child />
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
_handled(ev) {
|
||||||
|
steps.push(ev.type as string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const bodyListener = (ev) => {
|
||||||
|
steps.push(`body: ${ev.type}`);
|
||||||
|
};
|
||||||
|
document.body.addEventListener("click", bodyListener);
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
childInst!.el!.click();
|
||||||
|
|
||||||
|
expect(steps).toEqual(["body: click"]);
|
||||||
|
document.body.removeEventListener("click", bodyListener);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Nested portals event propagation", async () => {
|
||||||
|
const outside2 = document.createElement("div");
|
||||||
|
outside2.setAttribute("id", "outside2");
|
||||||
|
fixture.appendChild(outside2);
|
||||||
|
|
||||||
|
const steps: Array<string> = [];
|
||||||
|
let childInst: Component | null = null;
|
||||||
|
class Child2 extends Component {
|
||||||
|
static template = xml`<div>child2</div>`;
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
childInst = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Child extends Component {
|
||||||
|
static components = { Portal, Child2 };
|
||||||
|
static template = xml`
|
||||||
|
<Portal target="'#outside2'">
|
||||||
|
<Child2 />
|
||||||
|
</Portal>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-custom='_handled'>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
_handled(ev) {
|
||||||
|
steps.push(`${ev.type} from ${ev.originalComponent.constructor.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
childInst!.trigger("custom");
|
||||||
|
expect(steps).toEqual(["custom from Child2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("portal's parent's env is not polluted", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<button>child</button>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child />
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
const parentEnv = Object.assign({}, parent.env);
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(parentEnv).toStrictEqual(parent.env);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Portal composed with t-slot", async () => {
|
||||||
|
const steps: Array<string> = [];
|
||||||
|
let childInst: Component | null = null;
|
||||||
|
class Child2 extends Component {
|
||||||
|
static template = xml`<div>child2</div>`;
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
childInst = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Child extends Component {
|
||||||
|
static components = { Portal, Child2 };
|
||||||
|
static template = xml`
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<t t-slot="default"/>
|
||||||
|
</Portal>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child, Child2 };
|
||||||
|
static template = xml`
|
||||||
|
<div t-on-custom='_handled'>
|
||||||
|
<Child>
|
||||||
|
<Child2/>
|
||||||
|
</Child>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
_handled(ev) {
|
||||||
|
steps.push(ev.type as string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
childInst!.trigger("custom");
|
||||||
|
expect(steps).toEqual(["custom"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Portal: UI/UX", () => {
|
||||||
|
test("focus is kept across re-renders", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<input id="target-me" t-att-placeholder="props.val"/>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Portal, Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Portal target="'#outside'">
|
||||||
|
<Child val="state.val"/>
|
||||||
|
</Portal>
|
||||||
|
</div>`;
|
||||||
|
state = useState({ val: "ab" });
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
const input = document.querySelector("#target-me");
|
||||||
|
expect(input!.nodeName).toBe("INPUT");
|
||||||
|
expect((input as HTMLInputElement).placeholder).toBe("ab");
|
||||||
|
|
||||||
|
(input as HTMLInputElement).focus();
|
||||||
|
expect(document.activeElement === input).toBeTruthy();
|
||||||
|
|
||||||
|
parent.state.val = "bc";
|
||||||
|
await nextTick();
|
||||||
|
const inputReRendered = document.querySelector("#target-me");
|
||||||
|
expect(inputReRendered!.nodeName).toBe("INPUT");
|
||||||
|
expect((inputReRendered as HTMLInputElement).placeholder).toBe("bc");
|
||||||
|
expect(document.activeElement === inputReRendered).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
+3033
-1143
File diff suppressed because it is too large
Load Diff
+837
-48
File diff suppressed because it is too large
Load Diff
@@ -6,12 +6,12 @@ describe("tokenizer", () => {
|
|||||||
|
|
||||||
expect(tokenize("{}")).toEqual([
|
expect(tokenize("{}")).toEqual([
|
||||||
{ type: "LEFT_BRACE", value: "{" },
|
{ type: "LEFT_BRACE", value: "{" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("{ }}")).toEqual([
|
expect(tokenize("{ }}")).toEqual([
|
||||||
{ type: "LEFT_BRACE", value: "{" },
|
{ type: "LEFT_BRACE", value: "{" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" },
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("a")).toEqual([{ type: "SYMBOL", value: "a" }]);
|
expect(tokenize("a")).toEqual([{ type: "SYMBOL", value: "a" }]);
|
||||||
expect(tokenize("true")).toEqual([{ type: "SYMBOL", value: "true" }]);
|
expect(tokenize("true")).toEqual([{ type: "SYMBOL", value: "true" }]);
|
||||||
@@ -25,12 +25,15 @@ describe("tokenizer", () => {
|
|||||||
{ type: "SYMBOL", value: "a" },
|
{ type: "SYMBOL", value: "a" },
|
||||||
{ type: "COLON", value: ":" },
|
{ type: "COLON", value: ":" },
|
||||||
{ type: "VALUE", value: "2" },
|
{ type: "VALUE", value: "2" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
|
]);
|
||||||
|
expect(tokenize("a,")).toEqual([
|
||||||
|
{ type: "SYMBOL", value: "a" },
|
||||||
|
{ type: "COMMA", value: "," },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("a,")).toEqual([{ type: "SYMBOL", value: "a" }, { type: "COMMA", value: "," }]);
|
|
||||||
expect(tokenize("][")).toEqual([
|
expect(tokenize("][")).toEqual([
|
||||||
{ type: "RIGHT_BRACKET", value: "]" },
|
{ type: "RIGHT_BRACKET", value: "]" },
|
||||||
{ type: "LEFT_BRACKET", value: "[" }
|
{ type: "LEFT_BRACKET", value: "[" },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,7 +44,23 @@ describe("tokenizer", () => {
|
|||||||
{ type: "OPERATOR", value: "<" },
|
{ type: "OPERATOR", value: "<" },
|
||||||
{ type: "OPERATOR", value: ">" },
|
{ type: "OPERATOR", value: ">" },
|
||||||
{ type: "OPERATOR", value: "!==" },
|
{ type: "OPERATOR", value: "!==" },
|
||||||
{ type: "OPERATOR", value: "!=" }
|
{ type: "OPERATOR", value: "!=" },
|
||||||
|
]);
|
||||||
|
expect(tokenize("typeof a")).toEqual([
|
||||||
|
{ type: "OPERATOR", value: "typeof " },
|
||||||
|
{ type: "SYMBOL", value: "a" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(tokenize("a...1")).toEqual([
|
||||||
|
{ type: "SYMBOL", value: "a" },
|
||||||
|
{ type: "OPERATOR", value: "..." },
|
||||||
|
{ type: "VALUE", value: "1" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(tokenize("a in b")).toEqual([
|
||||||
|
{ type: "SYMBOL", value: "a" },
|
||||||
|
{ type: "OPERATOR", value: "in " },
|
||||||
|
{ type: "SYMBOL", value: "b" },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -57,7 +76,7 @@ describe("tokenizer", () => {
|
|||||||
expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]);
|
expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]);
|
||||||
expect(tokenize('"hello ged"}')).toEqual([
|
expect(tokenize('"hello ged"}')).toEqual([
|
||||||
{ type: "VALUE", value: '"hello ged"' },
|
{ type: "VALUE", value: '"hello ged"' },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize('"hello \\"ged\\""')).toEqual([{ type: "VALUE", value: '"hello \\"ged\\""' }]);
|
expect(tokenize('"hello \\"ged\\""')).toEqual([{ type: "VALUE", value: '"hello \\"ged\\""' }]);
|
||||||
});
|
});
|
||||||
@@ -85,7 +104,7 @@ describe("expression evaluation", () => {
|
|||||||
|
|
||||||
test("parenthesis", () => {
|
test("parenthesis", () => {
|
||||||
expect(compileExpr("(1)", {})).toBe("(1)");
|
expect(compileExpr("(1)", {})).toBe("(1)");
|
||||||
expect(compileExpr("a*(1 +3)", {})).toBe("context['a']*(1+3)");
|
expect(compileExpr("a*(1 +3)", {})).toBe("scope['a']*(1+3)");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("objects and sub objects", () => {
|
test("objects and sub objects", () => {
|
||||||
@@ -93,8 +112,8 @@ describe("expression evaluation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("replacing variables", () => {
|
test("replacing variables", () => {
|
||||||
expect(compileExpr("a", {})).toBe("context['a']");
|
expect(compileExpr("a", {})).toBe("scope['a']");
|
||||||
expect(compileExpr("a", { a: { id: "_3", expr: "" } })).toBe("_3");
|
expect(compileExpr("a", { a: { id: "_3", expr: "scope._3" } })).toBe("scope._3");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("arrays and objects", () => {
|
test("arrays and objects", () => {
|
||||||
@@ -104,55 +123,77 @@ describe("expression evaluation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("dot operator", () => {
|
test("dot operator", () => {
|
||||||
expect(compileExpr("a.b", {})).toBe("context['a'].b");
|
expect(compileExpr("a.b", {})).toBe("scope['a'].b");
|
||||||
expect(compileExpr("a.b.c", {})).toBe("context['a'].b.c");
|
expect(compileExpr("a.b.c", {})).toBe("scope['a'].b.c");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("various unary operators", () => {
|
test("various unary operators", () => {
|
||||||
expect(compileExpr("!flag", {})).toBe("!context['flag']");
|
expect(compileExpr("!flag", {})).toBe("!scope['flag']");
|
||||||
expect(compileExpr("-3", {})).toBe("-3");
|
expect(compileExpr("-3", {})).toBe("-3");
|
||||||
expect(compileExpr("-a", {})).toBe("-context['a']");
|
expect(compileExpr("-a", {})).toBe("-scope['a']");
|
||||||
|
expect(compileExpr("typeof a", {})).toBe("typeof scope['a']");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("various binary operators", () => {
|
test("various binary operators", () => {
|
||||||
expect(compileExpr("color == 'black'", {})).toBe("context['color']=='black'");
|
expect(compileExpr("color == 'black'", {})).toBe("scope['color']=='black'");
|
||||||
expect(compileExpr("a || b", {})).toBe("context['a']||context['b']");
|
expect(compileExpr("a || b", {})).toBe("scope['a']||scope['b']");
|
||||||
expect(compileExpr("color === 'black'", {})).toBe("context['color']==='black'");
|
expect(compileExpr("color === 'black'", {})).toBe("scope['color']==='black'");
|
||||||
expect(compileExpr("'li_'+item", {})).toBe("'li_'+context['item']");
|
expect(compileExpr("'li_'+item", {})).toBe("'li_'+scope['item']");
|
||||||
expect(compileExpr("state.val > 1", {})).toBe("context['state'].val>1");
|
expect(compileExpr("state.val > 1", {})).toBe("scope['state'].val>1");
|
||||||
|
expect(compileExpr("a in b", {})).toBe("scope['a']in scope['b']");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("boolean operations", () => {
|
test("boolean operations", () => {
|
||||||
expect(compileExpr("a && b", {})).toBe("context['a']&&context['b']");
|
expect(compileExpr("a && b", {})).toBe("scope['a']&&scope['b']");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("ternary operators", () => {
|
test("ternary operators", () => {
|
||||||
expect(compileExpr("a ? b: '2'", {})).toBe("context['a']?context['b']:'2'");
|
expect(compileExpr("a ? b: '2'", {})).toBe("scope['a']?scope['b']:'2'");
|
||||||
expect(compileExpr("a ? b: (c or '2') ", {})).toBe(
|
expect(compileExpr("a ? b: (c or '2') ", {})).toBe("scope['a']?scope['b']:(scope['c']||'2')");
|
||||||
"context['a']?context['b']:(context['c']||'2')"
|
|
||||||
);
|
|
||||||
expect(compileExpr("a ? {test:c}: [1,u]", {})).toBe(
|
expect(compileExpr("a ? {test:c}: [1,u]", {})).toBe(
|
||||||
"context['a']?{test:context['c']}:[1,context['u']]"
|
"scope['a']?{test:scope['c']}:[1,scope['u']]"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("word replacement", () => {
|
test("word replacement", () => {
|
||||||
expect(compileExpr("a or b", {})).toBe("context['a']||context['b']");
|
expect(compileExpr("a or b", {})).toBe("scope['a']||scope['b']");
|
||||||
expect(compileExpr("a and b", {})).toBe("context['a']&&context['b']");
|
expect(compileExpr("a and b", {})).toBe("scope['a']&&scope['b']");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("function calls", () => {
|
test("function calls", () => {
|
||||||
expect(compileExpr("a()", {})).toBe("context['a']()");
|
expect(compileExpr("a()", {})).toBe("scope['a']()");
|
||||||
expect(compileExpr("a(1)", {})).toBe("context['a'](1)");
|
expect(compileExpr("a(1)", {})).toBe("scope['a'](1)");
|
||||||
expect(compileExpr("a(1,2)", {})).toBe("context['a'](1,2)");
|
expect(compileExpr("a(1,2)", {})).toBe("scope['a'](1,2)");
|
||||||
expect(compileExpr("a(1,2,{a:[a]})", {})).toBe("context['a'](1,2,{a:[context['a']]})");
|
expect(compileExpr("a(1,2,{a:[a]})", {})).toBe("scope['a'](1,2,{a:[scope['a']]})");
|
||||||
expect(compileExpr("'x'.toUpperCase()", {})).toBe("'x'.toUpperCase()");
|
expect(compileExpr("'x'.toUpperCase()", {})).toBe("'x'.toUpperCase()");
|
||||||
expect(compileExpr("'x'.toUpperCase({a: 3})", {})).toBe("'x'.toUpperCase({a:3})");
|
expect(compileExpr("'x'.toUpperCase({a: 3})", {})).toBe("'x'.toUpperCase({a:3})");
|
||||||
expect(compileExpr("'x'.toUpperCase(a)", { a: { id: "_v5", expr: "" } })).toBe(
|
expect(compileExpr("'x'.toUpperCase(a)", { a: { id: "_v5", expr: "scope._v5" } })).toBe(
|
||||||
"'x'.toUpperCase(_v5)"
|
"'x'.toUpperCase(scope._v5)"
|
||||||
);
|
);
|
||||||
expect(compileExpr("'x'.toUpperCase({b: a})", { a: { id: "_v5", expr: "" } })).toBe(
|
expect(compileExpr("'x'.toUpperCase({b: a})", { a: { id: "_v5", expr: "scope._v5" } })).toBe(
|
||||||
"'x'.toUpperCase({b:_v5})"
|
"'x'.toUpperCase({b:scope._v5})"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("arrow functions", () => {
|
||||||
|
expect(compileExpr("list.map(e => e.val)", {})).toBe("scope['list'].map(e=>e.val)");
|
||||||
|
expect(compileExpr("list.map(e => a + e)", {})).toBe("scope['list'].map(e=>scope['a']+e)");
|
||||||
|
expect(compileExpr("list.map((e) => e)", {})).toBe("scope['list'].map((e)=>e)");
|
||||||
|
expect(compileExpr("list.map((elem, index) => elem + index)", {})).toBe(
|
||||||
|
"scope['list'].map((elem,index)=>elem+index)"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("assignation", () => {
|
||||||
|
expect(compileExpr("a = b", {})).toBe("scope['a']=scope['b']");
|
||||||
|
expect(compileExpr("a += b", {})).toBe("scope['a']+=scope['b']");
|
||||||
|
expect(compileExpr("a -= b", {})).toBe("scope['a']-=scope['b']");
|
||||||
|
expect(compileExpr("a.b = !a.b", {})).toBe("scope['a'].b=!scope['a'].b");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("spread operator", () => {
|
||||||
|
expect(compileExpr("[...state.list]", {})).toBe("[...scope['state'].list]");
|
||||||
|
expect(compileExpr("f(...state.list)", {})).toBe("scope['f'](...scope['state'].list)");
|
||||||
|
expect(compileExpr("f([...list])", {})).toBe("scope['f']([...scope['list']])");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,24 +1,22 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
exports[`Link component can render simple cases 1`] = `
|
exports[`Link component can render simple cases 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let owner = context;
|
let scope = Object.create(context);
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
let _1 = utils.toObj({'router-link-active':context['isActive']});
|
let _4 = utils.toObj({'router-link-active':scope['isActive']});
|
||||||
var _2 = context['href'];
|
let _5 = scope['href'];
|
||||||
let c3 = [], p3 = {key:3,attrs:{href: _2},class:_1,on:{}};
|
let c6 = [], p6 = {key:6,attrs:{href: _5},class:_4,on:{}};
|
||||||
var vn3 = h('a', p3, c3);
|
let vn6 = h('a', p6, c6);
|
||||||
if (!context['navigate']) {
|
extra.handlers['click__7__'] = extra.handlers['click__7__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['navigate'](e);};
|
||||||
throw new Error('Missing handler \\\\'' + 'navigate' + \`\\\\' when evaluating template '__template__1'\`)
|
p6.on['click'] = extra.handlers['click__7__'];
|
||||||
|
const slot8 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot8) {
|
||||||
|
slot8.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c6, parent: extra.parent || context}));
|
||||||
}
|
}
|
||||||
extra.handlers['click' + 3] = extra.handlers['click' + 3] || context['navigate'].bind(owner);
|
return vn6;
|
||||||
p3.on['click'] = extra.handlers['click' + 3];
|
|
||||||
const slot4 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
|
||||||
if (slot4) {
|
|
||||||
slot4.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c3, vars: extra.vars, parent: owner}));
|
|
||||||
}
|
|
||||||
return vn3;
|
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|||||||
@@ -1,44 +1,45 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
exports[`RouteComponent can render simple cases 1`] = `
|
exports[`RouteComponent can render simple cases 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let QWeb = this.constructor;
|
let QWeb = this.constructor;
|
||||||
let parent = context;
|
let parent = context;
|
||||||
let owner = context;
|
let scope = Object.create(context);
|
||||||
let result;
|
let result;
|
||||||
var h = this.h;
|
let h = this.h;
|
||||||
if (context['routeComponent']) {
|
if (scope['routeComponent']) {
|
||||||
//COMPONENT
|
{
|
||||||
let key4 = 'key' + context['env'].router.currentRouteName;
|
let key0 = scope['env'].router.currentRouteName;
|
||||||
let def2;
|
// Component 'routeComponent'
|
||||||
let templateId5 = key4;
|
let k5 = \`__5__\${key0}__\`;
|
||||||
let w3 = templateId5 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId5]] : false;
|
let w4 = k5 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k5]] : false;
|
||||||
let vn6 = {};
|
let vn6 = {};
|
||||||
result = vn6;
|
result = vn6;
|
||||||
let props3 = Object.assign({}, context['env'].router.currentParams);
|
let props4 = Object.assign({}, scope['env'].router.currentParams);
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
||||||
if (utils.shallowEqual(props3, w3.__owl__.currentFiber.props)) {
|
w4.destroy();
|
||||||
def2 = w3.__owl__.currentFiber.promise;
|
w4 = false;
|
||||||
} else {
|
|
||||||
w3.destroy();
|
|
||||||
w3 = false;
|
|
||||||
}
|
}
|
||||||
|
if (w4) {
|
||||||
|
w4.__updateProps(props4, extra.fiber, undefined);
|
||||||
|
let pvnode = w4.__owl__.pvnode;
|
||||||
|
utils.defineProxy(vn6, pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey4 = \`routeComponent\`;
|
||||||
|
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| scope['routeComponent'];
|
||||||
|
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||||
|
w4 = new W4(parent, props4);
|
||||||
|
parent.__owl__.cmap[k5] = w4.__owl__.id;
|
||||||
|
let fiber = w4.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k5, hook: {remove() {},destroy(vn) {w4.destroy();}}});
|
||||||
|
utils.defineProxy(vn6, pvnode);
|
||||||
|
w4.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w4.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
}
|
}
|
||||||
if (!w3) {
|
|
||||||
let componentKey3 = \`routeComponent\`;
|
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['routeComponent'];
|
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
|
||||||
w3 = new W3(parent, props3);
|
|
||||||
parent.__owl__.cmap[templateId5] = w3.__owl__.id;
|
|
||||||
def2 = w3.__prepare(extra.fiber, undefined, undefined);
|
|
||||||
def2 = def2.then(vnode=>{if (w3.__owl__.isDestroyed){return}let pvnode=h(vnode.sel, {key: templateId5, hook: {insert(vn) {let nvn=w3.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});utils.defineProxy(vn6, pvnode);w3.__owl__.pvnode = pvnode;});
|
|
||||||
} else {
|
|
||||||
def2 = def2 || w3.__updateProps(props3, extra.fiber, undefined, undefined);
|
|
||||||
def2 = def2.then(()=>{if (w3.__owl__.isDestroyed) {return};let pvnode=w3.__owl__.pvnode;utils.defineProxy(vn6, pvnode);});
|
|
||||||
}
|
|
||||||
extra.promises.push(def2);
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}"
|
}"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ describe("Link component", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = <RouterEnv>makeTestEnv();
|
env = <RouterEnv>makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -30,15 +31,18 @@ describe("Link component", () => {
|
|||||||
</div>
|
</div>
|
||||||
</templates>
|
</templates>
|
||||||
`);
|
`);
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { Link: Link };
|
static components = { Link: Link };
|
||||||
}
|
}
|
||||||
|
|
||||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
const routes = [
|
||||||
|
{ name: "about", path: "/about" },
|
||||||
|
{ name: "users", path: "/users" },
|
||||||
|
];
|
||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
router.navigate({ to: "users" });
|
router.navigate({ to: "users" });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe('<div><a href="/about">About</a></div>');
|
expect(fixture.innerHTML).toBe('<div><a href="/about">About</a></div>');
|
||||||
|
|
||||||
@@ -61,20 +65,23 @@ describe("Link component", () => {
|
|||||||
</div>
|
</div>
|
||||||
</templates>
|
</templates>
|
||||||
`);
|
`);
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { Link: Link };
|
static components = { Link: Link };
|
||||||
}
|
}
|
||||||
|
|
||||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
const routes = [
|
||||||
|
{ name: "about", path: "/about" },
|
||||||
|
{ name: "users", path: "/users" },
|
||||||
|
];
|
||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
router.navigate({ to: "users" });
|
router.navigate({ to: "users" });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
|
|
||||||
expect(window.location.pathname).toBe("/users");
|
expect(window.location.pathname).toBe("/users");
|
||||||
var evt = new MouseEvent("click", {
|
var evt = new MouseEvent("click", {
|
||||||
button: 1
|
button: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
fixture.querySelector("a")!.dispatchEvent(evt);
|
fixture.querySelector("a")!.dispatchEvent(evt);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user