mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
473 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 9e65b0686f | |||
| 1d72164015 | |||
| 2825a5a55d | |||
| d40ff53f5a | |||
| 23246c42aa | |||
| 895fe7c60f | |||
| 19b10f7c1d | |||
| 0788d9fe75 | |||
| 4a346d0615 | |||
| 1337aa0107 | |||
| 3e8f60cefa | |||
| 41b0618c93 | |||
| 0928c189f4 | |||
| 2f27768be2 | |||
| aa1b0f502d | |||
| da1824f4dd | |||
| 07dac970f7 | |||
| 5f6f081ae2 | |||
| 1c3c2e5c51 | |||
| 17ce73e6a9 | |||
| cedb1f411f | |||
| e7516be95c | |||
| 683993dbc4 | |||
| 50d569411c | |||
| c3453d35b9 | |||
| b0dd0252a4 | |||
| e2b2e54e29 | |||
| 766c378ac9 | |||
| 022b29b6a0 | |||
| 367725d194 | |||
| e82ed7dc8c | |||
| 63c3d4f6b0 | |||
| b859fcb8f0 | |||
| 3005756d89 | |||
| f6820bb8ac | |||
| 090880f478 | |||
| 5cdaa7b473 | |||
| 91b9e78182 | |||
| 5335fb8fba | |||
| 4513e3f31c | |||
| ecf12f6eee | |||
| 82a6961b3a | |||
| 78a4550ebb | |||
| cc82b3ffcd | |||
| bbbaf95c8e | |||
| caa63628dc | |||
| 7a49b9d94e | |||
| 01eb338e69 | |||
| 3048c6f961 | |||
| 8edc637033 | |||
| c9910077a4 | |||
| 6bf70f016c | |||
| 905619f80f | |||
| 14ceb382ef | |||
| 9846b2e997 | |||
| cfc2fb2ba2 | |||
| d57017b6ed | |||
| 5bf7a5c671 | |||
| 9b589af75a | |||
| 471fd49063 | |||
| 4fc3423682 | |||
| ffb3263c79 | |||
| e1acf66143 | |||
| 2a40907e35 | |||
| 1c0dd79955 | |||
| 9fad164c79 | |||
| 53a8841914 | |||
| 19f0863aa3 | |||
| 28f7b44f9e | |||
| fe46a6ccee | |||
| 3c23a7b246 | |||
| c52799de2c | |||
| 4edb90f44b | |||
| 0c1a7aabae | |||
| cfdce29ce7 | |||
| b344d73e07 | |||
| 4cd08d25c8 | |||
| f9861040c8 | |||
| 40d8090232 | |||
| 55be6437f1 | |||
| 6ff4dd74bf | |||
| 3628b49c37 | |||
| f289cb17ec | |||
| e6a3ede4a6 | |||
| 10cfe0b740 | |||
| a3d563ebb4 | |||
| 3b1247d476 | |||
| beb6c2bc82 | |||
| f0cd6f61cd | |||
| c950b385a0 | |||
| c172b31481 | |||
| 9b3a97e732 | |||
| 670c98916c | |||
| c59abef374 | |||
| bb4c2506c0 | |||
| 9843d16585 | |||
| 34e463ad0a | |||
| 2294c1967f | |||
| 4b53e48e91 | |||
| 70a70161e7 | |||
| e690991a6a | |||
| a621a14028 | |||
| 9754cc7521 | |||
| aa268937a7 | |||
| 3db6f0a643 | |||
| 635a7fc72c | |||
| 6cd5ec10f0 | |||
| 0a276fbf1d | |||
| d593131cc1 | |||
| 3c3dcb44a9 | |||
| 6ecd1d6ea2 | |||
| 1a931a2a08 | |||
| bf705fcd99 | |||
| bb46346767 | |||
| cd0762b436 | |||
| ca920a0091 | |||
| e5b1ba24d8 | |||
| eaf912bed7 | |||
| fd0fb5be00 | |||
| f9f730ab7b | |||
| b30b72fc36 | |||
| ab08e84bff | |||
| cd9cac1246 | |||
| f6369f9750 | |||
| f18c73e59f | |||
| 93d0a7dd46 | |||
| b1d022b583 | |||
| 5382e824b1 | |||
| 15a3f59744 | |||
| 4a90ec7ff0 | |||
| 9f9b6b174e | |||
| 545ceefc3d | |||
| 591508e769 | |||
| d9cbd23cd9 | |||
| f4cd111cc8 | |||
| ea015af741 | |||
| bfc7c81c0d | |||
| e24ff8f8aa | |||
| 9f1e64d399 | |||
| 8e1aa71436 | |||
| be2fc965b1 | |||
| 7245ccf8f9 | |||
| 1c8e1af86d | |||
| 60a6cca960 | |||
| ad55b42ccb | |||
| 50c0a4b126 | |||
| 2ca42e7470 | |||
| d381e85d94 | |||
| af7520d869 | |||
| 0095bfa61f | |||
| 1b12cf9b91 | |||
| dbfc7e4acd | |||
| e838e879c0 | |||
| ee63f6bb0f | |||
| 16bbb8bc9f | |||
| 4a5db0c283 | |||
| cc50a2e3bb | |||
| 1e2b204fdd | |||
| 4a889b7b6b | |||
| 34695883c2 | |||
| 3d2e2a1873 | |||
| af6aca83a2 | |||
| 8c8ffb6a6b | |||
| 63a8fcd7e2 | |||
| e6a5934162 | |||
| 5524c2e323 | |||
| 35c1de26b8 | |||
| d1cf6b1b8d | |||
| bfa2c681cd | |||
| 609c108607 | |||
| a56939f13a | |||
| 5ff501f8b8 | |||
| 60917bb102 | |||
| b201ef8162 | |||
| 9cacc78ad7 | |||
| 0d933b8570 | |||
| 72f6daa695 | |||
| 567d78a9ac | |||
| f013c57050 | |||
| b9fae87273 | |||
| 1f0457f69b | |||
| c481a73a76 | |||
| e64e415b3b | |||
| aa406b53e2 | |||
| 57027bd0fa | |||
| 671c662fee | |||
| 0ae70b1d63 | |||
| 2701a7d861 | |||
| 3ebe985c3c | |||
| 1c0d4b5832 | |||
| 2840794fa2 | |||
| 710f42d4e4 | |||
| 45a2b0122d | |||
| 4c41f62364 | |||
| c2ab9774fb | |||
| 22e48e3be0 | |||
| 1ff3c32fe4 | |||
| 9a3e1ed99e | |||
| 438e2fbc2e | |||
| b3db085745 | |||
| b948c59c6d | |||
| 6426fe98f9 | |||
| 4dd9de349e | |||
| e1bcea77b5 | |||
| 2a19aeb6a3 | |||
| b53a34b7d1 | |||
| f881640d3d | |||
| 54c3dd76e4 | |||
| 7b887447da | |||
| 438b21df3f | |||
| d1094f647a | |||
| 49baf0de6e | |||
| b14d069ee7 | |||
| e14a4fe338 | |||
| 1f9ec46236 | |||
| 1464a3631b | |||
| 7d3c374b78 | |||
| 1dd257f33c | |||
| 1206afe6be | |||
| 5842ed51b0 | |||
| d22219f084 | |||
| 0be1a54e03 | |||
| 32921ecc20 | |||
| 1c290c1172 | |||
| 2f9d7ea58f | |||
| fe23e76341 | |||
| 73023d4869 | |||
| ff51443b8e | |||
| f8e07f6d30 | |||
| 00da778753 | |||
| 187eb922c0 | |||
| 466c12a0e6 | |||
| 8dc3ec94bf | |||
| a554436d03 | |||
| 34b5049dee | |||
| 0eccfd08fe | |||
| 98b063fd70 | |||
| e9ba94ae55 | |||
| 4d72a4f240 | |||
| a08deb895d | |||
| 60cea14b01 |
+9
-1
@@ -1,5 +1,6 @@
|
||||
/node_modules
|
||||
/dist
|
||||
|
||||
npm-debug.log
|
||||
|
||||
# misc
|
||||
@@ -14,8 +15,15 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
|
||||
#ide's
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
node_modules
|
||||
|
||||
# Extras temp file
|
||||
/extras/owl.js
|
||||
/tools/owl.js
|
||||
|
||||
release-notes.md
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
Most of the files are
|
||||
|
||||
Copyright (c) 2004-2015 Odoo S.A.
|
||||
|
||||
Many files also contain contributions from third
|
||||
parties. In this case the original copyright of
|
||||
the contributions can be traced through the
|
||||
history of the source version control system.
|
||||
|
||||
When that is not the case, the files contain a prominent
|
||||
notice stating the original copyright and applicable
|
||||
license, or come with their own dedicated COPYRIGHT
|
||||
and/or LICENSE file.
|
||||
@@ -1,19 +1,83 @@
|
||||
<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 web framework for structured, dynamic and maintainable applications_
|
||||
_Class based components with hooks, reactive state and concurrent mode_
|
||||
|
||||
## Project Overview
|
||||
|
||||
The Odoo Web Library (OWL) is a small
|
||||
UI framework intended to be the basis for the [Odoo](https://www.odoo.com/) Web Client, and hopefully many
|
||||
other Odoo related projects. OWL's main feature is a _declarative component system_, with QWeb as a template engine, asynchronous rendering, and an underlying virtual dom.
|
||||
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
|
||||
framework, written in Typescript, taking the best ideas from React and Vue in a
|
||||
simple and consistent way. Owl's main features are:
|
||||
|
||||
**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.
|
||||
- a declarative component system,
|
||||
- a reactivity system based on hooks,
|
||||
- concurrent mode by default,
|
||||
- a store and a frontend router
|
||||
|
||||
## OWL's design principles
|
||||
Owl components are defined with ES6 classes, they use QWeb templates, an
|
||||
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 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
|
||||
|
||||
Here is a short example to illustrate interactive components:
|
||||
|
||||
```javascript
|
||||
const { Component, useState } = owl;
|
||||
const { xml } = owl.tags;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-on-click="state.value++">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
state = useState({ value: 0 });
|
||||
}
|
||||
|
||||
class App extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span>Hello Owl</span>
|
||||
<Counter />
|
||||
</div>`;
|
||||
|
||||
static components = { Counter };
|
||||
}
|
||||
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
|
||||
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.
|
||||
|
||||
More interesting examples can be found on the
|
||||
[playground](https://odoo.github.io/owl/playground) application.
|
||||
|
||||
## Design Principles
|
||||
|
||||
OWL is designed to be used in highly dynamic applications where changing
|
||||
requirements are common, code needs to be maintained by large teams.
|
||||
requirements are common and code needs to be maintained by large teams.
|
||||
|
||||
- **XML based**: templates are based on the XML format, which allows interesting
|
||||
applications. For example, they could be stored in a database and modified
|
||||
@@ -26,62 +90,40 @@ requirements are common, code needs to be maintained by large teams.
|
||||
for various reasons (security/deployment/dynamic modules/specific assets tools),
|
||||
it is not ok to use standard web tools based on `npm`.
|
||||
|
||||
Owl is not designed to be fast or small (even though it is quite good on those
|
||||
two topics). If you are interested in a comparison with React or Vue, you will
|
||||
find some more information [here](doc/comparison.md).
|
||||
Owl is not designed to be fast nor small (even though it is quite good on those
|
||||
two topics). It is a no nonsense framework to build applications. There is only
|
||||
one way to define components (with classes). There is no black magic. It just
|
||||
works.
|
||||
|
||||
# Example
|
||||
|
||||
Here is a short example to illustrate interactive widgets:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
|
||||
const TEMPLATES = `
|
||||
<button t-name="ClickCounter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const counter = new ClickCounter({ qweb });
|
||||
counter.mount(document.body);
|
||||
```
|
||||
|
||||
More interesting examples can be found on the [playground](https://odoo.github.io/owl/playground) application.
|
||||
|
||||
## Installing/Building
|
||||
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
- [owl-0.12.0.js](https://github.com/odoo/owl/releases/download/v0.12.0/owl.js)
|
||||
- [owl-0.12.0.min.js](https://github.com/odoo/owl/releases/download/v0.12.0/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 tests |
|
||||
| `npm run test:watch` | run all tests, and keep a watcher |
|
||||
| `npm run extras` | build extras applications, start a static server (see [here](extras/readme.md)) |
|
||||
| `npm run extras:watch` | same as `extras`, but with a watcher to rebuild owl |
|
||||
|
||||
## Documentation
|
||||
|
||||
The complete documentation can be found [here](doc/readme.md). The most important sections are:
|
||||
A complete documentation for Owl can be found here:
|
||||
|
||||
- [Quick Start](doc/quick_start.md)
|
||||
- [Component](doc/component.md)
|
||||
- [QWeb](doc/qweb.md)
|
||||
- [Main documentation page](doc/readme.md).
|
||||
|
||||
Some of the most important pages are:
|
||||
|
||||
- [Tutorial: TodoList application](doc/learning/tutorial_todoapp.md)
|
||||
- [How to start an Owl project](doc/learning/quick_start.md)
|
||||
- [QWeb templating language](doc/reference/qweb_templating_language.md)
|
||||
- [Component](doc/reference/component.md)
|
||||
- [Hooks](doc/reference/hooks.md)
|
||||
|
||||
|
||||
## 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:
|
||||
|
||||
- [owl-1.0.8.js](https://github.com/odoo/owl/releases/download/v1.0.8/owl.js)
|
||||
- [owl-1.0.8.min.js](https://github.com/odoo/owl/releases/download/v1.0.8/owl.min.js)
|
||||
|
||||
## License
|
||||
|
||||
OWL is [GPL licensed](./LICENSE).
|
||||
OWL is [LGPL licensed](./LICENSE).
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
# 🦉 Animations 🦉
|
||||
|
||||
|
||||
Animation is a complex topic. There are many different use cases, and many
|
||||
solutions and technologies. Owl only supports some basic use cases.
|
||||
|
||||
## Simple CSS effects
|
||||
|
||||
Sometimes, using pure CSS is enough. For these use cases, Owl is not really
|
||||
necessary: it just needs to render a DOM element with a specific class. For
|
||||
example:
|
||||
|
||||
|
||||
```xml
|
||||
<a class="btn flash" t-on-click="doSomething">Click</a>
|
||||
```
|
||||
|
||||
with the following CSS:
|
||||
|
||||
```css
|
||||
btn {
|
||||
background-color: gray;
|
||||
}
|
||||
|
||||
.flash {
|
||||
transition: background 0.5s;
|
||||
}
|
||||
|
||||
.flash:active {
|
||||
background-color: #41454a;
|
||||
transition: background 0s;
|
||||
}
|
||||
```
|
||||
|
||||
will produce a nice flash effect whenever the user click (or activate with the
|
||||
keyboard) the button.
|
||||
|
||||
## CSS Transitions (single element)
|
||||
|
||||
A more complex situation occurs when we want to transition an element in or out
|
||||
of the page. For example, we may want a fade-in and fade-out effect.
|
||||
|
||||
The `t-transition` directive is here to help us (see [QWeb documentation](qweb.md#t-transition-directive)).
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
# Comparison with Vue/React
|
||||
|
||||
OWL, React and Vue have the same main feature: they allow developers to build
|
||||
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
||||
|
||||
In this page, we try to highlight some of these differences. Obviously, some
|
||||
effort was done to be fair. However, if you disagree with some of the points
|
||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||
|
||||
- [Size](#size)
|
||||
- [Tooling/Build Step](#toolingbuild-step)
|
||||
- [Templating](#templating)
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
- [Reactiveness](#reactiveness)
|
||||
- [State Management](#state-management)
|
||||
|
||||
### Size
|
||||
|
||||
OWL is intended to be small and to work at a slightly lower level of abstraction
|
||||
than React and Vue. Also, jQuery is not the same kind of framework, but it is interesting to compare.
|
||||
|
||||
| Framework | Size (minified) | Size (minified, gzipped) |
|
||||
| ------------------------ | --------------- | ------------------------ |
|
||||
| OWL | 32kb | 11kb |
|
||||
| Vue + VueX | | 30kb |
|
||||
| React + ReactDOM + Redux | | 40kb |
|
||||
| jQuery | 86kb | 30kb |
|
||||
|
||||
### Tooling/Build step
|
||||
|
||||
OWL is designed to be easy to use in a standalone way. For various reasons,
|
||||
Odoo does not want to rely on standard web tools (such as webpack), and OWL can
|
||||
be used by simply adding a script tag to a page.
|
||||
|
||||
```html
|
||||
<script src="owl.min.js" />
|
||||
```
|
||||
|
||||
In comparison, React encourages using JSX,
|
||||
which necessitate a build step, and most Vue applications uses single file
|
||||
components, which also necessitate a build step.
|
||||
|
||||
On the flipside, external tooling may make it harder to use in some case, but it
|
||||
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
||||
|
||||
### Templating
|
||||
|
||||
OWL uses its own QWeb engine, which compiles templates on the
|
||||
frontend, as they are needed. This is extremely convenient for our use case, in
|
||||
particular because templates are described in XML files, and can be modified by
|
||||
XPaths. Since Odoo is at its heart a modular application, this is an important
|
||||
feature for us.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<button t-on-click="increment">Click Me! [<t t-esc="state.value"/>]</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
Vue is actually kind of similar. Its template language is kind of close to QWeb,
|
||||
with the `v` replaced by the `t`. However, it is also more fully featured. For
|
||||
example, Vue templates have slots, or event modifiers. A large difference is that
|
||||
most Vue applications will need to be built ahead of time, to compile the templates
|
||||
into javascript functions. Note that Vue has a separate build which includes the
|
||||
template compiler.
|
||||
|
||||
In contrast, most React applications do not use a templating language, but write
|
||||
some JSX code, which is precompiled into plain JavaScript by a build step.
|
||||
|
||||
```jsx
|
||||
class Clock extends React.Component {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Hello, world!</h1>
|
||||
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This has the advantage of having the full power of Javascript, but is less
|
||||
structured than a template language. Note that the tooling is quite impressive:
|
||||
there is a syntax highlighter for jsx here on github!
|
||||
|
||||
### Asynchronous rendering
|
||||
|
||||
This is actually a big difference between OWL and React/Vue: components in OWL
|
||||
are totally asynchronous. They have two asynchronous hooks in their lifecycle:
|
||||
|
||||
- `willStart` (before the widget starts rendering)
|
||||
- `willUpdateProps` (before new props are set)
|
||||
|
||||
Both these methods can be implemented and return a promise. The rendering will
|
||||
then wait for these promises to be completed before patching the DOM. This is
|
||||
useful for some use cases: for example, a widget may want to fetch an external
|
||||
library (a calendar widget may need a specialized calendar rendering library),
|
||||
in its willStart hook.
|
||||
|
||||
```javascript
|
||||
class MyCalendarWidget extends owl.Component {
|
||||
...
|
||||
|
||||
willStart() {
|
||||
return utils.lazyLoad('static/libs/fullcalendar/fullcalendar.js');
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
This may be dangerous (to stop the rendering waiting for the network), but it is
|
||||
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
||||
|
||||
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
||||
more convoluted.
|
||||
|
||||
### Reactiveness
|
||||
|
||||
React has a simple model: whenever the state changes, it is
|
||||
replaced with a new state (via the setState method). Then, the DOM is patched.
|
||||
This is simple, efficient, and a little bit awkward to write.
|
||||
|
||||
Vue is a little bit different: it replace magically the properties in the state
|
||||
by getters/setters. With that, it can notify components whenever the state that
|
||||
they read was changed.
|
||||
|
||||
Owl is closer to vue: it also tracks magically the state properties, but it does
|
||||
only increment a counter whenever it changes (and a _deep_ counter for each of
|
||||
its parents). This assumes that the state is actually a tree.
|
||||
|
||||
### State Management
|
||||
|
||||
Managing the state of an application is a tricky issue. Many solutions have
|
||||
been proposed these last few years. It also depends on the kind of application we
|
||||
are talking about. A small application may not need much more than a simple
|
||||
object to contain its state.
|
||||
|
||||
However, there are some common solutions for React and Vue: redux and vuex.
|
||||
Both of them are a centralized store that own the state, and they dictate how
|
||||
the state can be mutated.
|
||||
|
||||
**Redux**
|
||||
|
||||
In Redux, the state is mutated by reducers. Reducers are functions
|
||||
that modify the state by returning a different object:
|
||||
|
||||
```javascript
|
||||
...
|
||||
switch (action.type) {
|
||||
case ADD_TODO: {
|
||||
const { id, content } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
allIds: [...state.allIds, id],
|
||||
byIds: {
|
||||
...state.byIds,
|
||||
[id]: {
|
||||
content,
|
||||
completed: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This is a little bit awkward to write, but this allows the component system to
|
||||
check if a part of the state was changed. This is exactly what is done by the
|
||||
`connect` function: it create a _connected_ component, which is subscribed to
|
||||
the state and triggers a rerender if some part of the state was modified.
|
||||
|
||||
**VueX**
|
||||
|
||||
VueX is based on a different principle: the state is mutated through
|
||||
some special functions (the mutations), which modify the state in place:
|
||||
|
||||
```javascript
|
||||
function ({state}, payload) {
|
||||
const { id, content } = payload;
|
||||
const message = {id, content, completed: false};
|
||||
state.messages.push(message)
|
||||
}
|
||||
```
|
||||
|
||||
This is simpler, but there is a little bit more happening behind the scene:
|
||||
each key from the state is silently replaced by getters and setters, and VueX
|
||||
keeps track of who get data, and retrigger a render when it was changed.
|
||||
|
||||
**Owl**
|
||||
|
||||
Owl store is a little bit like a mix of redux and vuex: it has mutations and
|
||||
actions, like VueX, it keeps track of the state changes, but it does not notify
|
||||
a component when the state changes. Instead, components need to connect to the
|
||||
store like in redux, with a function that will listen to the relevant state.
|
||||
@@ -1,558 +0,0 @@
|
||||
# 🦉 OWL Component 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Composition](#composition)
|
||||
- [Reference](#reference)
|
||||
- [Properties](#properties)
|
||||
- [Static Properties](#static-properties)
|
||||
- [Methods](#methods)
|
||||
- [Lifecycle](#lifecycle)
|
||||
- [Semantics](#semantics)
|
||||
- [Props Validation](#props-validation)
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
|
||||
## Overview
|
||||
|
||||
OWL components are the building blocks for user interface. They are designed to be:
|
||||
|
||||
1. **declarative:** the user interface should be described in term of the state
|
||||
of the application, not as a sequence of imperative steps.
|
||||
|
||||
2. **composable:** each widget can seamlessly be created in a parent widget by
|
||||
a simple directive in its template.
|
||||
|
||||
3. **asynchronous rendering:** the framework will transparently wait for each
|
||||
subwidgets to be ready before applying the rendering. It uses native promises
|
||||
under the hood.
|
||||
|
||||
4. **uses QWeb as a template system:** the templates are described in XML
|
||||
and follow the QWeb specification. This is a requirement for Odoo.
|
||||
|
||||
OWL components are defined as a subclass of Component. The rendering is
|
||||
exclusively done by a [QWeb](qweb.md) template (which needs to be preloaded in QWeb).
|
||||
Rendering a component generates a virtual dom representation
|
||||
of the widget, which is then patched to the DOM, in order to apply the changes in an efficient way.
|
||||
|
||||
OWL components observe their states, and rerender themselves whenever it is
|
||||
changed. This is done by an [observer](observer.md).
|
||||
|
||||
## Example
|
||||
|
||||
Let us have a look at a simple component:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="ClickCounter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
Note that this code is written in ESNext style, so it will only run on the
|
||||
latest browsers without a transpilation step.
|
||||
|
||||
This example show how a component should be defined: it simply subclasses the
|
||||
Component class. If no `template` key is defined, then
|
||||
Owl will use the component's name as template name. Here,
|
||||
a state object is defined. It is not mandatory to use the state object, but it
|
||||
is certainly encouraged. The state object is [observed](observer.md), and any
|
||||
change to it will cause a rerendering.
|
||||
|
||||
## Composition
|
||||
|
||||
The example above shows a QWeb template with a `t-on-click` directive. Widget
|
||||
templates are standard [QWeb](qweb.md) templates, but with an extra directive:
|
||||
`t-widget`. With the `t-widget` directive, widget templates can declare sub
|
||||
widgets:
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<span>some text</span>
|
||||
<t t-widget="MyWidget" t-props="{info: 13}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentWidget extends owl.Component {
|
||||
widgets = { MyWidget: MyWidget};
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the `ParentWidget`'s template creates a widget `MyWidget` just
|
||||
after the span. See the [QWeb](qweb.md) documentation for more information on the
|
||||
`t-widget` directive.
|
||||
|
||||
Note that the rendering context for the template is the widget itself. This means
|
||||
that the template can access `state`, `props`, `env`, or any methods defined in the widget.
|
||||
|
||||
**CSS and style:** there is some specific support to allow the parent to declare
|
||||
additional css classes or style for the sub widget: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||
root widget element.
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="MyWidget" class="someClass" style="font-weight:bold;" t-props="{info: 13}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
Warning: there is a small caveat with dynamic class attributes: since Owl needs
|
||||
to be able to add/remove proper classes whenever necessary, it needs to be aware
|
||||
of the possible classes. Otherwise, it will not be able to make the difference
|
||||
between a valid css class added by the component, or some custom code, and a
|
||||
class that need to be removed. This is why we only support the explicit syntax
|
||||
with a class object:
|
||||
|
||||
```xml
|
||||
<t t-widget="MyWidget" t-att-class="{a: state.flagA, b: state.flagB}" />
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
An Owl component is a small class which represent a widget or some UI element.
|
||||
It exists in the context of an environment (`env`), which is propagated from a
|
||||
parent to its children. The environment needs to have a QWeb instance, which
|
||||
will be used to render the component template.
|
||||
|
||||
Be aware that the name of the component may be significant: if a component does
|
||||
not define a `template` key, then Owl will lookup in QWeb to
|
||||
find a template with the component name (or one of its ancestor).
|
||||
|
||||
### Properties
|
||||
|
||||
- **`el`** (HTMLElement | null): reference to the DOM root node of the element. It is `null` when the
|
||||
component is not mounted.
|
||||
|
||||
- **`env`** (Object): the component environment, which contains a QWeb instance.
|
||||
|
||||
- **`template`** (string, optional): if given, this is the name of the QWeb template that will render
|
||||
the component.
|
||||
|
||||
- **`state`** (Object): this is the location of the component's state, if there is
|
||||
any. After the willStart method, the `state` property is observed, and each
|
||||
change will cause the widget to rerender itself.
|
||||
|
||||
- **`props`** (Object): this is an object given (in the constructor) by the parent
|
||||
to configure the component. It can be dynamically changed later by the parent,
|
||||
in some case. Note that `props` are owned by the parent, not by the component.
|
||||
As such, it should not ever be modified by the component!!
|
||||
|
||||
- **`refs`** (Object): the `refs` object contains all references to sub DOM nodes
|
||||
or sub widgets defined by a `t-ref` directive in the component's template.
|
||||
|
||||
### Static Properties
|
||||
|
||||
- **`props`** (Object, optional): if given, this is an object that describes the
|
||||
type and shape of the (actual) props given to the component. If Owl mode is
|
||||
`dev`, this will be used to validate the props each time the component is
|
||||
created/updated. See [Props Validation](#props-validation) for more information.
|
||||
- **`defaultProps`** (Object, optional): if given, this object define default
|
||||
values for (top-level) props. Whenever `props` are given to the object, they
|
||||
will be altered to add default value (if missing). Note that it does not
|
||||
change the initial object, a new object will be created instead.
|
||||
|
||||
### Methods
|
||||
|
||||
- **`mount(target)`** (async): this is the main way a component's hierarchy is added to the
|
||||
DOM: the root component is mounted to a target HTMLElement. Obviously, this
|
||||
is asynchronous, since each children need to be created as well. Most applications
|
||||
will need to call `mount` exactly once, on the root component.
|
||||
|
||||
- **`unmount()`**: in case a component need to be detached/removed from the DOM, this
|
||||
method can be used. Most applications should not call `unmount`, this is more
|
||||
useful to the underlying component system.
|
||||
|
||||
- **`render()`** (async): calling this method directly will cause a rerender. Note
|
||||
that this should be very rare to have to do it manually, the Owl framework is
|
||||
most of the time responsible for doing that at an appropriate moment.
|
||||
|
||||
Note that the render method is asynchronous, so one cannot observe the updated
|
||||
DOM in the same stack frame.
|
||||
|
||||
- **`shouldUpdate(nextProps)`**: this method is called each time a component's props
|
||||
are updated. It returns a boolean, which indicates if the widget should
|
||||
ignore a props update. If it returns false, then `willUpdateProps` will not
|
||||
be called, and no rendering will occur. Its default implementation is to
|
||||
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
||||
can be useful if we are handling large number of components.
|
||||
|
||||
- **`updateEnv(nextEnv)`**: update the environment of a component and all its
|
||||
children. This forces a complete rerender. For example, this could be useful
|
||||
if we have a `isMobile` key in the environment, to decide if we want a mobile
|
||||
interface or a destkop one.
|
||||
|
||||
- **`set(target, key, value)`**. This method is necessary in some cases when we
|
||||
need to modify the state of the component in a way that is not visible to the
|
||||
observer (see [observer's technical limitations](observer.md#technical-limitations)).
|
||||
For example, if we need to add a key to the state.
|
||||
|
||||
- **`destroy()`**. As its name suggests, this method will remove the component,
|
||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||
removing the parent/children relationship. This method should almost never be
|
||||
called directly (except maybe on the root component), but should be done by the
|
||||
framework instead.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
A solid and robust component system needs useful hooks/methods to help
|
||||
developers write components. Here is a complete description of the lifecycle of
|
||||
a owl component:
|
||||
|
||||
| Method | Description |
|
||||
| ------------------------------------------------ | ----------------------------------------------------- |
|
||||
| **[constructor](#constructor)** | constructor |
|
||||
| **[willStart](#willStart)** | async, before first rendering |
|
||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
||||
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
||||
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
||||
| **[willUnmount](#willUnmount)** | just before removing component from DOM |
|
||||
|
||||
Notes:
|
||||
|
||||
- hooks call order is precisely defined: `[willX]` hooks are called first on parent,
|
||||
then on children, and `[Xed]` are called in the reverse order: first children,
|
||||
then parent.
|
||||
- no hook method should ever be called manually. They are supposed to be
|
||||
called by the owl framework whenever it is required.
|
||||
|
||||
#### `constructor(parent, props)`
|
||||
|
||||
The constructor is not exactly a hook, it is the regular,
|
||||
normal, constructor of the component. Since it is not a hook, you need to make
|
||||
sure that `super` is called.
|
||||
|
||||
This is usually where you would set the initial state and the template of the
|
||||
component.
|
||||
|
||||
```javascript
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = {someValue: true};
|
||||
this.template = 'mytemplate';
|
||||
}
|
||||
```
|
||||
|
||||
Note that with ESNext class fields, the constructor method does not need to be
|
||||
implemented in most cases:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
#### `willStart()`
|
||||
|
||||
willStart is an asynchronous hook that can be implemented to
|
||||
perform some action before the initial rendering of a component.
|
||||
|
||||
It will be called exactly once before the initial rendering. It is useful
|
||||
in some cases, for example, to load external assets (such as a JS library)
|
||||
before the widget is rendered. Another use case is to load data from a server.
|
||||
|
||||
```javascript
|
||||
async willStart() {
|
||||
await owl.utils.loadJS("my-awesome-lib.js");
|
||||
}
|
||||
```
|
||||
|
||||
At this point, the component is not yet rendered. Note that a slow `willStart` method will slow down the rendering of the user
|
||||
interface. Therefore, some care should be made to make this method as
|
||||
fast as possible.
|
||||
|
||||
The widget rendering will take place after `willStart` is completed.
|
||||
|
||||
#### `mounted()`
|
||||
|
||||
`mounted` is called each time a component is attached to the
|
||||
DOM, after the initial rendering and possibly later if the component was unmounted
|
||||
and remounted. At this point, the component is considered _active_. This is a good place to add some listeners, or to interact with the
|
||||
DOM, if the component needs to perform some measure for example.
|
||||
|
||||
It is the opposite of `willUnmount`. If a component has been mounted, it will
|
||||
always be unmounted at some point in the future.
|
||||
|
||||
The mounted method will be called recursively on each of its children. First,
|
||||
the parent, then all its children.
|
||||
|
||||
Note that the state is now observed. It is however allowed (but not encouraged)
|
||||
to modify the state in the `mounted` hook. Doing so will cause a rerender,
|
||||
which will not be perceptible by the user, but will slightly slow down the
|
||||
component.
|
||||
|
||||
#### `willUpdateProps(nextProps)`
|
||||
|
||||
The willUpdateProps is an asynchronous hook, called just before new props
|
||||
are set. This is useful if the component needs some asynchronous task
|
||||
performed, depending on the props (for example, assuming that the props are
|
||||
some record Id, fetching the record data).
|
||||
|
||||
```javascript
|
||||
willUpdateProps(nextProps) {
|
||||
return this.loadData({id: nextProps.id});
|
||||
}
|
||||
```
|
||||
|
||||
This hook is not called during the first render (but willStart is called
|
||||
and performs a similar job).
|
||||
|
||||
#### `willPatch()`
|
||||
|
||||
The willPatch hook is called just before the DOM patching process starts.
|
||||
It is not called on the initial render. This is useful to read some
|
||||
information from the DOM. For example, the current position of the
|
||||
scrollbar.
|
||||
|
||||
Note that modifying the state object is not allowed here. This method is called just
|
||||
before an actual DOM patch, and is only intended to be used to save some local
|
||||
DOM state. Also, it will not be called if the widget is not in the DOM (this can
|
||||
happen with widgets with `t-keepalive`).
|
||||
|
||||
The return value of this method will be given as the first argument of the
|
||||
corresponding `patched` call.
|
||||
|
||||
#### `patched(snapshot)`
|
||||
|
||||
This hook is called whenever a component did actually update its DOM (most
|
||||
likely via a change in its state/props or environment).
|
||||
|
||||
This method is not called on the initial render. It is useful to interact
|
||||
with the DOM (for example, through an external library) whenever the
|
||||
component was patched. Note that this hook will not be called if the widget is
|
||||
not in the DOM (this can happen with widgets with `t-keepalive`).
|
||||
|
||||
The `snapshot` parameter is the result of the previous `willPatch` call.
|
||||
|
||||
Updating the widget state in this hook is possible, but not encouraged.
|
||||
One need to be careful, because updates here will cause rerender, which in
|
||||
turn will cause other calls to patched. So, we need to be particularly
|
||||
careful at avoiding endless cycles.
|
||||
|
||||
#### `willUnmount()`
|
||||
|
||||
willUnmount is a hook that is called each time just before a component is unmounted from
|
||||
the DOM. This is a good place to remove some listeners, for example.
|
||||
|
||||
```javascript
|
||||
mounted() {
|
||||
this.env.bus.on('someevent', this, this.doSomething);
|
||||
}
|
||||
willUnmount() {
|
||||
this.env.bus.off('someevent', this, this.doSomething);
|
||||
}
|
||||
```
|
||||
|
||||
This is the opposite method of `mounted`.
|
||||
|
||||
### 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.
|
||||
|
||||
- widget `B` is created
|
||||
1. `willStart` is called on `B`
|
||||
2. template `B` is rendered
|
||||
- widget `C` is created
|
||||
1. `willStart` is called on `C`
|
||||
2. template `C` is rendered
|
||||
- widget `D` is created
|
||||
1. `willStart` is called on `D`
|
||||
2. template `D` is rendered
|
||||
- widget `E` is created
|
||||
1. `willStart` is called on `E`
|
||||
2. template `E` is rendered
|
||||
|
||||
3. widget `A` is patched into a detached DOM element. This will create the actual
|
||||
widget `A` DOM structure. The patching process will cause recursively the
|
||||
patching of the `B`, `C`, `D` and `E` DOM trees. (so the actual full DOM tree is created
|
||||
in one pass)
|
||||
|
||||
4. the widget `A` root element is actually appended to `document.body`
|
||||
|
||||
5. The method `mounted` is called recursively on all widgets in the following
|
||||
order: `B`, `D`, `E`, `C`, `A`.
|
||||
|
||||
**Scenario 2: rerendering a component**. Now, let's assume that the user clicked on some
|
||||
button in `C`, and this results in a state update, which is supposed to:
|
||||
|
||||
- update `D`,
|
||||
- remove `E`,
|
||||
- add new widget `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
|
||||
|
||||
- widget `D` is updated:
|
||||
1. hook `willUpdateProps` is called on `D` (async)
|
||||
2. template `D` is rerendered
|
||||
- widget `F` is created:
|
||||
1. hook `willStart` is called on `E` (async)
|
||||
2. template `F` is rendered
|
||||
|
||||
3. `willPatch` hooks are called recursively on widgets `C`, `D` (not on `F`,
|
||||
because it is not mounted yet)
|
||||
|
||||
4. widget `C` is patched, which will cause recursively:
|
||||
|
||||
2. `willUnmount` hook on `E`, then destruction of `E`,
|
||||
3. (initial) patching of `F`, then hook `mounted` is called on `F`
|
||||
|
||||
5. patching of `D`
|
||||
|
||||
6. `patched` hooks are called on `D`, `C`
|
||||
|
||||
### Props Validation
|
||||
|
||||
As an application becomes complex, it may be quite unsafe to define props in an informal way. This leads to two issues:
|
||||
|
||||
- hard to tell how a component should be used, by looking at its code.
|
||||
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parent.
|
||||
|
||||
A props type system would solve both issues, by describing the types and shapes
|
||||
of the props. Here is how it works in Owl:
|
||||
|
||||
- `props` key is a static key (so, different from `this.props` in a component instance)
|
||||
- it is optional: it is ok for a component to not define a `props` key.
|
||||
- props are validated whenever a component is created/updated
|
||||
- props are only validated in `dev` mode (see [tooling page](tooling.md#development-mode))
|
||||
- if a key does not match the description, an error is thrown
|
||||
- it only validates keys defined in (static) `props`. Additional keys in (component) `props` are not validated.
|
||||
|
||||
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.
|
||||
- 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 constructor, a list of constructors, or an object:
|
||||
|
||||
- a constructor: this should describe the type, for example: `id: Number` describe
|
||||
the props `id` as a number
|
||||
- a list of constructors. In that case, this means that we allow more than one
|
||||
type. For example, `id: [Number, String]` means that `id` can be either a string
|
||||
or a number.
|
||||
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed:
|
||||
- `type`: the main type of the prop being validated
|
||||
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. It is optional (not set means that we only validate the array, not its elements),
|
||||
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. It is optional (not set means that we only validate the object, not its elements)
|
||||
|
||||
Examples:
|
||||
|
||||
```js
|
||||
// only the existence of those 3 keys is documented
|
||||
static props = ['message', 'id', 'date'];
|
||||
```
|
||||
|
||||
```js
|
||||
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
|
||||
};
|
||||
```
|
||||
|
||||
## 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 widget can delay the rendering (initial and subsequent) of the whole
|
||||
application
|
||||
- for a given widget, 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 widgets:
|
||||
|
||||
1. minimize the use of asynchronous widgets!
|
||||
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`)
|
||||
@@ -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
@@ -0,0 +1,345 @@
|
||||
# Comparison with Vue/React
|
||||
|
||||
OWL, React and Vue have the same main feature: they allow developers to build
|
||||
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
||||
|
||||
In this page, we try to highlight some of these differences. Obviously, a lot of
|
||||
effort was done to be fair. However, if you disagree with some of the points
|
||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||
|
||||
## Content
|
||||
|
||||
- [Size](#size)
|
||||
- [Class Based](#class-based)
|
||||
- [Tooling/Build Step](#toolingbuild-step)
|
||||
- [Templating](#templating)
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
- [Reactiveness](#reactiveness)
|
||||
- [State Management](#state-management)
|
||||
- [Hooks](#hooks)
|
||||
|
||||
## Size
|
||||
|
||||
OWL is intended to be small and to work at a slightly lower level of abstraction
|
||||
than React and Vue. Also, jQuery is not the same kind of framework, but it is interesting to compare.
|
||||
|
||||
| Framework | Size (minified, gzipped) |
|
||||
| ------------------------ | ------------------------ |
|
||||
| OWL | 18kb |
|
||||
| Vue + VueX | 30kb |
|
||||
| Vue + VueX + Vue Router | 39kb |
|
||||
| React + ReactDOM + Redux | 40kb |
|
||||
| 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
|
||||
|
||||
Both React and Vue moved away from defining components with classes. They prefer
|
||||
a more functional approach, in particular, with the new `hooks` mechanisms.
|
||||
|
||||
This has some advantages and disadvantages. But the end result is that React
|
||||
and Vue both offers multiple different ways of defining new components. In
|
||||
contrast, Owl has only one mechanism: class-based components. We believe that Owl
|
||||
components are fast enough for all our usecases, and making it as simple as
|
||||
possible for developers is more valuable (for us).
|
||||
|
||||
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
|
||||
|
||||
OWL is designed to be easy to use in a standalone way. For various reasons,
|
||||
Odoo does not want to rely on standard web tools (such as webpack), and OWL can
|
||||
be used by simply adding a script tag to a page.
|
||||
|
||||
```html
|
||||
<script src="owl.min.js" />
|
||||
```
|
||||
|
||||
In comparison, React encourages using JSX, which necessitate a build step, and
|
||||
most Vue applications uses single file components, which also necessitate a build step.
|
||||
|
||||
On the flipside, external tooling may make it harder to use in some case, but it
|
||||
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
||||
|
||||
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
|
||||
|
||||
OWL uses its own QWeb engine, which compiles templates on the
|
||||
frontend, as they are needed. This is extremely convenient for our use case, in
|
||||
particular because templates are described in XML files, and can be modified by
|
||||
XPaths. Since Odoo is at its heart a modular application, this is an important
|
||||
feature for us.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<button t-on-click="increment">Click Me! [<t t-esc="state.value"/>]</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
Vue is actually kind of similar. Its template language is kind of close to QWeb,
|
||||
with the `v` replaced by the `t`. However, it is also more fully featured. For
|
||||
example, Vue templates have slots, or event modifiers. A large difference is that
|
||||
most Vue applications will need to be built ahead of time, to compile the templates
|
||||
into javascript functions. Note that Vue has a separate build which includes the
|
||||
template compiler.
|
||||
|
||||
In contrast, most React applications do not use a templating language, but write
|
||||
some JSX code, which is precompiled into plain JavaScript by a build step. This
|
||||
example is done with the (kind of outdated) React class system:
|
||||
|
||||
```jsx
|
||||
class Clock extends React.Component {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Hello, world!</h1>
|
||||
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This has the advantage of having the full power of Javascript, but is less
|
||||
structured than a template language. Note that the tooling is quite impressive:
|
||||
there is a syntax highlighter for jsx here on github!
|
||||
|
||||
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
|
||||
|
||||
This is actually a big difference between OWL and React/Vue: components in OWL
|
||||
are totally asynchronous. They have two asynchronous hooks in their lifecycle:
|
||||
|
||||
- `willStart` (before the component starts rendering)
|
||||
- `willUpdateProps` (before new props are set)
|
||||
|
||||
Both these methods can be implemented and return a promise. The rendering will
|
||||
then wait for these promises to be completed before patching the DOM. This is
|
||||
useful for some use cases: for example, a component may want to fetch an external
|
||||
library (a calendar component may need a specialized calendar rendering library),
|
||||
in its willStart hook.
|
||||
|
||||
```javascript
|
||||
class MyCalendarComponent extends owl.Component {
|
||||
...
|
||||
|
||||
willStart() {
|
||||
return utils.lazyLoad('static/libs/fullcalendar/fullcalendar.js');
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
This may be dangerous (to stop the rendering waiting for the network), but it is
|
||||
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
||||
|
||||
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
||||
more convoluted. 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
|
||||
|
||||
React has a simple model: whenever the state changes, it is
|
||||
replaced with a new state (via the `setState` method). Then, the DOM is patched.
|
||||
This is simple, efficient, and a little bit awkward to write.
|
||||
|
||||
Vue is a little bit different: it replace magically the properties in the state
|
||||
by getters/setters. With that, it can notify components whenever the state that
|
||||
they read was changed.
|
||||
|
||||
Owl is closer to vue: it also tracks magically the state properties, but it does
|
||||
only increment an internal counter whenever it changes. Note that it is done
|
||||
with a `Proxy`, which means that it is totally transparent to the developers.
|
||||
Adding new keys is supported. Once any part of the state has been changed, a
|
||||
rendering is scheduled in the next microtask tick (promise queue).
|
||||
|
||||
## State Management
|
||||
|
||||
Managing the state of an application is a tricky issue. Many solutions have
|
||||
been proposed these last few years. It also depends on the kind of application we
|
||||
are talking about. A small application may not need much more than a simple
|
||||
object to contain its state.
|
||||
|
||||
However, there are some common solutions for React and Vue: redux and vuex.
|
||||
Both of them are a centralized store that own the state, and they dictate how
|
||||
the state can be mutated.
|
||||
|
||||
**Redux**
|
||||
|
||||
In Redux, the state is mutated by reducers. Reducers are functions
|
||||
that modify the state by returning a different object:
|
||||
|
||||
```javascript
|
||||
...
|
||||
switch (action.type) {
|
||||
case ADD_TODO: {
|
||||
const { id, content } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
allIds: [...state.allIds, id],
|
||||
byIds: {
|
||||
...state.byIds,
|
||||
[id]: {
|
||||
content,
|
||||
completed: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This is a little bit awkward to write, but this allows the component system to
|
||||
check if a part of the state was changed. This is exactly what is done by the
|
||||
`connect` function: it create a _connected_ component, which is subscribed to
|
||||
the state and triggers a rerender if some part of the state was modified.
|
||||
|
||||
**VueX**
|
||||
|
||||
VueX is based on a different principle: the state is mutated through
|
||||
some special functions (the mutations), which modify the state in place:
|
||||
|
||||
```javascript
|
||||
function ({state}, payload) {
|
||||
const { id, content } = payload;
|
||||
const message = {id, content, completed: false};
|
||||
state.messages.push(message)
|
||||
}
|
||||
```
|
||||
|
||||
This is simpler, but there is a little bit more happening behind the scene:
|
||||
each key from the state is silently replaced by getters and setters, and VueX
|
||||
keeps track of who get data, and retrigger a render when it was changed.
|
||||
|
||||
**Owl**
|
||||
|
||||
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
||||
mutations), and like VueX, it keeps track of the state changes. However, it does
|
||||
not notify a component when the state changes. Instead, components need to connect
|
||||
to the store like in redux, with the `useStore` hook (see the [store documentation](../reference/store.md#connecting-a-component)).
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter.value += val;
|
||||
},
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: { value: 0 },
|
||||
};
|
||||
const store = new owl.Store({ state, actions });
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="counter.value"/>]
|
||||
</button>`;
|
||||
counter = useStore((state) => state.counter);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
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,18 @@
|
||||
# 🦉 VDom 🦉
|
||||
|
||||
Owl is a declarative component system: we declare the structure of the component
|
||||
tree, and Owl will translate that to a list of imperative operations. This
|
||||
translation is done by a virtual dom. This is the low level layer of Owl, most
|
||||
developer will not need to call directly the virtual dom functions.
|
||||
|
||||
The main idea behind a virtual dom is to keep a in-memory representation of the
|
||||
DOM (called a virtual node), and whenever some change is needed, to regenerate
|
||||
a new representation, compute the difference between the old and the new, then
|
||||
apply the changes.
|
||||
|
||||
`vdom` exports two functions:
|
||||
|
||||
- `h`: create a new virtual node
|
||||
- `patch`: compare two virtual nodes, and apply the difference.
|
||||
|
||||
Note: Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
|
||||
@@ -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,54 +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");
|
||||
observer.observe(obj);
|
||||
|
||||
const obj = { a: { b: 1 } };
|
||||
obj.a.b = 2;
|
||||
```
|
||||
|
||||
## Technical Limitations
|
||||
|
||||
Since the observer uses getters and setters, it is actually unable to react to
|
||||
changes in two situations:
|
||||
|
||||
- adding a key to an object:
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const obj = { a: 1 };
|
||||
observer.observe(obj);
|
||||
obj.b = 2; // will do nothing
|
||||
```
|
||||
|
||||
In that case, we need a way to tell the observer that something happened.
|
||||
This can be done by using the `set` method:
|
||||
|
||||
```javascript
|
||||
observer.set(obj, "b", 2);
|
||||
```
|
||||
|
||||
- modifying an array by setting a new value at a given index:
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const obj = { todos: [{ id: 1, text: "todo" }] };
|
||||
observer.observe(obj);
|
||||
obj[0] = { id: 2, text: "othertodo" }; // will do nothing, and obj[0] is not observed
|
||||
```
|
||||
|
||||
In that case, the solution is the same, we can simply use the `set` method:
|
||||
|
||||
```javascript
|
||||
observer.set(obj, 0, { id: 2, text: "othertodo" });
|
||||
```
|
||||
@@ -1,101 +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 widget, which can
|
||||
have sub widgets
|
||||
|
||||
Here are a few steps that we may take to get started:
|
||||
|
||||
- get the templates
|
||||
- create a qweb engine, with the templates
|
||||
- create an environment
|
||||
- create an instance of the root widget
|
||||
- mount the root widget to a DOM element
|
||||
|
||||
Let us now add the javascript to make it work, in `app.js`:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.template = "clickcounter";
|
||||
this.state = { 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();
|
||||
```
|
||||
-679
@@ -1,679 +0,0 @@
|
||||
# 🦉 QWeb 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [QWeb Engine](#qweb-engine)
|
||||
- [QWeb Specification](#qweb-specification)
|
||||
|
||||
- [Static html nodes](#static-html-nodes)
|
||||
- [`t-esc` directive](#t-esc-directive)
|
||||
- [`t-raw` directive](#t-raw-directive)
|
||||
- [`t-set` directive](#t-set-directive)
|
||||
- [`t-if` directive](#t-if-directive)
|
||||
- [Expression evaluation](#expression-evaluation)
|
||||
- [Dynamic attributes (`t-att` and `t-attf` directives)](#dynamic-attributes-t-att-and-t-attf-directives)
|
||||
- [`t-call` directive (sub templates)](#t-call-directive-sub-templates)
|
||||
|
||||
- [JS/OWL Specific Extensions](#jsowl-specific-extensions)
|
||||
|
||||
- [`t-on` directive](#t-on-directive)
|
||||
- [Component: `t-widget`, `t-props`](#component-t-widget-t-props)
|
||||
- [`t-ref` directive](#t-ref-directive)
|
||||
- [`t-key` directive](#t-key-directive)
|
||||
- [`t-transition` directive](#t-transition-directive)
|
||||
- [`t-mounted` directive](#t-mounted-directive)
|
||||
- [Debugging (`t-debug` and `t-log`)](#debugging-t-debug-and-t-log)
|
||||
- [White spaces](#white-spaces)
|
||||
- [Root nodes](#root-nodes)
|
||||
|
||||
## 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
|
||||
mostly to generate html. In OWL, QWeb templates are compiled into functions that
|
||||
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.
|
||||
|
||||
The QWeb implementation in the OWL project is slightly different. It compiles
|
||||
templates into functions that output a virtual DOM instead of a string. This is
|
||||
necessary for the component system. In addition, it has a few extra directives
|
||||
(see [OWL Specific Extensions](#owlspecificextensions))
|
||||
|
||||
## 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)`**: add a specific template.
|
||||
|
||||
```js
|
||||
qweb.addTemplate("mytemplate", "<div>hello</div>");
|
||||
```
|
||||
|
||||
- **`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="OtherWidget">other widget</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", widget);
|
||||
```
|
||||
|
||||
- **`register(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-widget` directive). This is useful for commonly used
|
||||
components accross the application.
|
||||
|
||||
```js
|
||||
class Dialog extends owl.Component { ... }
|
||||
QWeb.register("Dialog", Dialog);
|
||||
|
||||
...
|
||||
|
||||
class ParentWidget extends owl.Component { ... }
|
||||
qweb.addTemplate("ParentWidget", "<div><t t-widget='Dialog'/></div>");
|
||||
```
|
||||
|
||||
## QWeb Specification
|
||||
|
||||
We define in this section the specification of how `QWeb` templates should be
|
||||
rendered.
|
||||
|
||||
### Static html nodes
|
||||
|
||||
Normal, regular html nodes are rendered into themselves:
|
||||
|
||||
```xml
|
||||
<div>hello</div> <!–– rendered as itself ––>
|
||||
```
|
||||
|
||||
### `t-esc` directive
|
||||
|
||||
The `t-esc` directive is necessary whenever you want to add a dynamic text
|
||||
expression in a template. The text is escaped to avoid security issues.
|
||||
|
||||
```xml
|
||||
<p><t t-esc="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `42` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p>42</p>
|
||||
```
|
||||
|
||||
### `t-raw` directive
|
||||
|
||||
The `t-raw` directive is almost the same as `t-esc`, but without the escaping.
|
||||
This is mostly useful to inject a raw html string somewhere. Obviously, this
|
||||
is unsafe to do in general, and should only be used for strings known to be safe.
|
||||
|
||||
```xml
|
||||
<p><t t-esc="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `<span>foo</span>` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p><span>foo</span></p>
|
||||
```
|
||||
|
||||
### `t-set` directive
|
||||
|
||||
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
|
||||
|
||||
This is done via the `t-set` directive, which takes the name of the variable to create. The value to set can be provided in two ways:
|
||||
|
||||
1. a `t-value` attribute containing an expression, and the result of its
|
||||
evaluation will be set:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="2 + 1"/>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will print `3`. Note that the evaluation is done at rendering time, not at
|
||||
compilte time.
|
||||
|
||||
2. if there is no `t-value` attribute, the node’s body is saved and its value is
|
||||
set as the variable’s value:
|
||||
|
||||
```xml
|
||||
<t t-set="foo">
|
||||
<li>ok</li>
|
||||
</t>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will generate `<li>ok</li>` (the content is escaped as we used the `t-esc` directive)
|
||||
|
||||
The `t-set` directive acts like a regular variable in most programming language.
|
||||
It is lexically scoped (inner nodes are sub scopes), can be shadowed, ...
|
||||
|
||||
### `t-if` directive
|
||||
|
||||
The `t-if` directive is useful to conditionally render something. It evaluates
|
||||
the expression given as attribute value, and then acts accordingly.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<t t-if="condition">
|
||||
<p>ok</p>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
The element is rendered if the condition (evaluated with the current rendering
|
||||
context) is true:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p>ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
but if the condition is false it is removed from the result:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
</div>
|
||||
```
|
||||
|
||||
The conditional rendering applies to the bearer of the directive, which does not
|
||||
have to be `<t>`:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="condition">ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
will give the same results as the previous example.
|
||||
|
||||
Extra conditional branching directives `t-elif` and `t-else` are also available:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="user.birthday == today()">Happy bithday!</p>
|
||||
<p t-elif="user.login == 'root'">Welcome master!</p>
|
||||
<p t-else="">Welcome!</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Expression evaluation
|
||||
|
||||
It is useful to explain the various rules that applies on QWeb expressions. These
|
||||
expressions are strings that will be converted to a javascript expression at
|
||||
compile time.
|
||||
|
||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||
|
||||
```xml
|
||||
<div><p t-if="1 + 2 === 3">ok</p></div>
|
||||
```
|
||||
|
||||
is valid, but the following is not valid:
|
||||
|
||||
```xml
|
||||
<div><p t-if="console.log(1)">NOT valid</p></div>
|
||||
```
|
||||
|
||||
2. it can use anything in the rendering context:
|
||||
|
||||
```xml
|
||||
<p t-if="user.birthday == today()">Happy bithday!</p>
|
||||
```
|
||||
|
||||
is valid, and will read the `user` object from the context, and call the
|
||||
`today` function.
|
||||
|
||||
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
||||
`&` or `|`. This is useful to make sure that we still write valid XML.
|
||||
|
||||
| Word | will be replaced by |
|
||||
| ----- | ------------------- |
|
||||
| `and` | `&&` |
|
||||
| `or` | `\|\|` |
|
||||
| `gt` | `>` |
|
||||
| `gte` | `>=` |
|
||||
| `lt` | `<` |
|
||||
| `lte` | `<=` |
|
||||
|
||||
So, one can write this:
|
||||
|
||||
```xml
|
||||
<div><p t-if="10 + 2 gt 5">ok</p></div>
|
||||
```
|
||||
|
||||
### Dynamic attributes (`t-att` and `t-attf` directives)
|
||||
|
||||
One can use the `t-att-` directive to add dynamic attributes. Its main use is to
|
||||
evaluate an expression (at rendering time) and bind an attribute to its result:
|
||||
|
||||
For example, if we have `id` set to 32 in the rendering context,
|
||||
|
||||
```xml
|
||||
<div t-att-data-action-id="id"/> <!-- result: <div data-action-id="32"></div> -->
|
||||
```
|
||||
|
||||
If an expression evaluates to a falsy value, it will not be set at all:
|
||||
|
||||
```xml
|
||||
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
||||
```
|
||||
|
||||
There is another way to format a string attribute: the `t-attf-` directive. With
|
||||
it, you get string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a #{value1} is #{value2} of #{value3} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
```
|
||||
|
||||
For historical reason, there is an alternate form of string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
```
|
||||
|
||||
### `t-call` directive (sub templates)
|
||||
|
||||
QWeb templates can be used for top level rendering, but they can also be used
|
||||
from within another template (to avoid duplication or give names to parts of
|
||||
templates), using the `t-call` directive:
|
||||
|
||||
```xml
|
||||
<div t-name="other-template">
|
||||
<p><t t-value="var"/></p>
|
||||
</div>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-set="var" t-value="owl"/>
|
||||
<t t-call="other-template"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
will be rendered as `<div><p>owl</p></div>`. This example shows that the sub
|
||||
template is rendered with the execution context of the parent. The sub template
|
||||
is actually inlined in the main template, but in a sub scope: variables defined
|
||||
in the sub template do not escape.
|
||||
|
||||
Sometimes, one might want to pass information to the sub template. In that case,
|
||||
the content of the body of the `t-call` directive is available as a special
|
||||
magic variable `0`:
|
||||
|
||||
```xml
|
||||
<t t-name="other-template">
|
||||
This template was called with content:
|
||||
<t t-raw="0"/>
|
||||
</t>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-call="other-template">
|
||||
<em>content</em>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
will result in :
|
||||
|
||||
```xml
|
||||
<div>
|
||||
This template was called with content:
|
||||
<em>content</em>
|
||||
</div>
|
||||
```
|
||||
|
||||
## JS/OWL Specific Extensions
|
||||
|
||||
### `t-on` directive
|
||||
|
||||
In a component's template, it is useful to be able to register handlers on some
|
||||
elements to some specific events. This
|
||||
is what makes a template _alive_. There are two different use cases.
|
||||
|
||||
1. Register an event handler on a DOM node
|
||||
|
||||
```xml
|
||||
<button t-on-click="someMethod">Do something</button>
|
||||
```
|
||||
|
||||
This will be roughly translated in javascript like this:
|
||||
|
||||
```js
|
||||
button.addEventListener("click", widget.someMethod.bind(widget));
|
||||
```
|
||||
|
||||
The suffix (`click` in this example) is simply the name of the actual DOM
|
||||
event.
|
||||
|
||||
In order to remove the DOM event details from the event handlers (like calls
|
||||
to `event.preventDefault`) and let them focus on data logic, _modifiers_ can
|
||||
be specified as additional suffixes of the `t-on` directive.
|
||||
|
||||
| Modifier | Description |
|
||||
| ---------- | ----------------------------------------------------------------- |
|
||||
| `.stop` | calls `event.stopPropagation()` before calling the method |
|
||||
| `.prevent` | calls `event.preventDefault()` before calling the method |
|
||||
| `.self` | calls the method only if the `event.target` is the element itself |
|
||||
|
||||
```xml
|
||||
<button t-on-click.stop="someMethod">Do something</button>
|
||||
```
|
||||
|
||||
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
|
||||
the order may matter. For instance `t-on-click.prevent.self` will prevent all
|
||||
clicks while `t-on-click.self.prevent` will only prevent clicks on the
|
||||
element itself.
|
||||
|
||||
2. Register an event handler on a component. This will not capture a DOM event,
|
||||
but rather a _business_ event:
|
||||
|
||||
```xml
|
||||
<t t-widget="MyWidget" t-on-menuLoaded="someMethod"/>
|
||||
```
|
||||
|
||||
```js
|
||||
class MyWidget {
|
||||
someWhere() {
|
||||
const payload = ...;
|
||||
this.trigger('menuLoaded', payload);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here, the parent widget will receive the payload in its `someMethod` handler,
|
||||
whenever the event is triggered.
|
||||
|
||||
The `t-on` directive also allows to prebind some 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.
|
||||
|
||||
### Component: `t-widget`, `t-props`
|
||||
|
||||
The `t-widget` and the `t-props` directives are the key to a declarative component
|
||||
system. They allow a template to define where and how a sub widget is created
|
||||
and/or updated. For example:
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="ChildWidget" t-props="{count: state.val}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentWidget {
|
||||
widgets = { ChildWidget };
|
||||
state = { val: 4 };
|
||||
}
|
||||
```
|
||||
|
||||
Whenever the template is rendered, it will automatically create the subwidget
|
||||
`ChildWidget` at the correct place. It needs to find the reference to the
|
||||
actual component class in the special `widgets` key, or the class registered in
|
||||
QWeb's global registry (see `register` function of QWeb). It first looks inside
|
||||
the local `widgets` key, then fallbacks on the global registry.
|
||||
|
||||
In this example, the child widget will receive the object `{count: 4}` in its
|
||||
constructor. This will be assigned to the `props` variable, which can be accessed
|
||||
on the widget (and also, in the template). Whenever the state is updated, then
|
||||
the subwidget will also be updated automatically.
|
||||
|
||||
The `t-widget` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](#dynamic-attributes-t-att-and-t-attf-directives) directive):
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="ChildWidget#{id}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentWidget {
|
||||
widgets = { ChildWidget1, ChildWidget2 };
|
||||
state = { id: 1 };
|
||||
}
|
||||
```
|
||||
|
||||
Similarly to `t-attf-`, there is an alternate form of string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="ChildWidget{{id}}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
### `t-ref` directive
|
||||
|
||||
The `t-ref` directive helps a component keep reference to some inside part of it.
|
||||
Like the `t-on` directive, it can work either on a DOM node, or on a component:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-ref="someDiv"/>
|
||||
<t t-widget="SubWidget" t-ref="someWidget"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
In this example, the widget will be able to access the `div` and the component
|
||||
inside the special `refs` variable:
|
||||
|
||||
```js
|
||||
this.refs.someDiv;
|
||||
this.refs.someWidget;
|
||||
```
|
||||
|
||||
This is useful for various usecases: for example, integrating with an external
|
||||
library that needs to render itself inside an actual DOM node. Or for calling
|
||||
some method on a sub widget.
|
||||
|
||||
Note: if used on a component, the reference will be set in the `refs`
|
||||
variable between `willPatch` and `patched`.
|
||||
|
||||
The `t-ref` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](#dynamic-attributes-t-att-and-t-attf-directives) and
|
||||
[`t-widget-`](#component-t-widget-t-props) directives). For example, if we have
|
||||
`id` set to 44 in the rendering context,
|
||||
|
||||
```xml
|
||||
<div t-ref="widget_#{id}"/>
|
||||
```
|
||||
|
||||
```js
|
||||
this.refs.widget_44;
|
||||
```
|
||||
|
||||
Similarly to `t-attf-` and `t-widget`, there is an alternate form of string
|
||||
interpolation:
|
||||
|
||||
```xml
|
||||
<div t-ref="widget_{{id}}"/>
|
||||
```
|
||||
|
||||
### `t-key` directive
|
||||
|
||||
Even though Owl tries to be as declarative as possible, some DOM state is still
|
||||
locked inside the DOM: for example, the scrolling state, the current user selection,
|
||||
the focused element or the state of an input. This is why we use a virtual dom
|
||||
algorithm to keep the actual DOM node as much as possible. However, this is
|
||||
sometimes not enough, and we need to help Owl decide if an element is actually
|
||||
the same, or is different. The `t-key` directive is used to give an identity to an element.
|
||||
|
||||
There are three main use cases:
|
||||
|
||||
- _elements in a list_:
|
||||
|
||||
```xml
|
||||
<span t-foreach="todos" t-as="todo" t-key="todo.id">
|
||||
<t t-esc="todo.text"/>
|
||||
</span>
|
||||
```
|
||||
|
||||
- _`t-if`/`t-else`_
|
||||
|
||||
- _animations_: give a different identity to a component. Ex: thread id with
|
||||
animations on add/remove message.
|
||||
|
||||
### `t-transition` directive
|
||||
|
||||
To perform useful transition effects, whenever an element appears or disappears,
|
||||
it is necessary to add/remove some css style or class at some precise moment in
|
||||
the lifetime of a node. Since this is not easy to do by hand, Owl `t-transition`
|
||||
directive is there to help.
|
||||
|
||||
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
||||
will happen:
|
||||
|
||||
At node insertion:
|
||||
|
||||
- the css classes `name-enter` and `name-enter-active` will be added directly
|
||||
when the node is inserted into the DOM,
|
||||
- on the next animation frame: the css class `name-enter` will be removed and the
|
||||
class `name-enter-to` will be added (so they can be used to trigger css
|
||||
transition effects),
|
||||
- the css class `name-enter-active` will be removed whenever a css transition
|
||||
ends.
|
||||
|
||||
At node destruction:
|
||||
|
||||
- the css classes `name-leave` and `name-leave-active` will be added before the
|
||||
node is removed to the DOM,
|
||||
- the css class `name-leave` will be removed on the next animation frame (so it
|
||||
can be used to trigger css transition effects),
|
||||
- the css class `name-leave-active` will be removed whenever a css transition
|
||||
ends. Only then will the element be removed from the DOM.
|
||||
|
||||
For example, a simple fade in/out effect can be done with this:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-if="state.flag" class="square" t-transition="fade">Hello</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
```css
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.5s;
|
||||
}
|
||||
.fade-enter,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
```
|
||||
|
||||
The `t-transition` directive can be combined with `t-widget`.
|
||||
|
||||
Notes:
|
||||
|
||||
- more information on animations are available [here](animations.md).
|
||||
- the value for `t-transition` must be a single class name. Owl does not support
|
||||
more than one transition on a single node.
|
||||
|
||||
### `t-mounted` directive
|
||||
|
||||
The `t-mounted` directive allows to register a callback to execute whenever the node
|
||||
is inserted into the DOM.
|
||||
|
||||
```xml
|
||||
<div><input t-ref="someInput" t-mounted="focusMe"/></div>
|
||||
```
|
||||
|
||||
```js
|
||||
class MyWidget extends owl.Component {
|
||||
...
|
||||
focusMe() {
|
||||
this.refs.someInput.focus();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Debugging (`t-debug` and `t-log`)
|
||||
|
||||
The javascript QWeb implementation provides two useful debugging directives:
|
||||
|
||||
`t-debug` adds a debugger statement during template rendering:
|
||||
|
||||
```xml
|
||||
<t t-if="a_test">
|
||||
<t t-debug="">
|
||||
</t>
|
||||
```
|
||||
|
||||
will stop execution if the browser dev tools are open.
|
||||
|
||||
`t-log` takes an expression parameter, evaluates the expression during rendering and logs its result with console.log:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="42"/>
|
||||
<t t-log="foo"/>
|
||||
```
|
||||
|
||||
will print 42 to the console
|
||||
|
||||
### White spaces
|
||||
|
||||
White spaces in a templates are handled in a special way:
|
||||
|
||||
- consecutive whitespaces are always condensed to a single whitespace
|
||||
- if a whitespace-only text node contains a linebreak, it is ignored
|
||||
- the previous rules do not apply if we are in a `<pre>` tag
|
||||
|
||||
### Root nodes
|
||||
|
||||
For many reasons, Owl QWeb templates should have a single root node. More
|
||||
precisely, the result of a template rendering should have a single root node:
|
||||
|
||||
```xml
|
||||
<!–– not ok: two root nodes ––>
|
||||
<t>
|
||||
<div>foo</div>
|
||||
<div>bar</div>
|
||||
</t>
|
||||
|
||||
<!–– ok: result has one single root node ––>
|
||||
<t>
|
||||
<div t-if="someCondition">foo</div>
|
||||
<span t-else="1">bar</span>
|
||||
</t>
|
||||
```
|
||||
|
||||
Extra root nodes will actually be ignored (even though they will be rendered
|
||||
in memory).
|
||||
|
||||
Note: this does not apply to subtemplates (see the `t-call` directive). In that
|
||||
case, they will be inlined in the main template, and can actually have many
|
||||
root nodes.
|
||||
+49
-11
@@ -1,17 +1,55 @@
|
||||
# 🦉 OWL Documentation 🦉
|
||||
|
||||
## Learning Owl
|
||||
|
||||
Are you new to Owl? This is the place to start!
|
||||
|
||||
- [Tutorial: create a TodoList application](learning/tutorial_todoapp.md)
|
||||
- [Quick Overview](learning/overview.md)
|
||||
- [How to start an Owl project](learning/quick_start.md)
|
||||
- [How to test Components](learning/how_to_test.md)
|
||||
- [How to write Single File Components](learning/how_to_write_sfc.md)
|
||||
- [How to write debug Owl applications](learning/how_to_debug.md)
|
||||
|
||||
## Reference
|
||||
|
||||
- [Component](component.md)
|
||||
- [QWeb](qweb.md)
|
||||
- [Store](store.md)
|
||||
- [Observer](observer.md)
|
||||
- [Virtual DOM](vdom.md)
|
||||
- [Utils](utils.md)
|
||||
You will find here a complete reference of every feature, class or object
|
||||
provided by Owl.
|
||||
|
||||
## Miscellaneous
|
||||
- [Quick Start](quick_start.md)
|
||||
- [Animations](animations.md)
|
||||
- [Tooling](tooling.md)
|
||||
- [Comparison with React/Vue](comparison.md)
|
||||
- [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)
|
||||
|
||||
## Other Topics
|
||||
|
||||
This section provides miscellaneous document that explains some topics
|
||||
which cannot be considered either a tutorial, or reference documentation.
|
||||
|
||||
- [Owl architecture: the Virtual DOM](miscellaneous/vdom.md)
|
||||
- [Owl architecture: the rendering pipeline](miscellaneous/rendering.md)
|
||||
- [Comparison with React/Vue](miscellaneous/comparison.md)
|
||||
- [Why did Odoo built Owl?](miscellaneous/why_owl.md)
|
||||
|
||||
---
|
||||
|
||||
Found an issue in the documentation? A broken link? Some outdated information?
|
||||
Please open an issue or submit a PR!
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# 🦉 Animations 🦉
|
||||
|
||||
Animation is a complex topic. There are many different use cases, and many
|
||||
solutions and technologies. Owl only supports some basic use cases.
|
||||
|
||||
## Simple CSS effects
|
||||
|
||||
Sometimes, using pure CSS is enough. For these use cases, Owl is not really
|
||||
necessary: it just needs to render a DOM element with a specific class. For
|
||||
example:
|
||||
|
||||
```xml
|
||||
<a class="btn flash" t-on-click="doSomething">Click</a>
|
||||
```
|
||||
|
||||
with the following CSS:
|
||||
|
||||
```css
|
||||
btn {
|
||||
background-color: gray;
|
||||
}
|
||||
|
||||
.flash {
|
||||
transition: background 0.5s;
|
||||
}
|
||||
|
||||
.flash:active {
|
||||
background-color: #41454a;
|
||||
transition: background 0s;
|
||||
}
|
||||
```
|
||||
|
||||
will produce a nice flash effect whenever the user clicks (or activates with the
|
||||
keyboard) the button.
|
||||
|
||||
## CSS Transitions
|
||||
|
||||
A more complex situation occurs when we want to transition an element in or out
|
||||
of the page. For example, we may want a fade-in and fade-out effect.
|
||||
|
||||
The `t-transition` directive is here to help us. It works on html elements and
|
||||
on components, by adding and removing some css classes.
|
||||
|
||||
To perform useful transition effects, whenever an element appears or disappears,
|
||||
it is necessary to add/remove some css style or class at some precise moment in
|
||||
the lifetime of a node. Since this is not easy to do by hand, Owl `t-transition`
|
||||
directive is there to help.
|
||||
|
||||
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
||||
sequence of events will happen:
|
||||
|
||||
At node insertion:
|
||||
|
||||
- the css classes `name-enter` and `name-enter-active` will be added directly
|
||||
when the node is inserted into the DOM,
|
||||
- on the next animation frame: the css class `name-enter` will be removed and the
|
||||
class `name-enter-to` will be added (so they can be used to trigger css
|
||||
transition effects),
|
||||
- the css class `name-enter-active` will be removed whenever a css transition
|
||||
ends.
|
||||
|
||||
At node destruction:
|
||||
|
||||
- the css classes `name-leave` and `name-leave-active` will be added before the
|
||||
node is removed to the DOM,
|
||||
- the css class `name-leave` will be removed on the next animation frame (so it
|
||||
can be used to trigger css transition effects),
|
||||
- the css class `name-leave-active` will be removed whenever a css transition
|
||||
ends. Only then will the element be removed from the DOM.
|
||||
|
||||
For example, a simple fade in/out effect can be done with this:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-if="state.flag" class="square" t-transition="fade">Hello</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
```css
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.5s;
|
||||
}
|
||||
.fade-enter,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
```
|
||||
|
||||
The `t-transition` directive can be applied on a node element or on a component.
|
||||
|
||||
Notes:
|
||||
|
||||
Owl does not support more than one transition on a single node, so the
|
||||
`t-transition` expression must be a single value (i.e. no space allowed).
|
||||
@@ -0,0 +1,820 @@
|
||||
# 🦉 OWL Component 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Reactive System](#reactive-system)
|
||||
- [Properties](#properties)
|
||||
- [Static Properties](#static-properties)
|
||||
- [Methods](#methods)
|
||||
- [Lifecycle](#lifecycle)
|
||||
- [Root Component](#root-component)
|
||||
- [Composition](#composition)
|
||||
- [Form Input Bindings](#form-input-bindings)
|
||||
- [References](#references)
|
||||
- [Dynamic sub components](#dynamic-sub-components)
|
||||
- [Functional Components](#functional-components)
|
||||
- [SVG components](#svg-components)
|
||||
|
||||
## Overview
|
||||
|
||||
OWL components are the building blocks for user interface. They are designed to be:
|
||||
|
||||
1. **declarative:** the user interface should be described in terms of the state
|
||||
of the application, not as a sequence of imperative steps.
|
||||
|
||||
2. **composable:** each component can seamlessly be created in a parent component by
|
||||
a simple tag or directive in its template.
|
||||
|
||||
3. **asynchronous rendering:** the framework will transparently wait for each
|
||||
sub components to be ready before applying the rendering. It uses native promises
|
||||
under the hood.
|
||||
|
||||
4. **uses QWeb as a template system:** the templates are described in XML
|
||||
and follow the QWeb specification. This is a requirement for Odoo.
|
||||
|
||||
OWL components are defined as a subclass of Component. The rendering is
|
||||
exclusively done by a [QWeb](qweb_templating_language.md) template (which needs to be preloaded in QWeb).
|
||||
Rendering a component generates a virtual dom representation
|
||||
of the component, which is then patched to the DOM, in order to apply the changes in an efficient way.
|
||||
|
||||
## Example
|
||||
|
||||
Let us have a look at a simple component:
|
||||
|
||||
```javascript
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class ClickCounter extends owl.Component {
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="ClickCounter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
Note that this code is written in ESNext style, so it will only run on the
|
||||
latest browsers without a transpilation step.
|
||||
|
||||
This example shows how a component should be defined: it simply subclasses the
|
||||
Component class. If no static `template` key is defined, then
|
||||
Owl will use the component's name as template name. Here,
|
||||
a state object is defined, by using the `useState` hook. It is not mandatory to use the state object, but it is certainly encouraged. The result of the `useState` call is
|
||||
[observed](observer.md), and any change to it will cause a rerendering.
|
||||
|
||||
## Reference
|
||||
|
||||
An Owl component is a small class which represents a component or some UI element.
|
||||
It exists in the context of an [environment](environment.md) (`env`), which is propagated from a
|
||||
parent to its children. The environment needs to have a [QWeb](qweb_templating_language.md) instance, which
|
||||
will be used to render the component template.
|
||||
|
||||
Be aware that the name of the component may be significant: if a component does
|
||||
not define a `template` key, then Owl will lookup in QWeb to
|
||||
find a template with the component name (or one of its ancestors).
|
||||
|
||||
### Reactive system
|
||||
|
||||
OWL components are normal javascript classes. So, changing a component internal
|
||||
state does nothing more:
|
||||
|
||||
```js
|
||||
class Counter extends Component {
|
||||
static template = xml`<div t-on-click="increment"><t t-esc="state.value"/></div>`;
|
||||
state = { value: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Clicking on the `Counter` component defined above will call the `increment`
|
||||
method, but it will not rerender the component. To fix that, one could add an
|
||||
explicit call to `render` in `increment`:
|
||||
|
||||
```js
|
||||
increment() {
|
||||
this.state.value++;
|
||||
this.render();
|
||||
}
|
||||
```
|
||||
|
||||
However, it may be simple in this case, but it quickly become cumbersome, as a
|
||||
component get more complex, and its internal state is modified by more than one
|
||||
method.
|
||||
|
||||
A better way is to use the reactive system: by using the `useState` hook (see the
|
||||
[hooks](hooks.md) section for more details), one can make Owl react to state
|
||||
changes. The `useState` hook generates a proxy version of an object
|
||||
(this is done by an [observer](observer.md)), which allows the component to
|
||||
react to any change. So, the `Counter` example above can be improved like this:
|
||||
|
||||
```js
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`<div t-on-click="increment"><t t-esc="state.value"/></div>`;
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Obviously, we can call the `useState` hook more than once:
|
||||
|
||||
```js
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-on-click="increment(counter1)"><t t-esc="counter1.value"/></span>
|
||||
<span t-on-click="increment(counter2)"><t t-esc="counter2.value"/></span>
|
||||
</div>`;
|
||||
counter1 = useState({ value: 0 });
|
||||
counter2 = useState({ value: 0 });
|
||||
|
||||
increment(counter) {
|
||||
counter.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that hooks are subject to one important [rule](hooks.md#one-rule): they need
|
||||
to be called in the constructor.
|
||||
|
||||
### Properties
|
||||
|
||||
- **`el`** (HTMLElement | null): reference to the DOM root node of the element. It is `null` when the
|
||||
component is not mounted.
|
||||
|
||||
- **`env`** (Object): the component [environment](environment.md), which contains a QWeb instance.
|
||||
|
||||
- **`props`** (Object): this is an object containing all the properties given by
|
||||
the parent to a child component. For example, in the following situation,
|
||||
the parent component gives a `user` and a `color` value to the `ChildComponent`.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<ChildComponent user="state.user" color="color">
|
||||
</div>
|
||||
```
|
||||
|
||||
Note that `props` are owned by the parent, not by the component.
|
||||
As such, it should not ever be modified by the component (otherwise you risk
|
||||
unintended effects, since the parent may not be aware of the change)!!
|
||||
|
||||
The `props` can be modified dynamically by the parent. In that case, the
|
||||
component will go through the following lifecycle methods: `willUpdateProps`,
|
||||
`willPatch` and `patched`.
|
||||
|
||||
### Static Properties
|
||||
|
||||
- **`template`** (string, optional): if given, this is the name of the QWeb template that will render the component. Note that there is a helper `xml` to
|
||||
make it easy to define an inline template.
|
||||
|
||||
* **`components`** (Object, optional): if given, this is an object that contains
|
||||
the classes of any sub components needed by the template. This is the main way
|
||||
used by Owl to be able to create sub components.
|
||||
|
||||
```js
|
||||
class ParentComponent extends owl.Component {
|
||||
static components = { SubComponent };
|
||||
}
|
||||
```
|
||||
|
||||
* **`props`** (Object, optional): if given, this is an object that describes the
|
||||
type and shape of the (actual) props given to the component. If Owl mode is
|
||||
`dev`, this will be used to validate the props each time the component is
|
||||
created/updated. See [Props Validation](props_validation.md) for more information.
|
||||
|
||||
```js
|
||||
class Counter extends owl.Component {
|
||||
static props = {
|
||||
initialValue: Number,
|
||||
optional: true,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- **`defaultProps`** (Object, optional): if given, this object define default
|
||||
values for (top-level) props. Whenever `props` are given to the object, they
|
||||
will be altered to add default value (if missing). Note that it does not
|
||||
change the initial object, a new object will be created instead.
|
||||
|
||||
```js
|
||||
class Counter extends owl.Component {
|
||||
static defaultProps = {
|
||||
initialValue: 0,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- **`style`** (string, optional): it should be the return value of the [`css` tag](tags.md#css-tag),
|
||||
which is used to inject stylesheet whenever the component is visible on the
|
||||
screen.
|
||||
|
||||
There is another static property defined on the `Component` class: `current`.
|
||||
This property is set to the currently being defined component (in the constructor).
|
||||
This is the way [hooks](hooks.md) are able to get a reference to the target
|
||||
component.
|
||||
|
||||
### Methods
|
||||
|
||||
We explain here all the public methods of the `Component` class.
|
||||
|
||||
- **`mount(target, options)`** (async): this is the main way a
|
||||
component is added to the DOM: the root component is mounted to a target
|
||||
HTMLElement (or document fragment). Obviously, this is asynchronous, since each children need to be
|
||||
created as well. Most applications will need to call `mount` exactly once, on
|
||||
the root component.
|
||||
|
||||
The `options` argument is an optional object with a `position` key. The
|
||||
`position` key can have three possible values: `first-child`, `last-child`, `self`.
|
||||
|
||||
- `first-child`: with this option, the component will be prepended inside the target,
|
||||
- `last-child` (default value): with this option, the component will be
|
||||
appended in the target element,
|
||||
- `self`: the target will be used as the root element for the component. This
|
||||
means that the target has to be an HTMLElement (and not a document fragment).
|
||||
In this situation, it is possible that the component cannot be unmounted. For
|
||||
example, if its target is `document.body`.
|
||||
|
||||
Note that if a component is mounted, unmounted and remounted, it will be
|
||||
automatically re-rendered to ensure that changes in its state (or something
|
||||
in the environment, or in the store, or ...) will be taken into account.
|
||||
|
||||
If a component is mounted inside an element or a fragment which is not in the
|
||||
DOM, then it will be rendered fully, but not active: the `mounted` hooks will
|
||||
not be called. This is sometimes useful if we want to load an application in
|
||||
memory. In that case, we need to mount the root component again in an element
|
||||
which is in the DOM:
|
||||
|
||||
```js
|
||||
const app = new App();
|
||||
await app.mount(document.createDocumentFragment());
|
||||
// app is rendered in memory, but not active
|
||||
await app.mount(document.body);
|
||||
// app is now visible
|
||||
```
|
||||
|
||||
* **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
||||
method can be used. Most applications should not call `unmount`, this is more
|
||||
useful to the underlying component system.
|
||||
|
||||
* **`render()`** (async): calling this method directly will cause a rerender. Note
|
||||
that this should be very rare to have to do it manually, the Owl framework is
|
||||
most of the time responsible for doing that at an appropriate moment.
|
||||
|
||||
Note that the render method is asynchronous, so one cannot observe the updated
|
||||
DOM in the same stack frame.
|
||||
|
||||
* **`shouldUpdate(nextProps)`**: this method is called each time a component's props
|
||||
are updated. It returns a boolean, which indicates if the component should
|
||||
ignore a props update. If it returns false, then `willUpdateProps` will not
|
||||
be called, and no rendering will occur. Its default implementation is to
|
||||
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
||||
can be useful if we are handling large number of components.
|
||||
|
||||
* **`destroy()`**. As its name suggests, this method will remove the component,
|
||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||
removing the parent/children relationship. This method should almost never be
|
||||
called directly (except maybe on the root component), but should be done by the
|
||||
framework instead.
|
||||
|
||||
Obviously, these methods are reserved for Owl, and should not be used by Owl
|
||||
users, unless they want to override them. Also, Owl reserves all method names
|
||||
starting with `__`, in order to prevent possible future conflicts with user code
|
||||
whenever Owl needs to change.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
A solid and robust component system needs useful hooks/methods to help
|
||||
developers write components. Here is a complete description of the lifecycle of
|
||||
a owl component:
|
||||
|
||||
| Method | Description |
|
||||
| ------------------------------------------------ | ----------------------------------------------------------- |
|
||||
| **[constructor](#constructorparent-props)** | constructor |
|
||||
| **[willStart](#willstart)** | async, before first rendering |
|
||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
||||
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
||||
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
||||
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
||||
| **[catchError](#catcherrorerror)** | catch errors (see [error handling page](error_handling.md)) |
|
||||
|
||||
Notes:
|
||||
|
||||
- hooks call order is precisely defined: `[willX]` hooks are called first on parent,
|
||||
then on children, and `[Xed]` are called in the reverse order: first children,
|
||||
then parent.
|
||||
- no hook method should ever be called manually. They are supposed to be
|
||||
called by the owl framework whenever it is required.
|
||||
|
||||
#### `constructor(parent, props)`
|
||||
|
||||
The constructor is not exactly a hook, it is the regular,
|
||||
normal, constructor of the component. Since it is not a hook, you need to make
|
||||
sure that `super` is called.
|
||||
|
||||
This is usually where you would set the initial state and the template of the
|
||||
component.
|
||||
|
||||
```javascript
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = useState({someValue: true});
|
||||
this.template = 'mytemplate';
|
||||
}
|
||||
```
|
||||
|
||||
Note that with ESNext class fields, the constructor method does not need to be
|
||||
implemented in most cases:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
state = useState({ value: 0 });
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
#### `willStart()`
|
||||
|
||||
willStart is an asynchronous hook that can be implemented to
|
||||
perform some action before the initial rendering of a component.
|
||||
|
||||
It will be called exactly once before the initial rendering. It is useful
|
||||
in some cases, for example, to load external assets (such as a JS library)
|
||||
before the component is rendered. Another use case is to load data from a server.
|
||||
|
||||
```javascript
|
||||
async willStart() {
|
||||
await owl.utils.loadJS("my-awesome-lib.js");
|
||||
}
|
||||
```
|
||||
|
||||
At this point, the component is not yet rendered. Note that a slow `willStart` method will slow down the rendering of the user
|
||||
interface. Therefore, some care should be made to make this method as
|
||||
fast as possible.
|
||||
|
||||
#### `mounted()`
|
||||
|
||||
`mounted` is called each time a component is attached to the
|
||||
DOM, after the initial rendering and possibly later if the component was unmounted
|
||||
and remounted. At this point, the component is considered _active_. This is a good place to add some listeners, or to interact with the
|
||||
DOM, if the component needs to perform some measure for example.
|
||||
|
||||
It is the opposite of `willUnmount`. If a component has been mounted, it will
|
||||
always be unmounted at some point in the future.
|
||||
|
||||
The mounted method will be called recursively on each of its children. First,
|
||||
the parent, then all its children.
|
||||
|
||||
It is allowed (but not encouraged) to modify the state in the `mounted` hook.
|
||||
Doing so will cause a rerender, which will not be perceptible by the user, but
|
||||
will slightly slow down the component.
|
||||
|
||||
#### `willUpdateProps(nextProps)`
|
||||
|
||||
The willUpdateProps is an asynchronous hook, called just before new props
|
||||
are set. This is useful if the component needs to perform an asynchronous task,
|
||||
depending on the props (for example, assuming that the props are
|
||||
some record Id, fetching the record data).
|
||||
|
||||
```javascript
|
||||
willUpdateProps(nextProps) {
|
||||
return this.loadData({id: nextProps.id});
|
||||
}
|
||||
```
|
||||
|
||||
This hook is not called during the first render (but willStart is called
|
||||
and performs a similar job).
|
||||
|
||||
#### `willPatch()`
|
||||
|
||||
The willPatch hook is called just before the DOM patching process starts.
|
||||
It is not called on the initial render. This is useful to read
|
||||
information from the DOM. For example, the current position of the
|
||||
scrollbar.
|
||||
|
||||
Note that modifying the state is not allowed here. This method is called just
|
||||
before an actual DOM patch, and is only intended to be used to save some local
|
||||
DOM state. Also, it will not be called if the component is not in the DOM.
|
||||
|
||||
#### `patched(snapshot)`
|
||||
|
||||
This hook is called whenever a component did actually update its DOM (most
|
||||
likely via a change in its state/props or environment).
|
||||
|
||||
This method is not called on the initial render. It is useful to interact
|
||||
with the DOM (for example, through an external library) whenever the
|
||||
component was patched. Note that this hook will not be called if the component is
|
||||
not in the DOM.
|
||||
|
||||
Updating the component state in this hook is possible, but not encouraged.
|
||||
One needs to be careful, because updates here will create an additional rendering, which in
|
||||
turn will cause other calls to the `patched` method. So, we need to be particularly
|
||||
careful at avoiding endless cycles.
|
||||
|
||||
#### `willUnmount()`
|
||||
|
||||
willUnmount is a hook that is called each time just before a component is unmounted from
|
||||
the DOM. This is a good place to remove listeners, for example.
|
||||
|
||||
```javascript
|
||||
mounted() {
|
||||
this.env.bus.on('someevent', this, this.doSomething);
|
||||
}
|
||||
willUnmount() {
|
||||
this.env.bus.off('someevent', this, this.doSomething);
|
||||
}
|
||||
```
|
||||
|
||||
This is the opposite method of `mounted`.
|
||||
|
||||
#### `catchError(error)`
|
||||
|
||||
The `catchError` method is useful when we need to intercept and properly react
|
||||
to (rendering) errors that occur in some sub components. See the page on
|
||||
[error handling](error_handling.md).
|
||||
|
||||
### Root Component
|
||||
|
||||
Most of the time, an Owl component will be created automatically by a tag (or the `t-component`
|
||||
directive) in a template. There is however an obvious exception: the root component
|
||||
of an Owl application has to be created manually:
|
||||
|
||||
```js
|
||||
class App extends owl.Component { ... }
|
||||
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
The root component does not have a parent nor `props` (see note below). It will be setup with an
|
||||
[environment](environment.md) (either the `env` defined on its class, or a
|
||||
default empty environment).
|
||||
|
||||
Note: a root component can however be given a `props` object in its constructor,
|
||||
like this: `new App(null, {some: 'object'});`. It will not be a true `props`
|
||||
object, managed by Owl (so, for example, it will never be updated).
|
||||
|
||||
### Composition
|
||||
|
||||
The example above shows a QWeb template with a sub component. In a template,
|
||||
components are declared with a tagname corresponding to the class name. It has
|
||||
to be capitalized.
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<span>some text</span>
|
||||
<MyComponent info="13" />
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentComponent extends owl.Component {
|
||||
static components = { MyComponent: MyComponent};
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the `ParentComponent`'s template creates a component `MyComponent` just
|
||||
after the span. The `info` key will be added to the subcomponent's `props`. Each
|
||||
`props` is a string which represents a javascript (QWeb) expression, so it is
|
||||
dynamic. If it is necessary to give a string, this can be done by quoting it:
|
||||
`someString="'somevalue'"`.
|
||||
|
||||
Note that the rendering context for the template is the component itself. This means
|
||||
that the template can access `state` (if it exists), `props`, `env`, or any
|
||||
methods defined in the component.
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<ChildComponent count="state.val" />
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
static components = { ChildComponent };
|
||||
state = useState({ val: 4 });
|
||||
}
|
||||
```
|
||||
|
||||
Whenever the template is rendered, it will automatically create the subcomponent
|
||||
`ChildComponent` at the correct place. It needs to find the reference to the
|
||||
actual component class in the special static `components` key, or the class registered in
|
||||
QWeb's global registry (see `register` function of QWeb). It first looks inside
|
||||
the static `components` key, then fallbacks on the global registry.
|
||||
|
||||
_Props_: In this example, the child component will receive the object `{count: 4}` in its
|
||||
constructor. This will be assigned to the `props` variable, which can be accessed
|
||||
on the component (and also, in the template). Whenever the state is updated, then
|
||||
the sub component will also be updated automatically. See the [props section](props.md)
|
||||
for more information.
|
||||
|
||||
**CSS and style:** Owl allows the parent to declare
|
||||
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||
root component element.
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<MyComponent class="someClass" style="font-weight:bold;" info="13" />
|
||||
</div>
|
||||
```
|
||||
|
||||
Warning: there is a small caveat with dynamic class attributes: since Owl needs
|
||||
to be able to add/remove proper classes whenever necessary, it needs to be aware
|
||||
of the possible classes. Otherwise, it will not be able to make the difference
|
||||
between a valid css class added by the component, or other custom code, and a
|
||||
class that need to be removed. This is why we only support the explicit syntax
|
||||
with a class object:
|
||||
|
||||
```xml
|
||||
<MyComponent t-att-class="{a: state.flagA, b: state.flagB}" />
|
||||
```
|
||||
|
||||
### Form Input Bindings
|
||||
|
||||
It is very common to need to be able to read the value out of an html `input` (or
|
||||
`textarea`, or `select`) in order to use it (note: it does not need to be in a
|
||||
form!). A possible way to do this is to do it by hand:
|
||||
|
||||
```js
|
||||
class Form extends owl.Component {
|
||||
state = useState({ text: "" });
|
||||
|
||||
_updateInputValue(event) {
|
||||
this.state.text = event.target.value;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<input t-on-input="_updateInputValue" />
|
||||
<span t-esc="state.text" />
|
||||
</div>
|
||||
```
|
||||
|
||||
This works. However, this requires a little bit of _plumbing_ code. Also, the
|
||||
plumbing code is slightly different if you need to interact with a checkbox,
|
||||
or with radio buttons, or with select tags.
|
||||
|
||||
To help with this situation, Owl has a builtin directive `t-model`: its value
|
||||
should be an observed value in the component (usually `state.someValue`). With
|
||||
the `t-model` directive, we can write a shorter code, equivalent to the previous
|
||||
example:
|
||||
|
||||
```js
|
||||
class Form extends owl.Component {
|
||||
state = { text: "" };
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<input t-model="state.text" />
|
||||
<span t-esc="state.text" />
|
||||
</div>
|
||||
```
|
||||
|
||||
The `t-model` directive works with `<input>`, `<input type="checkbox">`,
|
||||
`<input type="radio">`, `<textarea>` and `<select>`:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div>Text in an input: <input t-model="state.someVal"/></div>
|
||||
<div>Textarea: <textarea t-model="state.otherVal"/></div>
|
||||
<div>Boolean value: <input type="checkbox" t-model="state.someFlag"/></div>
|
||||
<div>Selection:
|
||||
<select t-model="state.color">
|
||||
<option value="">Select a color</option>
|
||||
<option value="red">Red</option>
|
||||
<option value="blue">Blue</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
Selection with radio buttons:
|
||||
<span>
|
||||
<input type="radio" name="color" id="red" value="red" t-model="state.color"/>
|
||||
<label for="red">Red</label>
|
||||
</span>
|
||||
<span>
|
||||
<input type="radio" name="color" id="blue" value="blue" t-model="state.color" />
|
||||
<label for="blue">Blue</label>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
Like event handling, the `t-model` directive accepts the following modifiers:
|
||||
|
||||
| Modifier | Description |
|
||||
| --------- | -------------------------------------------------------------------- |
|
||||
| `.lazy` | update the value on the `change` event (default is on `input` event) |
|
||||
| `.number` | try to parse the value to a number (using `parseFloat`) |
|
||||
| `.trim` | trim the resulting value |
|
||||
|
||||
For example:
|
||||
|
||||
```xml
|
||||
<input t-model.lazy="state.someVal" />
|
||||
```
|
||||
|
||||
These modifiers can be combined. For instance, `t-model.lazy.number` will only
|
||||
update a number whenever the change is done.
|
||||
|
||||
Note: the online playground has an example to show how it works.
|
||||
|
||||
### References
|
||||
|
||||
The `useRef` hook is useful when we need a way to interact with some inside part
|
||||
of a component, rendered by Owl. It can work either on a DOM node, or on a component,
|
||||
tagged by the `t-ref` directive. See the [hooks section](hooks.md#useref) for
|
||||
more detail.
|
||||
|
||||
As a short example, here is how we could set the focus on a given input:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<input t-ref="input"/>
|
||||
<button t-on-click="focusInput">Click</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
import { useRef } from "owl/hooks";
|
||||
|
||||
class SomeComponent extends Component {
|
||||
inputRef = useRef("input");
|
||||
|
||||
focusInput() {
|
||||
this.inputRef.el.focus();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `useRef` hook can also be used to get a reference to an instance of a sub
|
||||
component rendered by Owl. In that case, we need to access it with the `comp`
|
||||
property instead of `el`:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<SubComponent t-ref="sub"/>
|
||||
<button t-on-click="doSomething">Click</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
import { useRef } from "owl/hooks";
|
||||
|
||||
class SomeComponent extends Component {
|
||||
static components = { SubComponent };
|
||||
subRef = useRef("sub");
|
||||
|
||||
doSomething() {
|
||||
this.subRef.comp.doSomeThingElse();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that these two examples uses the suffix `ref` to name the reference. This
|
||||
is not mandatory, but it is a useful convention, so we do not forget to access
|
||||
it with the `el` or `comp` suffix.
|
||||
|
||||
### Dynamic sub components
|
||||
|
||||
It is not common, but sometimes we need a dynamic component name. In this case,
|
||||
the `t-component` directive can also be used to accept dynamic values with string interpolation (like the [`t-attf-`](qweb_templating_language.md#dynamic-attributes) directive):
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<t t-component="ChildComponent{{id}}" />
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
static components = { ChildComponent1, ChildComponent2 };
|
||||
state = { id: 1 };
|
||||
}
|
||||
```
|
||||
|
||||
There is an even more dynamic way to use `t-component`: its value can be an
|
||||
expression evaluating to an actual component class. In that case, this is the
|
||||
class that will be used to create the component:
|
||||
|
||||
```js
|
||||
class A extends Component<any, any, any> {
|
||||
static template = xml`<span>child a</span>`;
|
||||
}
|
||||
class B extends Component<any, any, any> {
|
||||
static template = xml`<span>child b</span>`;
|
||||
}
|
||||
class App extends Component<any, any, any> {
|
||||
static template = xml`<t t-component="myComponent" t-key="state.child"/>`;
|
||||
|
||||
state = { child: "a" };
|
||||
|
||||
get myComponent() {
|
||||
return this.state.child === "a" ? A : B;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the component `App` selects dynamically the concrete sub
|
||||
component class.
|
||||
|
||||
Note that the `t-component` directive can only be used on `<t>` nodes.
|
||||
|
||||
### Functional Components
|
||||
|
||||
Owl does not exactly have functional components. However, there is an extremely
|
||||
close alternative: calling sub templates.
|
||||
|
||||
A stateless functional component in react is usually some kind of function that
|
||||
maps props to a virtual dom (often with `jsx`). So, basically, almost like a
|
||||
template rendered with `props`. In Owl, this can be done by
|
||||
simply defining a template, that will access the `props` object:
|
||||
|
||||
```js
|
||||
const Welcome = xml`<h1>Hello, {props.name}</h1>`;
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<t t-call=${Welcome}/>
|
||||
<div>something</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
```
|
||||
|
||||
The way this works is that sub templates are inlined, and have access to the
|
||||
ambient context. They can therefore access `props`, and any other part of the
|
||||
caller component.
|
||||
|
||||
### SVG Components
|
||||
|
||||
Owl components can be used to generate dynamic SVG graphs:
|
||||
|
||||
```js
|
||||
class Node extends Component {
|
||||
static template = xml`
|
||||
<g>
|
||||
<circle t-att-cx="props.x" t-att-cy="props.y" r="4" fill="black"/>
|
||||
<text t-att-x="props.x - 5" t-att-y="props.y + 18"><t t-esc="props.node.label"/></text>
|
||||
<t t-set="childx" t-value="props.x + 100"/>
|
||||
<t t-set="height" t-value="props.height/(props.node.children || []).length"/>
|
||||
<t t-foreach="props.node.children || []" t-as="child">
|
||||
<t t-set="childy" t-value="props.y + child_index*height"/>
|
||||
<line t-att-x1="props.x" t-att-y1="props.y" t-att-x2="childx" t-att-y2="childy" stroke="black" />
|
||||
<Node x="childx" y="childy" node="child" height="height"/>
|
||||
</t>
|
||||
</g>
|
||||
`;
|
||||
static components = { Node };
|
||||
}
|
||||
|
||||
class RootNode extends Component {
|
||||
static template = xml`
|
||||
<svg height="180">
|
||||
<Node node="graph" x="10" y="20" height="180"/>
|
||||
</svg>
|
||||
`;
|
||||
static components = { Node };
|
||||
graph = {
|
||||
label: "a",
|
||||
children: [
|
||||
{ label: "b" },
|
||||
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
||||
{ label: "f", children: [{ label: "g" }] },
|
||||
],
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This `RootNode` component will then display a live SVG representation of the
|
||||
graph described by the `graph` property. Note that there is a recursive structure
|
||||
here: the `Node` component uses itself as a subcomponent.
|
||||
|
||||
Note that since SVG needs to be handled in a specific way (its namespace needs
|
||||
to be properly set), there is a small constraint for Owl components: if an owl
|
||||
component is supposed to be a part of an svg graph, then its root node needs to
|
||||
be a `g` tag, so Owl can properly set the namespace.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,105 @@
|
||||
# 🦉 Context 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [`Context`](#context)
|
||||
- [`useContext`](#usecontext)
|
||||
|
||||
## Overview
|
||||
|
||||
The `Context` object provides a way to share data between an arbitrary number
|
||||
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
|
||||
annoying, since each component will need to pass the information to each children,
|
||||
even though some or most of them will not use the information.
|
||||
|
||||
With a `Context` object, each component can subscribe (with the `useContext` hook)
|
||||
to its state, and will be updated whenever the context state is updated.
|
||||
|
||||
## Example
|
||||
|
||||
Assume that we have an application with various components which needs to render
|
||||
differently depending on the size of the device. Here is how we could proceed
|
||||
to make sure that the information is properly shared. First, let us create a
|
||||
context, and add it to the environment:
|
||||
|
||||
```js
|
||||
const deviceContext = new Context({ isMobile: true });
|
||||
App.env.deviceContext = deviceContext;
|
||||
```
|
||||
|
||||
If we want to make it completely responsive, we need to update its value whenever
|
||||
the size of the screen is updated:
|
||||
|
||||
```js
|
||||
const isMobile = () => window.innerWidth <= 768;
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
owl.utils.debounce(() => {
|
||||
const state = deviceContext.state;
|
||||
if (state.isMobile !== isMobile()) {
|
||||
state.isMobile = !state.isMobile;
|
||||
}
|
||||
}, 15)
|
||||
);
|
||||
```
|
||||
|
||||
Then, each component that want can subscribe and render differently depending on the
|
||||
fact that we are in a mobile or desktop mode.
|
||||
|
||||
```js
|
||||
class SomeComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<t t-if=device.isMobile>
|
||||
some simplified user interface
|
||||
</t>
|
||||
<t t-else="">
|
||||
a more advanced user interface
|
||||
</t>
|
||||
</div>`;
|
||||
device = useContext(this.env.deviceContext);
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
### `Context`
|
||||
|
||||
A `Context` object should be created with a state object:
|
||||
|
||||
```js
|
||||
const someContext = new Context({ some: "key" });
|
||||
```
|
||||
|
||||
Its state is now available in the `state` key:
|
||||
|
||||
```js
|
||||
someContext.state.some = "other key";
|
||||
```
|
||||
|
||||
This is the way some global code (such as the responsive code above) should
|
||||
read and update the context state. However, components should not ever read the
|
||||
context state directly from the context, they should instead use the `useContext`
|
||||
hook to properly register themselves to state changes.
|
||||
|
||||
Note that the `Context` hook is different from the React version. For example,
|
||||
there is no concept of provider/consumer. So, the `Context` feature does not
|
||||
by itself allow the use of a different context state depending on the component
|
||||
place in the component tree. However, this functionality can be obtained, if
|
||||
necessary, with the use of sub environment.
|
||||
|
||||
### `useContext`
|
||||
|
||||
The `useContext` hook is the normal way for a component to register themselve
|
||||
to context state changes. The `useContext` method returns the context state:
|
||||
|
||||
```js
|
||||
device = useContext(this.env.deviceContext);
|
||||
```
|
||||
|
||||
It is a simple observed state (with an owl `Observer`), which contains the shared
|
||||
information.
|
||||
@@ -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
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# 🦉 Event Bus 🦉
|
||||
|
||||
It is sometimes useful to use a `Bus` to communicate informations between various
|
||||
parts of the code. Owl has a very simple bus class, which manages subscriptions,
|
||||
triggering events, and callbacks.
|
||||
|
||||
```js
|
||||
const bus = new owl.core.EventBus();
|
||||
|
||||
bus.on("some-event", null, function (...args) {
|
||||
console.log(...args);
|
||||
});
|
||||
|
||||
bus.trigger("some-event", 1, 2, 3);
|
||||
// [1,2,3] will be logged to the console
|
||||
```
|
||||
|
||||
Its API is:
|
||||
|
||||
| Method | Description |
|
||||
| -------------------------------- | --------------------------------- |
|
||||
| `on(eventType, owner, callback)` | add a listener |
|
||||
| `off(eventType, owner)` | remove all listeners for an owner |
|
||||
| `trigger(eventType, ...args)` | trigger an event |
|
||||
| `clear` | remove all subscriptions |
|
||||
|
||||
Note that the [`Store`](store.md) is an example of an `EventBus`.
|
||||
@@ -0,0 +1,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.
|
||||
@@ -0,0 +1,447 @@
|
||||
# 🦉 Hooks 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example: Mouse Position](#example-mouse-position)
|
||||
- [Example: Autofocus](#example-autofocus)
|
||||
- [Reference](#reference)
|
||||
- [One Rule](#one-rule)
|
||||
- [`useState`](#usestate)
|
||||
- [`onMounted`](#onmounted)
|
||||
- [`onWillUnmount`](#onwillunmount)
|
||||
- [`onWillPatch`](#onwillpatch)
|
||||
- [`onPatched`](#onpatched)
|
||||
- [`onWillStart`](#onwillstart)
|
||||
- [`onWillUpdateProps`](#onwillupdateprops)
|
||||
- [`useContext`](#usecontext)
|
||||
- [`useRef`](#useref)
|
||||
- [`useSubEnv`](#usesubenv)
|
||||
- [`useExternalListener`](#useexternallistener)
|
||||
- [`useStore`](#usestore)
|
||||
- [`useDispatch`](#usedispatch)
|
||||
- [`useGetters`](#usegetters)
|
||||
- [Making customized hooks](#making-customized-hooks)
|
||||
|
||||
## Overview
|
||||
|
||||
Hooks were popularised by React as a way to solve the following issues:
|
||||
|
||||
- help reusing stateful logic between components
|
||||
- help organizing code by feature in complex components
|
||||
- use state in functional components, without writing a class.
|
||||
|
||||
Owl hooks serve the same purpose, except that they work for class components
|
||||
(note: React hooks do not work on class components, and maybe because of that,
|
||||
there seems to be the misconception that hooks are in opposition to class. This
|
||||
is clearly not true, as shown by Owl hooks).
|
||||
|
||||
Hooks work beautifully with Owl components: they solve the problems mentioned
|
||||
above, and in particular, they are the perfect way to make your component
|
||||
reactive.
|
||||
|
||||
## Example: mouse position
|
||||
|
||||
Here is the classical example of a non trivial hook to track the mouse position.
|
||||
|
||||
```js
|
||||
const { useState, onMounted, onWillUnmount } = owl.hooks;
|
||||
|
||||
// We define here a custom behaviour: this hook tracks the state of the mouse
|
||||
// position
|
||||
function useMouse() {
|
||||
const position = useState({ x: 0, y: 0 });
|
||||
|
||||
function update(e) {
|
||||
position.x = e.clientX;
|
||||
position.y = e.clientY;
|
||||
}
|
||||
onMounted(() => {
|
||||
window.addEventListener("mousemove", update);
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
window.removeEventListener("mousemove", update);
|
||||
});
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
static template = xml`
|
||||
<div t-name="App">
|
||||
<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>
|
||||
</div>`;
|
||||
|
||||
// this hooks is bound to the 'mouse' property.
|
||||
mouse = useMouse();
|
||||
}
|
||||
```
|
||||
|
||||
Note that we use the prefix `use` for hooks, just like in React. This is just
|
||||
a convention.
|
||||
|
||||
## Example: autofocus
|
||||
|
||||
Hooks can be combined to create the desired effect. For example, the following
|
||||
hook combines the `useRef` hook with the `onPatched` and `onMounted` functions
|
||||
to create an easy way to focus an input whenever it appears in the DOM:
|
||||
|
||||
```js
|
||||
function useAutofocus(name) {
|
||||
let ref = useRef(name);
|
||||
let isInDom = false;
|
||||
function updateFocus() {
|
||||
if (!isInDom && ref.el) {
|
||||
isInDom = true;
|
||||
ref.el.focus();
|
||||
} else if (isInDom && !ref.el) {
|
||||
isInDom = false;
|
||||
}
|
||||
}
|
||||
onPatched(updateFocus);
|
||||
onMounted(updateFocus);
|
||||
}
|
||||
```
|
||||
|
||||
This hook takes the name of a valid `t-ref` directive, which should be present
|
||||
in the template. It then checks whenever the component is mounted or patched if
|
||||
the reference is not valid, and in this case, it will focus the node element.
|
||||
This hook can be used like this:
|
||||
|
||||
```js
|
||||
class SomeComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<input />
|
||||
<input t-ref="myinput"/>
|
||||
</div>`;
|
||||
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
useAutofocus("myinput");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
### One rule
|
||||
|
||||
There is only one rule: every hook for a component has to be called in the
|
||||
constructor (or in class fields):
|
||||
|
||||
```js
|
||||
// ok
|
||||
class SomeComponent extends Component {
|
||||
state = useState({ value: 0 });
|
||||
}
|
||||
|
||||
// also ok
|
||||
class SomeComponent extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
// not ok: this is executed after the constructor is called
|
||||
class SomeComponent extends Component {
|
||||
async willStart() {
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
As you can see, the `useState` hook does not need to be given a reference to
|
||||
the component. This is possible because there is a way to get a reference to the
|
||||
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`
|
||||
|
||||
The `useState` hook is certainly the most important hook for Owl components:
|
||||
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
|
||||
an observed version of it (using a `Proxy`).
|
||||
|
||||
```javascript
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends owl.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++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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` 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
|
||||
is mounted (see example on top of this page).
|
||||
|
||||
### `onWillUnmount`
|
||||
|
||||
`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
|
||||
is unmounted (see example on top of this page).
|
||||
|
||||
### `onWillPatch`
|
||||
|
||||
`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
|
||||
before the component patched.
|
||||
|
||||
### `onPatched`
|
||||
|
||||
`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
|
||||
after the component patched.
|
||||
|
||||
### `onWillStart`
|
||||
|
||||
`onWillStart` is an asynchronous hook. This means that the function registered
|
||||
in the hook will be run just before the component is first rendered and can return a
|
||||
promise, to express the fact that it is an asynchronous operation.
|
||||
|
||||
Note that if there are more than one `onWillStart` registered callback, then they
|
||||
will all be run in parallel.
|
||||
|
||||
It can be used to load some initial data. For example, the following hook will
|
||||
automatically load some data from the server, and return an object that will
|
||||
be ready whenever the component is rendered:
|
||||
|
||||
```js
|
||||
function useLoader() {
|
||||
const component = Component.current;
|
||||
const record = useState({});
|
||||
onWillStart(async () => {
|
||||
const recordId = component.props.id;
|
||||
Object.assign(record, await fetchSomeRecord(recordId));
|
||||
});
|
||||
return record;
|
||||
}
|
||||
```
|
||||
|
||||
Note that this example does not update the record value whenever props are
|
||||
updated. For that situation, we need to use the `onWillUpdateProps` hook.
|
||||
|
||||
### `onWillUpdateProps`
|
||||
|
||||
Just like `onWillStart`, `onWillUpdateProps` is an asynchronous hook. It is
|
||||
designed to be run whenever the component props are updated. This could be
|
||||
useful to perform some asynchronous task such as fetching updated data.
|
||||
|
||||
```js
|
||||
function useLoader() {
|
||||
const component = Component.current;
|
||||
const record = useState({});
|
||||
|
||||
async function updateRecord(id) {
|
||||
Object.assign(record, await fetchSomeRecord(id));
|
||||
}
|
||||
|
||||
onWillStart(() => updateRecord(component.props.id));
|
||||
onWillUpdateProps((nextProps) => updateRecord(nextProps.id));
|
||||
|
||||
return record;
|
||||
}
|
||||
```
|
||||
|
||||
Note that if there are more than one `onWillUpdateProps` registered callback,
|
||||
then they will all be run in parallel.
|
||||
|
||||
### `useContext`
|
||||
|
||||
See [`useContext`](context.md#usecontext) for reference documentation.
|
||||
|
||||
### `useRef`
|
||||
|
||||
The `useRef` hook is useful when we need a way to interact with some inside part
|
||||
of a component, rendered by Owl. It can work either on a DOM node, or on a component,
|
||||
tagged by the `t-ref` directive:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-ref="someDiv"/>
|
||||
<SubComponent t-ref="someComponent"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
In this example, the component will be able to access the `div` and the component
|
||||
`SubComponent` using the `useRef` hook:
|
||||
|
||||
```js
|
||||
class Parent extends Component {
|
||||
subRef = useRef("someComponent");
|
||||
divRef = useRef("someDiv");
|
||||
|
||||
someMethod() {
|
||||
// here, if component is mounted, refs are active:
|
||||
// - this.divRef.el is the div HTMLElement
|
||||
// - 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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
As shown by the example above, html elements are accessed by using the `el`
|
||||
key, and components references are accessed with `comp`.
|
||||
|
||||
Notes:
|
||||
|
||||
- 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
|
||||
(like the [`t-attf-`](qweb_templating_language.md#dynamic-attributes) and
|
||||
`t-component` directives). For example,
|
||||
|
||||
```xml
|
||||
<div t-ref="component_{{someCondition ? '1' : '2'}}"/>
|
||||
```
|
||||
|
||||
Here, the references need to be set like this:
|
||||
|
||||
```js
|
||||
this.ref1 = useRef("component_1");
|
||||
this.ref2 = useRef("component_2");
|
||||
```
|
||||
|
||||
References are only guaranteed to be active while the parent component is mounted.
|
||||
If this is not the case, accessing `el` or `comp` on it will return `null`.
|
||||
|
||||
### `useSubEnv`
|
||||
|
||||
The environment is sometimes useful to share some common information between
|
||||
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
|
||||
`model` object available to all sub components, but not to the whole application.
|
||||
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
|
||||
can access it:
|
||||
|
||||
```js
|
||||
class FormComponent extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
const model = makeModel();
|
||||
useSubEnv({ model });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `useSubEnv` takes one argument: an object which contains some key/value that
|
||||
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
|
||||
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`
|
||||
|
||||
The `useStore` hook is the entry point for a component to connect to the store.
|
||||
See the [store documentation](store.md) for more information.
|
||||
|
||||
### `useDispatch`
|
||||
|
||||
The `useDispatch` hook is the way for components to get a reference to the store
|
||||
`dispatch` function. See the [store documentation](store.md) for more information.
|
||||
|
||||
### `useGetters`
|
||||
|
||||
The `useGetters` hook is the way for components to get a reference to the store
|
||||
getters. See the [store documentation](store.md) for more information.
|
||||
|
||||
### Making customized hooks
|
||||
|
||||
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
|
||||
easily composed together.
|
||||
|
||||
But, like every good things in life, hooks should be used with moderation. They are
|
||||
not the solution to every problem.
|
||||
|
||||
- they may be overkill: if your component needs to perform some action specific
|
||||
to itself (so, the specific code does not need to be shared), there is nothing
|
||||
wrong with a simple class method:
|
||||
|
||||
```js
|
||||
// maybe overkill
|
||||
class A extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
useMySpecificHook();
|
||||
}
|
||||
}
|
||||
|
||||
// ok
|
||||
class B extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.performSpecificTask();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that the second solution is easier to extend in sub components.
|
||||
|
||||
- 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
|
||||
manipulation. For example, assume that we want to give a reference to a
|
||||
router in a `useRouter` hook. We could do this:
|
||||
|
||||
```js
|
||||
const router = new Router(...);
|
||||
|
||||
function useRouter() {
|
||||
return router;
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
A better way would be to do something like this: get the reference from the
|
||||
environment.
|
||||
|
||||
```js
|
||||
function useRouter() {
|
||||
return Component.current.env.router;
|
||||
}
|
||||
```
|
||||
|
||||
This means that we give control to the application developer to create the
|
||||
router, which is good, so they can set it up, subclass it, ... And then, to
|
||||
test our components, we can just add a mock router in the environment.
|
||||
|
||||
Note: the code above makes use of the `Component.current` property. This is the
|
||||
way hooks are able to get a reference to the component currently being created.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,548 @@
|
||||
# 🦉 QWeb Templating Language🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Directives](#directives)
|
||||
- [Reference](#reference)
|
||||
- [White Spaces](#white-spaces)
|
||||
- [Root Nodes](#root-nodes)
|
||||
- [Expression Evaluation](#expression-evaluation)
|
||||
- [Static html Nodes](#static-html-nodes)
|
||||
- [Outputting Data](#outputting-data)
|
||||
- [Setting Variables](#setting-variables)
|
||||
- [Conditionals](#conditionals)
|
||||
- [Dynamic Attributes](#dynamic-attributes)
|
||||
- [Loops](#loops)
|
||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||
- [Translations](#translations)
|
||||
- [Debugging](#debugging)
|
||||
|
||||
## Overview
|
||||
|
||||
[QWeb](https://www.odoo.com/documentation/13.0/reference/qweb.html) is the primary
|
||||
templating engine used by Odoo. It is based on the XML format, and used
|
||||
mostly to generate HTML. In OWL, QWeb templates are compiled into functions that
|
||||
generate a virtual dom representation of the HTML.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<span t-if="somecondition">Some string</span>
|
||||
<ul t-else="">
|
||||
<li t-foreach="messages" t-as="message">
|
||||
<t t-esc="message"/>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
We present in this section the templating language, including its Owl specific
|
||||
extensions.
|
||||
|
||||
## Directives
|
||||
|
||||
For reference, here is a list of all standard QWeb directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------------ | -------------------------------------------------------------- |
|
||||
| `t-esc` | [Outputting safely a value](#outputting-data) |
|
||||
| `t-raw` | [Outputting value, without escaping](#outputting-data) |
|
||||
| `t-set`, `t-value` | [Setting variables](#setting-variables) |
|
||||
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
|
||||
| `t-foreach`, `t-as` | [Loops](#loops) |
|
||||
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
||||
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
||||
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
||||
| `t-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
|
||||
needs. Here is a list of all Owl specific directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------ | ------------------------------------------------------------------------------- |
|
||||
| `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-key` | [Defining a key (to help virtual dom reconciliation)](#loops) |
|
||||
| `t-on-*` | [Event handling](event_handling.md) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-slot` | [Rendering a slot](slots.md) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
|
||||
## Reference
|
||||
|
||||
### White Spaces
|
||||
|
||||
White spaces in a template are handled in a special way:
|
||||
|
||||
- consecutive whitespaces are always condensed to a single whitespace
|
||||
- if a whitespace-only text node contains a linebreak, it is ignored
|
||||
- the previous rules do not apply if we are in a `<pre>` tag
|
||||
|
||||
### Root Nodes
|
||||
|
||||
For many reasons, Owl QWeb templates should have a single root node. More
|
||||
precisely, the result of a template rendering should have a single root node:
|
||||
|
||||
```xml
|
||||
<!–– not ok: two root nodes ––>
|
||||
<t>
|
||||
<div>foo</div>
|
||||
<div>bar</div>
|
||||
</t>
|
||||
|
||||
<!–– ok: result has one single root node ––>
|
||||
<t>
|
||||
<div t-if="someCondition">foo</div>
|
||||
<span t-else="">bar</span>
|
||||
</t>
|
||||
```
|
||||
|
||||
Extra root nodes will actually be ignored (even though they will be rendered
|
||||
in memory).
|
||||
|
||||
Note: this does not apply to subtemplates (see the `t-call` directive). In that
|
||||
case, they will be inlined in the main template, and can actually have many
|
||||
root nodes.
|
||||
|
||||
### Expression Evaluation
|
||||
|
||||
QWeb expressions are strings that will be processed at compile time. Each variable in
|
||||
the javascript expression will be replaced with a lookup in the context (so, the
|
||||
component). For example, `a + b.c(d)` will be converted into:
|
||||
|
||||
```js
|
||||
context["a"] + context["b"].c(context["d"]);
|
||||
```
|
||||
|
||||
It is useful to explain the various rules that apply on these expressions:
|
||||
|
||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||
|
||||
```xml
|
||||
<div><p t-if="1 + 2 === 3">ok</p></div>
|
||||
```
|
||||
|
||||
is valid, but the following is not valid:
|
||||
|
||||
```xml
|
||||
<div><p t-if="console.log(1)">NOT valid</p></div>
|
||||
```
|
||||
|
||||
2. it can use anything in the rendering context (typically, the component):
|
||||
|
||||
```xml
|
||||
<p t-if="user.birthday === today()">Happy bithday!</p>
|
||||
```
|
||||
|
||||
is valid, and will read the `user` object from the context, and call the
|
||||
`today` function.
|
||||
|
||||
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
||||
`&` or `|`. This is useful to make sure that we still write valid XML.
|
||||
|
||||
| Word | replaced with |
|
||||
| ----- | ------------- |
|
||||
| `and` | `&&` |
|
||||
| `or` | `\|\|` |
|
||||
| `gt` | `>` |
|
||||
| `gte` | `>=` |
|
||||
| `lt` | `<` |
|
||||
| `lte` | `<=` |
|
||||
|
||||
So, one can write this:
|
||||
|
||||
```xml
|
||||
<div><p t-if="10 + 2 gt 5">ok</p></div>
|
||||
```
|
||||
|
||||
### Static Html Nodes
|
||||
|
||||
Normal, regular html nodes are rendered into themselves:
|
||||
|
||||
```xml
|
||||
<div>hello</div> <!–– rendered as itself ––>
|
||||
```
|
||||
|
||||
### Outputting Data
|
||||
|
||||
The `t-esc` directive is necessary whenever you want to add a dynamic text
|
||||
expression in a template. The text is escaped to avoid security issues.
|
||||
|
||||
```xml
|
||||
<p><t t-esc="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `42` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p>42</p>
|
||||
```
|
||||
|
||||
The `t-raw` directive is almost the same as `t-esc`, but without the escaping.
|
||||
This is mostly useful to inject a raw html string somewhere. Obviously, this
|
||||
is unsafe to do in general, and should only be used for strings known to be safe.
|
||||
|
||||
```xml
|
||||
<p><t t-raw="value"/></p>
|
||||
```
|
||||
|
||||
rendered with the value `value` set to `<span>foo</span>` in the rendering context yields:
|
||||
|
||||
```html
|
||||
<p><span>foo</span></p>
|
||||
```
|
||||
|
||||
Note that since the content of the expression is not known beforehand, the `t-raw`
|
||||
directive has to parse the html (and convert it to a virtual dom structure) for
|
||||
each rendering. So, it will be much slower than a regular template. It is
|
||||
therefore advised to limit the use of `t-raw` whenever possible.
|
||||
|
||||
### Setting Variables
|
||||
|
||||
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
|
||||
|
||||
This is done via the `t-set` directive, which takes the name of the variable to create. The value to set can be provided in two ways:
|
||||
|
||||
1. a `t-value` attribute containing an expression, and the result of its
|
||||
evaluation will be set:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="2 + 1"/>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will print `3`. Note that the evaluation is done at rendering time, not at
|
||||
compilte time.
|
||||
|
||||
2. if there is no `t-value` attribute, the node’s body is saved and its value is
|
||||
set as the variable’s value:
|
||||
|
||||
```xml
|
||||
<t t-set="foo">
|
||||
<li>ok</li>
|
||||
</t>
|
||||
<t t-esc="foo"/>
|
||||
```
|
||||
|
||||
will generate `<li>ok</li>` (the content is escaped as we used the `t-esc` directive)
|
||||
|
||||
The `t-set` directive acts like a regular variable in most programming language.
|
||||
It is lexically scoped (inner nodes are sub scopes), can be shadowed, ...
|
||||
|
||||
### Conditionals
|
||||
|
||||
The `t-if` directive is useful to conditionally render something. It evaluates
|
||||
the expression given as attribute value, and then acts accordingly.
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<t t-if="condition">
|
||||
<p>ok</p>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
The element is rendered if the condition (evaluated with the current rendering
|
||||
context) is true:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p>ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
but if the condition is false it is removed from the result:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
</div>
|
||||
```
|
||||
|
||||
The conditional rendering applies to the bearer of the directive, which does not
|
||||
have to be `<t>`:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="condition">ok</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
will give the same results as the previous example.
|
||||
|
||||
Extra conditional branching directives `t-elif` and `t-else` are also available:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<p t-if="user.birthday == today()">Happy bithday!</p>
|
||||
<p t-elif="user.login == 'root'">Welcome master!</p>
|
||||
<p t-else="">Welcome!</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Dynamic Attributes
|
||||
|
||||
One can use the `t-att-` directive to add dynamic attributes. Its main use is to
|
||||
evaluate an expression (at rendering time) and bind an attribute to its result:
|
||||
|
||||
For example, if we have `id` set to 32 in the rendering context,
|
||||
|
||||
```xml
|
||||
<div t-att-data-action-id="id"/> <!-- result: <div data-action-id="32"></div> -->
|
||||
```
|
||||
|
||||
If an expression evaluates to a falsy value, it will not be set at all:
|
||||
|
||||
```xml
|
||||
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
||||
```
|
||||
|
||||
It is sometimes convenient to format an attribute with string interpolation. In
|
||||
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
|
||||
<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> -->
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
||||
collection to iterate on, and a second parameter `t-as` providing the name to use
|
||||
for the current item of the iteration:
|
||||
|
||||
```xml
|
||||
<t t-foreach="[1, 2, 3]" t-as="i">
|
||||
<p><t t-esc="i"/></p>
|
||||
</t>
|
||||
```
|
||||
|
||||
will be rendered as:
|
||||
|
||||
```xml
|
||||
<p>1</p>
|
||||
<p>2</p>
|
||||
<p>3</p>
|
||||
```
|
||||
|
||||
Like conditions, `t-foreach` applies to the element bearing the directive’s attribute, and
|
||||
|
||||
```xml
|
||||
<p t-foreach="[1, 2, 3]" t-as="i">
|
||||
<t t-esc="i"/>
|
||||
</p>
|
||||
```
|
||||
|
||||
is equivalent to the previous example.
|
||||
|
||||
`t-foreach` can iterate on an array (the current item will be the current value)
|
||||
or an object (the current item will be the current key).
|
||||
|
||||
In addition to the name passed via t-as, `t-foreach` provides a few other
|
||||
variables for various data points (note: `$as` will be replaced with the name
|
||||
passed to `t-as`):
|
||||
|
||||
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
||||
integers, but for objects, it provides the value (where `$as` provides the key)
|
||||
- `$as_index`: the current iteration index (the first item of the iteration has index 0)
|
||||
- `$as_first`: whether the current item is the first of the iteration
|
||||
(equivalent to `$as_index == 0`)
|
||||
- `$as_last`: whether the current item is the last of the iteration
|
||||
(equivalent to `$as_index + 1 == $as_size`), requires the iteratee’s size be
|
||||
available
|
||||
|
||||
These extra variables provided and all new variables created into the `t-foreach`
|
||||
are only available in the scope of the `t-foreach`. If the variable exists outside
|
||||
the context of the `t-foreach`, the value is copied at the end of the foreach
|
||||
into the global context.
|
||||
|
||||
```xml
|
||||
<t t-set="existing_variable" t-value="false"/>
|
||||
<!-- existing_variable now False -->
|
||||
|
||||
<p t-foreach="Array(3)" t-as="i">
|
||||
<t t-set="existing_variable" t-value="true"/>
|
||||
<t t-set="new_variable" t-value="true"/>
|
||||
<!-- existing_variable and new_variable now true -->
|
||||
</p>
|
||||
|
||||
<!-- existing_variable always true -->
|
||||
<!-- new_variable undefined -->
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
QWeb templates can be used for top level rendering, but they can also be used
|
||||
from within another template (to avoid duplication or give names to parts of
|
||||
templates), using the `t-call` directive:
|
||||
|
||||
```xml
|
||||
<div t-name="other-template">
|
||||
<p><t t-value="var"/></p>
|
||||
</div>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-set="var" t-value="owl"/>
|
||||
<t t-call="other-template"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
will be rendered as `<div><p>owl</p></div>`. This example shows that the sub
|
||||
template is rendered with the execution context of the parent. The sub template
|
||||
is actually inlined in the main template, but in a sub scope: variables defined
|
||||
in the sub template do not escape.
|
||||
|
||||
Sometimes, one might want to pass information to the sub template. In that case,
|
||||
the content of the body of the `t-call` directive is available as a special
|
||||
magic variable `0`:
|
||||
|
||||
```xml
|
||||
<t t-name="other-template">
|
||||
This template was called with content:
|
||||
<t t-raw="0"/>
|
||||
</t>
|
||||
|
||||
<div t-name="main-template">
|
||||
<t t-call="other-template">
|
||||
<em>content</em>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
will result in :
|
||||
|
||||
```xml
|
||||
<div>
|
||||
This template was called with content:
|
||||
<em>content</em>
|
||||
</div>
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
The javascript QWeb implementation provides two useful debugging directives:
|
||||
|
||||
`t-debug` adds a debugger statement during template rendering:
|
||||
|
||||
```xml
|
||||
<t t-if="a_test">
|
||||
<t t-debug=""/>
|
||||
</t>
|
||||
```
|
||||
|
||||
will stop execution if the browser dev tools are open.
|
||||
|
||||
`t-log` takes an expression parameter, evaluates the expression during rendering and logs its result with console.log:
|
||||
|
||||
```xml
|
||||
<t t-set="foo" t-value="42"/>
|
||||
<t t-log="foo"/>
|
||||
```
|
||||
|
||||
will print 42 to the console.
|
||||
@@ -0,0 +1,181 @@
|
||||
# 🦉 Router 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Route Definition](#route-definition)
|
||||
- [Router](#router)
|
||||
- [Navigation Guards](#navigation-guards)
|
||||
- [RouteComponent](#routecomponent)
|
||||
- [Link](#link)
|
||||
|
||||
## Overview
|
||||
|
||||
It is often useful to organize an application around urls. If the application is
|
||||
a single page application, then we need a way to manage those urls in the browser.
|
||||
This is why there are many different routers for different frameworks. A generic
|
||||
router can do the job just fine, but a specialized router for Owl can give a
|
||||
better developer experience.
|
||||
|
||||
The Owl router support the following features:
|
||||
|
||||
- `history` or `hash` mode
|
||||
- declarative routes
|
||||
- route redirection
|
||||
- navigation guards
|
||||
- parameterized routes
|
||||
- a `<Link/>` component
|
||||
- a `<RouteComponent/>` component
|
||||
|
||||
Note that it is still in early stage of developments, and there are probably
|
||||
still some issues.
|
||||
|
||||
## Example
|
||||
|
||||
To use the Owl router, there are some steps that needs to be done:
|
||||
|
||||
- declare some routes
|
||||
- create a router
|
||||
- add it to the environment
|
||||
|
||||
```js
|
||||
async function protectRoute({ env, to }) {
|
||||
if (!env.session.authUser) {
|
||||
env.session.setNextRoute(to.name);
|
||||
return { to: "SIGN_IN" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export const ROUTES = [
|
||||
{ name: "LANDING", path: "/", component: Landing },
|
||||
{ name: "TASK", path: "/tasks/{{id}}", component: Task },
|
||||
{ name: "SIGN_UP", path: "/signup", component: SignUp },
|
||||
{ name: "SIGN_IN", path: "/signin", component: SignIn },
|
||||
{ name: "ADMIN", path: "/admin", component: Admin, beforeRouteEnter: protectRoute },
|
||||
{ name: "ACCOUNT", path: "/account", component: Account, beforeRouteEnter: protectRoute },
|
||||
{ name: "UNKNOWN", path: "*", redirect: { to: "LANDING" } }
|
||||
];
|
||||
|
||||
function makeEnvironment() {
|
||||
...
|
||||
const env = { qweb };
|
||||
env.session = new Session(env);
|
||||
env.router = new owl.router.Router(env, ROUTES);
|
||||
await env.router.start();
|
||||
return env;
|
||||
}
|
||||
|
||||
App.env = makeEnvironment();
|
||||
// create root component here
|
||||
```
|
||||
|
||||
Notice that the router needs to be started. This is an asynchronous operation
|
||||
because it needs to apply the potential navigation guards on the current route
|
||||
(which may or may not mean that the application is redirected to another route).
|
||||
|
||||
## Reference
|
||||
|
||||
### Route definition
|
||||
|
||||
A route need to be defined as an object with the following keys:
|
||||
|
||||
- `name` (optional): a (unique) string useful to identify the current route. If not
|
||||
given, it will be assigned an automatic name,
|
||||
- `path`: a string describing the url. It can be static: `/admin` or dynamic: `/users/{{id}}`.
|
||||
It also can be `*`, to catch all remaining routes.
|
||||
- `component` (optional): an Owl component that will be used by the `t-routecomponent`
|
||||
directive if the route is active
|
||||
- `redirect` (optional): should be destination object (with optional keys `path`, `to` and `params`) if given, the application will be redirected to the destination whenever we match this route
|
||||
- `beforeRouteEnter`: defines a [navigation guard](#navigation-guards).
|
||||
|
||||
### `Router`
|
||||
|
||||
The `Router` constructor takes three arguments:
|
||||
|
||||
- `env`: a valid environment,
|
||||
- a list of routes,
|
||||
- an optional object (with the only key `mode` which can be `history` (default
|
||||
value) or `hash`).
|
||||
|
||||
`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
|
||||
const ROUTES = [...];
|
||||
const router = new owl.router.Router(env, ROUTES, {mode: 'history'});
|
||||
```
|
||||
|
||||
Note that the route are defined in a list, and the order matters: the router
|
||||
tries to find a match by going down the list.
|
||||
|
||||
The router needs to be added to the environment in the `router` sub key.
|
||||
|
||||
Once a router is created, it needs to be started. This is necessary to initialize
|
||||
its current state to the current URL (and also, to potentially apply any
|
||||
navigation guards and/or redirecting).
|
||||
|
||||
```js
|
||||
await router.start();
|
||||
```
|
||||
|
||||
Once started, the router will keep track of the current url and reflect its
|
||||
value in two keys:
|
||||
|
||||
- `router.currentRoute`
|
||||
- `router.currentParams`
|
||||
|
||||
The router also has a `navigate` method, useful to programmatically change the
|
||||
application to another state (and the url):
|
||||
|
||||
```js
|
||||
router.navigate({ to: "USER", params: { id: 51 } });
|
||||
```
|
||||
|
||||
### Navigation Guards
|
||||
|
||||
Navigation guards are very useful to be able to execute some business logic/
|
||||
perform some actions or redirect to other routes whenever the application is
|
||||
entering a new route. For example, the following guard checks if there is an
|
||||
authenticated user, and if it is not the case, redirect to the sign in route.
|
||||
|
||||
```js
|
||||
async function protectRoute({ env, to }) {
|
||||
if (!env.session.authUser) {
|
||||
env.session.setNextRoute(to.name);
|
||||
return { to: "SIGN_IN" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
A navigation guard is a function that returns a promise, which either resolves
|
||||
to `true` (the navigation is accepted), or to another destination object.
|
||||
|
||||
### `RouteComponent`
|
||||
|
||||
The `RouteComponent` component directs Owl to render the component associated
|
||||
to the currently active route (if any):
|
||||
|
||||
```xml
|
||||
<div t-name="App">
|
||||
<NavBar />
|
||||
<RouteComponent />
|
||||
</div>
|
||||
```
|
||||
|
||||
### `Link`
|
||||
|
||||
The `Link` component is a Owl component which render as a `<a>` tag with any
|
||||
content. It will compute the proper href from its props, and allow Owl to
|
||||
properly navigate to a given url if clicked on it.
|
||||
|
||||
```xml
|
||||
<Link to="'HOME'">Home</Link>
|
||||
```
|
||||
@@ -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).
|
||||
@@ -0,0 +1,349 @@
|
||||
# 🦉 Store 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Store](#store)
|
||||
- [Actions](#actions)
|
||||
- [Getters](#getters)
|
||||
- [Connecting a Component](#connecting-a-component)
|
||||
- [`useStore`](#usestore)
|
||||
- [`useDispatch`](#usedispatch)
|
||||
- [`useGetters`](#usegetters)
|
||||
- [Semantics](#semantics)
|
||||
- [Good Practices](#good-practices)
|
||||
|
||||
## Overview
|
||||
|
||||
Managing the state in an application is not an easy task. In some cases, the
|
||||
state of an application can be part of the component tree, in a natural way.
|
||||
However, there are situations where some parts of the state need to be displayed
|
||||
in various parts of the user interface, and then, it is not obvious which
|
||||
component should own which part of the state.
|
||||
|
||||
Owl's solution to this issue is a centralized store. It is a class that owns
|
||||
some (or all) state, and lets the developer update it in a structured way, with
|
||||
`actions`. Owl components can then connect to the store to read their relevant
|
||||
state, and they will be rerendered if the state is updated.
|
||||
|
||||
Note: Owl store is inspired by React Redux and VueX.
|
||||
|
||||
## Example
|
||||
|
||||
Here is what a simple store looks like:
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
addTodo({ state }, message) {
|
||||
state.todos.push({
|
||||
id: state.nextId++,
|
||||
message,
|
||||
isCompleted: false,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const state = {
|
||||
todos: [],
|
||||
nextId: 1,
|
||||
};
|
||||
|
||||
const store = new owl.Store({ state, actions });
|
||||
store.on("update", null, () => console.log(store.state));
|
||||
|
||||
// updating the state
|
||||
store.dispatch("addTodo", "fix all bugs");
|
||||
```
|
||||
|
||||
This example shows how a store can be defined and used. Note that in most cases,
|
||||
actions will be dispatched by connected components.
|
||||
|
||||
## Reference
|
||||
|
||||
### `Store`
|
||||
|
||||
The store is a simple [`owl.EventBus`](event_bus.md) that triggers `update` events
|
||||
whenever its state is changed. Note that these events are triggered only after a
|
||||
microtask tick, so only one event will be triggered for any number of state changes in a
|
||||
call stack.
|
||||
|
||||
Also, it is important to mention that the state is observed (with an `owl.Observer`),
|
||||
which is the reason why it is able to know if it was changed. See the
|
||||
[Observer](observer.md)'s documentation for more details.
|
||||
|
||||
The `Store` class is quite small. It has two public methods:
|
||||
|
||||
- its constructor
|
||||
- `dispatch`
|
||||
|
||||
The constructor takes a configuration object with four (optional) keys:
|
||||
|
||||
- the initial state
|
||||
- the actions
|
||||
- the getters
|
||||
- the environment
|
||||
|
||||
```javascript
|
||||
const config = {
|
||||
state,
|
||||
actions,
|
||||
getters,
|
||||
env,
|
||||
};
|
||||
const store = new Store(config);
|
||||
```
|
||||
|
||||
### Actions
|
||||
|
||||
Actions are used to coordinate state changes. It can be used for both synchronous
|
||||
and asynchronous logic.
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
async login({ state }, info) {
|
||||
state.loginState = "pending";
|
||||
try {
|
||||
const loginInfo = await doSomeRPC("/login/", info);
|
||||
state.loginState = loginInfo;
|
||||
} catch (e) {
|
||||
state.loginState = "error";
|
||||
}
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
The first argument to an action method is an object with four keys:
|
||||
|
||||
- `state`: the current state of the store content,
|
||||
- `dispatch`: a function that can be used to dispatch other actions,
|
||||
- `getters`: an object containing all getters defined in the store,
|
||||
- `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
|
||||
the `rpc` method is located in the environment.
|
||||
|
||||
Actions are called with the `dispatch` method on the store, and can receive an
|
||||
arbitrary number of arguments.
|
||||
|
||||
```js
|
||||
store.dispatch("login", someInfo);
|
||||
```
|
||||
|
||||
Note that anything returned by an action will also be returned by the `dispatch`
|
||||
call.
|
||||
|
||||
Also, it is important to be aware that we need to be careful with asynchronous
|
||||
logic. Each state change will potentially trigger a rerendering, so we need to
|
||||
make sure that we do not have a partially corrupted state. Here is an example that
|
||||
is likely not a good idea:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
async fetchSomeData({ state }, recordId) {
|
||||
state.recordId = recordId;
|
||||
const data = await doSomeRPC("/read/", recordId);
|
||||
state.recordData = data;
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
In the previous example, there is a period of time in which the state has a
|
||||
`recordId` which does not correspond to the `recordData`. It is more likely that
|
||||
we want an atomic update: updating the `recordId` at the same time as the `recordData`
|
||||
values:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
async fetchSomeData({ state }, recordId) {
|
||||
const data = await doSomeRPC("/read/", recordId);
|
||||
state.recordId = recordId;
|
||||
state.recordData = data;
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Getters
|
||||
|
||||
Usually, data contained in the store will be stored in a normalized way. For
|
||||
example,
|
||||
|
||||
```js
|
||||
{
|
||||
posts: [{id: 11, authorId: 4, content: 'Greetings'}],
|
||||
authors: [{id: 4, name: 'John'}]
|
||||
}
|
||||
```
|
||||
|
||||
However, the user interface will probably need some denormalized data like
|
||||
|
||||
```js
|
||||
{id: 11, author: {id: 4, name: 'John'}, content: 'Greetings'}
|
||||
```
|
||||
|
||||
This is what `getters` are for: they give a centralized way to process and
|
||||
transform the data contained in the store.
|
||||
|
||||
```js
|
||||
const getters = {
|
||||
getPost({ state }, id) {
|
||||
const post = state.posts.find((p) => p.id === id);
|
||||
const author = state.authors.find((a) => a.id === post.id);
|
||||
return {
|
||||
id,
|
||||
author,
|
||||
content: post.content,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// somewhere else
|
||||
const post = store.getters.getPost(id);
|
||||
```
|
||||
|
||||
Getters take _at most_ one argument.
|
||||
|
||||
Note that getters are not cached.
|
||||
|
||||
### Connecting a Component
|
||||
|
||||
At some point, we need a way to interact with the store from a component. This
|
||||
means that the component needs a reference to the store. By default, it looks
|
||||
for it in the `env.store` key. However, this can be configured with the `useStore`
|
||||
hook.
|
||||
|
||||
Every component-store interactions are done with the help of the three store hooks:
|
||||
|
||||
- [`useStore`](#usestore) to subscribe a component to some part of the store state,
|
||||
- [`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:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter.value += val;
|
||||
},
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: { value: 0 },
|
||||
};
|
||||
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:
|
||||
|
||||
```js
|
||||
class Counter extends Component {
|
||||
counter = useStore((state) => state.counter);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="counter.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
### `useStore`
|
||||
|
||||
The `useStore` hook is used to select some part of the store state. It accepts
|
||||
two arguments:
|
||||
|
||||
- a selector function, which takes the store state as first argument (and the
|
||||
component props as second argument) and which must return the part of the
|
||||
store state that will be made available and observed for changes,
|
||||
- optionally, an object which can have the following optional keys:
|
||||
- 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
|
||||
will only be rerendered whenever this part of the state changes. Otherwise, it
|
||||
will perform a strict equality check (unless the `isEqual` option is defined,
|
||||
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
|
||||
|
||||
The `Store` class and the `useStore` hook try to be smart and to optimize as much
|
||||
as possible the rendering and update process. What is important to know is:
|
||||
|
||||
- components are always updated in the order of their creation (so, parent
|
||||
before children),
|
||||
- they are updated only if they are in the DOM,
|
||||
- if a parent is asynchronous, the system will wait for it to complete its
|
||||
update before updating other components,
|
||||
- in general, updates are not coordinated. This is not a problem for synchronous
|
||||
components, but if there are many asynchronous components, this could lead to
|
||||
a situation where some part of the UI is updated and some other part of the UI is
|
||||
not updated.
|
||||
|
||||
### Good Practices
|
||||
|
||||
- avoid asynchronous components as much as possible. Asynchronous components
|
||||
lead to situations where parts of the UI is not updated immediately,
|
||||
- do not be afraid to connect many components, parent or children if needed. For
|
||||
example, a `MessageList` component could get a list of ids in its `useStore`
|
||||
call and a `Message` component could get the data of its own
|
||||
message,
|
||||
- since the `useStore` function is called for each connected component,
|
||||
for each state update, it is important to make sure that these functions are
|
||||
as fast as possible.
|
||||
@@ -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);
|
||||
```
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
# 🦉 Store 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Public API](#public-api)
|
||||
- [Mutations](#mutations)
|
||||
- [Actions](#actions)
|
||||
- [Getters](#getters)
|
||||
- [Connecting a component](#connecting-a-component)
|
||||
|
||||
## Overview
|
||||
|
||||
Managing the state in an application is not an easy task. In some cases, the
|
||||
state of an application can be part of the component tree, in a natural way.
|
||||
However, there are situations where some part of the state need to be displayed
|
||||
in various parts of the user interface, and then, it is not obvious which
|
||||
component should own which part of the state.
|
||||
|
||||
Owl's solution to this issue is a centralized store. It is a class that owns
|
||||
some state, and let the developer update it in a structured way (through
|
||||
mutations and actions). Owl components can then connect to the store, and will
|
||||
be updated if necessary.
|
||||
|
||||
Note: Owl's store is inspired by React Redux and VueX.
|
||||
|
||||
## Example
|
||||
|
||||
Here is what a simple store look like:
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
addTodo({commit}, message) {
|
||||
commit('addTodo', message);
|
||||
}
|
||||
};
|
||||
|
||||
const mutations = {
|
||||
addTodo({state}, message) {
|
||||
const todo = {
|
||||
id: state.nextId++,
|
||||
message,
|
||||
isCompleted: false,
|
||||
};
|
||||
state.todos.push(todo);
|
||||
},
|
||||
};
|
||||
|
||||
const state = {
|
||||
todos: [],
|
||||
nextId: 1,
|
||||
};
|
||||
|
||||
const store = new owl.Store({state, actions, mutations});
|
||||
store.on('update', () => console.log(store.state));
|
||||
|
||||
// updating the state
|
||||
store.dispatch('addTodo', 'fix all bugs');
|
||||
```
|
||||
|
||||
|
||||
## Reference
|
||||
|
||||
The store is a simple `owl.EventBus` that triggers `update` events whenever its
|
||||
state is changed. Note that these events are triggered only after a microtask
|
||||
tick, so only one event will be triggered for any number of state changes in a
|
||||
call stack.
|
||||
|
||||
Also, it is important to mention that the state is observed (with a `owl.Observer`),
|
||||
which is the reason why it is able to know if it was changed. This implies that
|
||||
state changes need to be done carefully in some cases (adding a new key to an
|
||||
object, or modifying an array with the `arr[i] = newValue` syntax). See the
|
||||
[Observer](observer.md)'s documentation for more details.
|
||||
|
||||
### Public API
|
||||
|
||||
1. `constructor`
|
||||
2. `commit`
|
||||
3. `dispatch`
|
||||
|
||||
### Mutations
|
||||
|
||||
Mutations are the only way to modify the state. Changing the state outside a
|
||||
mutation is not allowed (and should throw an error). Mutations are synchronous.
|
||||
|
||||
### Actions
|
||||
|
||||
Actions are used to coordinate state changes. It is also useful whenever some
|
||||
asynchronous logic is necessary. For example, fetching data should be done
|
||||
in an action.
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
async login({commit}) {
|
||||
commit('setLoginState', 'pending');
|
||||
try {
|
||||
const loginInfo = await doSomeRPC('/login/', 'someinfo');
|
||||
commit('setLoginState', loginInfo);
|
||||
} catch {
|
||||
commit('setLoginState', 'error');
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Getters
|
||||
|
||||
Usually, data contained in the store will be stored in a normalized way. For
|
||||
example,
|
||||
|
||||
```js
|
||||
{
|
||||
posts: [{id: 11, authorId: 4, content: 'Greetings'}],
|
||||
authors: [{id: 4, name: 'John'}]
|
||||
}
|
||||
```
|
||||
|
||||
However, the user interface will probably need some denormalized data like
|
||||
|
||||
```js
|
||||
{id: 11, author: {id: 4, name: 'John'}, content: 'Greetings'}
|
||||
```
|
||||
|
||||
This is what `getters` are for: they give a centralized way to process and
|
||||
transform the data contained in the store.
|
||||
|
||||
```js
|
||||
const getters = {
|
||||
getPost({state}, id) {
|
||||
const post = state.posts.find(p => p.id === id);
|
||||
const author = state.authors.find(a => a.id = post.id);
|
||||
return {
|
||||
id,
|
||||
author,
|
||||
content: post.content
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// somewhere else
|
||||
const post = store.getters.getPost(id);
|
||||
|
||||
```
|
||||
|
||||
### Connecting a component
|
||||
|
||||
Todo
|
||||
@@ -1,18 +0,0 @@
|
||||
# 🦉 Tooling 🦉
|
||||
|
||||
## 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.
|
||||
@@ -1,39 +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)
|
||||
- [`loadJS`](#loadjs)
|
||||
- [`loadTemplates`](#loadtemplates)
|
||||
- [`escape`](#escape)
|
||||
- [`debounce`](#debounce)
|
||||
|
||||
## `whenReady`
|
||||
|
||||
The function `whenReady` is useful to register some code that need to be executed
|
||||
as soon as the document (page) is ready:
|
||||
|
||||
```js
|
||||
owl.utils.whenReady(function () {
|
||||
const qweb = new owl.QWeb();
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
## `loadJS`
|
||||
|
||||
## `loadTemplates`
|
||||
|
||||
## `escape`
|
||||
|
||||
## `debounce`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# 🦉 VDom 🦉
|
||||
|
||||
Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
|
||||
@@ -1,30 +0,0 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="message_count">
|
||||
Number of msg: 0
|
||||
</div>
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1000 messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10000 messages</button>
|
||||
<button class="o_btn_msg 50000">Add 50000 messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove" >Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,30 +0,0 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="message_count">
|
||||
Number of msg: 0
|
||||
</div>
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1000 messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10000 messages</button>
|
||||
<button class="o_btn_msg 50000">Add 50000 messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove" >Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,85 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure('remove message');
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,81 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="App" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,221 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
counter: 0
|
||||
};
|
||||
this.increment = this.increment.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
null,
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: this.increment
|
||||
},
|
||||
"Value: ",
|
||||
this.state.counter
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.setState({
|
||||
counter: this.state.counter + 1
|
||||
});
|
||||
}
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "message"
|
||||
},
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "author"
|
||||
},
|
||||
this.props.message.author
|
||||
),
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "msg"
|
||||
},
|
||||
this.props.message.msg
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
className: "remove",
|
||||
onClick: this.removeMessage
|
||||
},
|
||||
"Remove"
|
||||
),
|
||||
React.createElement(Counter, null)
|
||||
);
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.props.removeCB(this.props.message.id);
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Main extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
messages: []
|
||||
};
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
const msgList = this.state.messages.map(m =>
|
||||
React.createElement(Message, {
|
||||
key: m.id,
|
||||
message: m,
|
||||
removeCB: this.removeMessage
|
||||
})
|
||||
);
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "main"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "left-thing"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
null,
|
||||
"Number of msg: ",
|
||||
this.state.messages.length
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(100)
|
||||
},
|
||||
"Add 100 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(1000)
|
||||
},
|
||||
"Add 1000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(10000)
|
||||
},
|
||||
"Add 10000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(50000)
|
||||
},
|
||||
"Add 50000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.updateSomeMessages()
|
||||
},
|
||||
"Update every 10th messags"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.clear()
|
||||
},
|
||||
"Clear"
|
||||
)
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "right-thing"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "content"
|
||||
},
|
||||
msgList
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = this.state.messages.concat(buildData(n));
|
||||
this.setState({
|
||||
messages: newMessages
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.setState({
|
||||
messages: []
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
this.forceUpdate();
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === id);
|
||||
const messages = this.state.messages.slice();
|
||||
messages.splice(index, 1);
|
||||
this.setState({
|
||||
messages
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
} //-----------------------------
|
||||
// INIT
|
||||
//-----------------------------
|
||||
|
||||
ReactDOM.render(
|
||||
React.createElement(Main, null),
|
||||
document.getElementById("main")
|
||||
);
|
||||
@@ -1,42 +0,0 @@
|
||||
.main {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
}
|
||||
|
||||
.left-thing {
|
||||
background-color: gray;
|
||||
padding: 20px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.left-thing button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.right-thing {
|
||||
padding: 20px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* Message widget */
|
||||
.message .author {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.message {
|
||||
width: 400px;
|
||||
background-color: lightblue;
|
||||
margin: 10px 5px;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.remove {
|
||||
float: right;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("likes-counter", {
|
||||
data: function() {
|
||||
return {
|
||||
counter: 0
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
increment() {
|
||||
this.counter++;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div>
|
||||
<button @click="increment">Value: {{counter}}</button>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("my-message", {
|
||||
props: ["msg"],
|
||||
methods: {
|
||||
removeMessage() {
|
||||
this.$emit("removeMessage", this.msg.id);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="message">
|
||||
<span class="author">{{msg.author}}</span>
|
||||
<span class="msg">{{msg.msg}}</span>
|
||||
<button class="remove" @click="removeMessage">Remove</button>
|
||||
<likes-counter></likes-counter>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
const App = {
|
||||
name: "App",
|
||||
data() {
|
||||
return { messages: [] };
|
||||
},
|
||||
methods: {
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.messages.push.apply(this.messages, newMessages);
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.messages = [];
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.messages;
|
||||
for (let i = 0; i < this.messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.messages.findIndex(m => m.id === id);
|
||||
this.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: {{messages.length}}</div>
|
||||
<button @click="addMessages(100)">Add 100 messages</button>
|
||||
<button @click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button @click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button @click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button @click="updateSomeMessages">Update every 10th message</button>
|
||||
<button @click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<my-message v-for="msg in messages" v-bind:key="msg.id" v-bind:msg="msg" @removeMessage="removeMessage"></my-message>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
new Vue({
|
||||
render: h => h(App)
|
||||
}).$mount(`#main`);
|
||||
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>OWL Extras</title>
|
||||
<link rel="stylesheet" href="main.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="title">
|
||||
<h1>🦉 OWL Extra Stuff 🦉</h1>
|
||||
<div>Mysterious OWL: A web framework for structured, dynamic and maintainable applications</div>
|
||||
</div>
|
||||
|
||||
<div class="section misc">
|
||||
<h2>Misc</h2>
|
||||
<div class="links">
|
||||
<a href="playground">Playground (local)</a>
|
||||
<a href="https://github.com/odoo/owl">Github</a>
|
||||
<a href="https://odoo.github.io/owl/">Owl main page</a>
|
||||
<a href="https://github.com/odoo/owl/blob/master/doc/readme.md">Owl Documentation</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section benchmarks">
|
||||
<h2>Benchmarks</h2>
|
||||
|
||||
<ul>
|
||||
<li><a href="benchmarks/odoo-widgets-12.0">Odoo Widgets (12.0)</a></li>
|
||||
<li><a href="benchmarks/odoo-widgets-12.3">Odoo Widgets (12.3)</a></li>
|
||||
<li><a href="benchmarks/owl-0.7.0">OWL 0.7.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.8.0">OWL 0.8.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.9.0">OWL 0.9.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.10.0">OWL 0.10.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.11.0">OWL 0.11.0</a></li>
|
||||
<li><a href="benchmarks/owl-master">OWL Master</a></li>
|
||||
<li><a href="benchmarks/vue">Vue</a></li>
|
||||
<li><a href="benchmarks/react">React</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,23 +0,0 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
.title, .section {
|
||||
width: 768px;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.title div {
|
||||
color: #333333;
|
||||
font-style: italic;
|
||||
}
|
||||
.section {
|
||||
background-color: #d5d5d5;
|
||||
padding: 16px;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.links a {
|
||||
margin: 10px 5px;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
||||
# 🦉 Extra Stuff 🦉
|
||||
|
||||
To help work/improve/learn with OWL, we have here:
|
||||
|
||||
- a benchmarks application
|
||||
- a playground application
|
||||
|
||||
Both of them 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 extras` (and its version with a watcher: `npm run extras:watch`).
|
||||
|
||||
## Benchmarks
|
||||
|
||||
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.
|
||||
|
||||
## Playground
|
||||
|
||||
The playground is an important application designed to help learning and
|
||||
experimenting with Owl. It is available [online](https://odoo.github.io/owl/playground/).
|
||||
@@ -1,38 +0,0 @@
|
||||
import sys
|
||||
import thread
|
||||
import webbrowser
|
||||
import time
|
||||
|
||||
import BaseHTTPServer
|
||||
import SimpleHTTPServer
|
||||
|
||||
HOST = '127.0.0.1'
|
||||
PORT = 8000
|
||||
URL = 'http://{0}:{1}/extras'.format(HOST, PORT)
|
||||
|
||||
|
||||
# We define our own handler here to remap owl.js GET requests to the Owl build
|
||||
# in dist/. This is useful for the benchmarks and playground applications.
|
||||
# With this, we can simply copy the playground folder as is in the gh-page when
|
||||
# we want to update the playground.
|
||||
class OWLHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == '/extras/owl.js':
|
||||
self.path = '/dist/owl.js'
|
||||
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
|
||||
|
||||
|
||||
def start_server():
|
||||
httpd = BaseHTTPServer.HTTPServer((HOST, PORT), OWLHandler)
|
||||
httpd.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
thread.start_new_thread(start_server, ())
|
||||
webbrowser.open_new(URL)
|
||||
|
||||
while True:
|
||||
try:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(0)
|
||||
+33
-12
@@ -1,46 +1,63 @@
|
||||
{
|
||||
"name": "owl",
|
||||
"version": "0.12.0",
|
||||
"name": "@odoo/owl",
|
||||
"version": "1.0.8",
|
||||
"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": {
|
||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl src/*",
|
||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
||||
"build:bundle": "rollup -c",
|
||||
"build": "npm run build:js && npm run build:bundle",
|
||||
"buildcommonjs": "npm run build:js && npm run build:bundle -- -f cjs",
|
||||
"minify": "uglifyjs dist/owl.js -o dist/owl.min.js --compress --mangle",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"extras:serve": "python extras/server.py",
|
||||
"extras": "npm run build && npm run extras:serve",
|
||||
"extras:watch": "npm-run-all --parallel extras:serve \"build:* -- --watch\""
|
||||
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
||||
"tools": "npm run build && npm run tools:serve",
|
||||
"pretools:watch": "npm run build",
|
||||
"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": "mv dist/owl.js dist/owl-iife.js && npm run buildcommonjs && npm publish",
|
||||
"release": "node tools/release.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/odoo/owl.git"
|
||||
},
|
||||
"author": "Odoo",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"license": "LGPL-3.0-only",
|
||||
"bugs": {
|
||||
"url": "https://github.com/odoo/owl/issues"
|
||||
},
|
||||
"homepage": "https://github.com/odoo/owl#readme",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^23.3.12",
|
||||
"chalk": "^3.0.0",
|
||||
"cpx": "^1.5.0",
|
||||
"git-rev-sync": "^1.12.0",
|
||||
"github-api": "^3.3.0",
|
||||
"jest": "^23.6.0",
|
||||
"jest-environment-jsdom": "^24.7.1",
|
||||
"live-server": "^1.2.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^2.0.4",
|
||||
"rollup": "^1.6.0",
|
||||
"rollup-plugin-typescript2": "^0.20.1",
|
||||
"sass": "^1.16.1",
|
||||
"source-map-support": "^0.5.10",
|
||||
"ts-jest": "^23.10.5",
|
||||
"typescript": "^3.2.2",
|
||||
"uglify-es": "^3.3.9",
|
||||
"jest-environment-jsdom": "^24.7.1"
|
||||
"typescript": "^3.7.2",
|
||||
"uglify-es": "^3.3.9"
|
||||
},
|
||||
"dependencies": {},
|
||||
"jest": {
|
||||
"roots": [
|
||||
"<rootDir>/src",
|
||||
@@ -59,5 +76,9 @@
|
||||
"json",
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"prettier": {
|
||||
"printWidth": 100,
|
||||
"endOfLine": "auto"
|
||||
}
|
||||
}
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# 🦉 OWL Roadmap 🦉
|
||||
|
||||
- Current version: 1.0.8
|
||||
- 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,
|
||||
};
|
||||
@@ -1,610 +0,0 @@
|
||||
import { EventBus } from "./event_bus";
|
||||
import { Observer } from "./observer";
|
||||
import { QWeb, CompiledTemplate } from "./qweb_core";
|
||||
import { h, patch, VNode } from "./vdom";
|
||||
|
||||
/**
|
||||
* Owl Component System
|
||||
*
|
||||
* This file introduces a declarative and composable component system. It
|
||||
* contains:
|
||||
*
|
||||
* - the Env interface (generic type for the environment)
|
||||
* - the Meta interface (the owl specific metadata attached to a component)
|
||||
* - the Component class
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export interface Env {
|
||||
qweb: QWeb;
|
||||
}
|
||||
|
||||
export interface Meta<T extends Env, Props> {
|
||||
readonly id: number;
|
||||
vnode: VNode | null;
|
||||
isMounted: boolean;
|
||||
isDestroyed: boolean;
|
||||
parent: Component<T, any, any> | null;
|
||||
children: { [key: number]: Component<T, any, any> };
|
||||
// children mapping: from templateID to widgetID
|
||||
// should it be a map number => Widget?
|
||||
cmap: { [key: number]: number };
|
||||
|
||||
renderId: number;
|
||||
renderProps: Props | null;
|
||||
renderPromise: Promise<VNode> | null;
|
||||
boundHandlers: { [key: number]: any };
|
||||
observer?: Observer;
|
||||
render?: CompiledTemplate;
|
||||
mountedHandlers: { [key: number]: Function };
|
||||
}
|
||||
|
||||
// If a component does not define explicitely a template
|
||||
// key, it needs to find a template with its name (or a parent's). This is
|
||||
// qweb dependant, so we need a place to store this information indexed by
|
||||
// qweb instances.
|
||||
const TEMPLATE_MAP: { [key: number]: { [name: string]: string } } = {};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Widget
|
||||
//------------------------------------------------------------------------------
|
||||
let nextId = 1;
|
||||
|
||||
export class Component<
|
||||
T extends Env,
|
||||
Props extends {},
|
||||
State extends {}
|
||||
> extends EventBus {
|
||||
readonly __owl__: Meta<Env, Props>;
|
||||
template?: string;
|
||||
|
||||
get el(): HTMLElement | null {
|
||||
return this.__owl__.vnode ? (<any>this).__owl__.vnode.elm : null;
|
||||
}
|
||||
|
||||
env: T;
|
||||
state?: State;
|
||||
props: Props;
|
||||
|
||||
// type of props is not easily representable in typescript...
|
||||
static props?: any;
|
||||
static defaultProps?: any;
|
||||
|
||||
refs: {
|
||||
[key: string]: Component<T, any, any> | HTMLElement | undefined;
|
||||
} = {};
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Creates an instance of Component.
|
||||
*
|
||||
* The root widget of a component tree needs an environment:
|
||||
*
|
||||
* ```javascript
|
||||
* const root = new RootWidget(env, props);
|
||||
* ```
|
||||
*
|
||||
* Every other widget simply needs a reference to its parent:
|
||||
*
|
||||
* ```javascript
|
||||
* const child = new SomeWidget(parent, props);
|
||||
* ```
|
||||
*
|
||||
* Note that most of the time, only the root widget needs to be created by
|
||||
* hand. Other widgets should be created automatically by the framework (with
|
||||
* the t-widget directive in a template)
|
||||
*/
|
||||
constructor(parent: Component<T, any, any> | T, props?: Props) {
|
||||
super();
|
||||
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
if (defaultProps) {
|
||||
props = this._applyDefaultProps(props, defaultProps);
|
||||
}
|
||||
if (QWeb.dev) {
|
||||
this._validateProps(props || {});
|
||||
}
|
||||
// is this a good idea?
|
||||
// Pro: if props is empty, we can create easily a widget
|
||||
// Con: this is not really safe
|
||||
// Pro: but creating widget (by a template) is always unsafe anyway
|
||||
this.props = <Props>props || <Props>{};
|
||||
let id: number = nextId++;
|
||||
let p: Component<T, any, any> | null = null;
|
||||
if (parent instanceof Component) {
|
||||
p = parent;
|
||||
this.env = parent.env;
|
||||
parent.__owl__.children[id] = this;
|
||||
} else {
|
||||
this.env = parent;
|
||||
}
|
||||
this.__owl__ = {
|
||||
id: id,
|
||||
vnode: null,
|
||||
isMounted: false,
|
||||
isDestroyed: false,
|
||||
parent: p,
|
||||
children: {},
|
||||
cmap: {},
|
||||
renderId: 1,
|
||||
renderPromise: null,
|
||||
renderProps: props || null,
|
||||
boundHandlers: {},
|
||||
mountedHandlers: {}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* willStart is an asynchronous hook that can be implemented to perform some
|
||||
* action before the initial rendering of a component.
|
||||
*
|
||||
* It will be called exactly once before the initial rendering. It is useful
|
||||
* in some cases, for example, to load external assets (such as a JS library)
|
||||
* before the widget is rendered.
|
||||
*
|
||||
* Note that a slow willStart method will slow down the rendering of the user
|
||||
* interface. Therefore, some effort should be made to make this method as
|
||||
* fast as possible.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*/
|
||||
async willStart() {}
|
||||
|
||||
/**
|
||||
* mounted is a hook that is called each time a component is attached to the
|
||||
* DOM. This is a good place to add some listeners, or to interact with the
|
||||
* DOM, if the component needs to perform some measure for example.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*
|
||||
* @see willUnmount
|
||||
*/
|
||||
mounted() {}
|
||||
|
||||
/**
|
||||
* The willUpdateProps is an asynchronous hook, called just before new props
|
||||
* are set. This is useful if the component needs some asynchronous task
|
||||
* performed, depending on the props (for example, assuming that the props are
|
||||
* some record Id, fetching the record data).
|
||||
*
|
||||
* This hook is not called during the first render (but willStart is called
|
||||
* and performs a similar job).
|
||||
*/
|
||||
async willUpdateProps(nextProps: Props) {}
|
||||
|
||||
/**
|
||||
* The willPatch hook is called just before the DOM patching process starts.
|
||||
* It is not called on the initial render. This is useful to get some
|
||||
* information which are in the DOM. For example, the current position of the
|
||||
* scrollbar
|
||||
*
|
||||
* The return value of willPatch will be given to the patched function.
|
||||
*/
|
||||
willPatch(): any {}
|
||||
|
||||
/**
|
||||
* This hook is called whenever a component did actually update its props,
|
||||
* state or env.
|
||||
*
|
||||
* This method is not called on the initial render. It is useful to interact
|
||||
* with the DOM (for example, through an external library) whenever the
|
||||
* component was updated.
|
||||
*
|
||||
* Updating the widget state in this hook is possible, but not encouraged.
|
||||
* One need to be careful, because updates here will cause rerender, which in
|
||||
* turn will cause other calls to updated. So, we need to be particularly
|
||||
* careful at avoiding endless cycles.
|
||||
*
|
||||
* The snapshot parameter is the result of the call to willPatch.
|
||||
*/
|
||||
patched(snapshot: any) {}
|
||||
|
||||
/**
|
||||
* willUnmount is a hook that is called each time just before a component is
|
||||
* unmounted from the DOM. This is a good place to remove some listeners, for
|
||||
* example.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*
|
||||
* @see mounted
|
||||
*/
|
||||
willUnmount() {}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
async mount(target: HTMLElement): Promise<void> {
|
||||
const vnode = await this._prepare();
|
||||
if (this.__owl__.isDestroyed) {
|
||||
// widget was destroyed before we get here...
|
||||
return;
|
||||
}
|
||||
this._patch(vnode);
|
||||
target.appendChild(this.el!);
|
||||
|
||||
if (document.body.contains(target)) {
|
||||
this._callMounted();
|
||||
}
|
||||
}
|
||||
|
||||
_callMounted() {
|
||||
const __owl__ = this.__owl__;
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
const comp = children[id];
|
||||
if (!comp.__owl__.isMounted && this.el!.contains(comp.el)) {
|
||||
comp._callMounted();
|
||||
}
|
||||
}
|
||||
__owl__.isMounted = true;
|
||||
const handlers = __owl__.mountedHandlers;
|
||||
for (let key in handlers) {
|
||||
handlers[key]();
|
||||
}
|
||||
this.mounted();
|
||||
}
|
||||
|
||||
_callWillUnmount() {
|
||||
this.willUnmount();
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.isMounted = false;
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
const comp = children[id];
|
||||
if (comp.__owl__.isMounted) {
|
||||
comp._callWillUnmount();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unmount() {
|
||||
if (this.__owl__.isMounted) {
|
||||
this._callWillUnmount();
|
||||
this.el!.remove();
|
||||
}
|
||||
}
|
||||
|
||||
async render(force: boolean = false, patchQueue?: any[]): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isMounted) {
|
||||
return;
|
||||
}
|
||||
const shouldPatch: boolean = !patchQueue;
|
||||
if (shouldPatch) {
|
||||
patchQueue = [];
|
||||
}
|
||||
const renderVDom = this._render(force, patchQueue);
|
||||
const renderId = __owl__.renderId;
|
||||
await renderVDom;
|
||||
|
||||
if (shouldPatch && __owl__.isMounted && renderId === __owl__.renderId) {
|
||||
// we only update the vnode and the actual DOM if no other rendering
|
||||
// occurred between now and when the render method was initially called.
|
||||
const patchLen = patchQueue!.length;
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const patch = patchQueue![i];
|
||||
patch.push(patch[0].willPatch());
|
||||
}
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const patch = patchQueue![i];
|
||||
patch[0]._patch(patch[1]);
|
||||
}
|
||||
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
const patch = patchQueue![i];
|
||||
patch[0].patched(patch[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isDestroyed) {
|
||||
const el = this.el;
|
||||
this._destroy(__owl__.parent);
|
||||
if (el) {
|
||||
el.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_destroy(parent) {
|
||||
const __owl__ = this.__owl__;
|
||||
const isMounted = __owl__.isMounted;
|
||||
if (isMounted) {
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
}
|
||||
const children = __owl__.children;
|
||||
for (let key in children) {
|
||||
children[key]._destroy(this);
|
||||
}
|
||||
if (parent) {
|
||||
let id = __owl__.id;
|
||||
delete parent.__owl__.children[id];
|
||||
__owl__.parent = null;
|
||||
}
|
||||
this.clear();
|
||||
__owl__.isDestroyed = true;
|
||||
delete __owl__.vnode;
|
||||
}
|
||||
|
||||
shouldUpdate(nextProps: Props): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is the correct way to update the environment of a widget. Doing
|
||||
* this will cause a full rerender of the widget and its children, so this is
|
||||
* an operation that should not be done frequently.
|
||||
*
|
||||
* A good usecase for updating the environment would be to update some mostly
|
||||
* static config keys, such as a boolean to determine if we are in mobile
|
||||
* mode or not.
|
||||
*/
|
||||
async updateEnv(nextEnv: Partial<T>): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.parent && __owl__.parent.env === this.env) {
|
||||
this.env = Object.create(this.env);
|
||||
}
|
||||
Object.assign(this.env, nextEnv);
|
||||
if (__owl__.isMounted) {
|
||||
await this.render(true);
|
||||
}
|
||||
}
|
||||
|
||||
set(target: any, key: string | number, value: any) {
|
||||
this.__owl__.observer!.set(target, key, value);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Private
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
async _updateProps(
|
||||
nextProps: Props,
|
||||
forceUpdate: boolean = false,
|
||||
patchQueue?: any[]
|
||||
): Promise<void> {
|
||||
const shouldUpdate = forceUpdate || this.shouldUpdate(nextProps);
|
||||
if (shouldUpdate) {
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
if (defaultProps) {
|
||||
nextProps = this._applyDefaultProps(nextProps, defaultProps);
|
||||
}
|
||||
if (QWeb.dev) {
|
||||
this._validateProps(nextProps);
|
||||
}
|
||||
await this.willUpdateProps(nextProps);
|
||||
this.props = nextProps;
|
||||
await this.render(forceUpdate, patchQueue);
|
||||
}
|
||||
}
|
||||
|
||||
_patch(vnode) {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.renderPromise = null;
|
||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
||||
__owl__.vnode = patch(target, vnode);
|
||||
}
|
||||
_prepare(): Promise<VNode> {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.renderProps = this.props;
|
||||
__owl__.renderPromise = this._prepareAndRender();
|
||||
return __owl__.renderPromise;
|
||||
}
|
||||
|
||||
async _prepareAndRender(): Promise<VNode> {
|
||||
await this.willStart();
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.isDestroyed) {
|
||||
return Promise.resolve(h("div"));
|
||||
}
|
||||
const qweb = this.env.qweb;
|
||||
if (!this.template) {
|
||||
let tmap = TEMPLATE_MAP[qweb.id];
|
||||
if (!tmap) {
|
||||
tmap = {};
|
||||
TEMPLATE_MAP[qweb.id] = tmap;
|
||||
}
|
||||
let p = (<any>this).constructor;
|
||||
let name: string = p.name;
|
||||
let template = tmap[name];
|
||||
if (template) {
|
||||
this.template = template;
|
||||
} else {
|
||||
while (
|
||||
(template = p.name) &&
|
||||
!(template in qweb.templates) &&
|
||||
p !== Component
|
||||
) {
|
||||
p = p.__proto__;
|
||||
}
|
||||
if (p === Component) {
|
||||
this.template = "default";
|
||||
} else {
|
||||
tmap[name] = template;
|
||||
this.template = template;
|
||||
}
|
||||
}
|
||||
}
|
||||
__owl__.render = qweb.render.bind(qweb, this.template);
|
||||
this._observeState();
|
||||
return this._render();
|
||||
}
|
||||
async _render(
|
||||
force: boolean = false,
|
||||
patchQueue: any[] = []
|
||||
): Promise<VNode> {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.renderId++;
|
||||
const promises: Promise<void>[] = [];
|
||||
const patch: any[] = [this];
|
||||
if (__owl__.isMounted) {
|
||||
patchQueue.push(patch);
|
||||
}
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = false;
|
||||
}
|
||||
let vnode = __owl__.render!(this, {
|
||||
promises,
|
||||
handlers: __owl__.boundHandlers,
|
||||
mountedHandlers: __owl__.mountedHandlers,
|
||||
forceUpdate: force,
|
||||
patchQueue
|
||||
});
|
||||
patch.push(vnode);
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = true;
|
||||
}
|
||||
|
||||
// this part is critical for the patching process to be done correctly. The
|
||||
// tricky part is that a child widget can be rerendered on its own, which
|
||||
// will update its own vnode representation without the knowledge of the
|
||||
// parent widget. With this, we make sure that the parent widget will be
|
||||
// able to patch itself properly after
|
||||
vnode.key = __owl__.id;
|
||||
__owl__.renderProps = this.props;
|
||||
__owl__.renderPromise = Promise.all(promises).then(() => vnode);
|
||||
return __owl__.renderPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called by qweb t-widget directive
|
||||
*/
|
||||
_mount(vnode: VNode, elm: HTMLElement): VNode {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.vnode = patch(elm, vnode);
|
||||
if (__owl__.parent!.__owl__.isMounted && !__owl__.isMounted) {
|
||||
this._callMounted();
|
||||
}
|
||||
return __owl__.vnode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called by qweb t-widget directive (when t-keepalive is set)
|
||||
*/
|
||||
_remount() {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isMounted) {
|
||||
__owl__.isMounted = true;
|
||||
this.mounted();
|
||||
}
|
||||
}
|
||||
|
||||
_observeState() {
|
||||
if (this.state) {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.observer = new Observer();
|
||||
__owl__.observer.observe(this.state);
|
||||
__owl__.observer.notifyCB = this.render.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply default props (only top level).
|
||||
*
|
||||
* Note that this method does not modify in place the props, it returns a new
|
||||
* prop object
|
||||
*/
|
||||
_applyDefaultProps(props: Object | undefined, defaultProps: Object): Props {
|
||||
props = props ? Object.create(props) : {};
|
||||
for (let propName in defaultProps) {
|
||||
if (props![propName] === undefined) {
|
||||
props![propName] = defaultProps[propName];
|
||||
}
|
||||
}
|
||||
return <Props>props;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the component props (or next props) against the (static) props
|
||||
* description. This is potentially an expensive operation: it may needs to
|
||||
* visit recursively the props and all the children to check if they are valid.
|
||||
* This is why it is only done in 'dev' mode.
|
||||
*/
|
||||
_validateProps(props: Object) {
|
||||
const propsDef = (<any>this.constructor).props;
|
||||
if (propsDef instanceof Array) {
|
||||
// list of strings (prop names)
|
||||
for (let i = 0, l = propsDef.length; i < l; i++) {
|
||||
if (!(propsDef[i] in props)) {
|
||||
throw new Error(
|
||||
`Missing props '${propsDef[i]}' (widget '${this.constructor.name}')`
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (propsDef) {
|
||||
// propsDef is an object now
|
||||
for (let propName in propsDef) {
|
||||
if (!(propName in props)) {
|
||||
if (propsDef[propName] && !propsDef[propName].optional) {
|
||||
throw new Error(
|
||||
`Missing props '${propName}' (widget '${this.constructor.name}')`
|
||||
);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let isValid = isValidProp(props[propName], propsDef[propName]);
|
||||
if (!isValid) {
|
||||
throw new Error(
|
||||
`Props '${propName}' of invalid type in widget '${
|
||||
this.constructor.name
|
||||
}'`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Prop validation helper
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Check if an invidual prop value matches its (static) prop definition
|
||||
*/
|
||||
function isValidProp(prop, propDef): boolean {
|
||||
if (typeof propDef === "function") {
|
||||
// Check if a value is constructed by some Constructor. Note that there is a
|
||||
// slight abuse of language: we want to consider primitive values as well.
|
||||
//
|
||||
// So, even though 1 is not an instance of Number, we want to consider that
|
||||
// it is valid.
|
||||
if (typeof prop === "object") {
|
||||
return prop instanceof propDef;
|
||||
}
|
||||
return typeof prop === propDef.name.toLowerCase();
|
||||
} else if (propDef instanceof Array) {
|
||||
// If this code is executed, this means that we want to check if a prop
|
||||
// matches at least one of its descriptor.
|
||||
let result = false;
|
||||
for (let i = 0, iLen = propDef.length; i < iLen; i++) {
|
||||
result = result || isValidProp(prop, propDef[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// propsDef is an object
|
||||
let result = isValidProp(prop, propDef.type);
|
||||
if (propDef.type === Array) {
|
||||
for (let i = 0, iLen = prop.length; i < iLen; i++) {
|
||||
result = result && isValidProp(prop[i], propDef.element);
|
||||
}
|
||||
}
|
||||
if (propDef.type === Object) {
|
||||
const shape = propDef.shape;
|
||||
for (let key in shape) {
|
||||
result = result && isValidProp(prop[key], shape[key]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
import { Observer } from "../core/observer";
|
||||
import { OwlEvent } from "../core/owl_event";
|
||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
||||
import { patch, VNode } from "../vdom/index";
|
||||
import "./directive";
|
||||
import { Fiber } from "./fiber";
|
||||
import "./props_validation";
|
||||
import { Scheduler, scheduler } from "./scheduler";
|
||||
import { activateSheet } from "./styles";
|
||||
import { Browser, browser } from "../browser";
|
||||
|
||||
/**
|
||||
* Owl Component System
|
||||
*
|
||||
* This file introduces a declarative and composable component system. It
|
||||
* contains:
|
||||
*
|
||||
* - the Env interface (generic type for the environment)
|
||||
* - the Internal interface (the owl specific metadata attached to a component)
|
||||
* - the Component class
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* An Env (environment) is an object that will be (mostly) shared between all
|
||||
* components of an Owl application. It is the location which should contain
|
||||
* the qweb instance necessary to render all components.
|
||||
*
|
||||
* Note that it is totally fine to extend the environment with application
|
||||
* specific keys/objects/whatever. For example, a key `isMobile` (to declare
|
||||
* if we are in "mobile" mode), or a shared bus could be useful.
|
||||
*/
|
||||
export interface Env {
|
||||
qweb: QWeb;
|
||||
browser: Browser;
|
||||
}
|
||||
|
||||
export type MountPosition = "first-child" | "last-child" | "self";
|
||||
|
||||
interface MountOptions {
|
||||
position?: MountPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is mostly an internal detail of implementation. The Meta interface is
|
||||
* useful to typecheck and describe the internal keys used by Owl to manage the
|
||||
* component tree.
|
||||
*/
|
||||
interface Internal<T extends Env> {
|
||||
// each component has a unique id, useful mostly to handle parent/child
|
||||
// relationships
|
||||
readonly id: number;
|
||||
depth: number;
|
||||
vnode: VNode | null;
|
||||
pvnode: VNode | null;
|
||||
isMounted: boolean;
|
||||
isDestroyed: boolean;
|
||||
|
||||
// parent and children keys are obviously useful to setup the parent-children
|
||||
// relationship.
|
||||
parent: Component<any, T> | null;
|
||||
children: { [key: number]: Component<any, T> };
|
||||
// children mapping: from templateID to componentID. templateID identifies a
|
||||
// place in a template. The t-component directive needs it to be able to get
|
||||
// the component instance back whenever the template is rerendered.
|
||||
cmap: { [key: number]: number };
|
||||
|
||||
currentFiber: Fiber | null;
|
||||
// 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 };
|
||||
observer: Observer | null;
|
||||
renderFn: CompiledTemplate;
|
||||
mountedCB: Function | null;
|
||||
willUnmountCB: Function | null;
|
||||
willPatchCB: Function | null;
|
||||
patchedCB: Function | null;
|
||||
willStartCB: Function | null;
|
||||
willUpdatePropsCB: Function | null;
|
||||
classObj: { [key: string]: boolean } | null;
|
||||
refs: { [key: string]: Component<any, T> | HTMLElement | undefined } | null;
|
||||
}
|
||||
|
||||
export const portalSymbol = Symbol("portal"); // FIXME
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Component
|
||||
//------------------------------------------------------------------------------
|
||||
let nextId = 1;
|
||||
|
||||
export class Component<Props extends {} = any, T extends Env = Env> {
|
||||
readonly __owl__: Internal<T>;
|
||||
static template?: string | null = null;
|
||||
static _template?: string | null = null;
|
||||
static current: Component | null = null;
|
||||
static components = {};
|
||||
static props?: 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:
|
||||
* this is the case if the component is not mounted yet, or is destroyed.
|
||||
*/
|
||||
get el(): HTMLElement | null {
|
||||
return this.__owl__.vnode ? (<any>this).__owl__.vnode.elm : null;
|
||||
}
|
||||
|
||||
env: T;
|
||||
props: Props;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Creates an instance of Component.
|
||||
*
|
||||
* Note that most of the time, only the root component needs to be created by
|
||||
* hand. Other components should be created automatically by the framework (with
|
||||
* the t-component directive in a template)
|
||||
*/
|
||||
constructor(parent?: Component<any, T> | null, props?: Props) {
|
||||
Component.current = this;
|
||||
|
||||
let constr = this.constructor as any;
|
||||
const defaultProps = constr.defaultProps;
|
||||
if (defaultProps) {
|
||||
props = props || ({} as Props);
|
||||
this.__applyDefaultProps(props, defaultProps);
|
||||
}
|
||||
this.props = <Props>props;
|
||||
if (QWeb.dev) {
|
||||
QWeb.utils.validateProps(constr, this.props);
|
||||
}
|
||||
|
||||
const id: number = nextId++;
|
||||
let depth;
|
||||
if (parent) {
|
||||
this.env = parent.env;
|
||||
const __powl__ = parent.__owl__;
|
||||
__powl__.children[id] = this;
|
||||
depth = __powl__.depth + 1;
|
||||
} else {
|
||||
// we are the root component
|
||||
this.env = (this.constructor as any).env;
|
||||
if (!this.env.qweb) {
|
||||
this.env.qweb = new QWeb();
|
||||
}
|
||||
if (!this.env.browser) {
|
||||
this.env.browser = browser;
|
||||
}
|
||||
this.env.qweb.on("update", this, () => {
|
||||
if (this.__owl__.isMounted) {
|
||||
this.render(true);
|
||||
}
|
||||
if (this.__owl__.isDestroyed) {
|
||||
// this is unlikely to happen, but if a root widget is destroyed,
|
||||
// we want to remove our subscription. The usual way to do that
|
||||
// would be to perform some check in the destroy method, but since
|
||||
// it is very performance sensitive, and since this is a rare event,
|
||||
// we simply do it lazily
|
||||
this.env.qweb.off("update", this);
|
||||
}
|
||||
});
|
||||
depth = 0;
|
||||
}
|
||||
|
||||
const qweb = this.env.qweb;
|
||||
const template = constr.template || this.__getTemplate(qweb);
|
||||
this.__owl__ = {
|
||||
id: id,
|
||||
depth: depth,
|
||||
vnode: null,
|
||||
pvnode: null,
|
||||
isMounted: false,
|
||||
isDestroyed: false,
|
||||
parent: parent || null,
|
||||
children: {},
|
||||
cmap: {},
|
||||
currentFiber: null,
|
||||
parentLastFiberId: 0,
|
||||
boundHandlers: {},
|
||||
mountedCB: null,
|
||||
willUnmountCB: null,
|
||||
willPatchCB: null,
|
||||
patchedCB: null,
|
||||
willStartCB: null,
|
||||
willUpdatePropsCB: null,
|
||||
observer: null,
|
||||
renderFn: qweb.render.bind(qweb, template),
|
||||
classObj: null,
|
||||
refs: null,
|
||||
scope: null,
|
||||
};
|
||||
if (constr.style) {
|
||||
this.__applyStyles(constr);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* willStart is an asynchronous hook that can be implemented to perform some
|
||||
* action before the initial rendering of a component.
|
||||
*
|
||||
* It will be called exactly once before the initial rendering. It is useful
|
||||
* in some cases, for example, to load external assets (such as a JS library)
|
||||
* before the component is rendered.
|
||||
*
|
||||
* Note that a slow willStart method will slow down the rendering of the user
|
||||
* interface. Therefore, some effort should be made to make this method as
|
||||
* fast as possible.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*/
|
||||
async willStart() {}
|
||||
|
||||
/**
|
||||
* mounted is a hook that is called each time a component is attached to the
|
||||
* DOM. This is a good place to add some listeners, or to interact with the
|
||||
* DOM, if the component needs to perform some measure for example.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*
|
||||
* @see willUnmount
|
||||
*/
|
||||
mounted() {}
|
||||
|
||||
/**
|
||||
* The willUpdateProps is an asynchronous hook, called just before new props
|
||||
* are set. This is useful if the component needs some asynchronous task
|
||||
* performed, depending on the props (for example, assuming that the props are
|
||||
* some record Id, fetching the record data).
|
||||
*
|
||||
* This hook is not called during the first render (but willStart is called
|
||||
* and performs a similar job).
|
||||
*/
|
||||
async willUpdateProps(nextProps: Props) {}
|
||||
|
||||
/**
|
||||
* The willPatch hook is called just before the DOM patching process starts.
|
||||
* It is not called on the initial render. This is useful to get some
|
||||
* information which are in the DOM. For example, the current position of the
|
||||
* scrollbar
|
||||
*/
|
||||
willPatch(): any {}
|
||||
|
||||
/**
|
||||
* This hook is called whenever a component did actually update its props,
|
||||
* state or env.
|
||||
*
|
||||
* This method is not called on the initial render. It is useful to interact
|
||||
* with the DOM (for example, through an external library) whenever the
|
||||
* component was updated.
|
||||
*
|
||||
* Updating the component state in this hook is possible, but not encouraged.
|
||||
* One need to be careful, because updates here will cause rerender, which in
|
||||
* turn will cause other calls to updated. So, we need to be particularly
|
||||
* careful at avoiding endless cycles.
|
||||
*/
|
||||
patched() {}
|
||||
|
||||
/**
|
||||
* willUnmount is a hook that is called each time just before a component is
|
||||
* unmounted from the DOM. This is a good place to remove some listeners, for
|
||||
* example.
|
||||
*
|
||||
* Note: this method should not be called manually.
|
||||
*
|
||||
* @see mounted
|
||||
*/
|
||||
willUnmount() {}
|
||||
|
||||
/**
|
||||
* catchError is a method called whenever some error happens in the rendering or
|
||||
* lifecycle hooks of a child.
|
||||
*
|
||||
* It needs to be implemented by a component that is designed to handle the
|
||||
* error properly.
|
||||
*/
|
||||
catchError?(error?: Error): void;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Mount the component to a target element.
|
||||
*
|
||||
* This should only be done if the component was created manually. Components
|
||||
* created declaratively in templates are managed by the Owl system.
|
||||
*
|
||||
* Note that a component can be mounted an unmounted several times
|
||||
*/
|
||||
async mount(target: HTMLElement | DocumentFragment, options: MountOptions = {}): Promise<void> {
|
||||
const position = options.position || "last-child";
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.isMounted) {
|
||||
if (position !== "self" && this.el!.parentNode !== target) {
|
||||
// in this situation, we are trying to mount a component on a different
|
||||
// target. In this case, we need to unmount first, otherwise it will
|
||||
// not work.
|
||||
this.unmount();
|
||||
} else {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
if (__owl__.isDestroyed) {
|
||||
throw new Error("Cannot mount a destroyed component");
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* The unmount method is the opposite of the mount method. It is useful
|
||||
* to call willUnmount calls and remove the component from the DOM.
|
||||
*/
|
||||
unmount() {
|
||||
if (this.__owl__.isMounted) {
|
||||
this.__callWillUnmount();
|
||||
this.el!.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The render method is the main entry point to render a component (once it
|
||||
* is ready. This method is not initially called when the component is
|
||||
* rendered the first time).
|
||||
*
|
||||
* This method will cause all its sub components to potentially rerender
|
||||
* themselves. Note that `render` is not called if a component is updated via
|
||||
* its props.
|
||||
*/
|
||||
async render(force: boolean = false): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
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;
|
||||
}
|
||||
if (currentFiber && !currentFiber.isRendered && !currentFiber.isCompleted) {
|
||||
return scheduler.addFiber(currentFiber.root);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the component. This operation is quite complex:
|
||||
* - it recursively destroy all children
|
||||
* - call the willUnmount hooks if necessary
|
||||
* - remove the dom node from the dom
|
||||
*
|
||||
* This should only be called manually if you created the component. Most
|
||||
* components will be automatically destroyed.
|
||||
*/
|
||||
destroy() {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isDestroyed) {
|
||||
const el = this.el;
|
||||
this.__destroy(__owl__.parent);
|
||||
if (el) {
|
||||
el.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by the component system whenever its props are
|
||||
* updated. If it returns true, then the component will be rendered.
|
||||
* Otherwise, it will skip the rendering (also, its props will not be updated)
|
||||
*/
|
||||
shouldUpdate(nextProps: Props): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a custom event of type 'eventType' with the given 'payload' on the
|
||||
* component's el, if it exists. However, note that the event will only bubble
|
||||
* up to the parent DOM nodes. Thus, it must be called between mounted() and
|
||||
* willUnmount().
|
||||
*/
|
||||
trigger(eventType: string, payload?: any) {
|
||||
this.__trigger(this, eventType, payload);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Private
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Private helper to perform a full destroy, from the point of view of an Owl
|
||||
* component. It does not remove the el (this is done only once on the top
|
||||
* level destroyed component, for performance reasons).
|
||||
*
|
||||
* The job of this method is mostly to call willUnmount hooks, and to perform
|
||||
* all necessary internal cleanup.
|
||||
*
|
||||
* Note that it does not call the __callWillUnmount method to avoid visiting
|
||||
* all children many times.
|
||||
*/
|
||||
__destroy(parent: Component | null) {
|
||||
const __owl__ = this.__owl__;
|
||||
const isMounted = __owl__.isMounted;
|
||||
if (isMounted) {
|
||||
if (__owl__.willUnmountCB) {
|
||||
__owl__.willUnmountCB();
|
||||
}
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
}
|
||||
const children = __owl__.children;
|
||||
for (let key in children) {
|
||||
children[key].__destroy(this);
|
||||
}
|
||||
if (parent) {
|
||||
let id = __owl__.id;
|
||||
delete parent.__owl__.children[id];
|
||||
__owl__.parent = null;
|
||||
}
|
||||
__owl__.isDestroyed = true;
|
||||
delete __owl__.vnode;
|
||||
if (__owl__.currentFiber) {
|
||||
__owl__.currentFiber.isCompleted = true;
|
||||
}
|
||||
}
|
||||
|
||||
__callMounted() {
|
||||
const __owl__ = this.__owl__;
|
||||
|
||||
__owl__.isMounted = true;
|
||||
__owl__.currentFiber = null;
|
||||
this.mounted();
|
||||
if (__owl__.mountedCB) {
|
||||
__owl__.mountedCB();
|
||||
}
|
||||
}
|
||||
|
||||
__callWillUnmount() {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.willUnmountCB) {
|
||||
__owl__.willUnmountCB();
|
||||
}
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
if (this.__owl__.currentFiber) {
|
||||
this.__owl__.currentFiber.isCompleted = true;
|
||||
this.__owl__.currentFiber.root.counter = 0;
|
||||
}
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
const comp = children[id];
|
||||
if (comp.__owl__.isMounted) {
|
||||
comp.__callWillUnmount();
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
* it updates a component (so, when the parent template is rerendered).
|
||||
*/
|
||||
async __updateProps(nextProps: Props, parentFiber: Fiber, scope: any): Promise<void> {
|
||||
this.__owl__.scope = scope;
|
||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||
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;
|
||||
if (defaultProps) {
|
||||
this.__applyDefaultProps(nextProps, defaultProps);
|
||||
}
|
||||
if (QWeb.dev) {
|
||||
QWeb.utils.validateProps(this.constructor, nextProps);
|
||||
}
|
||||
await Promise.all([
|
||||
this.willUpdateProps(nextProps),
|
||||
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps),
|
||||
]);
|
||||
if (fiber.isCompleted) {
|
||||
return;
|
||||
}
|
||||
this.props = nextProps;
|
||||
|
||||
this.__render(fiber);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main patching method. We call the virtual dom patch method here to convert
|
||||
* a virtual dom vnode into some actual dom.
|
||||
*/
|
||||
__patch(target: HTMLElement | VNode | DocumentFragment, vnode: VNode) {
|
||||
this.__owl__.vnode = patch(target as any, vnode);
|
||||
}
|
||||
|
||||
/**
|
||||
* The __prepare method is only called by the t-component directive, when a
|
||||
* subcomponent is created. It gets its scope, if any, from the
|
||||
* parent template.
|
||||
*/
|
||||
__prepare(parentFiber: Fiber, scope: any, cb: CallableFunction): Fiber {
|
||||
this.__owl__.scope = scope;
|
||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null, null);
|
||||
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 {
|
||||
let p = (<any>this).constructor;
|
||||
if (!p.hasOwnProperty("_template")) {
|
||||
// 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 = p.name;
|
||||
while (!(template in qweb.templates) && p !== Component) {
|
||||
p = p.__proto__;
|
||||
template = p.name;
|
||||
}
|
||||
if (p === Component) {
|
||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
||||
} else {
|
||||
p._template = template;
|
||||
}
|
||||
}
|
||||
return p._template;
|
||||
}
|
||||
async __prepareAndRender(fiber: Fiber, cb: CallableFunction) {
|
||||
try {
|
||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
||||
} catch (e) {
|
||||
fiber.handleError(e);
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this.__owl__.isDestroyed) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!fiber.isCompleted) {
|
||||
this.__render(fiber);
|
||||
cb();
|
||||
}
|
||||
}
|
||||
|
||||
__render(fiber: Fiber) {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = false;
|
||||
}
|
||||
let error;
|
||||
try {
|
||||
let vnode = __owl__.renderFn!(this, {
|
||||
handlers: __owl__.boundHandlers,
|
||||
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) {
|
||||
let child = __owl__.children[childKey];
|
||||
if (!child.__owl__.isMounted && child.__owl__.parentLastFiberId < fiber.id) {
|
||||
child.destroy();
|
||||
}
|
||||
}
|
||||
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) {
|
||||
error = e;
|
||||
}
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = true;
|
||||
}
|
||||
|
||||
fiber.root.counter--;
|
||||
fiber.isRendered = true;
|
||||
if (error) {
|
||||
fiber.handleError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called by qweb t-component directive (when t-keepalive is set)
|
||||
*/
|
||||
__remount() {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isMounted) {
|
||||
__owl__.isMounted = true;
|
||||
this.mounted();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply default props (only top level).
|
||||
*
|
||||
* Note that this method does modify in place the props
|
||||
*/
|
||||
__applyDefaultProps(props: Object, defaultProps: Object) {
|
||||
for (let propName in defaultProps) {
|
||||
if (props![propName] === undefined) {
|
||||
props![propName] = defaultProps[propName];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
import { QWeb } from "../qweb/index";
|
||||
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
||||
import { makeHandlerCode, MODS_CODE } from "../qweb/extensions";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-component
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
||||
self: "if (e.target !== vn.elm) {return}",
|
||||
});
|
||||
|
||||
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
||||
for (let k in source) {
|
||||
Object.defineProperty(target, k, {
|
||||
get() {
|
||||
return source[k];
|
||||
},
|
||||
set(val) {
|
||||
source[k] = val;
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
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
|
||||
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
||||
* you this advice: Good luck...
|
||||
*
|
||||
* Since it is not 'direct' code, but rather code that generates other code, it
|
||||
* is not easy to understand. To help you, here is a detailed and commented
|
||||
* explanation of the code generated by the t-component directive for the following
|
||||
* situation:
|
||||
* ```xml
|
||||
* <Child
|
||||
* t-key="'somestring'"
|
||||
* flag="state.flag"
|
||||
* t-transition="fade"/>
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* // we assign utils on top of the function because it will be useful for
|
||||
* // each components
|
||||
* let utils = this.utils;
|
||||
*
|
||||
* // this is the virtual node representing the parent div
|
||||
* let c1 = [], p1 = { key: 1 };
|
||||
* var vn1 = h("div", p1, c1);
|
||||
*
|
||||
* // t-component directive: we start by evaluating the expression given by t-key:
|
||||
* let key5 = "somestring";
|
||||
*
|
||||
* // def3 is the promise that will contain later either the new component
|
||||
* // creation, or the props update...
|
||||
* let def3;
|
||||
*
|
||||
* // this is kind of tricky: we need here to find if the component was already
|
||||
* // created by a previous rendering. This is done by checking the internal
|
||||
* // `cmap` (children map) of the parent component: it maps keys to component ids,
|
||||
* // and, then, if there is an id, we look into the children list to get the
|
||||
* // instance
|
||||
* let w4 =
|
||||
* key5 in context.__owl__.cmap
|
||||
* ? context.__owl__.children[context.__owl__.cmap[key5]]
|
||||
* : false;
|
||||
*
|
||||
* // We keep the index of the position of the component in the closure. We push
|
||||
* // null to reserve the slot, and will replace it later by the component vnode,
|
||||
* // when it will be ready (do not forget that preparing/rendering a component is
|
||||
* // asynchronous)
|
||||
* let _2_index = c1.length;
|
||||
* c1.push(null);
|
||||
*
|
||||
* // we evaluate here the props given to the component. It is done here to be
|
||||
* // able to easily reference it later, and also, it might be an expensive
|
||||
* // computation, so it is certainly better to do it only once
|
||||
* let props4 = { flag: context["state"].flag };
|
||||
*
|
||||
* // If we have a component, currently rendering, but not ready yet, we do not want
|
||||
* // to wait for it to be ready if we can avoid it
|
||||
* if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
* // we check if the props are the same. In that case, we can simply reuse
|
||||
* // the previous rendering and skip all useless work
|
||||
* if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
* def3 = w4.__owl__.renderPromise;
|
||||
* } else {
|
||||
* // if the props are not the same, we destroy the component and starts anew.
|
||||
* // this will be faster than waiting for its rendering, then updating it
|
||||
* w4.destroy();
|
||||
* w4 = false;
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* if (!w4) {
|
||||
* // in this situation, we need to create a new component. First step is
|
||||
* // to get a reference to the class, then create an instance with
|
||||
* // current context as parent, and the props.
|
||||
* let W4 = context.component && context.components[componentKey4] || QWeb.component[componentKey4];
|
||||
|
||||
* if (!W4) {
|
||||
* throw new Error("Cannot find the definition of component 'child'");
|
||||
* }
|
||||
* w4 = new W4(owner, props4);
|
||||
*
|
||||
* // Whenever we rerender the parent component, we need to be sure that we
|
||||
* // are able to find the component instance. To do that, we register it to
|
||||
* // the parent cmap (children map). Note that the 'template' key is
|
||||
* // used here, since this is what identify the component from the template
|
||||
* // perspective.
|
||||
* context.__owl__.cmap[key5] = w4.__owl__.id;
|
||||
*
|
||||
* // __prepare is called, to basically call willStart, then render the
|
||||
* // component
|
||||
* def3 = w4.__prepare();
|
||||
*
|
||||
* def3 = def3.then(vnode => {
|
||||
* // we create here a virtual node for the parent (NOT the component). This
|
||||
* // means that the vdom of the parent will be stopped here, and from
|
||||
* // the parent's perspective, it simply is a vnode with no children.
|
||||
* // However, it shares the same dom element with the component root
|
||||
* // vnode.
|
||||
* let pvnode = h(vnode.sel, { key: key5 });
|
||||
*
|
||||
* // we add hooks to the parent vnode so we can interact with the new
|
||||
* // component at the proper time
|
||||
* pvnode.data.hook = {
|
||||
* insert(vn) {
|
||||
* // the __mount method will patch the component vdom into the elm vn.elm,
|
||||
* // then call the mounted hooks. However, suprisingly, the snabbdom
|
||||
* // patch method actually replace the elm by a new elm, so we need
|
||||
* // to synchronise the pvnode elm with the resulting elm
|
||||
* let nvn = w4.__mount(vnode, vn.elm);
|
||||
* pvnode.elm = nvn.elm;
|
||||
* // what follows is only present if there are animations on the component
|
||||
* utils.transitionInsert(vn, "fade");
|
||||
* },
|
||||
* remove() {
|
||||
* // override with empty function to prevent from removing the node
|
||||
* // directly. It will be removed when destroy is called anyway, which
|
||||
* // delays the removal if there are animations.
|
||||
* },
|
||||
* destroy() {
|
||||
* // if there are animations, we delay the call to destroy on the
|
||||
* // component, if not, we call it directly.
|
||||
* let finalize = () => {
|
||||
* w4.destroy();
|
||||
* };
|
||||
* utils.transitionRemove(vn, "fade", finalize);
|
||||
* }
|
||||
* };
|
||||
* // the pvnode is inserted at the correct position in the div's children
|
||||
* c1[_2_index] = pvnode;
|
||||
*
|
||||
* // we keep here a reference to the parent vnode (representing the
|
||||
* // component, so we can reuse it later whenever we update the component
|
||||
* w4.__owl__.pvnode = pvnode;
|
||||
* });
|
||||
* } else {
|
||||
* // this is the 'update' path of the directive.
|
||||
* // the call to __updateProps is the actual component update
|
||||
* // Note that we only update the props if we cannot reuse the previous
|
||||
* // rendering work (in the case it was rendered with the same props)
|
||||
* def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
* def3 = def3.then(() => {
|
||||
* // if component was destroyed in the meantime, we do nothing (so, this
|
||||
* // means that the parent's element children list will have a null in
|
||||
* // the component's position, which will cause the pvnode to be removed
|
||||
* // when it is patched.
|
||||
* if (w4.__owl__.isDestroyed) {
|
||||
* return;
|
||||
* }
|
||||
* // like above, we register the pvnode to the children list, so it
|
||||
* // will not be patched out of the dom.
|
||||
* let pvnode = w4.__owl__.pvnode;
|
||||
* c1[_2_index] = pvnode;
|
||||
* });
|
||||
* }
|
||||
*
|
||||
* // we register the deferred here so the parent can coordinate its patch operation
|
||||
* // with all the children.
|
||||
* extra.promises.push(def3);
|
||||
* return vn1;
|
||||
* ```
|
||||
*/
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "component",
|
||||
extraNames: ["props"],
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
ctx.addLine(`// Component '${value}'`);
|
||||
ctx.rootContext.shouldDefineQWeb = true;
|
||||
ctx.rootContext.shouldDefineParent = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||
|
||||
// t-on- events and t-transition
|
||||
const events: [string, string][] = [];
|
||||
let transition: string = "";
|
||||
const attributes = (<Element>node).attributes;
|
||||
const props: { [key: string]: string } = {};
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
const name = attributes[i].name;
|
||||
const value = attributes[i].textContent!;
|
||||
if (name.startsWith("t-on-")) {
|
||||
events.push([name, value]);
|
||||
} else if (name === "t-transition") {
|
||||
transition = value;
|
||||
} else if (!name.startsWith("t-")) {
|
||||
if (name !== "class" && name !== "style") {
|
||||
// this is a prop!
|
||||
props[name] = ctx.formatExpression(value) || "undefined";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// computing the props string representing the props object
|
||||
let propStr = Object.keys(props)
|
||||
.map((k) => k + ":" + props[k])
|
||||
.join(",");
|
||||
let componentID = ctx.generateID();
|
||||
|
||||
const templateKey = ctx.generateTemplateKey();
|
||||
let ref = node.getAttribute("t-ref");
|
||||
let refExpr = "";
|
||||
let refKey: string = "";
|
||||
if (ref) {
|
||||
ctx.rootContext.shouldDefineRefs = true;
|
||||
refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
||||
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
||||
}
|
||||
let finalizeComponentCode = `w${componentID}.destroy();`;
|
||||
if (ref) {
|
||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||
}
|
||||
if (transition) {
|
||||
finalizeComponentCode = `let finalize = () => {
|
||||
${finalizeComponentCode}
|
||||
};
|
||||
delete w${componentID}.__owl__.transitionInserted;
|
||||
utils.transitionRemove(vn, '${transition}', finalize);`;
|
||||
}
|
||||
|
||||
let createHook = "";
|
||||
let classAttr = node.getAttribute("class");
|
||||
let tattClass = node.getAttribute("t-att-class");
|
||||
let styleAttr = node.getAttribute("style");
|
||||
let tattStyle = node.getAttribute("t-att-style");
|
||||
if (tattStyle) {
|
||||
const attVar = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${attVar} = ${ctx.formatExpression(tattStyle)};`);
|
||||
tattStyle = attVar;
|
||||
}
|
||||
let classObj = "";
|
||||
if (classAttr || tattClass || styleAttr || tattStyle || events.length) {
|
||||
if (classAttr) {
|
||||
let classDef = classAttr
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.map((a) => `'${a}':true`)
|
||||
.join(",");
|
||||
classObj = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||
}
|
||||
if (tattClass) {
|
||||
let tattExpr = ctx.formatExpression(tattClass);
|
||||
if (tattExpr[0] !== "{" || tattExpr[tattExpr.length - 1] !== "}") {
|
||||
tattExpr = `utils.toObj(${tattExpr})`;
|
||||
}
|
||||
if (classAttr) {
|
||||
ctx.addLine(`Object.assign(${classObj}, ${tattExpr})`);
|
||||
} else {
|
||||
classObj = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${classObj} = ${tattExpr};`);
|
||||
}
|
||||
}
|
||||
let eventsCode = events
|
||||
.map(function ([name, value]) {
|
||||
const capture = name.match(/\.capture/);
|
||||
name = capture ? name.replace(/\.capture/, "") : name;
|
||||
const { event, handler } = makeHandlerCode(
|
||||
ctx,
|
||||
name,
|
||||
value,
|
||||
false,
|
||||
T_COMPONENT_MODS_CODE
|
||||
);
|
||||
if (capture) {
|
||||
return `vn.elm.addEventListener('${event}', ${handler}, true);`;
|
||||
}
|
||||
return `vn.elm.addEventListener('${event}', ${handler});`;
|
||||
})
|
||||
.join("");
|
||||
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
||||
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
||||
createHook = `utils.assignHooks(vnode.data, {create(_, vn){${styleCode}${eventsCode}}});`;
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let w${componentID} = ${templateKey} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateKey}]] : false;`
|
||||
);
|
||||
let shouldProxy = !ctx.parentNode;
|
||||
if (shouldProxy) {
|
||||
let id = ctx.generateID();
|
||||
ctx.rootContext.rootNode = id;
|
||||
shouldProxy = true;
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.addLine(`let vn${id} = {};`);
|
||||
ctx.addLine(`result = vn${id};`);
|
||||
}
|
||||
if (hasDynamicProps) {
|
||||
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
||||
ctx.addLine(`let props${componentID} = Object.assign({${propStr}}, ${dynamicProp});`);
|
||||
} else {
|
||||
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
||||
}
|
||||
ctx.addIf(
|
||||
`w${componentID} && w${componentID}.__owl__.currentFiber && !w${componentID}.__owl__.vnode`
|
||||
);
|
||||
ctx.addLine(`w${componentID}.destroy();`);
|
||||
ctx.addLine(`w${componentID} = false;`);
|
||||
ctx.closeIf();
|
||||
|
||||
let registerCode = "";
|
||||
if (shouldProxy) {
|
||||
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
||||
}
|
||||
|
||||
// SLOTS
|
||||
const 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
|
||||
let dynamicFallback = "";
|
||||
if (!value.match(INTERP_REGEXP)) {
|
||||
dynamicFallback = `|| ${ctx.formatExpression(value)}`;
|
||||
}
|
||||
const interpValue = ctx.interpolate(value);
|
||||
ctx.addLine(`let componentKey${componentID} = ${interpValue};`);
|
||||
ctx.addLine(
|
||||
`let W${componentID} = context.constructor.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}]${dynamicFallback};`
|
||||
);
|
||||
|
||||
// maybe only do this in dev mode...
|
||||
ctx.addLine(
|
||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
||||
);
|
||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
||||
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;`);
|
||||
|
||||
if (hasSlots) {
|
||||
const clone = <Element>node.cloneNode(true);
|
||||
const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
|
||||
|
||||
// The next code is a fallback for compatibility reason. It accepts t-set
|
||||
// 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 el of clone.children) {
|
||||
if (el.getAttribute("t-set") && el.hasChildNodes()) {
|
||||
slotNodes.push(el);
|
||||
}
|
||||
}
|
||||
const slotId = QWeb.nextSlotId++;
|
||||
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
||||
if (slotNodes.length) {
|
||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
||||
const slotNode = slotNodes[i];
|
||||
slotNode.parentElement!.removeChild(slotNode);
|
||||
let key = slotNode.getAttribute("t-set-slot")!;
|
||||
slotNode.removeAttribute("t-set-slot");
|
||||
|
||||
// here again, this code should be removed when we stop supporting
|
||||
// using t-set to define the content of named slots.
|
||||
if (!key) {
|
||||
key = slotNode.getAttribute("t-set")!;
|
||||
slotNode.removeAttribute("t-set");
|
||||
}
|
||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
||||
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
||||
}
|
||||
}
|
||||
if (clone.childNodes.length) {
|
||||
const t = clone.ownerDocument!.createElement("t");
|
||||
for (let child of Object.values(clone.childNodes)) {
|
||||
t.appendChild(child);
|
||||
}
|
||||
const slotFn = qweb._compile(`slot_default_template`, t, ctx);
|
||||
QWeb.slots[`${slotId}_default`] = slotFn;
|
||||
}
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let fiber = w${componentID}.__prepare(extra.fiber, ${scope}, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
const insertHook = refExpr ? `insert(vn) {${refExpr}},` : "";
|
||||
ctx.addLine(
|
||||
`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.closeIf();
|
||||
|
||||
if (classObj) {
|
||||
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
||||
}
|
||||
|
||||
ctx.addLine(`w${componentID}.__owl__.parentLastFiberId = extra.fiber.id;`);
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
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!);
|
||||
} else {
|
||||
component.__patch(document.createElement(fiber.vnode!.sel!), fiber.vnode!);
|
||||
component.__owl__.pvnode!.elm = component.__owl__.vnode!.elm;
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { QWeb } from "../qweb/index";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Prop validation helper
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Validate the component props (or next props) against the (static) props
|
||||
* description. This is potentially an expensive operation: it may needs to
|
||||
* visit recursively the props and all the children to check if they are valid.
|
||||
* This is why it is only done in 'dev' mode.
|
||||
*/
|
||||
|
||||
QWeb.utils.validateProps = function (Widget, props: Object) {
|
||||
const propsDef = (<any>Widget).props;
|
||||
if (propsDef instanceof Array) {
|
||||
// list of strings (prop names)
|
||||
for (let i = 0, l = propsDef.length; i < l; i++) {
|
||||
const propName = propsDef[i];
|
||||
if (propName[propName.length - 1] === "?") {
|
||||
// optional prop
|
||||
break;
|
||||
}
|
||||
if (!(propName in props)) {
|
||||
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
||||
}
|
||||
}
|
||||
for (let key in props) {
|
||||
if (!propsDef.includes(key) && !propsDef.includes(key + "?")) {
|
||||
throw new Error(`Unknown prop '${key}' given to component '${Widget.name}'`);
|
||||
}
|
||||
}
|
||||
} else if (propsDef) {
|
||||
// propsDef is an object now
|
||||
for (let propName in propsDef) {
|
||||
if (props[propName] === undefined) {
|
||||
if (propsDef[propName] && !propsDef[propName].optional) {
|
||||
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let isValid;
|
||||
try {
|
||||
isValid = isValidProp(props[propName], propsDef[propName]);
|
||||
} catch (e) {
|
||||
e.message = `Invalid prop '${propName}' in component ${Widget.name} (${e.message})`;
|
||||
throw e;
|
||||
}
|
||||
if (!isValid) {
|
||||
throw new Error(`Invalid Prop '${propName}' in component '${Widget.name}'`);
|
||||
}
|
||||
}
|
||||
for (let propName in props) {
|
||||
if (!(propName in propsDef)) {
|
||||
throw new Error(`Unknown prop '${propName}' given to component '${Widget.name}'`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if an invidual prop value matches its (static) prop definition
|
||||
*/
|
||||
function isValidProp(prop, propDef): boolean {
|
||||
if (propDef === true) {
|
||||
return true;
|
||||
}
|
||||
if (typeof propDef === "function") {
|
||||
// Check if a value is constructed by some Constructor. Note that there is a
|
||||
// slight abuse of language: we want to consider primitive values as well.
|
||||
//
|
||||
// So, even though 1 is not an instance of Number, we want to consider that
|
||||
// it is valid.
|
||||
if (typeof prop === "object") {
|
||||
return prop instanceof propDef;
|
||||
}
|
||||
return typeof prop === propDef.name.toLowerCase();
|
||||
} else if (propDef instanceof Array) {
|
||||
// If this code is executed, this means that we want to check if a prop
|
||||
// matches at least one of its descriptor.
|
||||
let result = false;
|
||||
for (let i = 0, iLen = propDef.length; i < iLen; i++) {
|
||||
result = result || isValidProp(prop, propDef[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// propsDef is an object
|
||||
if (propDef.optional && prop === undefined) {
|
||||
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++) {
|
||||
result = result && isValidProp(prop[i], propDef.element);
|
||||
}
|
||||
}
|
||||
if (propDef.type === Object && propDef.shape) {
|
||||
const shape = propDef.shape;
|
||||
for (let key in shape) {
|
||||
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;
|
||||
}
|
||||
@@ -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.`);
|
||||
}
|
||||
},
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import { Component } from "./component/component";
|
||||
import { scheduler } from "./component/scheduler";
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
|
||||
/**
|
||||
* The `Context` object provides a way to share data between an arbitrary number
|
||||
* of component. Usually, data is passed from a parent to its children component,
|
||||
* but when we have to deal with some mostly global information, this can be
|
||||
* annoying, since each component will need to pass the information to each
|
||||
* children, even though some or most of them will not use the information.
|
||||
*
|
||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
||||
* hook) to its state, and will be updated whenever the context state is updated.
|
||||
*/
|
||||
|
||||
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 {
|
||||
state: any;
|
||||
observer: Observer;
|
||||
rev: number = 1;
|
||||
// mapping from component id to last observed context id
|
||||
mapping: { [componentId: number]: number } = {};
|
||||
|
||||
constructor(state: Object = {}) {
|
||||
super();
|
||||
this.observer = new Observer();
|
||||
this.observer.notifyCB = () => {
|
||||
// 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.subscriptions.update = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Instead of using trigger to emit an update event, we actually implement
|
||||
* our own function to do that. The reason is that we need to be smarter than
|
||||
* a simple trigger function: we need to wait for parent components to be
|
||||
* done before doing children components. More precisely, if an update
|
||||
* as an effect of destroying a children, we do not want to call any code
|
||||
* from the child, and certainly not render it.
|
||||
*
|
||||
* This method implements a simple grouping algorithm by depth. If we have
|
||||
* connected components of depths [2, 4,4,4,4, 3,8,8], the Context will notify
|
||||
* them in the following groups: [2], [4,4,4,4], [3], [8,8]. Each group will
|
||||
* be updated sequentially, but each components in a given group will be done in
|
||||
* parallel.
|
||||
*
|
||||
* This is a very simple algorithm, but it avoids checking if a given
|
||||
* component is a child of another.
|
||||
*/
|
||||
async __notifyComponents() {
|
||||
const rev = ++this.rev;
|
||||
const subscriptions = this.subscriptions.update;
|
||||
const groups = partitionBy(subscriptions, (s) => (s.owner ? s.owner.__owl__.depth : -1));
|
||||
for (let group of groups) {
|
||||
const proms = group.map((sub) => sub.callback.call(sub.owner, rev));
|
||||
// at this point, each component in the current group has registered a
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The`useContext` hook is the normal way for a component to register themselve
|
||||
* to context state changes. The `useContext` method returns the context state
|
||||
*/
|
||||
export function useContext(ctx: Context): any {
|
||||
const component: Component = Component.current!;
|
||||
return useContextWithCB(ctx, component, component.render.bind(component));
|
||||
}
|
||||
|
||||
export function useContextWithCB(ctx: Context, component: Component, method): any {
|
||||
const __owl__ = component.__owl__;
|
||||
const id = __owl__.id;
|
||||
const mapping = ctx.mapping;
|
||||
if (id in mapping) {
|
||||
return ctx.state;
|
||||
}
|
||||
if (!__owl__.observer) {
|
||||
__owl__.observer = new Observer();
|
||||
__owl__.observer.notifyCB = component.render.bind(component);
|
||||
}
|
||||
const currentCB = __owl__.observer.notifyCB;
|
||||
__owl__.observer.notifyCB = function () {
|
||||
if (ctx.rev > mapping[id]) {
|
||||
// in this case, the context has been updated since we were rendering
|
||||
// last, and we do not need to render here with the observer. A
|
||||
// rendering is coming anyway, with the correct props.
|
||||
return;
|
||||
}
|
||||
currentCB();
|
||||
};
|
||||
|
||||
mapping[id] = 0;
|
||||
const renderFn = __owl__.renderFn;
|
||||
__owl__.renderFn = function (comp, params) {
|
||||
mapping[id] = ctx.rev;
|
||||
return renderFn(comp, params);
|
||||
};
|
||||
ctx.on("update", component, async (contextRev) => {
|
||||
if (mapping[id] < contextRev) {
|
||||
mapping[id] = contextRev;
|
||||
await method();
|
||||
}
|
||||
});
|
||||
const __destroy = component.__destroy;
|
||||
component.__destroy = (parent) => {
|
||||
ctx.off("update", component);
|
||||
delete mapping[id];
|
||||
__destroy.call(component, parent);
|
||||
};
|
||||
return ctx.state;
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export class EventBus {
|
||||
* Add a listener for the 'eventType' events.
|
||||
*
|
||||
* Note that the 'owner' of this event can be anything, but will more likely
|
||||
* be a widget or a class. The idea is that the callback will be called with
|
||||
* be a component or a class. The idea is that the callback will be called with
|
||||
* the proper owner bound.
|
||||
*
|
||||
* Also, the owner should be kind of unique. This will be used to remove the
|
||||
@@ -44,7 +44,7 @@ export class EventBus {
|
||||
}
|
||||
this.subscriptions[eventType].push({
|
||||
owner,
|
||||
callback
|
||||
callback,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ export class EventBus {
|
||||
off(eventType: string, owner: any) {
|
||||
const subs = this.subscriptions[eventType];
|
||||
if (subs) {
|
||||
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
|
||||
this.subscriptions[eventType] = subs.filter((s) => s.owner !== owner);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Owl Observer
|
||||
*
|
||||
* This code contains the logic that allows Owl to observe and react to state
|
||||
* changes.
|
||||
*
|
||||
* This is a Observer class that can observe any JS values. The way it works
|
||||
* can be summarized thusly:
|
||||
* - primitive values are not observed at all
|
||||
* - Objects and arrays are observed by replacing them with a Proxy
|
||||
* - each object/array metadata are tracked in a weakmap, and keep a revision
|
||||
* number
|
||||
*
|
||||
* Note that this code is loosely inspired by Vue.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Observer
|
||||
//------------------------------------------------------------------------------
|
||||
export class Observer {
|
||||
rev: number = 1;
|
||||
allowMutations: boolean = true;
|
||||
weakMap: WeakMap<any, any> = new WeakMap();
|
||||
|
||||
notifyCB() {}
|
||||
|
||||
observe<T>(value: T, parent?: any): T {
|
||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
||||
// fun fact: typeof null === 'object'
|
||||
return value;
|
||||
}
|
||||
let metadata = this.weakMap.get(value) || this._observe(value, parent);
|
||||
return metadata.proxy;
|
||||
}
|
||||
|
||||
revNumber(value): number {
|
||||
const metadata = this.weakMap.get(value);
|
||||
return metadata ? metadata.rev : 0;
|
||||
}
|
||||
|
||||
_observe(value, parent) {
|
||||
var self = this;
|
||||
|
||||
const proxy = new Proxy(value, {
|
||||
get(target, k) {
|
||||
const targetValue = target[k];
|
||||
return self.observe(targetValue, value);
|
||||
},
|
||||
set(target, key: string, newVal): boolean {
|
||||
const value = target[key];
|
||||
if (newVal !== value) {
|
||||
if (!self.allowMutations) {
|
||||
throw new Error(
|
||||
`Observed state cannot be changed here! (key: "${key}", val: "${newVal}")`
|
||||
);
|
||||
}
|
||||
self._updateRevNumber(target);
|
||||
target[key] = newVal;
|
||||
self.notifyCB();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
deleteProperty(target, key) {
|
||||
if (key in target) {
|
||||
delete target[key];
|
||||
self._updateRevNumber(target);
|
||||
self.notifyCB();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const metadata = {
|
||||
value,
|
||||
proxy,
|
||||
rev: this.rev,
|
||||
parent,
|
||||
};
|
||||
|
||||
this.weakMap.set(value, metadata);
|
||||
this.weakMap.set(metadata.proxy, metadata);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
_updateRevNumber(target: any) {
|
||||
this.rev++;
|
||||
let metadata = this.weakMap.get(target);
|
||||
let parent = target;
|
||||
do {
|
||||
metadata = this.weakMap.get(parent);
|
||||
metadata.rev++;
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import { Component } from "./component/component";
|
||||
import { Observer } from "./core/observer";
|
||||
|
||||
/**
|
||||
* Owl Hook System
|
||||
*
|
||||
* This file introduces the concept of hooks, similar to React or Vue hooks.
|
||||
* We have currently an implementation of:
|
||||
* - useState (reactive state)
|
||||
* - onMounted
|
||||
* - onWillUnmount
|
||||
* - useRef
|
||||
*/
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useState
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This is the main way a component can be made reactive. The useState hook
|
||||
* will return an observed object (or array). Changes to that value will then
|
||||
* trigger a rerendering of the current component.
|
||||
*/
|
||||
export function useState<T>(state: T): T {
|
||||
const component: Component = Component.current!;
|
||||
const __owl__ = component.__owl__;
|
||||
if (!__owl__.observer) {
|
||||
__owl__.observer = new Observer();
|
||||
__owl__.observer.notifyCB = component.render.bind(component);
|
||||
}
|
||||
return __owl__.observer.observe(state);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Life cycle hooks
|
||||
// -----------------------------------------------------------------------------
|
||||
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
||||
if (reverse) {
|
||||
return function (cb) {
|
||||
const component: Component = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function () {
|
||||
current.call(component);
|
||||
cb.call(component);
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return function (cb) {
|
||||
const component: Component = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function () {
|
||||
cb.call(component);
|
||||
current.call(component);
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function makeAsyncHook(method: string) {
|
||||
return function (cb) {
|
||||
const component: Component = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function (...args) {
|
||||
return Promise.all([current.call(component, ...args), cb.call(component, ...args)]);
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const onMounted = makeLifecycleHook("mountedCB", true);
|
||||
export const onWillUnmount = makeLifecycleHook("willUnmountCB");
|
||||
export const onWillPatch = makeLifecycleHook("willPatchCB");
|
||||
export const onPatched = makeLifecycleHook("patchedCB", true);
|
||||
|
||||
export const onWillStart = makeAsyncHook("willStartCB");
|
||||
export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useRef
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The purpose of this hook is to allow components to get a reference to a sub
|
||||
* html node or component.
|
||||
*/
|
||||
interface Ref<C extends Component = Component> {
|
||||
el: HTMLElement | null;
|
||||
comp: C | null;
|
||||
}
|
||||
|
||||
export function useRef<C extends Component = Component>(name: string): Ref<C> {
|
||||
const __owl__ = Component.current!.__owl__;
|
||||
return {
|
||||
get el(): HTMLElement | null {
|
||||
const val = __owl__.refs && __owl__.refs[name];
|
||||
if (val instanceof HTMLElement) {
|
||||
return val;
|
||||
} else if (val instanceof Component) {
|
||||
return val.el;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
get comp(): C | null {
|
||||
const val = __owl__.refs && __owl__.refs[name];
|
||||
return val instanceof Component ? (val as C) : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useSubEnv
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This hook is a simple way to let components use a sub environment. Note that
|
||||
* like for all hooks, it is important that this is only called in the
|
||||
* constructor method.
|
||||
*/
|
||||
export function useSubEnv(nextEnv) {
|
||||
const component = Component.current!;
|
||||
component.env = Object.assign(Object.create(component.env), nextEnv);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 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));
|
||||
}
|
||||
+30
-29
@@ -4,36 +4,37 @@
|
||||
*
|
||||
* Note that dynamic values, such as a date or a commit hash are added by rollup
|
||||
*/
|
||||
export { Component } from "./component";
|
||||
export { EventBus } from "./event_bus";
|
||||
export { Observer } from "./observer";
|
||||
|
||||
// we need to import manually the extra directives so they can register
|
||||
// themselves in QWeb, otherwise these files will not even be loaded.
|
||||
import "./qweb_directives";
|
||||
import "./qweb_extensions";
|
||||
import { QWeb } from "./qweb_core";
|
||||
export { QWeb };
|
||||
|
||||
export { connect, Store } from "./store";
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { QWeb } from "./qweb/index";
|
||||
import { config } from "./config";
|
||||
import * as _store from "./store";
|
||||
import * as _utils from "./utils";
|
||||
import * as _tags from "./tags";
|
||||
import { AsyncRoot } from "./misc/async_root";
|
||||
import { Portal } from "./misc/portal";
|
||||
import * as _hooks from "./hooks";
|
||||
import * as _context from "./context";
|
||||
import { Link } from "./router/link";
|
||||
import { RouteComponent } from "./router/route_component";
|
||||
import { Router } from "./router/router";
|
||||
|
||||
export const __info__ = {};
|
||||
export { Component } from "./component/component";
|
||||
export { QWeb };
|
||||
export { config };
|
||||
|
||||
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.`)
|
||||
}
|
||||
}
|
||||
});
|
||||
export const Context = _context.Context;
|
||||
export const useState = _hooks.useState;
|
||||
export const core = { EventBus, Observer };
|
||||
export const router = { Router, RouteComponent, Link };
|
||||
export const Store = _store.Store;
|
||||
export const utils = _utils;
|
||||
export const tags = _tags;
|
||||
export const misc = { AsyncRoot, Portal };
|
||||
export const hooks = Object.assign({}, _hooks, {
|
||||
useContext: _context.useContext,
|
||||
useDispatch: _store.useDispatch,
|
||||
useGetters: _store.useGetters,
|
||||
useStore: _store.useStore,
|
||||
});
|
||||
export const __info__ = {};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
/**
|
||||
* Owl Observer
|
||||
*
|
||||
* This code contains the logic that allows Owl to observe and react to state
|
||||
* changes.
|
||||
*
|
||||
* This is a Observer class that can observe any JS values. The way it works
|
||||
* can be summarized thusly:
|
||||
* - primitive values are not observed at all
|
||||
* - Objects are observed by replacing all their keys with getters/setters
|
||||
* (recursively)
|
||||
* - Arrays are observed by replacing their prototype with a customized version,
|
||||
* which wrap some methods to allow the tracking of each state change.
|
||||
*
|
||||
* Note that this code is inspired by Vue.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Modified Array prototype
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// we define here a new modified Array prototype, which basically override all
|
||||
// Array methods that change some state to be able to track their changes
|
||||
const methodsToPatch = [
|
||||
"push",
|
||||
"pop",
|
||||
"shift",
|
||||
"unshift",
|
||||
"splice",
|
||||
"sort",
|
||||
"reverse"
|
||||
];
|
||||
const methodLen = methodsToPatch.length;
|
||||
|
||||
const ArrayProto = Array.prototype;
|
||||
const ModifiedArrayProto = Object.create(ArrayProto);
|
||||
|
||||
for (let i = 0; i < methodLen; i++) {
|
||||
const method = methodsToPatch[i];
|
||||
const initialMethod = ArrayProto[method];
|
||||
ModifiedArrayProto[method] = function(...args) {
|
||||
if (!this.__observer__.allowMutations) {
|
||||
throw new Error(`Array cannot be changed here")`);
|
||||
}
|
||||
this.__observer__.rev++;
|
||||
this.__observer__.notifyChange();
|
||||
this.__owl__.rev++;
|
||||
let parent = this;
|
||||
do {
|
||||
parent.__owl__.deepRev++;
|
||||
} while ((parent = parent.__owl__.parent));
|
||||
let inserted;
|
||||
switch (method) {
|
||||
case "push":
|
||||
case "unshift":
|
||||
inserted = args;
|
||||
break;
|
||||
case "splice":
|
||||
inserted = args.slice(2);
|
||||
break;
|
||||
}
|
||||
if (inserted) {
|
||||
for (let i = 0, iLen = inserted.length; i < iLen; i++) {
|
||||
this.__observer__.observe(inserted[i], this);
|
||||
}
|
||||
}
|
||||
return initialMethod.call(this, ...args);
|
||||
};
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Observer
|
||||
//------------------------------------------------------------------------------
|
||||
export class Observer {
|
||||
rev: number = 1;
|
||||
allowMutations: boolean = true;
|
||||
dirty: boolean = false;
|
||||
|
||||
notifyCB() {}
|
||||
notifyChange() {
|
||||
this.dirty = true;
|
||||
Promise.resolve().then(() => {
|
||||
if (this.dirty) {
|
||||
this.dirty = false;
|
||||
this.notifyCB();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
observe(value: any, parent?: any) {
|
||||
if (value === null) {
|
||||
// fun fact: typeof null === 'object'
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object") {
|
||||
return;
|
||||
}
|
||||
if ("__owl__" in value) {
|
||||
// already observed
|
||||
value.__owl__.parent = parent;
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
this._observeArr(value, parent);
|
||||
} else {
|
||||
this._observeObj(value, parent);
|
||||
}
|
||||
}
|
||||
|
||||
set(target: any, key: number | string, value: any) {
|
||||
this.rev++;
|
||||
this._addProp(target, key, value);
|
||||
target.__owl__.rev++;
|
||||
this.notifyChange();
|
||||
}
|
||||
|
||||
_observeObj<T extends { __owl__?: any }>(obj: T, parent?: any) {
|
||||
obj.__owl__ = { rev: this.rev, deepRev: this.rev, parent };
|
||||
Object.defineProperty(obj, "__owl__", { enumerable: false });
|
||||
for (let key in obj) {
|
||||
this._addProp(obj, key, obj[key]);
|
||||
}
|
||||
}
|
||||
|
||||
_observeArr(arr: Array<any>, parent?: any) {
|
||||
(<any>arr).__owl__ = { rev: this.rev, deepRev: this.rev, parent };
|
||||
Object.defineProperty(arr, "__owl__", { enumerable: false });
|
||||
(<any>arr).__proto__ = Object.create(ModifiedArrayProto);
|
||||
(<any>arr).__proto__.__observer__ = this;
|
||||
for (let i = 0, iLen = arr.length; i < iLen; i++) {
|
||||
this.observe(arr[i], arr);
|
||||
}
|
||||
}
|
||||
|
||||
_addProp<T extends { __owl__?: any }>(
|
||||
obj: T,
|
||||
key: string | number,
|
||||
value: any
|
||||
) {
|
||||
var self = this;
|
||||
Object.defineProperty(obj, key, {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return value;
|
||||
},
|
||||
set(newVal) {
|
||||
if (newVal !== value) {
|
||||
self.rev++;
|
||||
if (!self.allowMutations) {
|
||||
throw new Error(
|
||||
`Observed state cannot be changed here! (key: "${key}", val: "${newVal}")`
|
||||
);
|
||||
}
|
||||
value = newVal;
|
||||
self.observe(newVal, obj);
|
||||
obj.__owl__.rev!++;
|
||||
let parent = obj;
|
||||
do {
|
||||
parent.__owl__.deepRev++;
|
||||
} while ((parent = parent.__owl__.parent) && parent !== obj);
|
||||
self.notifyChange();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.observe(value, obj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { CompilationContext } from "./compilation_context";
|
||||
import { QWeb } from "./qweb";
|
||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||
import { QWebVar } from "./expression_parser";
|
||||
|
||||
/**
|
||||
* Owl QWeb Directives
|
||||
*
|
||||
* This file contains the implementation of most standard QWeb directives:
|
||||
* - t-esc
|
||||
* - t-raw
|
||||
* - t-set/t-value
|
||||
* - t-if/t-elif/t-else
|
||||
* - t-call
|
||||
* - t-foreach/t-as
|
||||
* - t-debug
|
||||
* - t-log
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-esc and t-raw
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
if (value === "0") {
|
||||
if (ctx.parentNode) {
|
||||
// the 'zero' magical symbol is where we can find the result of the rendering
|
||||
// of the body of the t-call.
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
const zeroArgs = ctx.escaping
|
||||
? `{text: utils.vDomToString(scope[utils.zero])}`
|
||||
: `...scope[utils.zero]`;
|
||||
ctx.addLine(`c${ctx.parentNode}.push(${zeroArgs});`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let exprID: string;
|
||||
if (typeof value === "string") {
|
||||
exprID = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${exprID} = ${ctx.formatExpression(value)};`);
|
||||
} else {
|
||||
exprID = `scope.${value.id}`;
|
||||
}
|
||||
ctx.addIf(`${exprID} != null`);
|
||||
|
||||
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) {
|
||||
ctx.addLine(`vn${ctx.parentTextNode}.text += ${exprID};`);
|
||||
} else if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: ${exprID}});`);
|
||||
} else {
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
ctx.addLine(`let vn${nodeID} = {text: ${exprID}};`);
|
||||
if (ctx.rootContext.shouldDefineResult) {
|
||||
ctx.addLine(`result = vn${nodeID}`);
|
||||
}
|
||||
}
|
||||
if (value.hasBody) {
|
||||
ctx.stopProtectScope(protectID);
|
||||
}
|
||||
} else {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
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) {
|
||||
ctx.addElse();
|
||||
qweb._compileChildren(node, ctx);
|
||||
}
|
||||
|
||||
ctx.closeIf();
|
||||
}
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "esc",
|
||||
priority: 70,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "raw",
|
||||
priority: 80,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
||||
compileValueNode(value, node, qweb, ctx);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-set
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "set",
|
||||
extraNames: ["value"],
|
||||
priority: 60,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
const variable = node.getAttribute("t-set")!;
|
||||
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) {
|
||||
const formattedValue = ctx.formatExpression(value);
|
||||
let scopeExpr = `scope`;
|
||||
if (ctx.protectedScopeNumber) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
scopeExpr = `utils.getScope(scope, '${variable}')`;
|
||||
}
|
||||
ctx.addLine(`${scopeExpr}.${variable} = ${formattedValue};`);
|
||||
qwebvar.value = 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();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-if, t-elif, t-else
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "if",
|
||||
priority: 20,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id!}`);
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
},
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "elif",
|
||||
priority: 30,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
||||
ctx.addLine(
|
||||
`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id}`}) {`
|
||||
);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
},
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "else",
|
||||
priority: 40,
|
||||
atNodeEncounter({ ctx }): boolean {
|
||||
ctx.addLine(`else {`);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-call
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "call",
|
||||
priority: 50,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
// Step 1: sanity checks
|
||||
// ------------------------------------------------
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
if (node.nodeName !== "t") {
|
||||
throw new Error("Invalid tag for t-call directive (should be 't')");
|
||||
}
|
||||
const subTemplate = node.getAttribute("t-call")!;
|
||||
const nodeTemplate = qweb.templates[subTemplate];
|
||||
if (!nodeTemplate) {
|
||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
||||
}
|
||||
|
||||
// Step 2: compile target template in sub templates
|
||||
// ------------------------------------------------
|
||||
if (!qweb.subTemplates[subTemplate]) {
|
||||
qweb.subTemplates[subTemplate] = true;
|
||||
const subTemplateFn = qweb._compile(subTemplate, nodeTemplate.elem, ctx, true);
|
||||
qweb.subTemplates[subTemplate] = subTemplateFn;
|
||||
}
|
||||
|
||||
// Step 3: compile t-call body if necessary
|
||||
// ------------------------------------------------
|
||||
let hasBody = node.hasChildNodes();
|
||||
let protectID;
|
||||
if (hasBody) {
|
||||
// we add a sub scope to protect the ambient scope
|
||||
ctx.addLine(`{`);
|
||||
ctx.indent();
|
||||
protectID = ctx.startProtectScope();
|
||||
const nodeCopy = node.cloneNode(true) as Element;
|
||||
for (let attr of ["t-if", "t-else", "t-elif", "t-call"]) {
|
||||
nodeCopy.removeAttribute(attr);
|
||||
}
|
||||
const parentNode = ctx.parentNode;
|
||||
ctx.parentNode = "__0";
|
||||
// this local scope is intended to trap c__0
|
||||
ctx.addLine(`{`);
|
||||
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.addLine(`}`);
|
||||
}
|
||||
|
||||
// Step 4: add the appropriate function call to current component
|
||||
// ------------------------------------------------
|
||||
const callingScope = hasBody ? "scope" : "Object.assign(Object.create(context), scope)";
|
||||
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.subTemplates['${subTemplate}'].call(this, ${callingScope}, ${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.subTemplates['${subTemplate}'].call(this, ${callingScope}, ${extra});`);
|
||||
ctx.addLine(`result = result[0]`);
|
||||
}
|
||||
|
||||
// Step 5: restore previous scope
|
||||
// ------------------------------------------------
|
||||
if (hasBody) {
|
||||
ctx.stopProtectScope(protectID);
|
||||
ctx.dedent();
|
||||
ctx.addLine(`}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-foreach
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "foreach",
|
||||
extraNames: ["as"],
|
||||
priority: 10,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
ctx = ctx.subContext("loopNumber", ctx.loopNumber + 1);
|
||||
const elems = node.getAttribute("t-foreach")!;
|
||||
const name = node.getAttribute("t-as")!;
|
||||
let arrayID = ctx.generateID();
|
||||
ctx.addLine(`let _${arrayID} = ${ctx.formatExpression(elems)};`);
|
||||
ctx.addLine(`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`);
|
||||
let keysID = ctx.generateID();
|
||||
let valuesID = ctx.generateID();
|
||||
ctx.addLine(`let _${keysID} = _${valuesID} = _${arrayID};`);
|
||||
ctx.addIf(`!(_${arrayID} instanceof Array)`);
|
||||
ctx.addLine(`_${keysID} = Object.keys(_${arrayID});`);
|
||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
||||
ctx.closeIf();
|
||||
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.addLine(`scope.${name}_first = ${loopVar} === 0`);
|
||||
ctx.addLine(`scope.${name}_last = ${loopVar} === _length${keysID} - 1`);
|
||||
ctx.addLine(`scope.${name}_index = ${loopVar}`);
|
||||
ctx.addLine(`scope.${name} = _${keysID}[${loopVar}]`);
|
||||
ctx.addLine(`scope.${name}_value = _${valuesID}[${loopVar}]`);
|
||||
const nodeCopy = <Element>node.cloneNode(true);
|
||||
let shouldWarn =
|
||||
!nodeCopy.hasAttribute("t-key") &&
|
||||
node.children.length === 1 &&
|
||||
node.children[0].tagName !== "t" &&
|
||||
!node.children[0].hasAttribute("t-key");
|
||||
if (shouldWarn) {
|
||||
console.warn(
|
||||
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
||||
);
|
||||
}
|
||||
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");
|
||||
qweb._compileNode(nodeCopy, ctx);
|
||||
ctx.dedent();
|
||||
ctx.addLine("}");
|
||||
ctx.stopProtectScope(varsID);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-debug
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "debug",
|
||||
priority: 1,
|
||||
atNodeEncounter({ ctx }) {
|
||||
ctx.addLine("debugger;");
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-log
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "log",
|
||||
priority: 1,
|
||||
atNodeEncounter({ ctx, value }) {
|
||||
const expr = ctx.formatExpression(value);
|
||||
ctx.addLine(`console.log(${expr})`);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { compileExpr, compileExprToArray, QWebVar } from "./expression_parser";
|
||||
|
||||
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||
//------------------------------------------------------------------------------
|
||||
// Compilation Context
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export class CompilationContext {
|
||||
static nextID: number = 1;
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: QWebVar } = {};
|
||||
escaping: boolean = false;
|
||||
parentNode: number | null | string = null;
|
||||
parentTextNode: number | null = null;
|
||||
rootNode: number | null = null;
|
||||
indentLevel: number = 0;
|
||||
rootContext: CompilationContext;
|
||||
shouldDefineParent: boolean = false;
|
||||
shouldDefineScope: boolean = false;
|
||||
protectedScopeNumber: number = 0;
|
||||
shouldDefineQWeb: boolean = false;
|
||||
shouldDefineUtils: boolean = false;
|
||||
shouldDefineRefs: boolean = false;
|
||||
shouldDefineResult: boolean = true;
|
||||
loopNumber: number = 0;
|
||||
inPreTag: boolean = false;
|
||||
templateName: string;
|
||||
allowMultipleRoots: boolean = false;
|
||||
hasParentWidget: boolean = false;
|
||||
hasKey0: boolean = false;
|
||||
keyStack: boolean[] = [];
|
||||
|
||||
constructor(name?: string) {
|
||||
this.rootContext = this;
|
||||
this.templateName = name || "noname";
|
||||
this.addLine("let h = this.h;");
|
||||
}
|
||||
|
||||
generateID(): number {
|
||||
return CompilationContext.nextID++;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[] {
|
||||
if (this.shouldDefineResult) {
|
||||
this.code.unshift(" let result;");
|
||||
}
|
||||
|
||||
if (this.shouldDefineScope) {
|
||||
this.code.unshift(" let scope = Object.create(context);");
|
||||
}
|
||||
if (this.shouldDefineRefs) {
|
||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
||||
}
|
||||
if (this.shouldDefineParent) {
|
||||
if (this.hasParentWidget) {
|
||||
this.code.unshift(" let parent = extra.parent;");
|
||||
} else {
|
||||
this.code.unshift(" let parent = context;");
|
||||
}
|
||||
}
|
||||
if (this.shouldDefineQWeb) {
|
||||
this.code.unshift(" let QWeb = this.constructor;");
|
||||
}
|
||||
if (this.shouldDefineUtils) {
|
||||
this.code.unshift(" let utils = this.constructor.utils;");
|
||||
}
|
||||
return this.code;
|
||||
}
|
||||
|
||||
withParent(node: number): CompilationContext {
|
||||
if (
|
||||
!this.allowMultipleRoots &&
|
||||
this === this.rootContext &&
|
||||
(this.parentNode || this.parentTextNode)
|
||||
) {
|
||||
throw new Error("A template should not have more than one root node");
|
||||
}
|
||||
if (!this.rootContext.rootNode) {
|
||||
this.rootContext.rootNode = node;
|
||||
}
|
||||
if (!this.parentNode && this.rootContext.shouldDefineResult) {
|
||||
this.addLine(`result = vn${node};`);
|
||||
}
|
||||
return this.subContext("parentNode", node);
|
||||
}
|
||||
|
||||
subContext(key: keyof CompilationContext, value: any): CompilationContext {
|
||||
const newContext = Object.create(this);
|
||||
newContext[key] = value;
|
||||
return newContext;
|
||||
}
|
||||
|
||||
indent() {
|
||||
this.rootContext.indentLevel++;
|
||||
}
|
||||
|
||||
dedent() {
|
||||
this.rootContext.indentLevel--;
|
||||
}
|
||||
|
||||
addLine(line: string): number {
|
||||
const prefix = new Array(this.indentLevel + 2).join(" ");
|
||||
this.code.push(prefix + line);
|
||||
return this.code.length - 1;
|
||||
}
|
||||
|
||||
addIf(condition: string) {
|
||||
this.addLine(`if (${condition}) {`);
|
||||
this.indent();
|
||||
}
|
||||
|
||||
addElse() {
|
||||
this.dedent();
|
||||
this.addLine("} else {");
|
||||
this.indent();
|
||||
}
|
||||
|
||||
closeIf() {
|
||||
this.dedent();
|
||||
this.addLine("}");
|
||||
}
|
||||
|
||||
getValue(val: any): QWebVar | string {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare an expression for being consumed at render time. Its main job
|
||||
* is to
|
||||
* - replace unknown variables by a lookup in the context
|
||||
* - replace already defined variables by their internal name
|
||||
*/
|
||||
formatExpression(expr: string): string {
|
||||
this.rootContext.shouldDefineScope = true;
|
||||
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
|
||||
* string is an expression, it simply returns it (formatted and enclosed in
|
||||
* parentheses).
|
||||
* For instance:
|
||||
* 'Hello {{x}}!' -> `Hello ${x}`
|
||||
* '{{x ? 'a': 'b'}}' -> (x ? 'a' : 'b')
|
||||
*/
|
||||
interpolate(s: string): string {
|
||||
let matches = s.match(INTERP_REGEXP);
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
||||
}
|
||||
|
||||
let r = s.replace(/\{\{.*?\}\}/g, (s) => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
||||
return "`" + r + "`";
|
||||
}
|
||||
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};`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Owl QWeb Expression Parser
|
||||
*
|
||||
* Owl needs in various contexts to be able to understand the structure of a
|
||||
* string representing a javascript expression. The usual goal is to be able
|
||||
* to rewrite some variables. For example, if a template has
|
||||
*
|
||||
* ```xml
|
||||
* <t t-if="computeSomething({val: state.val})">...</t>
|
||||
* ```
|
||||
*
|
||||
* this needs to be translated in something like this:
|
||||
*
|
||||
* ```js
|
||||
* if (context["computeSomething"]({val: context["state"].val})) { ... }
|
||||
* ```
|
||||
*
|
||||
* This file contains the implementation of an extremely naive tokenizer/parser
|
||||
* and evaluator for javascript expressions. The supported grammar is basically
|
||||
* only expressive enough to understand the shape of objects, of arrays, and
|
||||
* various operators.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Misc types, constants and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||
","
|
||||
);
|
||||
|
||||
const WORD_REPLACEMENT = {
|
||||
and: "&&",
|
||||
or: "||",
|
||||
gt: ">",
|
||||
gte: ">=",
|
||||
lt: "<",
|
||||
lte: "<=",
|
||||
};
|
||||
|
||||
export interface QWebVar {
|
||||
id: string; // foo
|
||||
expr: string; // scope.foo (local variables => only foo)
|
||||
value?: string; // 1 + 3
|
||||
hasBody?: boolean;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tokenizer
|
||||
//------------------------------------------------------------------------------
|
||||
type TKind =
|
||||
| "LEFT_BRACE"
|
||||
| "RIGHT_BRACE"
|
||||
| "LEFT_BRACKET"
|
||||
| "RIGHT_BRACKET"
|
||||
| "LEFT_PAREN"
|
||||
| "RIGHT_PAREN"
|
||||
| "COMMA"
|
||||
| "VALUE"
|
||||
| "SYMBOL"
|
||||
| "OPERATOR"
|
||||
| "COLON";
|
||||
|
||||
interface Token {
|
||||
type: TKind;
|
||||
value: string;
|
||||
originalValue?: string;
|
||||
size?: number;
|
||||
varName?: string;
|
||||
}
|
||||
|
||||
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
||||
"{": "LEFT_BRACE",
|
||||
"}": "RIGHT_BRACE",
|
||||
"[": "LEFT_BRACKET",
|
||||
"]": "RIGHT_BRACKET",
|
||||
":": "COLON",
|
||||
",": "COMMA",
|
||||
"(": "LEFT_PAREN",
|
||||
")": "RIGHT_PAREN",
|
||||
};
|
||||
|
||||
// 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;
|
||||
|
||||
let tokenizeString: Tokenizer = function (expr) {
|
||||
let s = expr[0];
|
||||
let start = s;
|
||||
if (s !== "'" && s !== '"') {
|
||||
return false;
|
||||
}
|
||||
let i = 1;
|
||||
let cur;
|
||||
while (expr[i] && expr[i] !== start) {
|
||||
cur = expr[i];
|
||||
s += cur;
|
||||
if (cur === "\\") {
|
||||
i++;
|
||||
cur = expr[i];
|
||||
if (!cur) {
|
||||
throw new Error("Invalid expression");
|
||||
}
|
||||
s += cur;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (expr[i] !== start) {
|
||||
throw new Error("Invalid expression");
|
||||
}
|
||||
s += start;
|
||||
return { type: "VALUE", value: s };
|
||||
};
|
||||
|
||||
let tokenizeNumber: Tokenizer = function (expr) {
|
||||
let s = expr[0];
|
||||
if (s && s.match(/[0-9]/)) {
|
||||
let i = 1;
|
||||
while (expr[i] && expr[i].match(/[0-9]|\./)) {
|
||||
s += expr[i];
|
||||
i++;
|
||||
}
|
||||
return { type: "VALUE", value: s };
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let tokenizeSymbol: Tokenizer = function (expr) {
|
||||
let s = expr[0];
|
||||
if (s && s.match(/[a-zA-Z_\$]/)) {
|
||||
let i = 1;
|
||||
while (expr[i] && expr[i].match(/\w/)) {
|
||||
s += expr[i];
|
||||
i++;
|
||||
}
|
||||
if (s in WORD_REPLACEMENT) {
|
||||
return { type: "OPERATOR", value: WORD_REPLACEMENT[s], size: s.length };
|
||||
}
|
||||
return { type: "SYMBOL", value: s };
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const tokenizeStatic: Tokenizer = function (expr) {
|
||||
const char = expr[0];
|
||||
if (char && char in STATIC_TOKEN_MAP) {
|
||||
return { type: STATIC_TOKEN_MAP[char], value: char };
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const tokenizeOperator: Tokenizer = function (expr) {
|
||||
for (let op of OPERATORS) {
|
||||
if (expr.startsWith(op)) {
|
||||
return { type: "OPERATOR", value: op };
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const TOKENIZERS = [
|
||||
tokenizeString,
|
||||
tokenizeNumber,
|
||||
tokenizeOperator,
|
||||
tokenizeSymbol,
|
||||
tokenizeStatic,
|
||||
];
|
||||
|
||||
/**
|
||||
* Convert a javascript expression (as a string) into a list of tokens. For
|
||||
* example: `tokenize("1 + b")` will return:
|
||||
* ```js
|
||||
* [
|
||||
* {type: "VALUE", value: "1"},
|
||||
* {type: "OPERATOR", value: "+"},
|
||||
* {type: "SYMBOL", value: "b"}
|
||||
* ]
|
||||
* ```
|
||||
*/
|
||||
export function tokenize(expr: string): Token[] {
|
||||
const result: Token[] = [];
|
||||
let token: boolean | Token = true;
|
||||
|
||||
while (token) {
|
||||
expr = expr.trim();
|
||||
if (expr) {
|
||||
for (let tokenizer of TOKENIZERS) {
|
||||
token = tokenizer(expr);
|
||||
if (token) {
|
||||
result.push(token);
|
||||
expr = expr.slice(token.size || token.value.length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
token = false;
|
||||
}
|
||||
}
|
||||
if (expr.length) {
|
||||
throw new Error(`Tokenizer error: could not tokenize "${expr}"`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Expression "evaluator"
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This is the main function exported by this file. This is the code that will
|
||||
* process an expression (given as a string) and returns another expression with
|
||||
* proper lookups in the context.
|
||||
*
|
||||
* Usually, this kind of code would be very simple to do if we had an AST (so,
|
||||
* if we had a javascript parser), since then, we would only need to find the
|
||||
* variables and replace them. However, a parser is more complicated, and there
|
||||
* are no standard builtin parser API.
|
||||
*
|
||||
* Since this method is applied to simple javasript expressions, and the work to
|
||||
* be done is actually quite simple, we actually can get away with not using a
|
||||
* parser, which helps with the code size.
|
||||
*
|
||||
* Here is the heuristic used by this method to determine if a token is a
|
||||
* variable:
|
||||
* - by default, all symbols are considered a variable
|
||||
* - 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
|
||||
* 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 compileExprToArray(expr: string, scope: { [key: string]: QWebVar }): Token[] {
|
||||
scope = Object.create(scope);
|
||||
const tokens = tokenize(expr);
|
||||
for (let i = 0; i < tokens.length; 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 (prevToken) {
|
||||
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
||||
isVar = false;
|
||||
} else if (prevToken.type === "LEFT_BRACE" || prevToken.type === "COMMA") {
|
||||
if (nextToken && nextToken.type === "COLON") {
|
||||
isVar = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nextToken && nextToken.type === "OPERATOR" && nextToken.value === "=>") {
|
||||
if (token.type === "RIGHT_PAREN") {
|
||||
let j = i - 1;
|
||||
while (j > 0 && tokens[j].type !== "LEFT_PAREN") {
|
||||
if (tokens[j].type === "SYMBOL" && tokens[j].originalValue) {
|
||||
tokens[j].value = tokens[j].originalValue!;
|
||||
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}']`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function compileExpr(expr: string, scope: { [key: string]: QWebVar }): string {
|
||||
return compileExprToArray(expr, scope)
|
||||
.map((t) => t.value)
|
||||
.join("");
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
import { VNode } from "../vdom/index";
|
||||
import { QWeb } from "./qweb";
|
||||
|
||||
/**
|
||||
* Owl QWeb Extensions
|
||||
*
|
||||
* This file contains the implementation of non standard QWeb directives, added
|
||||
* by Owl and that will only work on Owl projects:
|
||||
*
|
||||
* - t-on
|
||||
* - t-ref
|
||||
* - t-transition
|
||||
* - t-mounted
|
||||
* - t-slot
|
||||
* - t-model
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-on
|
||||
//------------------------------------------------------------------------------
|
||||
// these are pieces of code that will be injected into the event handler if
|
||||
// modifiers are specified
|
||||
export const MODS_CODE = {
|
||||
prevent: "e.preventDefault();",
|
||||
self: "if (e.target !== this.elm) {return}",
|
||||
stop: "e.stopPropagation();",
|
||||
};
|
||||
|
||||
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({
|
||||
name: "on",
|
||||
priority: 90,
|
||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
||||
const { event, handler } = makeHandlerCode(ctx, fullName, value, true);
|
||||
ctx.addLine(`p${nodeID}.on['${event}'] = ${handler};`);
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-ref
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "ref",
|
||||
priority: 95,
|
||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
||||
ctx.rootContext.shouldDefineRefs = true;
|
||||
const refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
||||
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
||||
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-transition
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.utils.nextFrame = function (cb: () => void) {
|
||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
||||
};
|
||||
|
||||
QWeb.utils.transitionInsert = function (vn: VNode, name: string) {
|
||||
const elm = <HTMLElement>vn.elm;
|
||||
// remove potential duplicated vnode that is currently being removed, to
|
||||
// prevent from having twice the same node in the DOM during an animation
|
||||
const dup = elm.parentElement && elm.parentElement!.querySelector(`*[data-owl-key='${vn.key}']`);
|
||||
if (dup) {
|
||||
dup.remove();
|
||||
}
|
||||
|
||||
elm.classList.add(name + "-enter");
|
||||
elm.classList.add(name + "-enter-active");
|
||||
elm.classList.remove(name + "-leave-active");
|
||||
elm.classList.remove(name + "-leave-to");
|
||||
const finalize = () => {
|
||||
elm.classList.remove(name + "-enter-active");
|
||||
elm.classList.remove(name + "-enter-to");
|
||||
};
|
||||
this.nextFrame(() => {
|
||||
elm.classList.remove(name + "-enter");
|
||||
elm.classList.add(name + "-enter-to");
|
||||
whenTransitionEnd(elm, finalize);
|
||||
});
|
||||
};
|
||||
|
||||
QWeb.utils.transitionRemove = function (vn: VNode, name: string, rm: () => void) {
|
||||
const elm = <HTMLElement>vn.elm;
|
||||
elm.setAttribute("data-owl-key", vn.key!);
|
||||
|
||||
elm.classList.add(name + "-leave");
|
||||
elm.classList.add(name + "-leave-active");
|
||||
const finalize = () => {
|
||||
if (!elm.classList.contains(name + "-leave-active")) {
|
||||
return;
|
||||
}
|
||||
elm.classList.remove(name + "-leave-active");
|
||||
elm.classList.remove(name + "-leave-to");
|
||||
rm();
|
||||
};
|
||||
this.nextFrame(() => {
|
||||
elm.classList.remove(name + "-leave");
|
||||
elm.classList.add(name + "-leave-to");
|
||||
whenTransitionEnd(elm, finalize);
|
||||
});
|
||||
};
|
||||
|
||||
function getTimeout(delays: Array<string>, durations: Array<string>): number {
|
||||
/* istanbul ignore next */
|
||||
while (delays.length < durations.length) {
|
||||
delays = delays.concat(delays);
|
||||
}
|
||||
|
||||
return Math.max.apply(
|
||||
null,
|
||||
durations.map((d, i) => {
|
||||
return toMs(d) + toMs(delays[i]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
|
||||
// in a locale-dependent way, using a comma instead of a dot.
|
||||
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
|
||||
// as a floor function) causing unexpected behaviors
|
||||
function toMs(s: string): number {
|
||||
return Number(s.slice(0, -1).replace(",", ".")) * 1000;
|
||||
}
|
||||
|
||||
function whenTransitionEnd(elm: HTMLElement, cb) {
|
||||
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 delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
||||
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
||||
const timeout: number = getTimeout(delays, durations);
|
||||
if (timeout > 0) {
|
||||
elm.addEventListener("transitionend", cb, { once: true });
|
||||
} else {
|
||||
cb();
|
||||
}
|
||||
}
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "transition",
|
||||
priority: 96,
|
||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
let name = value;
|
||||
const hooks = {
|
||||
insert: `utils.transitionInsert(vn, '${name}');`,
|
||||
remove: `utils.transitionRemove(vn, '${name}', rm);`,
|
||||
};
|
||||
for (let hookName in hooks) {
|
||||
addNodeHook(hookName, hooks[hookName]);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-slot
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "slot",
|
||||
priority: 80,
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
const slotKey = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
||||
);
|
||||
ctx.addIf(`slot${slotKey}`);
|
||||
let parentNode = `c${ctx.parentNode}`;
|
||||
if (!ctx.parentNode) {
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
parentNode = `children${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${parentNode}= []`);
|
||||
ctx.addLine(`result = {}`);
|
||||
}
|
||||
ctx.addLine(
|
||||
`slot${slotKey}.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: ${parentNode}, parent: extra.parent || context}));`
|
||||
);
|
||||
if (!ctx.parentNode) {
|
||||
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();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-model
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.utils.toNumber = function (val: string): number | string {
|
||||
const n = parseFloat(val);
|
||||
return isNaN(n) ? val : n;
|
||||
};
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "model",
|
||||
priority: 42,
|
||||
atNodeCreation({ ctx, nodeID, value, node, fullName, addNodeHook }) {
|
||||
const type = node.getAttribute("type");
|
||||
let handler;
|
||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
||||
|
||||
// we keep here a reference to the "base expression" (if the expression
|
||||
// is `t-model="some.expr.value", then the base expression is "some.expr").
|
||||
// This is necessary so we can capture it in the handler closure.
|
||||
let expr = ctx.formatExpression(value);
|
||||
const index = expr.lastIndexOf(".");
|
||||
const baseExpr = expr.slice(0, index);
|
||||
ctx.addLine(`let expr${nodeID} = ${baseExpr};`);
|
||||
|
||||
expr = `expr${nodeID}.${expr.slice(index + 1)}`;
|
||||
const key = ctx.generateTemplateKey();
|
||||
if (node.tagName === "select") {
|
||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||
addNodeHook("create", `n.elm.value=${expr};`);
|
||||
event = "change";
|
||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
||||
} else if (type === "checkbox") {
|
||||
ctx.addLine(`p${nodeID}.props = {checked: ${expr}};`);
|
||||
handler = `(ev) => {${expr} = ev.target.checked}`;
|
||||
} else if (type === "radio") {
|
||||
const nodeValue = node.getAttribute("value")!;
|
||||
ctx.addLine(`p${nodeID}.props = {checked:${expr} === '${nodeValue}'};`);
|
||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
||||
event = "click";
|
||||
} else {
|
||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||
const trimCode = fullName.includes(".trim") ? ".trim()" : "";
|
||||
let valueCode = `ev.target.value${trimCode}`;
|
||||
if (fullName.includes(".number")) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
valueCode = `utils.toNumber(${valueCode})`;
|
||||
}
|
||||
handler = `(ev) => {${expr} = ${valueCode}}`;
|
||||
}
|
||||
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || (${handler});`);
|
||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers[${key}];`);
|
||||
},
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// 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;
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import "./base_directives";
|
||||
import "./extensions";
|
||||
|
||||
export { CompiledTemplate, QWeb } from "./qweb";
|
||||
@@ -0,0 +1,832 @@
|
||||
import { EventBus } from "../core/event_bus";
|
||||
import { h, patch, VNode } from "../vdom/index";
|
||||
import { CompilationContext } from "./compilation_context";
|
||||
import { shallowEqual, escape } from "../utils";
|
||||
import { addNS } from "../vdom/vdom";
|
||||
|
||||
/**
|
||||
* Owl QWeb Engine
|
||||
*
|
||||
* In this file, you will find a QWeb engine/template compiler. It is the core
|
||||
* of how Owl component works.
|
||||
*
|
||||
* Briefly, Owl QWeb compiles XML templates into functions that output a virtual
|
||||
* DOM representation.
|
||||
*
|
||||
* We have here:
|
||||
* - a CompilationContext class, which is an internal object that contains all
|
||||
* compilation specific information, while a template is being compiled.
|
||||
* - a QWeb class: this is the code of the QWeb compiler.
|
||||
*
|
||||
* Note that this file does not contain the implementation of the QWeb
|
||||
* directives (see qweb_directives.ts and qweb_extensions.ts).
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types
|
||||
//------------------------------------------------------------------------------
|
||||
export type EvalContext = { [key: string]: any };
|
||||
export type CompiledTemplate = (context: EvalContext, extra: any) => VNode;
|
||||
|
||||
interface Template {
|
||||
elem: Element;
|
||||
fn: CompiledTemplate;
|
||||
}
|
||||
|
||||
interface CompilationInfo {
|
||||
node: Element;
|
||||
qweb: QWeb;
|
||||
ctx: CompilationContext;
|
||||
fullName: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface NodeCreationCompilationInfo extends CompilationInfo {
|
||||
nodeID: number;
|
||||
addNodeHook: Function;
|
||||
}
|
||||
|
||||
export interface Directive {
|
||||
name: string;
|
||||
extraNames?: string[];
|
||||
priority: number;
|
||||
// if return true, then directive is fully applied and there is no need to
|
||||
// keep processing node. Otherwise, we keep going.
|
||||
atNodeEncounter?(info: CompilationInfo): boolean | void;
|
||||
atNodeCreation?(info: NodeCreationCompilationInfo): void;
|
||||
finalize?(info: CompilationInfo): void;
|
||||
}
|
||||
|
||||
interface QWebConfig {
|
||||
templates?: string;
|
||||
translateFn?(text: string): string;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Const/global stuff/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
|
||||
|
||||
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
|
||||
|
||||
const lineBreakRE = /[\r\n]/;
|
||||
const whitespaceRE = /\s+/g;
|
||||
|
||||
const NODE_HOOKS_PARAMS = {
|
||||
create: "(_, n)",
|
||||
insert: "vn",
|
||||
remove: "(vn, rm)",
|
||||
destroy: "()",
|
||||
};
|
||||
|
||||
interface Utils {
|
||||
toObj(expr: any): Object;
|
||||
shallowEqual(p1: Object, p2: Object): boolean;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
function isComponent(obj) {
|
||||
return obj && obj.hasOwnProperty("__owl__");
|
||||
}
|
||||
|
||||
const UTILS: Utils = {
|
||||
zero: Symbol("zero"),
|
||||
toObj(expr) {
|
||||
if (typeof expr === "string") {
|
||||
expr = expr.trim();
|
||||
if (!expr) {
|
||||
return {};
|
||||
}
|
||||
let words = expr.split(/\s+/);
|
||||
let result = {};
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
result[words[i]] = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return expr;
|
||||
},
|
||||
shallowEqual,
|
||||
addNameSpace(vnode) {
|
||||
addNS(vnode.data, vnode.children, vnode.sel);
|
||||
},
|
||||
VDomArray: class VDomArray extends Array {},
|
||||
vDomToString: function (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("");
|
||||
},
|
||||
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 {
|
||||
const parser = new DOMParser();
|
||||
|
||||
const doc = parser.parseFromString(xml, "text/xml");
|
||||
if (doc.getElementsByTagName("parsererror").length) {
|
||||
let msg = "Invalid XML in template.";
|
||||
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
|
||||
if (parsererrorText) {
|
||||
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
|
||||
const re = /\d+/g;
|
||||
const firstMatch = re.exec(parsererrorText);
|
||||
if (firstMatch) {
|
||||
const lineNumber = Number(firstMatch[0]);
|
||||
const line = xml.split("\n")[lineNumber - 1];
|
||||
const secondMatch = re.exec(parsererrorText);
|
||||
if (line && secondMatch) {
|
||||
const columnIndex = Number(secondMatch[0]) - 1;
|
||||
if (line[columnIndex]) {
|
||||
msg +=
|
||||
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
|
||||
`${line}\n${"-".repeat(columnIndex - 1)}^`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(msg);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
function escapeQuotes(str: string): string {
|
||||
return str.replace(/\'/g, "\\'");
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// QWeb rendering engine
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export class QWeb extends EventBus {
|
||||
templates: { [name: string]: Template };
|
||||
static utils = UTILS;
|
||||
static components = Object.create(null);
|
||||
|
||||
static DIRECTIVE_NAMES: { [key: string]: 1 } = {
|
||||
name: 1,
|
||||
att: 1,
|
||||
attf: 1,
|
||||
translation: 1,
|
||||
};
|
||||
static DIRECTIVES: Directive[] = [];
|
||||
|
||||
static TEMPLATES: { [name: string]: Template } = {};
|
||||
|
||||
static nextId: number = 1;
|
||||
|
||||
h = h;
|
||||
// dev mode enables better error messages or more costly validations
|
||||
static dev: boolean = false;
|
||||
|
||||
// slots contains sub templates defined with t-set inside t-component nodes, and
|
||||
// are meant to be used by the t-slot directive.
|
||||
static slots = {};
|
||||
static nextSlotId = 1;
|
||||
|
||||
// recursiveTemplates contains sub templates called with t-call, but which
|
||||
// ends up in recursive situations. This is very similar to the slot situation,
|
||||
// as in we need to propagate the scope.
|
||||
subTemplates = {};
|
||||
|
||||
isUpdating: boolean = false;
|
||||
translateFn?: QWebConfig["translateFn"];
|
||||
|
||||
constructor(config: QWebConfig = {}) {
|
||||
super();
|
||||
this.templates = Object.create(QWeb.TEMPLATES);
|
||||
if (config.templates) {
|
||||
this.addTemplates(config.templates);
|
||||
}
|
||||
if (config.translateFn) {
|
||||
this.translateFn = config.translateFn;
|
||||
}
|
||||
}
|
||||
|
||||
static addDirective(directive: Directive) {
|
||||
if (directive.name in QWeb.DIRECTIVE_NAMES) {
|
||||
throw new Error(`Directive "${directive.name} already registered`);
|
||||
}
|
||||
QWeb.DIRECTIVES.push(directive);
|
||||
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
||||
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
||||
if (directive.extraNames) {
|
||||
directive.extraNames.forEach((n) => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
||||
}
|
||||
}
|
||||
|
||||
static registerComponent(name: string, Component: any) {
|
||||
if (QWeb.components[name]) {
|
||||
throw new Error(`Component '${name}' has already been registered`);
|
||||
}
|
||||
QWeb.components[name] = Component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register globally a template. All QWeb instances will obtain their
|
||||
* templates from their own template map, and then, from the global static
|
||||
* TEMPLATES property.
|
||||
*/
|
||||
static registerTemplate(name: string, template: string) {
|
||||
if (QWeb.TEMPLATES[name]) {
|
||||
throw new Error(`Template '${name}' has already been registered`);
|
||||
}
|
||||
const qweb = new QWeb();
|
||||
qweb.addTemplate(name, template);
|
||||
QWeb.TEMPLATES[name] = qweb.templates[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a template to the internal template map. Note that it is not
|
||||
* immediately compiled.
|
||||
*/
|
||||
addTemplate(name: string, xmlString: string, allowDuplicate?: boolean) {
|
||||
if (allowDuplicate && name in this.templates) {
|
||||
return;
|
||||
}
|
||||
const doc = parseXML(xmlString);
|
||||
if (!doc.firstChild) {
|
||||
throw new Error("Invalid template (should not be empty)");
|
||||
}
|
||||
this._addTemplate(name, <Element>doc.firstChild);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load templates from a xml (as a string or xml document). This will look up
|
||||
* for the first <templates> tag, and will consider each child of this as a
|
||||
* template, with the name given by the t-name attribute.
|
||||
*/
|
||||
addTemplates(xmlstr: string | Document) {
|
||||
const doc = typeof xmlstr === "string" ? parseXML(xmlstr) : xmlstr;
|
||||
const templates = doc.getElementsByTagName("templates")[0];
|
||||
if (!templates) {
|
||||
return;
|
||||
}
|
||||
for (let elem of <any>templates.children) {
|
||||
const name = elem.getAttribute("t-name");
|
||||
this._addTemplate(name, elem);
|
||||
}
|
||||
}
|
||||
|
||||
_addTemplate(name: string, elem: Element) {
|
||||
if (name in this.templates) {
|
||||
throw new Error(`Template ${name} already defined`);
|
||||
}
|
||||
this._processTemplate(elem);
|
||||
const template = {
|
||||
elem,
|
||||
fn: function (this: QWeb, context, extra) {
|
||||
const compiledFunction = this._compile(name, elem);
|
||||
template.fn = compiledFunction;
|
||||
return compiledFunction.call(this, context, extra);
|
||||
},
|
||||
};
|
||||
this.templates[name] = template;
|
||||
}
|
||||
|
||||
_processTemplate(elem: Element) {
|
||||
let tbranch = elem.querySelectorAll("[t-elif], [t-else]");
|
||||
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
||||
let node = tbranch[i];
|
||||
let prevElem = node.previousElementSibling!;
|
||||
let pattr = function (name) {
|
||||
return prevElem.getAttribute(name);
|
||||
};
|
||||
let nattr = function (name) {
|
||||
return +!!node.getAttribute(name);
|
||||
};
|
||||
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
||||
if (pattr("t-foreach")) {
|
||||
throw new Error(
|
||||
"t-if cannot stay at the same level as t-foreach when using t-elif or t-else"
|
||||
);
|
||||
}
|
||||
if (
|
||||
["t-if", "t-elif", "t-else"].map(nattr).reduce(function (a, b) {
|
||||
return a + b;
|
||||
}) > 1
|
||||
) {
|
||||
throw new Error("Only one conditional branching directive is allowed per node");
|
||||
}
|
||||
// All text (with only spaces) and comment nodes (nodeType 8) between
|
||||
// branch nodes are removed
|
||||
let textNode;
|
||||
while ((textNode = node.previousSibling) !== prevElem) {
|
||||
if (textNode.nodeValue.trim().length && textNode.nodeType !== 8) {
|
||||
throw new Error("text is not allowed between branching directives");
|
||||
}
|
||||
textNode.remove();
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
"t-elif and t-else directives must be preceded by a t-if or t-elif directive"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Render a template
|
||||
*
|
||||
* @param {string} name the template should already have been added
|
||||
*/
|
||||
render(name: string, context: EvalContext = {}, extra: any = null): VNode {
|
||||
const template = this.templates[name];
|
||||
if (!template) {
|
||||
throw new Error(`Template ${name} does not exist`);
|
||||
}
|
||||
return template.fn.call(this, context, extra);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a template to a html string.
|
||||
*
|
||||
* Note that this is more limited than the `render` method: it is not suitable
|
||||
* to render a full component tree, since this is an asynchronous operation.
|
||||
* This method can only render templates without components.
|
||||
*/
|
||||
renderToString(name: string, context: EvalContext = {}, extra?: any): string {
|
||||
const vnode = this.render(name, context, extra);
|
||||
if (vnode.sel === undefined) {
|
||||
return vnode.text!;
|
||||
}
|
||||
const node = document.createElement(vnode.sel);
|
||||
const elem = patch(node, vnode).elm as HTMLElement;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Force all widgets connected to this QWeb instance to rerender themselves.
|
||||
*
|
||||
* This method is mostly useful for external code that want to modify the
|
||||
* application in some cases. For example, a router plugin.
|
||||
*/
|
||||
forceUpdate() {
|
||||
this.isUpdating = true;
|
||||
Promise.resolve().then(() => {
|
||||
if (this.isUpdating) {
|
||||
this.isUpdating = false;
|
||||
this.trigger("update");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_compile(
|
||||
name: string,
|
||||
elem: Element,
|
||||
parentContext?: CompilationContext,
|
||||
defineKey?: boolean
|
||||
): CompiledTemplate {
|
||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
||||
const ctx = new CompilationContext(name);
|
||||
if (elem.tagName !== "t") {
|
||||
ctx.shouldDefineResult = false;
|
||||
}
|
||||
if (parentContext) {
|
||||
ctx.variables = Object.create(parentContext.variables);
|
||||
ctx.parentNode = parentContext.parentNode || ctx.generateID();
|
||||
ctx.allowMultipleRoots = true;
|
||||
ctx.hasParentWidget = true;
|
||||
ctx.shouldDefineResult = false;
|
||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
||||
if (defineKey) {
|
||||
ctx.addLine(`let key0 = extra.key || "";`);
|
||||
ctx.hasKey0 = true;
|
||||
}
|
||||
}
|
||||
this._compileNode(elem, ctx);
|
||||
|
||||
if (!parentContext) {
|
||||
if (ctx.shouldDefineResult) {
|
||||
ctx.addLine(`return result;`);
|
||||
} else {
|
||||
if (!ctx.rootNode) {
|
||||
throw new Error(`A template should have one root node (${ctx.templateName})`);
|
||||
}
|
||||
ctx.addLine(`return vn${ctx.rootNode};`);
|
||||
}
|
||||
}
|
||||
|
||||
let code = ctx.generateCode();
|
||||
const templateName = ctx.templateName.replace(/`/g, "'").slice(0, 200);
|
||||
code.unshift(` // Template name: "${templateName}"`);
|
||||
|
||||
let template;
|
||||
try {
|
||||
template = new Function("context, extra", code.join("\n")) as CompiledTemplate;
|
||||
} catch (e) {
|
||||
console.groupCollapsed(`Invalid Code generated by ${templateName}`);
|
||||
console.warn(code.join("\n"));
|
||||
console.groupEnd();
|
||||
throw new Error(
|
||||
`Invalid generated code while compiling template '${templateName}': ${e.message}`
|
||||
);
|
||||
}
|
||||
if (isDebug) {
|
||||
const tpl = this.templates[name];
|
||||
if (tpl) {
|
||||
const msg = `Template: ${tpl.elem.outerHTML}\nCompiled code:\n${template.toString()}`;
|
||||
console.log(msg);
|
||||
}
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate code from an xml node
|
||||
*
|
||||
*/
|
||||
_compileNode(node: ChildNode, ctx: CompilationContext) {
|
||||
if (!(node instanceof Element)) {
|
||||
// this is a text node, there are no directive to apply
|
||||
let text = node.textContent!;
|
||||
if (!ctx.inPreTag) {
|
||||
if (lineBreakRE.test(text) && !text.trim()) {
|
||||
return;
|
||||
}
|
||||
text = text.replace(whitespaceRE, " ");
|
||||
}
|
||||
if (this.translateFn) {
|
||||
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
||||
text = this.translateFn(text);
|
||||
}
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
if (node.nodeType === 3) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||
} else if (node.nodeType === 8) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(h('!', \`${text}\`));`);
|
||||
}
|
||||
} else if (ctx.parentTextNode) {
|
||||
ctx.addLine(`vn${ctx.parentTextNode}.text += \`${text}\`;`);
|
||||
} else {
|
||||
// this is an unusual situation: this text node is the result of the
|
||||
// template rendering.
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.addLine(`let vn${nodeID} = {text: \`${text}\`};`);
|
||||
ctx.addLine(`result = vn${nodeID};`);
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const firstLetter = node.tagName[0];
|
||||
if (firstLetter === firstLetter.toUpperCase()) {
|
||||
// this is a component, we modify in place the xml document to change
|
||||
// <SomeComponent ... /> to <t t-component="SomeComponent" ... />
|
||||
node.setAttribute("t-component", node.tagName);
|
||||
} 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 validDirectives: {
|
||||
directive: Directive;
|
||||
value: string;
|
||||
fullName: string;
|
||||
}[] = [];
|
||||
|
||||
const finalizers: typeof validDirectives = [];
|
||||
|
||||
// maybe this is not optimal: we iterate on all attributes here, and again
|
||||
// just after for each directive.
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
let attrName = attributes[i].name;
|
||||
if (attrName.startsWith("t-")) {
|
||||
let dName = attrName.slice(2).split(/-|\./)[0];
|
||||
if (!(dName in QWeb.DIRECTIVE_NAMES)) {
|
||||
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
||||
}
|
||||
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
|
||||
const tNode = document.createElement("t");
|
||||
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
|
||||
for (let child of Array.from(node.childNodes)) {
|
||||
tNode.appendChild(child);
|
||||
}
|
||||
node.appendChild(tNode);
|
||||
node.removeAttribute(attrName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DIR_N = QWeb.DIRECTIVES.length;
|
||||
const ATTR_N = attributes.length;
|
||||
let withHandlers = false;
|
||||
for (let i = 0; i < DIR_N; i++) {
|
||||
let directive = QWeb.DIRECTIVES[i];
|
||||
let fullName;
|
||||
let value;
|
||||
for (let j = 0; j < ATTR_N; j++) {
|
||||
const name = attributes[j].name;
|
||||
if (
|
||||
name === "t-" + directive.name ||
|
||||
name.startsWith("t-" + directive.name + "-") ||
|
||||
name.startsWith("t-" + directive.name + ".")
|
||||
) {
|
||||
fullName = name;
|
||||
value = attributes[j].textContent;
|
||||
validDirectives.push({ directive, value, fullName });
|
||||
if (directive.name === "on" || directive.name === "model") {
|
||||
withHandlers = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.finalize) {
|
||||
finalizers.push({ directive, value, fullName });
|
||||
}
|
||||
if (directive.atNodeEncounter) {
|
||||
const isDone = directive.atNodeEncounter({
|
||||
node,
|
||||
qweb: this,
|
||||
ctx,
|
||||
fullName,
|
||||
value,
|
||||
});
|
||||
if (isDone) {
|
||||
for (let { directive, value, fullName } of finalizers) {
|
||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
let nodeHooks = {};
|
||||
let addNodeHook = function (hook, handler) {
|
||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||
nodeHooks[hook].push(handler);
|
||||
};
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.atNodeCreation) {
|
||||
directive.atNodeCreation({
|
||||
node,
|
||||
qweb: this,
|
||||
ctx,
|
||||
fullName,
|
||||
value,
|
||||
nodeID,
|
||||
addNodeHook,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(nodeHooks).length) {
|
||||
ctx.addLine(`p${nodeID}.hook = {`);
|
||||
for (let hook in nodeHooks) {
|
||||
ctx.addLine(` ${hook}: ${NODE_HOOKS_PARAMS[hook]} => {`);
|
||||
for (let handler of nodeHooks[hook]) {
|
||||
ctx.addLine(` ${handler}`);
|
||||
}
|
||||
ctx.addLine(` },`);
|
||||
}
|
||||
ctx.addLine(`};`);
|
||||
}
|
||||
}
|
||||
if (node.nodeName === "pre") {
|
||||
ctx = ctx.subContext("inPreTag", true);
|
||||
}
|
||||
|
||||
this._compileChildren(node, ctx);
|
||||
// svg support
|
||||
// we hadd svg namespace if it is a svg or if it is a g, but only if it is
|
||||
// the root node. This is the easiest way to support svg sub components:
|
||||
// they need to have a g tag as root. Otherwise, we would need a complete
|
||||
// list of allowed svg tags.
|
||||
const shouldAddNS =
|
||||
node.nodeName === "svg" || (node.nodeName === "g" && ctx.rootNode === ctx.parentNode);
|
||||
if (shouldAddNS) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.addLine(`utils.addNameSpace(vn${ctx.parentNode});`);
|
||||
}
|
||||
|
||||
for (let { directive, value, fullName } of finalizers) {
|
||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
}
|
||||
|
||||
_compileGenericNode(
|
||||
node: ChildNode,
|
||||
ctx: CompilationContext,
|
||||
withHandlers: boolean = true
|
||||
): number {
|
||||
// nodeType 1 is generic tag
|
||||
if (node.nodeType !== 1) {
|
||||
throw new Error("unsupported node type");
|
||||
}
|
||||
const attributes = (<Element>node).attributes;
|
||||
const attrs: string[] = [];
|
||||
const props: string[] = [];
|
||||
const tattrs: number[] = [];
|
||||
|
||||
function handleBooleanProps(key, val) {
|
||||
let isProp = false;
|
||||
if (node.nodeName === "input" && key === "checked") {
|
||||
let type = (<Element>node).getAttribute("type");
|
||||
if (type === "checkbox" || type === "radio") {
|
||||
isProp = true;
|
||||
}
|
||||
}
|
||||
if (node.nodeName === "option" && key === "selected") {
|
||||
isProp = true;
|
||||
}
|
||||
if (key === "disabled" && DISABLED_TAGS.indexOf(node.nodeName) > -1) {
|
||||
isProp = true;
|
||||
}
|
||||
if ((key === "readonly" && node.nodeName === "input") || node.nodeName === "textarea") {
|
||||
isProp = true;
|
||||
}
|
||||
if (isProp) {
|
||||
props.push(`${key}: _${val}`);
|
||||
}
|
||||
}
|
||||
let classObj = "";
|
||||
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
let name = attributes[i].name;
|
||||
let value = attributes[i].textContent!;
|
||||
|
||||
if (this.translateFn && TRANSLATABLE_ATTRS.includes(name)) {
|
||||
value = this.translateFn(value);
|
||||
}
|
||||
|
||||
// regular attributes
|
||||
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
||||
const attID = ctx.generateID();
|
||||
if (name === "class") {
|
||||
if ((value = value.trim())) {
|
||||
let classDef = value
|
||||
.split(/\s+/)
|
||||
.map((a) => `'${escapeQuotes(a)}':true`)
|
||||
.join(",");
|
||||
if (classObj) {
|
||||
ctx.addLine(`Object.assign(${classObj}, {${classDef}})`);
|
||||
} else {
|
||||
classObj = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx.addLine(`let _${attID} = '${escapeQuotes(value)}';`);
|
||||
if (!name.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
name = '"' + name + '"';
|
||||
}
|
||||
attrs.push(`${name}: _${attID}`);
|
||||
handleBooleanProps(name, attID);
|
||||
}
|
||||
}
|
||||
|
||||
// dynamic attributes
|
||||
if (name.startsWith("t-att-")) {
|
||||
let attName = name.slice(6);
|
||||
const v = ctx.getValue(value);
|
||||
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : `scope.${v.id}`;
|
||||
|
||||
if (attName === "class") {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
formattedValue = `utils.toObj(${formattedValue})`;
|
||||
if (classObj) {
|
||||
ctx.addLine(`Object.assign(${classObj}, ${formattedValue})`);
|
||||
} else {
|
||||
classObj = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${classObj} = ${formattedValue};`);
|
||||
}
|
||||
} else {
|
||||
const attID = ctx.generateID();
|
||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
attName = '"' + attName + '"';
|
||||
}
|
||||
// we need to combine dynamic with non dynamic attributes:
|
||||
// class="a" t-att-class="'yop'" should be rendered as class="a yop"
|
||||
const attValue = (<Element>node).getAttribute(attName);
|
||||
if (attValue) {
|
||||
const attValueID = ctx.generateID();
|
||||
ctx.addLine(`let _${attValueID} = ${formattedValue};`);
|
||||
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
||||
const attrIndex = attrs.findIndex((att) => att.startsWith(attName + ":"));
|
||||
attrs.splice(attrIndex, 1);
|
||||
}
|
||||
ctx.addLine(`let _${attID} = ${formattedValue};`);
|
||||
attrs.push(`${attName}: _${attID}`);
|
||||
handleBooleanProps(attName, attID);
|
||||
}
|
||||
}
|
||||
|
||||
if (name.startsWith("t-attf-")) {
|
||||
let attName = name.slice(7);
|
||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
attName = '"' + attName + '"';
|
||||
}
|
||||
const formattedExpr = ctx.interpolate(value);
|
||||
const attID = ctx.generateID();
|
||||
let staticVal = (<Element>node).getAttribute(attName);
|
||||
if (staticVal) {
|
||||
ctx.addLine(`let _${attID} = '${staticVal} ' + ${formattedExpr};`);
|
||||
} else {
|
||||
ctx.addLine(`let _${attID} = ${formattedExpr};`);
|
||||
}
|
||||
attrs.push(`${attName}: _${attID}`);
|
||||
}
|
||||
|
||||
// t-att= attributes
|
||||
if (name === "t-att") {
|
||||
let id = ctx.generateID();
|
||||
ctx.addLine(`let _${id} = ${ctx.formatExpression(value!)};`);
|
||||
tattrs.push(id);
|
||||
}
|
||||
}
|
||||
let nodeID = ctx.generateID();
|
||||
let key = ctx.loopNumber || ctx.hasKey0 ? `\`\${key${ctx.loopNumber}}_${nodeID}\`` : nodeID;
|
||||
const parts = [`key:${key}`];
|
||||
if (attrs.length + tattrs.length > 0) {
|
||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
||||
}
|
||||
if (props.length > 0) {
|
||||
parts.push(`props:{${props.join(",")}}`);
|
||||
}
|
||||
if (classObj) {
|
||||
parts.push(`class:${classObj}`);
|
||||
}
|
||||
if (withHandlers) {
|
||||
parts.push(`on:{}`);
|
||||
}
|
||||
|
||||
ctx.addLine(`let c${nodeID} = [], p${nodeID} = {${parts.join(",")}};`);
|
||||
for (let id of tattrs) {
|
||||
ctx.addIf(`_${id} instanceof Array`);
|
||||
ctx.addLine(`p${nodeID}.attrs[_${id}[0]] = _${id}[1];`);
|
||||
ctx.addElse();
|
||||
ctx.addLine(`for (let key in _${id}) {`);
|
||||
ctx.indent();
|
||||
ctx.addLine(`p${nodeID}.attrs[key] = _${id}[key];`);
|
||||
ctx.dedent();
|
||||
ctx.addLine(`}`);
|
||||
ctx.closeIf();
|
||||
}
|
||||
ctx.addLine(`let vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`);
|
||||
if (ctx.parentNode) {
|
||||
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;
|
||||
}
|
||||
|
||||
_compileChildren(node: ChildNode, ctx: CompilationContext) {
|
||||
if (node.childNodes.length > 0) {
|
||||
for (let child of Array.from(node.childNodes)) {
|
||||
this._compileNode(child, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,778 +0,0 @@
|
||||
import { VNode, h } from "./vdom";
|
||||
|
||||
/**
|
||||
* Owl QWeb Engine
|
||||
*
|
||||
* In this file, you will find a QWeb engine/template compiler. It is the core
|
||||
* of how Owl component works.
|
||||
*
|
||||
* Briefly, Owl QWeb compiles XML templates into functions that output a virtual
|
||||
* DOM representation.
|
||||
*
|
||||
* We have here:
|
||||
* - a CompilationContext class, which is an internal object that contains all
|
||||
* compilation specific information, while a template is being compiled.
|
||||
* - a QWeb class: this is the code of the QWeb compiler.
|
||||
*
|
||||
* Note that this file does not contain the implementation of the QWeb
|
||||
* directives (see qweb_directives.ts and qweb_extensions.ts).
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types
|
||||
//------------------------------------------------------------------------------
|
||||
export type EvalContext = { [key: string]: any };
|
||||
export type CompiledTemplate = (context: EvalContext, extra: any) => VNode;
|
||||
|
||||
interface Template {
|
||||
elem: Element;
|
||||
fn: CompiledTemplate;
|
||||
}
|
||||
|
||||
interface CompilationInfo {
|
||||
node: Element;
|
||||
qweb: QWeb;
|
||||
ctx: Context;
|
||||
fullName: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface NodeCreationCompilationInfo extends CompilationInfo {
|
||||
nodeID: number;
|
||||
addNodeHook: Function;
|
||||
}
|
||||
|
||||
export interface Directive {
|
||||
name: string;
|
||||
extraNames?: string[];
|
||||
priority: number;
|
||||
// if return true, then directive is fully applied and there is no need to
|
||||
// keep processing node. Otherwise, we keep going.
|
||||
atNodeEncounter?(info: CompilationInfo): boolean | void;
|
||||
atNodeCreation?(info: NodeCreationCompilationInfo): void;
|
||||
finalize?(info: CompilationInfo): void;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Const/global stuff/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 WORD_REPLACEMENT = {
|
||||
and: "&&",
|
||||
or: "||",
|
||||
gt: ">",
|
||||
gte: ">=",
|
||||
lt: "<",
|
||||
lte: "<="
|
||||
};
|
||||
|
||||
const DISABLED_TAGS = [
|
||||
"input",
|
||||
"textarea",
|
||||
"button",
|
||||
"select",
|
||||
"option",
|
||||
"optgroup"
|
||||
];
|
||||
|
||||
const lineBreakRE = /[\r\n]/;
|
||||
const whitespaceRE = /\s+/g;
|
||||
|
||||
const DIRECTIVE_NAMES = {
|
||||
name: 1,
|
||||
att: 1,
|
||||
attf: 1,
|
||||
key: 1
|
||||
};
|
||||
|
||||
const DIRECTIVES: Directive[] = [];
|
||||
|
||||
const NODE_HOOKS_PARAMS = {
|
||||
create: "(_, n)",
|
||||
insert: "vn",
|
||||
remove: "(vn, rm)"
|
||||
};
|
||||
|
||||
interface Utils {
|
||||
h: typeof h;
|
||||
objectToAttrString(obj: Object): string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export const UTILS: Utils = {
|
||||
h: h,
|
||||
objectToAttrString(obj: Object): string {
|
||||
let classes: string[] = [];
|
||||
for (let k in obj) {
|
||||
if (obj[k]) {
|
||||
classes.push(k);
|
||||
}
|
||||
}
|
||||
return classes.join(" ");
|
||||
}
|
||||
};
|
||||
|
||||
function parseXML(xml: string): Document {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(xml, "text/xml");
|
||||
if (doc.getElementsByTagName("parsererror").length) {
|
||||
throw new Error("Invalid XML in template");
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
let nextID = 1;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// QWeb rendering engine
|
||||
//------------------------------------------------------------------------------
|
||||
export class QWeb {
|
||||
templates: { [name: string]: Template } = {};
|
||||
utils = UTILS;
|
||||
static widgets = Object.create(null);
|
||||
|
||||
// dev mode enables better error messages or more costly validations
|
||||
static dev: boolean = false;
|
||||
|
||||
// the id field is useful to be able to hash qweb instances. The current
|
||||
// use case is that component's templates are qweb dependant, and need to be
|
||||
// able to map a qweb instance to a template name.
|
||||
id = nextID++;
|
||||
|
||||
constructor(data?: string) {
|
||||
if (data) {
|
||||
this.addTemplates(data);
|
||||
}
|
||||
this.addTemplate("default", "<div></div>");
|
||||
}
|
||||
|
||||
static addDirective(directive: Directive) {
|
||||
DIRECTIVES.push(directive);
|
||||
DIRECTIVE_NAMES[directive.name] = 1;
|
||||
DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
||||
if (directive.extraNames) {
|
||||
directive.extraNames.forEach(n => (DIRECTIVE_NAMES[n] = 1));
|
||||
}
|
||||
}
|
||||
|
||||
static register(name: string, Component: any) {
|
||||
if (QWeb.widgets[name]) {
|
||||
throw new Error(`Component '${name}' has already been registered`);
|
||||
}
|
||||
QWeb.widgets[name] = Component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a template to the internal template map. Note that it is not
|
||||
* immediately compiled.
|
||||
*/
|
||||
addTemplate(name: string, xmlString: string) {
|
||||
const doc = parseXML(xmlString);
|
||||
if (!doc.firstChild) {
|
||||
throw new Error("Invalid template (should not be empty)");
|
||||
}
|
||||
this._addTemplate(name, <Element>doc.firstChild);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load templates from a xml (as a string). This will look up for the first
|
||||
* <templates> tag, and will consider each child of this as a template, with
|
||||
* the name given by the t-name attribute.
|
||||
*/
|
||||
addTemplates(xmlstr: string) {
|
||||
const doc = parseXML(xmlstr);
|
||||
const templates = doc.getElementsByTagName("templates")[0];
|
||||
if (!templates) {
|
||||
return;
|
||||
}
|
||||
for (let elem of <any>templates.children) {
|
||||
const name = elem.getAttribute("t-name");
|
||||
this._addTemplate(name, elem);
|
||||
}
|
||||
}
|
||||
|
||||
_addTemplate(name: string, elem: Element) {
|
||||
if (name in this.templates) {
|
||||
throw new Error(`Template ${name} already defined`);
|
||||
}
|
||||
this._processTemplate(elem);
|
||||
const template = {
|
||||
elem,
|
||||
fn: (context, extra) => {
|
||||
const compiledFunction = this._compile(name, elem);
|
||||
template.fn = compiledFunction;
|
||||
return compiledFunction.call(this, context, extra);
|
||||
}
|
||||
};
|
||||
this.templates[name] = template;
|
||||
}
|
||||
|
||||
_processTemplate(elem: Element) {
|
||||
let tbranch = elem.querySelectorAll("[t-elif], [t-else]");
|
||||
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
||||
let node = tbranch[i];
|
||||
let prevElem = node.previousElementSibling!;
|
||||
let pattr = function(name) {
|
||||
return prevElem.getAttribute(name);
|
||||
};
|
||||
let nattr = function(name) {
|
||||
return +!!node.getAttribute(name);
|
||||
};
|
||||
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
||||
if (pattr("t-foreach")) {
|
||||
throw new Error(
|
||||
"t-if cannot stay at the same level as t-foreach when using t-elif or t-else"
|
||||
);
|
||||
}
|
||||
if (
|
||||
["t-if", "t-elif", "t-else"].map(nattr).reduce(function(a, b) {
|
||||
return a + b;
|
||||
}) > 1
|
||||
) {
|
||||
throw new Error(
|
||||
"Only one conditional branching directive is allowed per node"
|
||||
);
|
||||
}
|
||||
// All text nodes between branch nodes are removed
|
||||
let textNode;
|
||||
while ((textNode = node.previousSibling) !== prevElem) {
|
||||
if (textNode.nodeValue.trim().length) {
|
||||
throw new Error("text is not allowed between branching directives");
|
||||
}
|
||||
textNode.remove();
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
"t-elif and t-else directives must be preceded by a t-if or t-elif directive"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Render a template
|
||||
*
|
||||
* @param {string} name the template should already have been added
|
||||
*/
|
||||
render(name: string, context: EvalContext = {}, extra: any = null): VNode {
|
||||
const template = this.templates[name];
|
||||
if (!template) {
|
||||
throw new Error(`Template ${name} does not exist`);
|
||||
}
|
||||
return template.fn.call(this, context, extra);
|
||||
}
|
||||
|
||||
_compile(name: string, elem: Element): CompiledTemplate {
|
||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
||||
const ctx = new Context(name);
|
||||
this._compileNode(elem, ctx);
|
||||
|
||||
if (ctx.shouldProtectContext) {
|
||||
ctx.code.unshift(" context = Object.create(context);");
|
||||
}
|
||||
if (ctx.shouldDefineOwner) {
|
||||
// this is necessary to prevent some directives (t-forach for ex) to
|
||||
// pollute the rendering context by adding some keys in it.
|
||||
ctx.code.unshift(" let owner = context;");
|
||||
}
|
||||
if (ctx.shouldDefineQWeb) {
|
||||
ctx.code.unshift(" let QWeb = this.constructor;");
|
||||
}
|
||||
if (ctx.shouldDefineUtils) {
|
||||
ctx.code.unshift(" let utils = this.utils;");
|
||||
}
|
||||
|
||||
if (!ctx.rootNode) {
|
||||
throw new Error("A template should have one root node");
|
||||
}
|
||||
ctx.addLine(`return vn${ctx.rootNode};`);
|
||||
let template;
|
||||
try {
|
||||
template = new Function(
|
||||
"context",
|
||||
"extra",
|
||||
ctx.code.join("\n")
|
||||
) as CompiledTemplate;
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Invalid generated code while compiling template '${ctx.templateName.replace(
|
||||
/`/g,
|
||||
"'"
|
||||
)}': ${e.message}`
|
||||
);
|
||||
}
|
||||
if (isDebug) {
|
||||
console.log(
|
||||
`Template: ${this.templates[name].elem.outerHTML}\nCompiled code:\n` +
|
||||
template.toString()
|
||||
);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate code from an xml node
|
||||
*
|
||||
*/
|
||||
_compileNode(node: ChildNode, ctx: Context) {
|
||||
if (!(node instanceof Element)) {
|
||||
// this is a text node, there are no directive to apply
|
||||
let text = node.textContent!;
|
||||
if (!ctx.inPreTag) {
|
||||
if (lineBreakRE.test(text) && !text.trim()) {
|
||||
return;
|
||||
}
|
||||
text = text.replace(whitespaceRE, " ");
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||
} else {
|
||||
// this is an unusual situation: this text node is the result of the
|
||||
// template rendering.
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.addLine(`var vn${nodeID} = {text: \`${text}\`};`);
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentNode = nodeID;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const attributes = (<Element>node).attributes;
|
||||
|
||||
const validDirectives: {
|
||||
directive: Directive;
|
||||
value: string;
|
||||
fullName: string;
|
||||
}[] = [];
|
||||
|
||||
let withHandlers = false;
|
||||
|
||||
// maybe this is not optimal: we iterate on all attributes here, and again
|
||||
// just after for each directive.
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
let attrName = attributes[i].name;
|
||||
if (attrName.startsWith("t-")) {
|
||||
let dName = attrName.slice(2).split("-")[0];
|
||||
if (!(dName in DIRECTIVE_NAMES)) {
|
||||
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DIR_N = DIRECTIVES.length;
|
||||
const ATTR_N = attributes.length;
|
||||
for (let i = 0; i < DIR_N; i++) {
|
||||
let directive = DIRECTIVES[i];
|
||||
let fullName;
|
||||
let value;
|
||||
for (let j = 0; j < ATTR_N; j++) {
|
||||
const name = attributes[j].name;
|
||||
if (
|
||||
name === "t-" + directive.name ||
|
||||
name.startsWith("t-" + directive.name + "-")
|
||||
) {
|
||||
fullName = name;
|
||||
value = attributes[j].textContent;
|
||||
validDirectives.push({ directive, value, fullName });
|
||||
if (directive.name === "on") {
|
||||
withHandlers = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.atNodeEncounter) {
|
||||
const isDone = directive.atNodeEncounter({
|
||||
node,
|
||||
qweb: this,
|
||||
ctx,
|
||||
fullName,
|
||||
value
|
||||
});
|
||||
if (isDone) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
let nodeHooks = {};
|
||||
let addNodeHook = function(hook, handler) {
|
||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||
nodeHooks[hook].push(handler);
|
||||
};
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.atNodeCreation) {
|
||||
directive.atNodeCreation({
|
||||
node,
|
||||
qweb: this,
|
||||
ctx,
|
||||
fullName,
|
||||
value,
|
||||
nodeID,
|
||||
addNodeHook
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(nodeHooks).length) {
|
||||
ctx.addLine(`p${nodeID}.hook = {`);
|
||||
for (let hook in nodeHooks) {
|
||||
ctx.addLine(` ${hook}: ${NODE_HOOKS_PARAMS[hook]} => {`);
|
||||
for (let handler of nodeHooks[hook]) {
|
||||
ctx.addLine(` ${handler}`);
|
||||
}
|
||||
ctx.addLine(` },`);
|
||||
}
|
||||
ctx.addLine(`};`);
|
||||
}
|
||||
}
|
||||
if (node.nodeName === "pre") {
|
||||
ctx = ctx.subContext("inPreTag", true);
|
||||
}
|
||||
|
||||
this._compileChildren(node, ctx);
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.finalize) {
|
||||
directive.finalize({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_compileGenericNode(
|
||||
node: ChildNode,
|
||||
ctx: Context,
|
||||
withHandlers: boolean = true
|
||||
): number {
|
||||
// nodeType 1 is generic tag
|
||||
if (node.nodeType !== 1) {
|
||||
throw new Error("unsupported node type");
|
||||
}
|
||||
const attributes = (<Element>node).attributes;
|
||||
const attrs: string[] = [];
|
||||
const props: string[] = [];
|
||||
const tattrs: number[] = [];
|
||||
|
||||
function handleBooleanProps(key, val) {
|
||||
let isProp = false;
|
||||
if (node.nodeName === "input" && key === "checked") {
|
||||
let type = (<Element>node).getAttribute("type");
|
||||
if (type === "checkbox" || type === "radio") {
|
||||
isProp = true;
|
||||
}
|
||||
}
|
||||
if (node.nodeName === "option" && key === "selected") {
|
||||
isProp = true;
|
||||
}
|
||||
if (key === "disabled" && DISABLED_TAGS.indexOf(node.nodeName) > -1) {
|
||||
isProp = true;
|
||||
}
|
||||
if (
|
||||
(key === "readonly" && node.nodeName === "input") ||
|
||||
node.nodeName === "textarea"
|
||||
) {
|
||||
isProp = true;
|
||||
}
|
||||
if (isProp) {
|
||||
props.push(`${key}: _${val}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
let name = attributes[i].name;
|
||||
const value = attributes[i].textContent!;
|
||||
|
||||
// regular attributes
|
||||
if (
|
||||
!name.startsWith("t-") &&
|
||||
!(<Element>node).getAttribute("t-attf-" + name)
|
||||
) {
|
||||
const attID = ctx.generateID();
|
||||
ctx.addLine(`var _${attID} = '${value}';`);
|
||||
if (!name.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
name = '"' + name + '"';
|
||||
}
|
||||
attrs.push(`${name}: _${attID}`);
|
||||
handleBooleanProps(name, attID);
|
||||
}
|
||||
|
||||
// dynamic attributes
|
||||
if (name.startsWith("t-att-")) {
|
||||
let attName = name.slice(6);
|
||||
let formattedValue = ctx.formatExpression(ctx.getValue(value!));
|
||||
if (
|
||||
formattedValue[0] === "{" &&
|
||||
formattedValue[formattedValue.length - 1] === "}"
|
||||
) {
|
||||
formattedValue = `this.utils.objectToAttrString(${formattedValue})`;
|
||||
}
|
||||
const attID = ctx.generateID();
|
||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
attName = '"' + attName + '"';
|
||||
}
|
||||
// we need to combine dynamic with non dynamic attributes:
|
||||
// class="a" t-att-class="'yop'" should be rendered as class="a yop"
|
||||
const attValue = (<Element>node).getAttribute(attName);
|
||||
if (attValue) {
|
||||
const attValueID = ctx.generateID();
|
||||
ctx.addLine(`var _${attValueID} = ${formattedValue};`);
|
||||
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
||||
const attrIndex = attrs.findIndex(att =>
|
||||
att.startsWith(attName + ":")
|
||||
);
|
||||
attrs.splice(attrIndex, 1);
|
||||
}
|
||||
ctx.addLine(`var _${attID} = ${formattedValue};`);
|
||||
attrs.push(`${attName}: _${attID}`);
|
||||
handleBooleanProps(attName, attID);
|
||||
}
|
||||
|
||||
if (name.startsWith("t-attf-")) {
|
||||
let attName = name.slice(7);
|
||||
if (!attName.match(/^[a-zA-Z]+$/)) {
|
||||
// attribute contains 'non letters' => we want to quote it
|
||||
attName = '"' + attName + '"';
|
||||
}
|
||||
const formattedExpr = ctx.interpolate(value);
|
||||
const attID = ctx.generateID();
|
||||
let staticVal = (<Element>node).getAttribute(attName);
|
||||
if (staticVal) {
|
||||
ctx.addLine(`var _${attID} = '${staticVal} ' + ${formattedExpr};`);
|
||||
} else {
|
||||
ctx.addLine(`var _${attID} = ${formattedExpr};`);
|
||||
}
|
||||
attrs.push(`${attName}: _${attID}`);
|
||||
}
|
||||
|
||||
// t-att= attributes
|
||||
if (name === "t-att") {
|
||||
let id = ctx.generateID();
|
||||
ctx.addLine(`var _${id} = ${ctx.formatExpression(value!)};`);
|
||||
tattrs.push(id);
|
||||
}
|
||||
}
|
||||
let nodeID = ctx.generateID();
|
||||
let nodeKey: any = (<Element>node).getAttribute("t-key");
|
||||
if (nodeKey) {
|
||||
nodeKey = ctx.formatExpression(nodeKey);
|
||||
} else {
|
||||
nodeKey = nodeID;
|
||||
}
|
||||
const parts = [`key:${nodeKey}`];
|
||||
if (attrs.length + tattrs.length > 0) {
|
||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
||||
}
|
||||
if (props.length > 0) {
|
||||
parts.push(`props:{${props.join(",")}}`);
|
||||
}
|
||||
if (withHandlers) {
|
||||
parts.push(`on:{}`);
|
||||
}
|
||||
|
||||
ctx.addLine(`let c${nodeID} = [], p${nodeID} = {${parts.join(",")}};`);
|
||||
for (let id of tattrs) {
|
||||
ctx.addIf(`_${id} instanceof Array`);
|
||||
ctx.addLine(`p${nodeID}.attrs[_${id}[0]] = _${id}[1];`);
|
||||
ctx.addElse();
|
||||
ctx.addLine(`for (let key in _${id}) {`);
|
||||
ctx.indent();
|
||||
ctx.addLine(`p${nodeID}.attrs[key] = _${id}[key];`);
|
||||
ctx.dedent();
|
||||
ctx.addLine(`}`);
|
||||
ctx.closeIf();
|
||||
}
|
||||
ctx.addLine(
|
||||
`var vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`
|
||||
);
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
||||
}
|
||||
|
||||
return nodeID;
|
||||
}
|
||||
|
||||
_compileChildren(node: ChildNode, ctx: Context) {
|
||||
if (node.childNodes.length > 0) {
|
||||
for (let child of Array.from(node.childNodes)) {
|
||||
this._compileNode(child, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Compilation Context
|
||||
//------------------------------------------------------------------------------
|
||||
export class Context {
|
||||
nextID: number = 1;
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: any } = {};
|
||||
definedVariables: { [key: string]: string } = {};
|
||||
escaping: boolean = false;
|
||||
parentNode: number | null = null;
|
||||
rootNode: number | null = null;
|
||||
indentLevel: number = 0;
|
||||
rootContext: Context;
|
||||
caller: Element | undefined;
|
||||
shouldDefineOwner: boolean = false;
|
||||
shouldDefineQWeb: boolean = false;
|
||||
shouldDefineUtils: boolean = false;
|
||||
shouldProtectContext: boolean = false;
|
||||
inLoop: boolean = false;
|
||||
inPreTag: boolean = false;
|
||||
templateName: string;
|
||||
|
||||
constructor(name?: string) {
|
||||
this.rootContext = this;
|
||||
this.templateName = name || "noname";
|
||||
this.addLine("var h = this.utils.h;");
|
||||
}
|
||||
|
||||
generateID(): number {
|
||||
const id = this.rootContext.nextID++;
|
||||
return id;
|
||||
}
|
||||
|
||||
withParent(node: number): Context {
|
||||
if (this === this.rootContext && this.parentNode) {
|
||||
throw new Error("A template should not have more than one root node");
|
||||
}
|
||||
if (!this.rootContext.rootNode) {
|
||||
this.rootContext.rootNode = node;
|
||||
}
|
||||
return this.subContext("parentNode", node);
|
||||
}
|
||||
|
||||
subContext(key: keyof Context, value: any): Context {
|
||||
const newContext = Object.create(this);
|
||||
newContext[key] = value;
|
||||
return newContext;
|
||||
}
|
||||
|
||||
indent() {
|
||||
this.indentLevel++;
|
||||
}
|
||||
|
||||
dedent() {
|
||||
this.indentLevel--;
|
||||
}
|
||||
|
||||
addLine(line: string) {
|
||||
const prefix = new Array(this.indentLevel + 2).join(" ");
|
||||
this.code.push(prefix + line);
|
||||
}
|
||||
|
||||
addIf(condition: string) {
|
||||
this.addLine(`if (${condition}) {`);
|
||||
this.indent();
|
||||
}
|
||||
|
||||
addElse() {
|
||||
this.dedent();
|
||||
this.addLine("} else {");
|
||||
this.indent();
|
||||
}
|
||||
|
||||
closeIf() {
|
||||
this.dedent();
|
||||
this.addLine("}");
|
||||
}
|
||||
|
||||
getValue(val: any): any {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
}
|
||||
|
||||
formatExpression(e: string): string {
|
||||
e = e.trim();
|
||||
if (e[0] === "{" && e[e.length - 1] === "}") {
|
||||
const innerExpr = e
|
||||
.slice(1, -1)
|
||||
.split(",")
|
||||
.map(p => {
|
||||
let [key, val] = p.trim().split(":");
|
||||
if (key === "") {
|
||||
return "";
|
||||
}
|
||||
if (!val) {
|
||||
val = key;
|
||||
}
|
||||
return `${key}: ${this.formatExpression(val)}`;
|
||||
})
|
||||
.join(",");
|
||||
return "{" + innerExpr + "}";
|
||||
}
|
||||
|
||||
// Thanks CHM for this code...
|
||||
const chars = e.split("");
|
||||
let instring = "";
|
||||
let invar = "";
|
||||
let invarPos = 0;
|
||||
let r = "";
|
||||
chars.push(" ");
|
||||
for (let i = 0, ilen = chars.length; i < ilen; i++) {
|
||||
let c = chars[i];
|
||||
if (instring.length) {
|
||||
if (c === instring && chars[i - 1] !== "\\") {
|
||||
instring = "";
|
||||
}
|
||||
} else if (c === '"' || c === "'") {
|
||||
instring = c;
|
||||
} else if (c.match(/[a-zA-Z_\$]/) && !invar.length) {
|
||||
invar = c;
|
||||
invarPos = i;
|
||||
continue;
|
||||
} else if (c.match(/\W/) && invar.length) {
|
||||
// TODO: Should check for possible spaces before dot
|
||||
if (chars[invarPos - 1] !== "." && RESERVED_WORDS.indexOf(invar) < 0) {
|
||||
if (!(invar in this.definedVariables)) {
|
||||
invar =
|
||||
WORD_REPLACEMENT[invar] ||
|
||||
(invar in this.variables &&
|
||||
this.formatExpression(this.variables[invar])) ||
|
||||
"context['" + invar + "']";
|
||||
}
|
||||
}
|
||||
r += invar;
|
||||
invar = "";
|
||||
} else if (invar.length) {
|
||||
invar += c;
|
||||
continue;
|
||||
}
|
||||
r += c;
|
||||
}
|
||||
const result = r.slice(0, -1);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform string interpolation on the given string. Note that if the whole
|
||||
* string is an expression, it simply returns it (formatted).
|
||||
* For instance:
|
||||
* 'Hello {{x}}!' -> `Hello ${x}`
|
||||
* '{{x}}' -> x
|
||||
*/
|
||||
interpolate(s: string): string {
|
||||
let matches = s.match(/\{\{.*?\}\}/g);
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return this.formatExpression(s.slice(2, -2));
|
||||
}
|
||||
matches = s.match(/\#\{.*?\}/g);
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return this.formatExpression(s.slice(2, -1));
|
||||
}
|
||||
|
||||
let formatter = expr => "${" + this.formatExpression(expr) + "}";
|
||||
let r = s
|
||||
.replace(/\{\{.*?\}\}/g, s => formatter(s.slice(2, -2)))
|
||||
.replace(/\#\{.*?\}/g, s => formatter(s.slice(2, -1)));
|
||||
return "`" + r + "`";
|
||||
}
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
import { Context, QWeb, UTILS } from "./qweb_core";
|
||||
|
||||
/**
|
||||
* Owl QWeb Directives
|
||||
*
|
||||
* This file contains the implementation of most standard QWeb directives:
|
||||
* - t-esc
|
||||
* - t-raw
|
||||
* - t-set/t-value
|
||||
* - t-if/t-elif/t-else
|
||||
* - t-call
|
||||
* - t-foreach/t-as
|
||||
* - t-debug
|
||||
* - t-log
|
||||
*/
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-esc and t-raw
|
||||
//------------------------------------------------------------------------------
|
||||
(<any>UTILS).getFragment = function(str: string): DocumentFragment {
|
||||
const temp = document.createElement("template");
|
||||
temp.innerHTML = str;
|
||||
return temp.content;
|
||||
};
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
|
||||
if (value === "0" && ctx.caller) {
|
||||
qweb._compileNode(ctx.caller, ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
let exprID = value;
|
||||
if (!(value in ctx.definedVariables)) {
|
||||
exprID = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
||||
}
|
||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
||||
if (!ctx.parentNode) {
|
||||
throw new Error("Should not have a text node without a parent");
|
||||
}
|
||||
if (ctx.escaping) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: ${exprID}});`);
|
||||
} else {
|
||||
let fragID = ctx.generateID();
|
||||
ctx.addLine(`var frag${fragID} = this.utils.getFragment(${exprID})`);
|
||||
let tempNodeID = ctx.generateID();
|
||||
ctx.addLine(`var p${tempNodeID} = {hook: {`);
|
||||
ctx.addLine(
|
||||
` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`
|
||||
);
|
||||
ctx.addLine(`}};`);
|
||||
ctx.addLine(`var vn${tempNodeID} = h('div', p${tempNodeID})`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
|
||||
}
|
||||
if (node.childNodes.length) {
|
||||
ctx.addElse();
|
||||
qweb._compileChildren(node, ctx);
|
||||
}
|
||||
ctx.closeIf();
|
||||
return;
|
||||
}
|
||||
if (value instanceof NodeList) {
|
||||
for (let node of Array.from(value)) {
|
||||
qweb._compileNode(<ChildNode>node, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "esc",
|
||||
priority: 70,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = qweb._compileGenericNode(node, ctx);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
}
|
||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "raw",
|
||||
priority: 80,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = qweb._compileGenericNode(node, ctx);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
}
|
||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
||||
compileValueNode(value, node, qweb, ctx);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-set
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "set",
|
||||
extraNames: ["value"],
|
||||
priority: 60,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
const variable = node.getAttribute("t-set")!;
|
||||
let value = node.getAttribute("t-value")!;
|
||||
if (value) {
|
||||
const formattedValue = ctx.formatExpression(value);
|
||||
if (ctx.variables.hasOwnProperty(variable)) {
|
||||
ctx.addLine(`${ctx.variables[variable]} = ${formattedValue}`);
|
||||
} else {
|
||||
const varName = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
||||
ctx.definedVariables[varName] = formattedValue;
|
||||
ctx.variables[variable] = varName;
|
||||
}
|
||||
} else {
|
||||
ctx.variables[variable] = node.childNodes;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-if, t-elif, t-else
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "if",
|
||||
priority: 20,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||
ctx.addIf(`${ctx.formatExpression(cond)}`);
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "elif",
|
||||
priority: 30,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
||||
ctx.addLine(`else if (${ctx.formatExpression(cond)}) {`);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
});
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "else",
|
||||
priority: 40,
|
||||
atNodeEncounter({ ctx }): boolean {
|
||||
ctx.addLine(`else {`);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-call
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "call",
|
||||
priority: 50,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
if (node.nodeName !== "t") {
|
||||
throw new Error("Invalid tag for t-call directive (should be 't')");
|
||||
}
|
||||
const subTemplate = node.getAttribute("t-call")!;
|
||||
const nodeTemplate = qweb.templates[subTemplate];
|
||||
if (!nodeTemplate) {
|
||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
||||
}
|
||||
const nodeCopy = node.cloneNode(true) as Element;
|
||||
nodeCopy.removeAttribute("t-call");
|
||||
|
||||
// extract variables from nodecopy
|
||||
const tempCtx = new Context();
|
||||
tempCtx.nextID = ctx.rootContext.nextID;
|
||||
qweb._compileNode(nodeCopy, tempCtx);
|
||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
||||
var definedVariables = Object.assign(
|
||||
{},
|
||||
ctx.definedVariables,
|
||||
tempCtx.definedVariables
|
||||
);
|
||||
ctx.rootContext.nextID = tempCtx.nextID;
|
||||
|
||||
// open new scope, if necessary
|
||||
const hasNewVariables = Object.keys(definedVariables).length > 0;
|
||||
if (hasNewVariables) {
|
||||
ctx.addLine("{");
|
||||
ctx.indent();
|
||||
}
|
||||
|
||||
// add new variables, if any
|
||||
for (let key in definedVariables) {
|
||||
ctx.addLine(`let ${key} = ${definedVariables[key]}`);
|
||||
}
|
||||
|
||||
// compile sub template
|
||||
const subCtx = ctx
|
||||
.subContext("caller", nodeCopy)
|
||||
.subContext("variables", Object.create(vars))
|
||||
.subContext("definedVariables", Object.create(definedVariables));
|
||||
|
||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
||||
|
||||
// close new scope
|
||||
if (hasNewVariables) {
|
||||
ctx.dedent();
|
||||
ctx.addLine("}");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-foreach
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "foreach",
|
||||
extraNames: ["as"],
|
||||
priority: 10,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
ctx.rootContext.shouldProtectContext = true;
|
||||
ctx = ctx.subContext("inLoop", true);
|
||||
const elems = node.getAttribute("t-foreach")!;
|
||||
const name = node.getAttribute("t-as")!;
|
||||
let arrayID = ctx.generateID();
|
||||
ctx.addLine(`var _${arrayID} = ${ctx.formatExpression(elems)};`);
|
||||
ctx.addLine(
|
||||
`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`
|
||||
);
|
||||
ctx.addLine(
|
||||
`if (typeof _${arrayID} === 'number') { _${arrayID} = Array.from(Array(_${arrayID}).keys())}`
|
||||
);
|
||||
let keysID = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`var _${keysID} = _${arrayID} instanceof Array ? _${arrayID} : Object.keys(_${arrayID});`
|
||||
);
|
||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
||||
let valuesID = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`var _${valuesID} = _${arrayID} instanceof Array ? _${arrayID} : Object.values(_${arrayID});`
|
||||
);
|
||||
ctx.addLine(`for (let i = 0; i < _length${keysID}; i++) {`);
|
||||
ctx.indent();
|
||||
ctx.addLine(`context.${name}_first = i === 0;`);
|
||||
ctx.addLine(`context.${name}_last = i === _length${keysID} - 1;`);
|
||||
ctx.addLine(`context.${name}_parity = i % 2 === 0 ? 'even' : 'odd';`);
|
||||
ctx.addLine(`context.${name}_index = i;`);
|
||||
ctx.addLine(`context.${name} = _${keysID}[i];`);
|
||||
ctx.addLine(`context.${name}_value = _${valuesID}[i];`);
|
||||
const nodeCopy = <Element>node.cloneNode(true);
|
||||
let shouldWarn =
|
||||
nodeCopy.tagName !== "t" && !nodeCopy.hasAttribute("t-key");
|
||||
if (!shouldWarn && node.tagName === "t") {
|
||||
if (node.hasAttribute("t-widget") && !node.hasAttribute("t-key")) {
|
||||
shouldWarn = true;
|
||||
}
|
||||
if (
|
||||
!shouldWarn &&
|
||||
node.children.length === 1 &&
|
||||
node.children[0].tagName !== "t" &&
|
||||
!node.children[0].hasAttribute("t-key")
|
||||
) {
|
||||
shouldWarn = true;
|
||||
}
|
||||
}
|
||||
if (shouldWarn) {
|
||||
console.warn(
|
||||
`Directive t-foreach should always be used with a t-key! (in template: '${
|
||||
ctx.templateName
|
||||
}')`
|
||||
);
|
||||
}
|
||||
nodeCopy.removeAttribute("t-foreach");
|
||||
qweb._compileNode(nodeCopy, ctx);
|
||||
ctx.dedent();
|
||||
ctx.addLine("}");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-debug
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "debug",
|
||||
priority: 99,
|
||||
atNodeEncounter({ ctx }) {
|
||||
ctx.addLine("debugger;");
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-log
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "log",
|
||||
priority: 99,
|
||||
atNodeEncounter({ ctx, value }) {
|
||||
const expr = ctx.formatExpression(value);
|
||||
ctx.addLine(`console.log(${expr})`);
|
||||
}
|
||||
});
|
||||
@@ -1,556 +0,0 @@
|
||||
import { QWeb, UTILS } from "./qweb_core";
|
||||
|
||||
/**
|
||||
* Owl QWeb Extensions
|
||||
*
|
||||
* This file contains the implementation of non standard QWeb directives, added
|
||||
* by Owl and that will only work on Owl projects:
|
||||
*
|
||||
* - t-on
|
||||
* - t-ref
|
||||
* - t-transition
|
||||
* - t-widget/t-props/t-keepalive
|
||||
* - t-mounted
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-on
|
||||
//------------------------------------------------------------------------------
|
||||
// these are pieces of code that will be injected into the event handler if
|
||||
// modifiers are specified
|
||||
const MODS_CODE = {
|
||||
prevent: "e.preventDefault();",
|
||||
self: "if (e.target !== this.elm) {return}",
|
||||
stop: "e.stopPropagation();"
|
||||
};
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "on",
|
||||
priority: 90,
|
||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
const [eventName, ...mods] = fullName.slice(5).split(".");
|
||||
if (!eventName) {
|
||||
throw new Error("Missing event name with t-on directive");
|
||||
}
|
||||
let extraArgs;
|
||||
let handlerName = value.replace(/\(.*\)/, function(args) {
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
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";
|
||||
let handler;
|
||||
if (mods.length > 0) {
|
||||
handler = `function (e) {`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
handler += `context['${handlerName}'].call(${params}, e);}`;
|
||||
} else {
|
||||
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}];`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-ref
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "ref",
|
||||
priority: 95,
|
||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
||||
const refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
||||
addNodeHook("create", `context.refs[${refKey}] = n.elm;`);
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-transition
|
||||
//------------------------------------------------------------------------------
|
||||
UTILS.nextFrame = function(cb: () => void) {
|
||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
||||
};
|
||||
|
||||
UTILS.transitionInsert = function(elm: HTMLElement, name: string) {
|
||||
elm.classList.add(name + "-enter");
|
||||
elm.classList.add(name + "-enter-active");
|
||||
const finalize = () => {
|
||||
elm.classList.remove(name + "-enter-active");
|
||||
elm.classList.remove(name + "-enter-to");
|
||||
};
|
||||
this.nextFrame(() => {
|
||||
elm.classList.remove(name + "-enter");
|
||||
elm.classList.add(name + "-enter-to");
|
||||
whenTransitionEnd(elm, finalize);
|
||||
});
|
||||
};
|
||||
|
||||
UTILS.transitionRemove = function(
|
||||
elm: HTMLElement,
|
||||
name: string,
|
||||
rm: () => void
|
||||
) {
|
||||
elm.classList.add(name + "-leave");
|
||||
elm.classList.add(name + "-leave-active");
|
||||
const finalize = () => {
|
||||
elm.classList.remove(name + "-leave-active");
|
||||
elm.classList.remove(name + "-leave-to");
|
||||
rm();
|
||||
};
|
||||
this.nextFrame(() => {
|
||||
elm.classList.remove(name + "-leave");
|
||||
elm.classList.add(name + "-leave-to");
|
||||
whenTransitionEnd(elm, finalize);
|
||||
});
|
||||
};
|
||||
|
||||
function getTimeout(delays: Array<string>, durations: Array<string>): number {
|
||||
/* istanbul ignore next */
|
||||
while (delays.length < durations.length) {
|
||||
delays = delays.concat(delays);
|
||||
}
|
||||
|
||||
return Math.max.apply(
|
||||
null,
|
||||
durations.map((d, i) => {
|
||||
return toMs(d) + toMs(delays[i]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
|
||||
// in a locale-dependent way, using a comma instead of a dot.
|
||||
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
|
||||
// as a floor function) causing unexpected behaviors
|
||||
function toMs(s: string): number {
|
||||
return Number(s.slice(0, -1).replace(",", ".")) * 1000;
|
||||
}
|
||||
|
||||
function whenTransitionEnd(elm: HTMLElement, cb) {
|
||||
const styles = window.getComputedStyle(elm);
|
||||
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
||||
const durations: Array<string> = (styles.transitionDuration || "").split(
|
||||
", "
|
||||
);
|
||||
const timeout: number = getTimeout(delays, durations);
|
||||
if (timeout > 0) {
|
||||
elm.addEventListener("transitionend", cb, { once: true });
|
||||
} else {
|
||||
cb();
|
||||
}
|
||||
}
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "transition",
|
||||
priority: 96,
|
||||
atNodeCreation({ value, addNodeHook }) {
|
||||
let name = value;
|
||||
const hooks = {
|
||||
insert: `this.utils.transitionInsert(vn.elm, '${name}');`,
|
||||
remove: `this.utils.transitionRemove(vn.elm, '${name}', rm);`
|
||||
};
|
||||
for (let hookName in hooks) {
|
||||
addNodeHook(hookName, hooks[hookName]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-widget
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The t-widget directive is certainly a complicated and hard to maintain piece
|
||||
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
||||
* you this advice: Good luck...
|
||||
*
|
||||
* Since it is not 'direct' code, but rather code that generates other code, it
|
||||
* is not easy to understand. To help you, here is a detailed and commented
|
||||
* explanation of the code generated by the t-widget directive for the following
|
||||
* situation:
|
||||
* ```xml
|
||||
* <t t-widget="child"
|
||||
* t-key="'somestring'"
|
||||
* t-props="{flag:state.flag}"
|
||||
* t-transition="fade"/>
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* // this is the virtual node representing the parent div
|
||||
* let c1 = [], p1 = { key: 1 };
|
||||
* var vn1 = h("div", p1, c1);
|
||||
*
|
||||
* // t-widget directive: we start by evaluating the expression given by t-key:
|
||||
* let key5 = "somestring";
|
||||
*
|
||||
* // We keep the index of the position of the widget in the closure. We push
|
||||
* // null to reserve the slot, and will replace it later by the widget vnode,
|
||||
* // when it will be ready (do not forget that preparing/rendering a widget is
|
||||
* // asynchronous)
|
||||
* let _2_index = c1.length;
|
||||
* c1.push(null);
|
||||
*
|
||||
* // def3 is the deferred that will contain later either the new widget
|
||||
* // creation, or the props update...
|
||||
* let def3;
|
||||
*
|
||||
* // this is kind of tricky: we need here to find if the widget was already
|
||||
* // created by a previous rendering. This is done by checking the internal
|
||||
* // `cmap` (children map) of the parent widget: it maps keys to widget ids,
|
||||
* // and, then, if there is an id, we look into the children list to get the
|
||||
* // instance
|
||||
* let w4 =
|
||||
* key5 in context.__owl__.cmap
|
||||
* ? context.__owl__.children[context.__owl__.cmap[key5]]
|
||||
* : false;
|
||||
*
|
||||
* // we evaluate here the props given to the component. It is done here to be
|
||||
* // able to easily reference it later, and also, it might be an expensive
|
||||
* // computation, so it is certainly better to do it only once
|
||||
* let props4 = { flag: context["state"].flag };
|
||||
*
|
||||
* // If we have a widget, currently rendering, but not ready yet, and which was
|
||||
* // rendered with different props, we do not want to wait for it to be ready,
|
||||
* // then update it. We simply destroy it, and start anew.
|
||||
* if (
|
||||
* w4 &&
|
||||
* w4.__owl__.renderPromise &&
|
||||
* !w4.__owl__.isStarted &&
|
||||
* props4 !== w4.__owl__.renderProps
|
||||
* ) {
|
||||
* w4.destroy();
|
||||
* w4 = false;
|
||||
* }
|
||||
*
|
||||
* if (!w4) {
|
||||
* // in this situation, we need to create a new widget. First step is
|
||||
* // to get a reference to the class, then create an instance with
|
||||
* // current context as parent, and the props.
|
||||
* let W4 = context.widgets["child"];
|
||||
* if (!W4) {
|
||||
* throw new Error("Cannot find the definition of widget 'child'");
|
||||
* }
|
||||
* w4 = new W4(owner, props4);
|
||||
*
|
||||
* let utils = this.utils;
|
||||
*
|
||||
* // Whenever we rerender the parent widget, we need to be sure that we
|
||||
* // are able to find the widget instance. To do that, we register it to
|
||||
* // the parent cmap (children map). Note that the 'template' key is
|
||||
* // used here, since this is what identify the widget from the template
|
||||
* // perspective.
|
||||
* context.__owl__.cmap[key5] = w4.__owl__.id;
|
||||
*
|
||||
* // _prepare is called, to basically call willStart, then render the
|
||||
* // widget
|
||||
* def3 = w4._prepare();
|
||||
*
|
||||
* def3 = def3.then(vnode => {
|
||||
* // we create here a virtual node for the parent (NOT the widget). This
|
||||
* // means that the vdom of the parent will be stopped here, and from
|
||||
* // the parent's perspective, it simply is a vnode with no children.
|
||||
* // However, it shares the same dom element with the component root
|
||||
* // vnode.
|
||||
* let pvnode = h(vnode.sel, { key: key5 });
|
||||
*
|
||||
* // we add hooks to the parent vnode so we can interact with the new
|
||||
* // widget at the proper time
|
||||
* pvnode.data.hook = {
|
||||
* insert(vn) {
|
||||
* // the _mount method will patch the widget vdom into the elm vn.elm,
|
||||
* // then call the mounted hooks. However, suprisingly, the snabbdom
|
||||
* // patch method actually replace the elm by a new elm, so we need
|
||||
* // to synchronise the pvnode elm with the resulting elm
|
||||
* let nvn = w4._mount(vnode, vn.elm);
|
||||
* pvnode.elm = nvn.elm;
|
||||
* // what follows is only present if there are animations on the widget
|
||||
* utils.transitionInsert(vn.elm, "fade");
|
||||
* },
|
||||
* remove() {
|
||||
* // override with empty function to prevent from removing the node
|
||||
* // directly. It will be removed when destroy is called anyway, which
|
||||
* // delays the removal if there are animations.
|
||||
* },
|
||||
* destroy() {
|
||||
* // if there are animations, we delay the call to destroy on the
|
||||
* // widget, if not, we call it directly.
|
||||
* let finalize = () => {
|
||||
* w4.destroy();
|
||||
* };
|
||||
* utils.transitionRemove(vn.elm, "fade", finalize);
|
||||
* }
|
||||
* };
|
||||
* // the pvnode is inserted at the correct position in the div's children
|
||||
* c1[_2_index] = pvnode;
|
||||
*
|
||||
* // we keep here a reference to the parent vnode (representing the
|
||||
* // widget, so we can reuse it later whenever we update the widget
|
||||
* w4.__owl__.pvnode = pvnode;
|
||||
* });
|
||||
* } else {
|
||||
* // this is the 'update' path of the directive.
|
||||
* // the call to _updateProps is the actual widget update
|
||||
* def3 = w4._updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
* def3 = def3.then(() => {
|
||||
* // if widget was destroyed in the meantime, we do nothing (so, this
|
||||
* // means that the parent's element children list will have a null in
|
||||
* // the widget's position, which will cause the pvnode to be removed
|
||||
* // when it is patched.
|
||||
* if (w4.__owl__.isDestroyed) {
|
||||
* return;
|
||||
* }
|
||||
* // like above, we register the pvnode to the children list, so it
|
||||
* // will not be patched out of the dom.
|
||||
* let pvnode = w4.__owl__.pvnode;
|
||||
* c1[_2_index] = pvnode;
|
||||
* });
|
||||
* }
|
||||
*
|
||||
* // we register the deferred here so the parent can coordinate its patch operation
|
||||
* // with all the children.
|
||||
* extra.promises.push(def3);
|
||||
* return vn1;
|
||||
* ```
|
||||
*/
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "widget",
|
||||
extraNames: ["props", "keepalive"],
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node }): boolean {
|
||||
ctx.addLine("//WIDGET");
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
ctx.rootContext.shouldDefineQWeb = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
let props = node.getAttribute("t-props");
|
||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
||||
|
||||
// t-on- events and t-transition
|
||||
const events: [string, string][] = [];
|
||||
let transition: string = "";
|
||||
const attributes = (<Element>node).attributes;
|
||||
for (let i = 0; i < attributes.length; i++) {
|
||||
const name = attributes[i].name;
|
||||
if (name.startsWith("t-on-")) {
|
||||
events.push([name.slice(5), attributes[i].textContent!]);
|
||||
} else if (name === "t-transition") {
|
||||
transition = attributes[i].textContent!;
|
||||
}
|
||||
}
|
||||
|
||||
let key = node.getAttribute("t-key");
|
||||
if (key) {
|
||||
key = ctx.formatExpression(key);
|
||||
}
|
||||
if (props) {
|
||||
props = ctx.formatExpression(props);
|
||||
}
|
||||
let dummyID = ctx.generateID();
|
||||
let defID = ctx.generateID();
|
||||
let widgetID = 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};`);
|
||||
}
|
||||
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(null);`);
|
||||
ctx.addLine(`let def${defID};`);
|
||||
let templateID = key
|
||||
? `key${keyID}`
|
||||
: ctx.inLoop
|
||||
? `String(-${widgetID} - i)`
|
||||
: String(widgetID);
|
||||
|
||||
let ref = node.getAttribute("t-ref");
|
||||
let refExpr = "";
|
||||
let refKey: string = "";
|
||||
if (ref) {
|
||||
refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
||||
refExpr = `context.refs[${refKey}] = w${widgetID};`;
|
||||
}
|
||||
let transitionsInsertCode = "";
|
||||
if (transition) {
|
||||
transitionsInsertCode = `utils.transitionInsert(vn.elm, '${transition}');`;
|
||||
}
|
||||
let finalizeWidgetCode = `w${widgetID}.${
|
||||
keepAlive ? "unmount" : "destroy"
|
||||
}();`;
|
||||
if (ref) {
|
||||
finalizeWidgetCode += `delete context.refs[${refKey}];`; // FIXME: shouldn't we keep ref if keepAlive is true?
|
||||
}
|
||||
if (transition) {
|
||||
finalizeWidgetCode = `let finalize = () => {
|
||||
${finalizeWidgetCode}
|
||||
};
|
||||
utils.transitionRemove(vn.elm, '${transition}', finalize);`;
|
||||
}
|
||||
|
||||
let createHook = "";
|
||||
let classAttr = node.getAttribute("class");
|
||||
let tattClass = node.getAttribute("t-att-class");
|
||||
let styleAttr = node.getAttribute("style");
|
||||
let tattStyle = node.getAttribute("t-att-style");
|
||||
if (tattStyle) {
|
||||
const attVar = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${attVar} = ${ctx.formatExpression(tattStyle)};`);
|
||||
tattStyle = attVar;
|
||||
}
|
||||
let updateClassCode = "";
|
||||
if (classAttr || tattClass || styleAttr || tattStyle) {
|
||||
let classCode = "";
|
||||
if (classAttr) {
|
||||
classCode =
|
||||
classAttr
|
||||
.split(" ")
|
||||
.map(c => `vn.elm.classList.add('${c}')`)
|
||||
.join(";") + ";";
|
||||
}
|
||||
if (tattClass) {
|
||||
const attVar = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${attVar} = ${ctx.formatExpression(tattClass)};`);
|
||||
classCode = `for (let k in ${attVar}) {
|
||||
if (${attVar}[k]) {
|
||||
vn.elm.classList.add(k);
|
||||
}
|
||||
}`;
|
||||
updateClassCode = `let cl=w${widgetID}.el.classList;for (let k in ${attVar}) {if (${attVar}[k]) {cl.add(k)} else {cl.remove(k)}}`;
|
||||
}
|
||||
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
||||
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr}` : "";
|
||||
createHook = `vnode.data.hook = {create(_, vn){${classCode}${styleCode}}};`;
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let w${widgetID} = ${templateID} in context.__owl__.cmap ? context.__owl__.children[context.__owl__.cmap[${templateID}]] : false;`
|
||||
);
|
||||
ctx.addLine(`let props${widgetID} = ${props || "{}"};`);
|
||||
ctx.addIf(
|
||||
`w${widgetID} && w${widgetID}.__owl__.renderPromise && !w${widgetID}.__owl__.vnode && props${widgetID} !== w${widgetID}.__owl__.renderProps`
|
||||
);
|
||||
ctx.addLine(`w${widgetID}.destroy();`);
|
||||
ctx.addLine(`w${widgetID} = false`);
|
||||
ctx.closeIf();
|
||||
|
||||
ctx.addIf(`!w${widgetID}`);
|
||||
// new widget
|
||||
ctx.addLine(`let widgetKey${widgetID} = ${ctx.interpolate(value)};`);
|
||||
ctx.addLine(
|
||||
`let W${widgetID} = context.widgets && context.widgets[widgetKey${widgetID}] || QWeb.widgets[widgetKey${widgetID}];`
|
||||
);
|
||||
|
||||
// maybe only do this in dev mode...
|
||||
ctx.addLine(
|
||||
`if (!W${widgetID}) {throw new Error('Cannot find the definition of widget "' + widgetKey${widgetID} + '"')}`
|
||||
);
|
||||
ctx.addLine(`w${widgetID} = new W${widgetID}(owner, props${widgetID});`);
|
||||
ctx.addLine(
|
||||
`context.__owl__.cmap[${templateID}] = w${widgetID}.__owl__.id;`
|
||||
);
|
||||
for (let [event, method] of events) {
|
||||
ctx.addLine(`w${widgetID}.on('${event}', owner, owner['${method}'])`);
|
||||
}
|
||||
ctx.addLine(`def${defID} = w${widgetID}._prepare();`);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
// FIXME: click to re-add widget during remove transition -> leak
|
||||
ctx.addLine(
|
||||
`def${defID} = def${defID}.then(vnode=>{${createHook}let pvnode=h(vnode.sel, {key: ${templateID}, hook: {insert(vn) {let nvn=w${widgetID}._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeWidgetCode}}}});c${
|
||||
ctx.parentNode
|
||||
}[_${dummyID}_index]=pvnode;w${widgetID}.__owl__.pvnode = pvnode;});`
|
||||
);
|
||||
|
||||
ctx.addElse();
|
||||
// need to update widget
|
||||
ctx.addLine(
|
||||
`def${defID} = w${widgetID}._updateProps(props${widgetID}, extra.forceUpdate, extra.patchQueue);`
|
||||
);
|
||||
let keepAliveCode = "";
|
||||
if (keepAlive) {
|
||||
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${widgetID}.el,vn.elm);vn.elm=w${widgetID}.el;w${widgetID}._remount();};`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`def${defID} = def${defID}.then(()=>{if (w${widgetID}.__owl__.isDestroyed) {return};${
|
||||
tattStyle ? `w${widgetID}.el.style=${tattStyle};` : ""
|
||||
}${updateClassCode}let pvnode=w${widgetID}.__owl__.pvnode;${keepAliveCode}c${
|
||||
ctx.parentNode
|
||||
}[_${dummyID}_index]=pvnode;});`
|
||||
);
|
||||
ctx.closeIf();
|
||||
|
||||
ctx.addLine(`extra.promises.push(def${defID});`);
|
||||
|
||||
if (
|
||||
node.hasAttribute("t-if") ||
|
||||
node.hasAttribute("t-else") ||
|
||||
node.hasAttribute("t-elif")
|
||||
) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-mounted
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "mounted",
|
||||
priority: 97,
|
||||
atNodeCreation({ ctx, fullName, value, nodeID, addNodeHook }) {
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
const eventName = fullName.slice(5);
|
||||
if (!eventName) {
|
||||
throw new Error("Missing event name with t-on directive");
|
||||
}
|
||||
let extraArgs;
|
||||
let handler = value.replace(/\(.*\)/, function(args) {
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
let error = `(function () {throw new Error('Missing handler \\'' + '${handler}' + \`\\' when evaluating template '${ctx.templateName.replace(
|
||||
/`/g,
|
||||
"'"
|
||||
)}'\`)})()`;
|
||||
if (extraArgs) {
|
||||
ctx.addLine(
|
||||
`extra.mountedHandlers[${nodeID}] = (context['${handler}'] || ${error}).bind(owner, ${ctx.formatExpression(
|
||||
extraArgs
|
||||
)});`
|
||||
);
|
||||
} else {
|
||||
ctx.addLine(
|
||||
`extra.mountedHandlers[${nodeID}] = extra.mountedHandlers[${nodeID}] || (context['${handler}'] || ${error}).bind(owner);`
|
||||
);
|
||||
}
|
||||
addNodeHook(
|
||||
"insert",
|
||||
`if (context.__owl__.isMounted) { extra.mountedHandlers[${nodeID}](); }`
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Component } from "../component/component";
|
||||
import { xml } from "../tags";
|
||||
import { Destination, RouterEnv } from "./router";
|
||||
|
||||
type Props = Destination;
|
||||
|
||||
export class Link<Env extends RouterEnv> extends Component<Props, Env> {
|
||||
static template = xml`
|
||||
<a t-att-class="{'router-link-active': isActive }"
|
||||
t-att-href="href"
|
||||
t-on-click="navigate">
|
||||
<t t-slot="default"/>
|
||||
</a>
|
||||
`;
|
||||
|
||||
href: string = this.env.router.destToPath(this.props);
|
||||
|
||||
async willUpdateProps(nextProps) {
|
||||
this.href = this.env.router.destToPath(nextProps);
|
||||
}
|
||||
|
||||
get isActive() {
|
||||
if (this.env.router.mode === "hash") {
|
||||
return (<any>document.location).hash === this.href;
|
||||
}
|
||||
return (<any>document.location).pathname === this.href;
|
||||
}
|
||||
|
||||
navigate(ev) {
|
||||
// don't redirect with control keys
|
||||
if (ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey) {
|
||||
return;
|
||||
}
|
||||
// don't redirect on right click
|
||||
if (ev.button !== undefined && ev.button !== 0) {
|
||||
return;
|
||||
}
|
||||
// don't redirect if `target="_blank"`
|
||||
if (ev.currentTarget && ev.currentTarget.getAttribute) {
|
||||
const target = ev.currentTarget.getAttribute("target");
|
||||
if (/\b_blank\b/i.test(target)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
ev.preventDefault();
|
||||
this.env.router.navigate(this.props);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Component } from "../component/component";
|
||||
import { xml } from "../tags";
|
||||
import { EnvWithRouter } from "./router";
|
||||
|
||||
export class RouteComponent extends Component<{}, EnvWithRouter> {
|
||||
static template = xml`
|
||||
<t>
|
||||
<t
|
||||
t-if="routeComponent"
|
||||
t-component="routeComponent"
|
||||
t-key="env.router.currentRouteName"
|
||||
t-props="env.router.currentParams" />
|
||||
</t>
|
||||
`;
|
||||
|
||||
get routeComponent(): any {
|
||||
return this.env.router.currentRoute && this.env.router.currentRoute.component;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user