mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
157 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2042f2ec01 | |||
| 37313c47a3 | |||
| 3f563de9c0 | |||
| 97564a7612 | |||
| f1abf7f2ea | |||
| 8464a1b04e | |||
| c0a62dfd05 | |||
| 600f1e35d4 | |||
| b3181f119d | |||
| 1e1e05350a | |||
| b242230e20 | |||
| 9fe2da704e | |||
| 21b1661d39 | |||
| ec05b1f5e3 | |||
| 8083678f03 | |||
| 61c2ec5d83 | |||
| e579a993fd | |||
| ea3c6f7bf0 | |||
| 9cfafc30b5 | |||
| ad42c583c6 | |||
| 6faaa6c361 | |||
| bff539cabf | |||
| 88fd1cf483 | |||
| f0b75b6890 | |||
| a1552117f9 | |||
| 17ae1d06c4 | |||
| 27629cedfa | |||
| 3a93370ab6 | |||
| a6bb4d8ee1 | |||
| caf842c482 | |||
| 1b513a1637 | |||
| 52a200878a | |||
| f4994a20d8 | |||
| 7419c1982a | |||
| a8c8f6affe | |||
| dabe7f9bfa | |||
| d08ea63565 | |||
| 7ebe0da962 | |||
| 3e0e8475a6 | |||
| 2e83c739b9 | |||
| 922eb7cd98 | |||
| d12115554c | |||
| 1a6b26c8c6 | |||
| d67d295eaa | |||
| 9cbcf20b33 | |||
| 3a461e1dd1 | |||
| e8387810e6 | |||
| acac9d1741 | |||
| 968a5460bb | |||
| e646eb697e | |||
| 7dfa901332 | |||
| 0290f63ba3 | |||
| 370fae4e1a | |||
| 76735410f8 | |||
| 19a47a7001 | |||
| 398f9f4e53 | |||
| af426aa902 | |||
| 490cf18079 | |||
| dfc782599b | |||
| 71f545058b | |||
| 1a20cc57de | |||
| 25738a1bf0 | |||
| 4a96eff3c6 | |||
| d043d47754 | |||
| 3a10468f7b | |||
| 144b323d2b | |||
| bb64e87634 | |||
| 9a87b9a4a0 | |||
| 2a53a9592e | |||
| f54b9a4a0c | |||
| abb9d0b364 | |||
| 8483cc805e | |||
| 142f47ac82 | |||
| c8a27aa1a3 | |||
| 323cb61d2c | |||
| ac9cc91701 | |||
| d83cfc12ee | |||
| cb07c99d40 | |||
| d615ffd81b | |||
| 8d2b250fef | |||
| 7626cc01b3 | |||
| 392185ab67 | |||
| 392dc0131a | |||
| 4e8e9dee3e | |||
| 25d4cb2aab | |||
| 4724652533 | |||
| b08cc1d084 | |||
| a68d7774c6 | |||
| ed9d820d9e | |||
| 4a2d019161 | |||
| 89eae191b1 | |||
| 3fbc02986c | |||
| a28ce440dc | |||
| 8e018fbbda | |||
| 33f7fc8e83 | |||
| 6a833c54ec | |||
| cb38d795f9 | |||
| 8da68e925b | |||
| 474ffa1cd9 | |||
| e73fb462c5 | |||
| 38c7ad9629 | |||
| d0c76c5854 | |||
| e032314739 | |||
| b2db7f21ed | |||
| 7b8ac13d3f | |||
| 06d852fcf9 | |||
| 7e4baf668a | |||
| fe34ba00a6 | |||
| e5e7790530 | |||
| 3bf91afc3f | |||
| 2529aa3ef2 | |||
| 8d25bddda4 | |||
| 81af21a025 | |||
| 9baea2c1cd | |||
| 8e03f9cd9c | |||
| c5a2f52afb | |||
| 9fd8315c53 | |||
| 85318b3ae6 | |||
| 4b961cbffe | |||
| 2af8cccd65 | |||
| b8d3618afa | |||
| 559fadb62a | |||
| c36333dbbc | |||
| b5c3422b4d | |||
| 23ce19e57a | |||
| aaf40e9bec | |||
| 211f6ebdd6 | |||
| 1707bd240d | |||
| 142b69823f | |||
| 94c8bce810 | |||
| ae172d42e7 | |||
| ddf30a8a97 | |||
| 8d0d8538ad | |||
| 2b0315c03f | |||
| c469cac315 | |||
| b4ad14edc0 | |||
| 718e5264ae | |||
| f5d019bb69 | |||
| afa36f52a0 | |||
| fd6327b068 | |||
| d5098dd138 | |||
| ce052e0992 | |||
| b00188c1ce | |||
| 2c01802b8e | |||
| 20eb848262 | |||
| 8b479749b7 | |||
| f7728b93bd | |||
| 03585d8fea | |||
| 047a9c8993 | |||
| 69d35abe4f | |||
| 1d7503913e | |||
| ee956a1977 | |||
| 3fdc7a48f3 | |||
| d212309f1b | |||
| 8866905f33 | |||
| 50b116c56d | |||
| a823373220 |
@@ -0,0 +1,27 @@
|
|||||||
|
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
|
||||||
|
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
|
||||||
|
|
||||||
|
name: Node.js CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [ master ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
node-version: [12.x, 14.x, 16.x]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Use Node.js ${{ matrix.node-version }}
|
||||||
|
uses: actions/setup-node@v1
|
||||||
|
with:
|
||||||
|
node-version: ${{ matrix.node-version }}
|
||||||
|
- run: npm install
|
||||||
|
- run: npm run test
|
||||||
|
- run: npm run prettier
|
||||||
+9
-1
@@ -15,6 +15,7 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
|
||||||
#ide's
|
#ide's
|
||||||
.vscode
|
.vscode
|
||||||
@@ -25,4 +26,11 @@ node_modules
|
|||||||
# Extras temp file
|
# Extras temp file
|
||||||
/tools/owl.js
|
/tools/owl.js
|
||||||
|
|
||||||
release-notes.md
|
release-notes.md
|
||||||
|
|
||||||
|
.rpt2_cache
|
||||||
|
|
||||||
|
# useful in some cases
|
||||||
|
/temp
|
||||||
|
|
||||||
|
coverage
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
<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>
|
||||||
|
|
||||||
|
[](https://www.gnu.org/licenses/lgpl-3.0)
|
||||||
|
[](https://badge.fury.io/js/@odoo%2Fowl)
|
||||||
|
[](https://www.npmjs.com/package/@odoo/owl)
|
||||||
|
|
||||||
_Class based components with hooks, reactive state and concurrent mode_
|
_Class based components with hooks, reactive state and concurrent mode_
|
||||||
|
|
||||||
@@ -11,24 +15,37 @@ simple and consistent way. Owl's main features are:
|
|||||||
|
|
||||||
- a declarative component system,
|
- a declarative component system,
|
||||||
- a reactivity system based on hooks,
|
- a reactivity system based on hooks,
|
||||||
- a store implementation (for state management),
|
- concurrent mode by default,
|
||||||
- a small frontend router
|
- a store and a frontend router
|
||||||
|
|
||||||
Owl components are defined with ES6 classes, they use QWeb templates, an underlying
|
Owl components are defined with ES6 classes, they use QWeb templates, an
|
||||||
virtual dom, integrates beautifully with hooks, and the rendering is asynchronous.
|
underlying virtual DOM, integrates beautifully with hooks, and the rendering is
|
||||||
|
asynchronous.
|
||||||
|
|
||||||
**Try it online!** An online playground is available at [https://odoo.github.io/owl/playground](https://odoo.github.io/owl/playground) to let you experiment with the Owl framework. There
|
**Try it online!** An online playground is available at
|
||||||
are some code examples to showcase some interesting features.
|
[https://odoo.github.io/owl/playground](https://odoo.github.io/owl/playground)
|
||||||
|
to let you experiment with the Owl framework. There are some code examples to
|
||||||
|
showcase some interesting features.
|
||||||
|
|
||||||
Owl is currently mostly stable. Possible future changes are explained in the
|
Owl is currently stable. Possible future changes are explained in the
|
||||||
[roadmap](roadmap.md).
|
[roadmap](roadmap.md).
|
||||||
|
|
||||||
|
## Why Owl?
|
||||||
|
|
||||||
|
Why did Odoo decide to make Yet Another Framework? This is really a question
|
||||||
|
that deserves [a long answer](doc/miscellaneous/why_owl.md). But in short, we believe that
|
||||||
|
while the current state of the art frameworks are excellent, they are not
|
||||||
|
optimized for our use case, and there is still room for something else.
|
||||||
|
|
||||||
|
If you are interested in a comparison with React or Vue, you will
|
||||||
|
find some more additional information [here](doc/miscellaneous/comparison.md).
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
Here is a short example to illustrate interactive components:
|
Here is a short example to illustrate interactive components:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const { Component, useState } = owl;
|
const { Component, useState, mount } = owl;
|
||||||
const { xml } = owl.tags;
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
@@ -50,8 +67,7 @@ class App extends Component {
|
|||||||
static components = { Counter };
|
static components = { Counter };
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App();
|
mount(App, { target: document.body });
|
||||||
app.mount(document.body);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
|
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
|
||||||
@@ -79,10 +95,9 @@ requirements are common and code needs to be maintained by large teams.
|
|||||||
|
|
||||||
Owl is not designed to be fast nor small (even though it is quite good on those
|
Owl is not designed to be fast nor small (even though it is quite good on those
|
||||||
two topics). It is a no nonsense framework to build applications. There is only
|
two topics). It is a no nonsense framework to build applications. There is only
|
||||||
one way to define components (with classes).
|
one way to define components (with classes). There is no black magic. It just
|
||||||
|
works.
|
||||||
|
|
||||||
If you are interested in a comparison with React or Vue, you will
|
|
||||||
find some more information [here](doc/comparison.md).
|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@@ -90,19 +105,18 @@ A complete documentation for Owl can be found here:
|
|||||||
|
|
||||||
- [Main documentation page](doc/readme.md).
|
- [Main documentation page](doc/readme.md).
|
||||||
|
|
||||||
The most important sections are:
|
Some of the most important pages are:
|
||||||
|
|
||||||
- [Tutorial: TodoList application](doc/learning/tutorial_todoapp.md)
|
- [Tutorial: TodoList application](doc/learning/tutorial_todoapp.md)
|
||||||
|
- [How to start an Owl project](doc/learning/quick_start.md)
|
||||||
- [QWeb templating language](doc/reference/qweb_templating_language.md)
|
- [QWeb templating language](doc/reference/qweb_templating_language.md)
|
||||||
- [Component](doc/reference/component.md)
|
- [Component](doc/reference/component.md)
|
||||||
- [Hooks](doc/reference/hooks.md)
|
- [Hooks](doc/reference/hooks.md)
|
||||||
|
|
||||||
Found an issue in the documentation? A broken link? Some outdated information?
|
|
||||||
Submit a PR!
|
|
||||||
|
|
||||||
## Installing/Building
|
## Installing Owl
|
||||||
|
|
||||||
Owl can be installed with the following command:
|
Owl is available on `npm` and can be installed with the following command:
|
||||||
|
|
||||||
```
|
```
|
||||||
npm install @odoo/owl
|
npm install @odoo/owl
|
||||||
@@ -110,148 +124,7 @@ npm install @odoo/owl
|
|||||||
|
|
||||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||||
|
|
||||||
- [owl-1.0.4.js](https://github.com/odoo/owl/releases/download/v1.0.4/owl.js)
|
- [owl-1.4.5](https://github.com/odoo/owl/releases/tag/v1.4.5)
|
||||||
- [owl-1.0.4.min.js](https://github.com/odoo/owl/releases/download/v1.0.4/owl.min.js)
|
|
||||||
|
|
||||||
Some npm scripts are available:
|
|
||||||
|
|
||||||
| Command | Description |
|
|
||||||
| ---------------- | -------------------------------------------------- |
|
|
||||||
| `npm install` | install every dependency required for this project |
|
|
||||||
| `npm run build` | build a bundle of _owl_ in the _/dist/_ folder |
|
|
||||||
| `npm run minify` | minify the prebuilt owl.js file |
|
|
||||||
| `npm run test` | run all (owl) tests |
|
|
||||||
|
|
||||||
## Quick Overview
|
|
||||||
|
|
||||||
Owl components in an application are used to define a (dynamic) tree of components.
|
|
||||||
|
|
||||||
```
|
|
||||||
Root
|
|
||||||
/ \
|
|
||||||
A B
|
|
||||||
/ \
|
|
||||||
C D
|
|
||||||
```
|
|
||||||
|
|
||||||
**State:** each component can manage its own local state. It is a simple ES6
|
|
||||||
class, there are no special rules:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Counter extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<button t-on-click="increment">
|
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
|
||||||
</button>`;
|
|
||||||
|
|
||||||
state = { value: 0 };
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
this.render();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The example above shows a component with a local state. Note that since there
|
|
||||||
is nothing magical to the `state` object, we need to manually call the `render`
|
|
||||||
function whenever we update it. This can quickly become annoying (and not
|
|
||||||
efficient if we do it too much). There is a better way: using the `useState`
|
|
||||||
hook, which transforms an object into a reactive version of itself:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const { useState } = owl.hooks;
|
|
||||||
|
|
||||||
class Counter extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<button t-on-click="increment">
|
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
|
||||||
</button>`;
|
|
||||||
|
|
||||||
state = useState({ value: 0 });
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that the `t-on-click` handler can even be replaced by an inline statement:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="state.value++">
|
|
||||||
```
|
|
||||||
|
|
||||||
**Props:** sub components often needs some information from their parents. This
|
|
||||||
is done by adding the required information to the template. This will then be
|
|
||||||
accessible by the sub component in the `props` object. Note that there is an
|
|
||||||
important rule here: the information contained in the `props` object is not
|
|
||||||
owned by the sub component, and should never be modified.
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Child extends Component {
|
|
||||||
static template = xml`<div>Hello <t t-esc="props.name"/></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
class Parent extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div>
|
|
||||||
<Child name="'Owl'" />
|
|
||||||
<Child name="'Framework'" />
|
|
||||||
</div>`;
|
|
||||||
static components = { Child };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Communication:** there are multiple ways to communicate information between
|
|
||||||
components. However, the two most important ways are the following:
|
|
||||||
|
|
||||||
- from parent to children: by using `props`,
|
|
||||||
- from a children to one of its parent: by triggering events.
|
|
||||||
|
|
||||||
The following example illustrate both mechanisms:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class OrderLine extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div t-on-click="add">
|
|
||||||
<div><t t-esc="props.line.name"/></div>
|
|
||||||
<div>Quantity: <t t-esc="props.line.quantity"/></div>
|
|
||||||
</div>`;
|
|
||||||
|
|
||||||
add() {
|
|
||||||
this.trigger("add-to-order", { line: props.line });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Parent extends Component {
|
|
||||||
static template = xml`
|
|
||||||
<div t-on-add-to-order="addToOrder">
|
|
||||||
<OrderLine
|
|
||||||
t-foreach="orders"
|
|
||||||
t-as="line"
|
|
||||||
line="line" />
|
|
||||||
</div>`;
|
|
||||||
static components = { OrderLine };
|
|
||||||
orders = useState([{ id: 1, name: "Coffee", quantity: 0 }, { id: 2, name: "Tea", quantity: 0 }]);
|
|
||||||
|
|
||||||
addToOrder(event) {
|
|
||||||
const line = event.detail.line;
|
|
||||||
line.quantity++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the `OrderLine` component trigger a `add-to-order` event. This
|
|
||||||
will generate a DOM event which will bubble along the DOM tree. It will then be
|
|
||||||
intercepted by the parent component, which will then get the line (from the
|
|
||||||
`detail` key) and then increment its quantity. See the section on [event handling](doc/reference/component.md#event-handling)
|
|
||||||
for more details on how events work.
|
|
||||||
|
|
||||||
Note that this example would have also worked if the `OrderLine` component
|
|
||||||
directly modifies the `line` object. However, this is not a good practice: this
|
|
||||||
only works because the `props` object received by the child component is reactive,
|
|
||||||
so the child component is then coupled to the parents implementation.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# 🦉 How to debug Owl applications 🦉
|
||||||
|
|
||||||
|
Non trivial applications become quickly more difficult to understand. It is then
|
||||||
|
useful to have a solid understanding of what is going on. To help with that,
|
||||||
|
logging useful information is extremely valuable. There is a [javascript file](../../tools/debug.js) which can be evaluated in an application.
|
||||||
|
|
||||||
|
Once it is executed, it will log a lot of information on each component main hooks. The following code is a minified version to make it easier to copy/paste:
|
||||||
|
|
||||||
|
```
|
||||||
|
function debugOwl(t,e){let n,o="[OWL_DEBUG]";function r(t){let e;try{e=JSON.stringify(t||{})}catch(t){e="<JSON error>"}return e.length>200&&(e=e.slice(0,200)+"..."),e}if(Object.defineProperty(t.Component,"current",{get:()=>n,set(s){n=s;const i=s.constructor.name;if(e.componentBlackList&&e.componentBlackList.test(i))return;if(e.componentWhiteList&&!e.componentWhiteList.test(i))return;let l;Object.defineProperty(n,"__owl__",{get:()=>l,set(n){!function(n,s,i){let l=`${s}<id=${i}>`,c=t=>console.log(`${o} ${l} ${t}`),u=t=>(!e.methodBlackList||!e.methodBlackList.includes(t))&&!(e.methodWhiteList&&!e.methodWhiteList.includes(t));u("constructor")&&c(`constructor, props=${r(n.props)}`);u("willStart")&&t.hooks.onWillStart(()=>{c("willStart")});u("mounted")&&t.hooks.onMounted(()=>{c("mounted")});u("willUpdateProps")&&t.hooks.onWillUpdateProps(t=>{c(`willUpdateProps, nextprops=${r(t)}`)});u("willPatch")&&t.hooks.onWillPatch(()=>{c("willPatch")});u("patched")&&t.hooks.onPatched(()=>{c("patched")});u("willUnmount")&&t.hooks.onWillUnmount(()=>{c("willUnmount")});const d=n.__render.bind(n);n.__render=function(...t){c("rendering template"),d(...t)};const h=n.render.bind(n);n.render=function(...t){const e=n.__owl__;let o="render";return e.isMounted||e.currentFiber||(o+=" (warning: component is not mounted, this render has no effect)"),c(o),h(...t)};const p=n.mount.bind(n);n.mount=function(...t){return c("mount"),p(...t)}}(s,i,(l=n).id)}})}}),e.logScheduler){let e=t.Component.scheduler.start,n=t.Component.scheduler.stop;t.Component.scheduler.start=function(){this.isRunning||console.log(`${o} scheduler: start running tasks queue`),e.call(this)},t.Component.scheduler.stop=function(){this.isRunning&&console.log(`${o} scheduler: stop running tasks queue`),n.call(this)}}if(e.logStore){let e=t.Store.prototype.dispatch;t.Store.prototype.dispatch=function(t,...n){return console.log(`${o} store: action '${t}' dispatched. Payload: '${r(n)}'`),e.call(this,t,...n)}}}
|
||||||
|
debugOwl(owl, {
|
||||||
|
// componentBlackList: /App/, // regexp
|
||||||
|
// componentWhiteList: /SomeComponent/, // regexp
|
||||||
|
// methodBlackList: ["mounted"], // list of method names
|
||||||
|
// methodWhiteList: ["willStart"], // list of method names
|
||||||
|
logScheduler: false, // display/mute scheduler logs
|
||||||
|
logStore: true, // display/mute store logs
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The above code, once pasted somewhere in the main javascript file of an owl
|
||||||
|
application, will log information looking like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> constructor, props={}
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> mount
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> willStart
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> constructor, props={"id":2,"completed":false,"title":"hey"}
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> willStart
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> constructor, props={"id":4,"completed":false,"title":"aaa"}
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> willStart
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> rendering template
|
||||||
|
[OWL_DEBUG] TodoItem<id=3> mounted
|
||||||
|
[OWL_DEBUG] TodoItem<id=2> mounted
|
||||||
|
[OWL_DEBUG] TodoApp<id=1> mounted
|
||||||
|
```
|
||||||
|
|
||||||
|
Each component has an internal `id`, which is very useful when debugging.
|
||||||
|
|
||||||
|
Note that it is certainly useful to run this code at some point in an application,
|
||||||
|
just to get a feel of what each user action implies, for the framework.
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# 🦉 Testing Owl components 🦉
|
# 🦉 How to test Components 🦉
|
||||||
|
|
||||||
## Content
|
## Content
|
||||||
|
|
||||||
@@ -11,8 +11,7 @@ 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
|
behave as expected. There are many ways to test a user interface: manual
|
||||||
testing, integration testing, unit testing, ...
|
testing, integration testing, unit testing, ...
|
||||||
|
|
||||||
In this section, we will discuss how to write unit tests for components, and
|
In this section, we will discuss how to write unit tests for components.
|
||||||
how to debug them if necessary.
|
|
||||||
|
|
||||||
## Unit Tests
|
## Unit Tests
|
||||||
|
|
||||||
@@ -86,8 +85,7 @@ afterEach(() => {
|
|||||||
describe("SomeComponent", () => {
|
describe("SomeComponent", () => {
|
||||||
test("component behaves as expected", async () => {
|
test("component behaves as expected", async () => {
|
||||||
const props = {...}; // depends on the component
|
const props = {...}; // depends on the component
|
||||||
const comp = new SomeComponent(null, props);
|
const comp = await mount(SomeComponent, { target: fixture, props });
|
||||||
await comp.mount(fixture);
|
|
||||||
|
|
||||||
// do some assertions
|
// do some assertions
|
||||||
expect(...).toBe(...);
|
expect(...).toBe(...);
|
||||||
@@ -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: this.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.
|
||||||
+371
-70
@@ -1,107 +1,408 @@
|
|||||||
# 🦉 Quick Start 🦉
|
# 🦉 How to start an Owl project 🦉
|
||||||
|
|
||||||
## Static Server
|
## Content
|
||||||
|
|
||||||
Let us assume that we have a static server running somewhere. Let us start by
|
- [Overview](#overview)
|
||||||
adding an html page with a few extra files:
|
- [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:
|
||||||
|
|
||||||
```
|
```
|
||||||
my-app/
|
hello_owl/
|
||||||
index.html
|
index.html
|
||||||
app.css
|
owl.js
|
||||||
app.js
|
app.js
|
||||||
owl-X.Y.Z.js
|
|
||||||
templates.xml
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### HTML and CSS
|
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.
|
||||||
|
|
||||||
In a file `index.html`:
|
Now, `index.html` should contain the following:
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<title>Hello Owl</title>
|
||||||
<title>My OWL App</title>
|
<script src="owl.js"></script>
|
||||||
<link href="app.css" rel="stylesheet" />
|
<script src="app.js"></script>
|
||||||
<script src="owl-X.Y.Z.js"></script>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body></body>
|
||||||
<div id="main"></div>
|
|
||||||
<script src="app.js" type="module"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
In `app.css`:
|
And `app.js` should look like this:
|
||||||
|
|
||||||
```css
|
```js
|
||||||
button {
|
const { Component, mount } = owl;
|
||||||
color: darkred;
|
const { xml } = owl.tags;
|
||||||
font-size: 30px;
|
const { whenReady } = owl.utils;
|
||||||
width: 220px;
|
|
||||||
|
// Owl Components
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div>Hello Owl</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup code
|
||||||
|
function setup() {
|
||||||
|
mount(App, target: { 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, mount } = 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() {
|
||||||
|
mount(App, { target: 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"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Also, let's not forget to add a release of OWL (`owl-X.Y.Z.js`)
|
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.
|
||||||
|
|
||||||
### XML
|
## Standard Javascript project
|
||||||
|
|
||||||
In `templates.xml`:
|
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.
|
||||||
|
|
||||||
```xml
|
Each of these features, and many others, can be done in many different ways.
|
||||||
<templates>
|
Since it is really not trivial to configure such a project, we provide here an
|
||||||
<button t-name="clickcounter" t-on-click="increment">
|
example that can be used as a starting point.
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
|
||||||
</button>
|
Our standard Owl project has the following file structure:
|
||||||
</templates>
|
|
||||||
|
```
|
||||||
|
hello_owl/
|
||||||
|
public/
|
||||||
|
index.html
|
||||||
|
src/
|
||||||
|
components/
|
||||||
|
App.js
|
||||||
|
main.js
|
||||||
|
tests/
|
||||||
|
components/
|
||||||
|
App.test.js
|
||||||
|
helpers.js
|
||||||
|
.gitignore
|
||||||
|
package.json
|
||||||
|
webpack.config.js
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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.
|
||||||
|
|
||||||
To build an application (or a sub-part of an application), we need two things:
|
Here is the content of `index.html`:
|
||||||
|
|
||||||
- an environment: it is the global context in which we are working. It needs to
|
```html
|
||||||
contain a QWeb instance (preloaded with templates), and anything else that we
|
<!DOCTYPE html>
|
||||||
need. In practice, it could be used to contain some user session information, some
|
<html lang="en">
|
||||||
configuration keys (for example, isMobile = true/false if we are in mobile mode).
|
<head>
|
||||||
|
<title>Hello Owl</title>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
- a description of the user interface: there should be a root component, which can
|
Note that there are no `<script>` tag here. They will be injected by webpack.
|
||||||
have sub components
|
Now, let's have a look at the javascript files:
|
||||||
|
|
||||||
Here are a few steps that we may take to get started:
|
```js
|
||||||
|
// src/components/App.js -------------------------------------------------------
|
||||||
|
import { Component, tags, useState } from "@odoo/owl";
|
||||||
|
|
||||||
- get the templates
|
const { xml } = tags;
|
||||||
- create a qweb engine, with the templates
|
|
||||||
- create an environment
|
|
||||||
- create an instance of the root component
|
|
||||||
- mount the root component to a DOM element
|
|
||||||
|
|
||||||
Let us now add the javascript to make it work, in `app.js`:
|
export class App extends Component {
|
||||||
|
static template = xml`<div t-on-click="update">Hello <t t-esc="state.text"/></div>`;
|
||||||
```javascript
|
state = useState({ text: "Owl" });
|
||||||
const useState = owl.hooks.useState;
|
update() {
|
||||||
|
this.state.text = this.state.text === "Owl" ? "World" : "Owl";
|
||||||
class ClickCounter extends owl.Component {
|
|
||||||
static template = "clickcounter";
|
|
||||||
state = useState({ value: 0 });
|
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
// src/main.js -----------------------------------------------------------------
|
||||||
// Application initialization
|
import { utils, mount } from "@odoo/owl";
|
||||||
//------------------------------------------------------------------------------
|
import { App } from "./components/App";
|
||||||
async function start() {
|
|
||||||
const templates = await owl.utils.loadFile("templates.xml");
|
function setup() {
|
||||||
ClickCounter.env = { qweb: new owl.QWeb({ templates }) };
|
mount(App, { target: document.body });
|
||||||
const counter = new ClickCounter();
|
|
||||||
const target = document.getElementById("main");
|
|
||||||
await counter.mount(target);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
start();
|
utils.whenReady(setup);
|
||||||
|
|
||||||
|
// tests/components/App.test.js ------------------------------------------------
|
||||||
|
import { App } from "../../src/components/App";
|
||||||
|
import { makeTestFixture, nextTick, click } from "../helpers";
|
||||||
|
import { mount } from "@odoo/owl";
|
||||||
|
|
||||||
|
let fixture;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = makeTestFixture();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("App", () => {
|
||||||
|
test("Works as expected...", async () => {
|
||||||
|
await mount(App, { target: 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
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ todoapp/
|
|||||||
index.html
|
index.html
|
||||||
app.css
|
app.css
|
||||||
app.js
|
app.js
|
||||||
owl.min.js
|
owl.js
|
||||||
```
|
```
|
||||||
|
|
||||||
The entry point for this application is the file `index.html`, which should have
|
The entry point for this application is the file `index.html`, which should have
|
||||||
@@ -62,7 +62,7 @@ our application. `app.js` is where we will write all our code. For now, let's
|
|||||||
just put the following code:
|
just put the following code:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
(function() {
|
(function () {
|
||||||
console.log("hello owl", owl.__info__.version);
|
console.log("hello owl", owl.__info__.version);
|
||||||
})();
|
})();
|
||||||
```
|
```
|
||||||
@@ -70,7 +70,9 @@ just put the following code:
|
|||||||
Note that we put everything inside an immediately executed function to avoid leaking
|
Note that we put everything inside an immediately executed function to avoid leaking
|
||||||
anything to the global scope.
|
anything to the global scope.
|
||||||
|
|
||||||
Finally, `owl.js` should be the last version downloaded from the Owl repository (you can use `owl.min.js` if you prefer).
|
Finally, `owl.js` should be the last version downloaded from the Owl repository (you can use `owl.min.js` if you prefer). Be aware that you should download the `owl.iife.js` or `owl.iife.min.js`, because these files
|
||||||
|
are built to run directly on the browser (other files such as `owl.cjs.js` are
|
||||||
|
built to be bundled by other tools).
|
||||||
|
|
||||||
Now, the project should be ready. Loading the `index.html` file into a browser
|
Now, the project should be ready. Loading the `index.html` file into a browser
|
||||||
should show an empty page, with the title `Owl Todo App`, and it should log a
|
should show an empty page, with the title `Owl Todo App`, and it should log a
|
||||||
@@ -83,7 +85,7 @@ a single root component. Let us start by defining an `App` component. Replace th
|
|||||||
content of the function in `app.js` by the following code:
|
content of the function in `app.js` by the following code:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Component } = owl;
|
const { Component, mount } = owl;
|
||||||
const { xml } = owl.tags;
|
const { xml } = owl.tags;
|
||||||
const { whenReady } = owl.utils;
|
const { whenReady } = owl.utils;
|
||||||
|
|
||||||
@@ -94,8 +96,7 @@ class App extends Component {
|
|||||||
|
|
||||||
// Setup code
|
// Setup code
|
||||||
function setup() {
|
function setup() {
|
||||||
const app = new App();
|
mount(App, { target: document.body });
|
||||||
app.mount(document.body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
whenReady(setup);
|
whenReady(setup);
|
||||||
@@ -170,13 +171,13 @@ class App extends Component {
|
|||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
title: "buy milk",
|
title: "buy milk",
|
||||||
isCompleted: true
|
isCompleted: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
title: "clean house",
|
title: "clean house",
|
||||||
isCompleted: false
|
isCompleted: false,
|
||||||
}
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -279,8 +280,7 @@ class App extends Component {
|
|||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
function setup() {
|
function setup() {
|
||||||
owl.config.mode = "dev";
|
owl.config.mode = "dev";
|
||||||
const app = new App();
|
mount(App, { target: document.body });
|
||||||
app.mount(document.body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
whenReady(setup);
|
whenReady(setup);
|
||||||
@@ -446,7 +446,7 @@ Now, this is an interesting situation: the task is displayed by the `Task`
|
|||||||
component, but it is not the owner of its state, so it cannot modify it. Instead,
|
component, but it is not the owner of its state, so it cannot modify it. Instead,
|
||||||
we want to communicate the request to toggle a task to the `App` component.
|
we want to communicate the request to toggle a task to the `App` component.
|
||||||
Since `App` is a parent of `Task`, we can
|
Since `App` is a parent of `Task`, we can
|
||||||
[trigger](../reference/component.md#event-handling) an event in `Task` and listen
|
[trigger](../reference/event_handling.md) an event in `Task` and listen
|
||||||
for it in `App`.
|
for it in `App`.
|
||||||
|
|
||||||
In `Task`, change the `input` to:
|
In `Task`, change the `input` to:
|
||||||
@@ -547,7 +547,7 @@ application), since it involves extracting all task related code out of the
|
|||||||
components. Here is the new content of the `app.js` file:
|
components. Here is the new content of the `app.js` file:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Component, Store } = owl;
|
const { Component, Store, mount } = owl;
|
||||||
const { xml } = owl.tags;
|
const { xml } = owl.tags;
|
||||||
const { whenReady } = owl.utils;
|
const { whenReady } = owl.utils;
|
||||||
const { useRef, useDispatch, useStore } = owl.hooks;
|
const { useRef, useDispatch, useStore } = owl.hooks;
|
||||||
@@ -562,23 +562,23 @@ const actions = {
|
|||||||
const task = {
|
const task = {
|
||||||
id: state.nextId++,
|
id: state.nextId++,
|
||||||
title: title,
|
title: title,
|
||||||
isCompleted: false
|
isCompleted: false,
|
||||||
};
|
};
|
||||||
state.tasks.push(task);
|
state.tasks.push(task);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
toggleTask({ state }, id) {
|
toggleTask({ state }, id) {
|
||||||
const task = state.tasks.find(t => t.id === id);
|
const task = state.tasks.find((t) => t.id === id);
|
||||||
task.isCompleted = !task.isCompleted;
|
task.isCompleted = !task.isCompleted;
|
||||||
},
|
},
|
||||||
deleteTask({ state }, id) {
|
deleteTask({ state }, id) {
|
||||||
const index = state.tasks.findIndex(t => t.id === id);
|
const index = state.tasks.findIndex((t) => t.id === id);
|
||||||
state.tasks.splice(index, 1);
|
state.tasks.splice(index, 1);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const initialState = {
|
const initialState = {
|
||||||
nextId: 1,
|
nextId: 1,
|
||||||
tasks: []
|
tasks: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
@@ -616,7 +616,7 @@ class App extends Component {
|
|||||||
static components = { Task };
|
static components = { Task };
|
||||||
|
|
||||||
inputRef = useRef("add-input");
|
inputRef = useRef("add-input");
|
||||||
tasks = useStore(state => state.tasks);
|
tasks = useStore((state) => state.tasks);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
|
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -639,8 +639,7 @@ function setup() {
|
|||||||
owl.config.mode = "dev";
|
owl.config.mode = "dev";
|
||||||
const store = new Store({ actions, state: initialState });
|
const store = new Store({ actions, state: initialState });
|
||||||
App.env.store = store;
|
App.env.store = store;
|
||||||
const app = new App();
|
mount(App, { target: document.body });
|
||||||
app.mount(document.body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
whenReady(setup);
|
whenReady(setup);
|
||||||
@@ -666,9 +665,8 @@ function makeStore() {
|
|||||||
|
|
||||||
function setup() {
|
function setup() {
|
||||||
owl.config.mode = "dev";
|
owl.config.mode = "dev";
|
||||||
App.env.store = makeStore();
|
const env = { store: makeStore() };
|
||||||
const app = new App();
|
mount(App, { target: document.body, env });
|
||||||
app.mount(document.body);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -811,8 +809,8 @@ For reference, here is the final code:
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
(function() {
|
(function () {
|
||||||
const { Component, Store } = owl;
|
const { Component, Store, mount } = owl;
|
||||||
const { xml } = owl.tags;
|
const { xml } = owl.tags;
|
||||||
const { whenReady } = owl.utils;
|
const { whenReady } = owl.utils;
|
||||||
const { useRef, useDispatch, useState, useStore } = owl.hooks;
|
const { useRef, useDispatch, useState, useStore } = owl.hooks;
|
||||||
@@ -827,24 +825,24 @@ For reference, here is the final code:
|
|||||||
const task = {
|
const task = {
|
||||||
id: state.nextId++,
|
id: state.nextId++,
|
||||||
title: title,
|
title: title,
|
||||||
isCompleted: false
|
isCompleted: false,
|
||||||
};
|
};
|
||||||
state.tasks.push(task);
|
state.tasks.push(task);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
toggleTask({ state }, id) {
|
toggleTask({ state }, id) {
|
||||||
const task = state.tasks.find(t => t.id === id);
|
const task = state.tasks.find((t) => t.id === id);
|
||||||
task.isCompleted = !task.isCompleted;
|
task.isCompleted = !task.isCompleted;
|
||||||
},
|
},
|
||||||
deleteTask({ state }, id) {
|
deleteTask({ state }, id) {
|
||||||
const index = state.tasks.findIndex(t => t.id === id);
|
const index = state.tasks.findIndex((t) => t.id === id);
|
||||||
state.tasks.splice(index, 1);
|
state.tasks.splice(index, 1);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const initialState = {
|
const initialState = {
|
||||||
nextId: 1,
|
nextId: 1,
|
||||||
tasks: []
|
tasks: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
@@ -897,7 +895,7 @@ For reference, here is the final code:
|
|||||||
static components = { Task };
|
static components = { Task };
|
||||||
|
|
||||||
inputRef = useRef("add-input");
|
inputRef = useRef("add-input");
|
||||||
tasks = useStore(state => state.tasks);
|
tasks = useStore((state) => state.tasks);
|
||||||
filter = useState({ value: "all" });
|
filter = useState({ value: "all" });
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
|
|
||||||
@@ -916,9 +914,9 @@ For reference, here is the final code:
|
|||||||
get displayedTasks() {
|
get displayedTasks() {
|
||||||
switch (this.filter.value) {
|
switch (this.filter.value) {
|
||||||
case "active":
|
case "active":
|
||||||
return this.tasks.filter(t => !t.isCompleted);
|
return this.tasks.filter((t) => !t.isCompleted);
|
||||||
case "completed":
|
case "completed":
|
||||||
return this.tasks.filter(t => t.isCompleted);
|
return this.tasks.filter((t) => t.isCompleted);
|
||||||
case "all":
|
case "all":
|
||||||
return this.tasks;
|
return this.tasks;
|
||||||
}
|
}
|
||||||
@@ -943,9 +941,8 @@ For reference, here is the final code:
|
|||||||
|
|
||||||
function setup() {
|
function setup() {
|
||||||
owl.config.mode = "dev";
|
owl.config.mode = "dev";
|
||||||
App.env.store = makeStore();
|
const env = { store: makeStore() };
|
||||||
const app = new App();
|
mount(App, { target: document.body, env });
|
||||||
app.mount(document.body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
whenReady(setup);
|
whenReady(setup);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ OWL, React and Vue have the same main feature: they allow developers to build
|
|||||||
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
|
||||||
|
|
||||||
In this page, we try to highlight some of these differences. Obviously, a lot of
|
In this page, we try to highlight some of these differences. Obviously, a lot of
|
||||||
effort was done to be fair. However, if you disagree with some of the points
|
effort was put to be fair. However, if you disagree with some of the points
|
||||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||||
|
|
||||||
## Content
|
## Content
|
||||||
@@ -47,7 +47,7 @@ components are fast enough for all our usecases, and making it as simple as
|
|||||||
possible for developers is more valuable (for us).
|
possible for developers is more valuable (for us).
|
||||||
|
|
||||||
Also, functions or class based components are more than just syntax. Functions
|
Also, functions or class based components are more than just syntax. Functions
|
||||||
comes with a mindset of composition and class are about inheritance. Clearly,
|
come with a mindset of composition and class are about inheritance. Clearly,
|
||||||
both of these are important mechanisms for reusing code. Also, one does not
|
both of these are important mechanisms for reusing code. Also, one does not
|
||||||
exclude the other.
|
exclude the other.
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ additional tools, we made a lot of effort to make the most of the web platform.
|
|||||||
|
|
||||||
For example, Owl uses the standard `xml` parser that comes with every browser.
|
For example, Owl uses the standard `xml` parser that comes with every browser.
|
||||||
Because of that, Owl did not have to write its own template parser. Another
|
Because of that, Owl did not have to write its own template parser. Another
|
||||||
example is the [`xml`](reference/tags.md#xml-tag) tag helper function, which makes use of
|
example is the [`xml`](../reference/tags.md#xml-tag) tag helper function, which makes use of
|
||||||
native template literals to allow in a natural way to write `xml` templates
|
native template literals to allow in a natural way to write `xml` templates
|
||||||
directly in the javascript code. This can be easily integrated with editor
|
directly in the javascript code. This can be easily integrated with editor
|
||||||
plugins to have autocompletion inside the template.
|
plugins to have autocompletion inside the template.
|
||||||
@@ -127,7 +127,7 @@ structured than a template language. Note that the tooling is quite impressive:
|
|||||||
there is a syntax highlighter for jsx here on github!
|
there is a syntax highlighter for jsx here on github!
|
||||||
|
|
||||||
By comparison, here is the equivalent Owl component, written with the
|
By comparison, here is the equivalent Owl component, written with the
|
||||||
[`xml`](reference/tags.md#xml-tag) tag helper:
|
[`xml`](../reference/tags.md#xml-tag) tag helper:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class Clock extends Component {
|
class Clock extends Component {
|
||||||
@@ -251,17 +251,17 @@ keeps track of who get data, and retrigger a render when it was changed.
|
|||||||
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
||||||
mutations), and like VueX, it keeps track of the state changes. However, it does
|
mutations), and like VueX, it keeps track of the state changes. However, it does
|
||||||
not notify a component when the state changes. Instead, components need to connect
|
not notify a component when the state changes. Instead, components need to connect
|
||||||
to the store like in redux, with the `useStore` hook (see the [store documentation](reference/store.md#connecting-a-component)).
|
to the store like in redux, with the `useStore` hook (see the [store documentation](../reference/store.md#connecting-a-component)).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const actions = {
|
const actions = {
|
||||||
increment({ state }, val) {
|
increment({ state }, val) {
|
||||||
state.counter.value += val;
|
state.counter.value += val;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
counter: { value: 0 }
|
counter: { value: 0 },
|
||||||
};
|
};
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
|
|
||||||
@@ -270,7 +270,7 @@ class Counter extends Component {
|
|||||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||||
Click Me! [<t t-esc="counter.value"/>]
|
Click Me! [<t t-esc="counter.value"/>]
|
||||||
</button>`;
|
</button>`;
|
||||||
counter = useStore(state => state.counter);
|
counter = useStore((state) => state.counter);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +315,7 @@ This work is based on the new ideas introduced by React hooks.
|
|||||||
|
|
||||||
From the way React and Vue introduce their hooks, it may look like hooks are not
|
From the way React and Vue introduce their hooks, it may look like hooks are not
|
||||||
compatible with class components. However, this is not the case, as shown by
|
compatible with class components. However, this is not the case, as shown by
|
||||||
Owl [hooks](reference/hooks.md). They are inspired by both React and Vue. For example,
|
Owl [hooks](../reference/hooks.md). They are inspired by both React and Vue. For example,
|
||||||
the `useState` hook is named after React, but its API is closer to the `reactive`
|
the `useState` hook is named after React, but its API is closer to the `reactive`
|
||||||
Vue hook.
|
Vue hook.
|
||||||
|
|
||||||
@@ -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 installs
|
||||||
|
or removes 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 resolved 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 components, and is easy to integrate
|
||||||
|
in any html page, with a simple `<script>` tag.
|
||||||
|
|
||||||
|
## Template based
|
||||||
|
|
||||||
|
Odoo stores templates as XML documents 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 developers 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 components, 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 an 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 read-only,
|
||||||
|
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 performs 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 wants 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 makes choices compatible with Odoo.
|
||||||
|
|
||||||
|
And that is why we built Owl 🦉.
|
||||||
+30
-50
@@ -1,15 +1,34 @@
|
|||||||
# 🦉 OWL Documentation 🦉
|
# 🦉 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
|
## Reference
|
||||||
|
|
||||||
|
You will find here a complete reference of every feature, class or object
|
||||||
|
provided by Owl.
|
||||||
|
|
||||||
- [Animations](reference/animations.md)
|
- [Animations](reference/animations.md)
|
||||||
|
- [Browser](reference/browser.md)
|
||||||
- [Component](reference/component.md)
|
- [Component](reference/component.md)
|
||||||
|
- [Content](reference/content.md)
|
||||||
- [Concurrency Model](reference/concurrency_model.md)
|
- [Concurrency Model](reference/concurrency_model.md)
|
||||||
- [Configuration](reference/config.md)
|
- [Configuration](reference/config.md)
|
||||||
- [Context](reference/context.md)
|
- [Context](reference/context.md)
|
||||||
- [Environment](reference/environment.md)
|
- [Environment](reference/environment.md)
|
||||||
- [Event Bus](reference/event_bus.md)
|
- [Event Bus](reference/event_bus.md)
|
||||||
|
- [Event Handling](reference/event_handling.md)
|
||||||
|
- [Error Handling](reference/error_handling.md)
|
||||||
- [Hooks](reference/hooks.md)
|
- [Hooks](reference/hooks.md)
|
||||||
|
- [Mounting a component](reference/mounting.md)
|
||||||
- [Miscellaneous Components](reference/misc.md)
|
- [Miscellaneous Components](reference/misc.md)
|
||||||
- [Observer](reference/observer.md)
|
- [Observer](reference/observer.md)
|
||||||
- [Props](reference/props.md)
|
- [Props](reference/props.md)
|
||||||
@@ -18,60 +37,21 @@
|
|||||||
- [QWeb Engine](reference/qweb_engine.md)
|
- [QWeb Engine](reference/qweb_engine.md)
|
||||||
- [Router](reference/router.md)
|
- [Router](reference/router.md)
|
||||||
- [Store](reference/store.md)
|
- [Store](reference/store.md)
|
||||||
|
- [Slots](reference/slots.md)
|
||||||
- [Tags](reference/tags.md)
|
- [Tags](reference/tags.md)
|
||||||
- [Utils](reference/utils.md)
|
- [Utils](reference/utils.md)
|
||||||
|
|
||||||
## Learning Resources
|
## Other Topics
|
||||||
|
|
||||||
- [Quick Start: create an (almost) empty Owl application](learning/quick_start.md)
|
This section provides miscellaneous document that explains some topics
|
||||||
- [Tutorial: create a TodoList application](learning/tutorial_todoapp.md)
|
which cannot be considered either a tutorial, or reference documentation.
|
||||||
- [Testing Owl components](learning/testing_components.md)
|
|
||||||
|
|
||||||
## Miscellaneous
|
- [Owl architecture: the Virtual DOM](miscellaneous/vdom.md)
|
||||||
|
- [Owl architecture: the rendering pipeline](miscellaneous/rendering.md)
|
||||||
|
- [Comparison with React/Vue](miscellaneous/comparison.md)
|
||||||
|
- [Why did Odoo built Owl?](miscellaneous/why_owl.md)
|
||||||
|
|
||||||
- [Comparison with React/Vue](comparison.md)
|
---
|
||||||
- [Tooling](tooling.md)
|
|
||||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
|
||||||
|
|
||||||
## Architecture
|
Found an issue in the documentation? A broken link? Some outdated information?
|
||||||
|
Please open an issue or submit a PR!
|
||||||
This section explains in more detail the inner workings of Owl. It is targeted
|
|
||||||
for developers working on Owl itself.
|
|
||||||
|
|
||||||
- [Virtual DOM](architecture/vdom.md)
|
|
||||||
- [Rendering](architecture/rendering.md)
|
|
||||||
|
|
||||||
## Owl Content
|
|
||||||
|
|
||||||
Here is a complete visual representation of everything exported by the `owl`
|
|
||||||
global object (so, 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.
|
|
||||||
|
|||||||
@@ -52,21 +52,20 @@ sequence of events will happen:
|
|||||||
At node insertion:
|
At node insertion:
|
||||||
|
|
||||||
- the css classes `name-enter` and `name-enter-active` will be added directly
|
- the css classes `name-enter` and `name-enter-active` will be added directly
|
||||||
when the node is inserted into the DOM,
|
when the node is inserted into the DOM.
|
||||||
- on the next animation frame: the css class `name-enter` will be removed and the
|
- 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
|
class `name-enter-to` will be added (so they can be used to trigger css
|
||||||
transition effects),
|
transition effects).
|
||||||
- the css class `name-enter-active` will be removed whenever a css transition
|
- at the end of the transition, `name-enter-to` and `name-enter-active` will be removed.
|
||||||
ends.
|
|
||||||
|
|
||||||
At node destruction:
|
At node destruction:
|
||||||
|
|
||||||
- the css classes `name-leave` and `name-leave-active` will be added before the
|
- the css classes `name-leave` and `name-leave-active` will be added before the
|
||||||
node is removed to the DOM,
|
node is removed to the DOM.
|
||||||
- the css class `name-leave` will be removed on the next animation frame (so it
|
- on the next animation frame: the css class `name-leave` will be removed and the
|
||||||
can be used to trigger css transition effects),
|
class `name-leave-to` will be added (so they can be used to trigger css
|
||||||
- the css class `name-leave-active` will be removed whenever a css transition
|
transition effects).
|
||||||
ends. Only then will the element be removed from the DOM.
|
- at the end of the transition, `name-leave-to` and `name-leave-active` will be removed.
|
||||||
|
|
||||||
For example, a simple fade in/out effect can be done with this:
|
For example, a simple fade in/out effect can be done with this:
|
||||||
|
|
||||||
@@ -93,3 +92,36 @@ Notes:
|
|||||||
|
|
||||||
Owl does not support more than one transition on a single node, so the
|
Owl does not support more than one transition on a single node, so the
|
||||||
`t-transition` expression must be a single value (i.e. no space allowed).
|
`t-transition` expression must be a single value (i.e. no space allowed).
|
||||||
|
|
||||||
|
## SCSS Mixins
|
||||||
|
|
||||||
|
If you use SCSS, you can use mixins to make generic animations. Here is an exemple with a fade in / fade out animation:
|
||||||
|
|
||||||
|
```scss
|
||||||
|
@mixin animation-fade($time, $name) {
|
||||||
|
.#{$name}_fade-enter-active,
|
||||||
|
.#{$name}_fade-active {
|
||||||
|
transition: all $time;
|
||||||
|
}
|
||||||
|
|
||||||
|
.#{$name}_fade-enter {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.#{$name}_fade-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
|
||||||
|
```scss
|
||||||
|
@include animation-fade(0.5s, "o_notification");
|
||||||
|
```
|
||||||
|
|
||||||
|
You can now have in your template:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<SomeTag t-transition="o_notification_fade"/>
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# 🦉 Browser 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Browser Content](#browser-content)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The browser object contains some browser native APIs, such as `setTimeout`, that
|
||||||
|
are used by Owl and its utility functions. They are exposed with the intent of
|
||||||
|
making them mockable if necessary.
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.browser.setTimeout === window.setTimeout; // return true
|
||||||
|
```
|
||||||
|
|
||||||
|
For now, this object contains some functions that are not used by Owl. They
|
||||||
|
will eventually be removed in Owl 2.0.
|
||||||
|
|
||||||
|
## Browser Content
|
||||||
|
|
||||||
|
More specifically, the `browser` object contains the following methods and objects:
|
||||||
|
|
||||||
|
- `setTimeout`
|
||||||
|
- `clearTimeout`
|
||||||
|
- `setInterval`
|
||||||
|
- `clearInterval`
|
||||||
|
- `requestAnimationFrame`
|
||||||
|
- `random`
|
||||||
|
- `Date`
|
||||||
|
- `fetch`
|
||||||
|
- `localStorage`
|
||||||
+55
-273
@@ -10,16 +10,22 @@
|
|||||||
- [Static Properties](#static-properties)
|
- [Static Properties](#static-properties)
|
||||||
- [Methods](#methods)
|
- [Methods](#methods)
|
||||||
- [Lifecycle](#lifecycle)
|
- [Lifecycle](#lifecycle)
|
||||||
|
- [`constructor(parent, props)`](#constructorparent-props)
|
||||||
|
- [`setup()`](#setup)
|
||||||
|
- [`willStart()`](#willstart)
|
||||||
|
- [`mounted()`](#mounted)
|
||||||
|
- [`willUpdateProps(nextProps)`](#willupdatepropsnextprops)
|
||||||
|
- [`willPatch()`](#willpatch)
|
||||||
|
- [`patched(snapshot)`](#patchedsnapshot)
|
||||||
|
- [`willUnmount()`](#willunmount)
|
||||||
|
- [`catchError(error)`](#catcherrorerror)
|
||||||
- [Root Component](#root-component)
|
- [Root Component](#root-component)
|
||||||
- [Composition](#composition)
|
- [Composition](#composition)
|
||||||
- [Event Handling](#event-handling)
|
|
||||||
- [Form Input Bindings](#form-input-bindings)
|
- [Form Input Bindings](#form-input-bindings)
|
||||||
- [References](#references)
|
- [References](#references)
|
||||||
- [Slots](#slots)
|
|
||||||
- [Dynamic sub components](#dynamic-sub-components)
|
- [Dynamic sub components](#dynamic-sub-components)
|
||||||
- [Error Handling](#error-handling)
|
|
||||||
- [Functional Components](#functional-components)
|
- [Functional Components](#functional-components)
|
||||||
- [SVG components](#svg-components)
|
- [SVG Components](#svg-components)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
@@ -207,7 +213,7 @@ to be called in the constructor.
|
|||||||
class Counter extends owl.Component {
|
class Counter extends owl.Component {
|
||||||
static props = {
|
static props = {
|
||||||
initialValue: Number,
|
initialValue: Number,
|
||||||
optional: true
|
optional: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -220,7 +226,7 @@ to be called in the constructor.
|
|||||||
```js
|
```js
|
||||||
class Counter extends owl.Component {
|
class Counter extends owl.Component {
|
||||||
static defaultProps = {
|
static defaultProps = {
|
||||||
initialValue: 0
|
initialValue: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -273,6 +279,10 @@ We explain here all the public methods of the `Component` class.
|
|||||||
// app is now visible
|
// app is now visible
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Note that the normal way of mounting an application is by using the `mount`
|
||||||
|
method on a component class, not by creating the instance by hand. See the
|
||||||
|
documentation on [mounting applications](mounting.md).
|
||||||
|
|
||||||
* **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
* **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
||||||
method can be used. Most applications should not call `unmount`, this is more
|
method can be used. Most applications should not call `unmount`, this is more
|
||||||
useful to the underlying component system.
|
useful to the underlying component system.
|
||||||
@@ -288,8 +298,13 @@ We explain here all the public methods of the `Component` class.
|
|||||||
are updated. It returns a boolean, which indicates if the component should
|
are updated. It returns a boolean, which indicates if the component should
|
||||||
ignore a props update. If it returns false, then `willUpdateProps` will not
|
ignore a props update. If it returns false, then `willUpdateProps` will not
|
||||||
be called, and no rendering will occur. Its default implementation is to
|
be called, and no rendering will occur. Its default implementation is to
|
||||||
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
always return true. Note that this is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
||||||
can be useful if we are handling large number of components.
|
can be useful if we are handling large number of components. Since this is an
|
||||||
|
optimization, Owl has the freedom to ignore the result of `shouldUpdate` in
|
||||||
|
some cases (for example, if a component is remounted, or if we want to force
|
||||||
|
a full rerender of the UI). However, if `shouldUpdate` returns true, then Owl
|
||||||
|
provides the guarantee that the component will be rendered at some point in
|
||||||
|
the future (except if the component is destroyed or if some part of the UI crashes).
|
||||||
|
|
||||||
* **`destroy()`**. As its name suggests, this method will remove the component,
|
* **`destroy()`**. As its name suggests, this method will remove the component,
|
||||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||||
@@ -308,16 +323,16 @@ A solid and robust component system needs useful hooks/methods to help
|
|||||||
developers write components. Here is a complete description of the lifecycle of
|
developers write components. Here is a complete description of the lifecycle of
|
||||||
a owl component:
|
a owl component:
|
||||||
|
|
||||||
| Method | Description |
|
| Method | Description |
|
||||||
| ------------------------------------------------ | ------------------------------------------------------------ |
|
| ------------------------------------------------ | ----------------------------------------------------------- |
|
||||||
| **[constructor](#constructorparent-props)** | constructor |
|
| **[setup](#setup)** | setup |
|
||||||
| **[willStart](#willstart)** | async, before first rendering |
|
| **[willStart](#willstart)** | async, before first rendering |
|
||||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||||
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
||||||
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
||||||
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
||||||
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
||||||
| **[catchError](#catcherrorerror)** | catch errors (see [error handling section](#error-handling)) |
|
| **[catchError](#catcherrorerror)** | catch errors (see [error handling page](error_handling.md)) |
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
@@ -355,6 +370,23 @@ class ClickCounter extends owl.Component {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Hook functions can be called in the constructor.
|
||||||
|
|
||||||
|
#### `setup()`
|
||||||
|
|
||||||
|
_setup_ is run just after the component is constructed. It is a lifecycle method,
|
||||||
|
very similar to the _constructor_, except that it does not receive any argument.
|
||||||
|
|
||||||
|
It is a valid method to call hook functions. Note that one of the main reason to
|
||||||
|
have the `setup` hook in the component lifecycle is to make it possible to
|
||||||
|
monkey patch it. It is a common need in the Odoo ecosystem.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
setup() {
|
||||||
|
useSetupAutofocus();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
#### `willStart()`
|
#### `willStart()`
|
||||||
|
|
||||||
willStart is an asynchronous hook that can be implemented to
|
willStart is an asynchronous hook that can be implemented to
|
||||||
@@ -452,8 +484,8 @@ This is the opposite method of `mounted`.
|
|||||||
#### `catchError(error)`
|
#### `catchError(error)`
|
||||||
|
|
||||||
The `catchError` method is useful when we need to intercept and properly react
|
The `catchError` method is useful when we need to intercept and properly react
|
||||||
to (rendering) errors that occur in some sub components. See the section on
|
to (rendering) errors that occur in some sub components. See the page on
|
||||||
[error handling](#error-handling).
|
[error handling](error_handling.md).
|
||||||
|
|
||||||
### Root Component
|
### Root Component
|
||||||
|
|
||||||
@@ -552,128 +584,6 @@ with a class object:
|
|||||||
<MyComponent t-att-class="{a: state.flagA, b: state.flagB}" />
|
<MyComponent t-att-class="{a: state.flagA, b: state.flagB}" />
|
||||||
```
|
```
|
||||||
|
|
||||||
### Event Handling
|
|
||||||
|
|
||||||
In a component's template, it is useful to be able to register handlers on DOM
|
|
||||||
elements to some specific events. This is what makes a template _alive_. There
|
|
||||||
are four different use cases.
|
|
||||||
|
|
||||||
1. Register an event handler on a DOM node (_pure_ DOM event)
|
|
||||||
2. Register an event handler on a component (_pure_ DOM event)
|
|
||||||
3. Register an event handler on a DOM node (_business_ DOM event)
|
|
||||||
4. Register an event handler on a component (_business_ DOM event)
|
|
||||||
|
|
||||||
A _pure_ DOM event is directly triggered by a user interaction (e.g. a `click`).
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click="someMethod">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
This will be roughly translated in javascript like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
button.addEventListener("click", component.someMethod.bind(component));
|
|
||||||
```
|
|
||||||
|
|
||||||
The suffix (`click` in this example) is simply the name of the actual DOM
|
|
||||||
event.
|
|
||||||
|
|
||||||
A _business_ DOM event is triggered by a call to `trigger` on a component.
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<MyComponent t-on-menu-loaded="someMethod" />
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
class MyComponent {
|
|
||||||
someWhere() {
|
|
||||||
const payload = ...;
|
|
||||||
this.trigger('menu-loaded', payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The call to `trigger` generates 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.
|
|
||||||
|
|
||||||
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>
|
|
||||||
```
|
|
||||||
|
|
||||||
In order to remove the DOM event details from the event handlers (like calls to
|
|
||||||
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
|
||||||
specified as additional suffixes of the `t-on` directive.
|
|
||||||
|
|
||||||
| Modifier | Description |
|
|
||||||
| ---------- | ----------------------------------------------------------------- |
|
|
||||||
| `.stop` | calls `event.stopPropagation()` before calling the method |
|
|
||||||
| `.prevent` | calls `event.preventDefault()` before calling the method |
|
|
||||||
| `.self` | calls the method only if the `event.target` is the element itself |
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click.stop="someMethod">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
|
|
||||||
the order may matter. For instance `t-on-click.prevent.self` will prevent all
|
|
||||||
clicks while `t-on-click.self.prevent` will only prevent clicks on the element
|
|
||||||
itself.
|
|
||||||
|
|
||||||
Finally, empty handlers are tolerated as they could be defined only to apply
|
|
||||||
modifiers. For example,
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<button t-on-click.stop="">Do something</button>
|
|
||||||
```
|
|
||||||
|
|
||||||
This will simply stop the propagation of the event.
|
|
||||||
|
|
||||||
### Form Input Bindings
|
### Form Input Bindings
|
||||||
|
|
||||||
It is very common to need to be able to read the value out of an html `input` (or
|
It is very common to need to be able to read the value out of an html `input` (or
|
||||||
@@ -823,75 +733,6 @@ Note that these two examples uses the suffix `ref` to name the reference. This
|
|||||||
is not mandatory, but it is a useful convention, so we do not forget to access
|
is not mandatory, but it is a useful convention, so we do not forget to access
|
||||||
it with the `el` or `comp` suffix.
|
it with the `el` or `comp` suffix.
|
||||||
|
|
||||||
### Slots
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
This is what _slots_ are for.
|
|
||||||
|
|
||||||
```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` directive:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="SomeComponent">
|
|
||||||
<div>some component</div>
|
|
||||||
<Dialog title="Some Dialog">
|
|
||||||
<t t-set="content">
|
|
||||||
<div>hey</div>
|
|
||||||
</t>
|
|
||||||
<t t-set="footer">
|
|
||||||
<button t-on-click="doSomething">ok</button>
|
|
||||||
</t>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
In this example, the component `Dialog` will render the slots `content` and `footer`
|
|
||||||
with its parent as rendering context. This means that clicking on the button
|
|
||||||
will execute the `doSomething` method on the parent, not on the dialog.
|
|
||||||
|
|
||||||
Default slot: the first element inside the component which is not a named slot will
|
|
||||||
be considered the `default` slot. For example:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="Parent">
|
|
||||||
<Child>
|
|
||||||
<span>some content</span>
|
|
||||||
</Child>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div t-name="Child">
|
|
||||||
<t t-slot="default"/>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
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> -->
|
|
||||||
```
|
|
||||||
|
|
||||||
### Dynamic sub components
|
### Dynamic sub components
|
||||||
|
|
||||||
It is not common, but sometimes we need a dynamic component name. In this case,
|
It is not common, but sometimes we need a dynamic component name. In this case,
|
||||||
@@ -937,65 +778,6 @@ component class.
|
|||||||
|
|
||||||
Note that the `t-component` directive can only be used on `<t>` nodes.
|
Note that the `t-component` directive can only be used on `<t>` nodes.
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
|
|
||||||
By default, whenever an error occurs in the rendering of an Owl application, we
|
|
||||||
destroy the whole application. Otherwise, we cannot offer any guarantee on the
|
|
||||||
state of the resulting component tree. It might be hopelessly corrupted, but
|
|
||||||
without any user-visible state.
|
|
||||||
|
|
||||||
Clearly, it sometimes is a little bit extreme to destroy the application. This
|
|
||||||
is why we have a builtin mechanism to handle rendering errors (and errors coming
|
|
||||||
from lifecycle hooks): the `catchError` hook.
|
|
||||||
|
|
||||||
Whenever the `catchError` lifecycle hook is implemented, all errors coming from
|
|
||||||
sub components rendering and/or lifecycle method calls will be caught and given
|
|
||||||
to the `catchError` method. This allows us to properly handle the error, and to
|
|
||||||
not break the application.
|
|
||||||
|
|
||||||
For example, here is how we could implement an `ErrorBoundary` component:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<div t-name="ErrorBoundary">
|
|
||||||
<t t-if="state.error">
|
|
||||||
Error handled
|
|
||||||
</t>
|
|
||||||
<t t-else="">
|
|
||||||
<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, it may be useful to know that whenever an error is caught, it is then
|
|
||||||
broadcasted to the application by an event on the `qweb` instance. It may be
|
|
||||||
useful, for example, to log the error somewhere.
|
|
||||||
|
|
||||||
```js
|
|
||||||
env.qweb.on("error", null, function(error) {
|
|
||||||
// do something
|
|
||||||
// react to the error
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Functional Components
|
### Functional Components
|
||||||
|
|
||||||
Owl does not exactly have functional components. However, there is an extremely
|
Owl does not exactly have functional components. However, there is an extremely
|
||||||
@@ -1007,7 +789,7 @@ template rendered with `props`. In Owl, this can be done by
|
|||||||
simply defining a template, that will access the `props` object:
|
simply defining a template, that will access the `props` object:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const Welcome = xml`<h1>Hello, {props.name}</h1>`;
|
const Welcome = xml`<h1>Hello, <t t-esc="props.name"/></h1>`;
|
||||||
|
|
||||||
class MyComponent extends Component {
|
class MyComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
@@ -1057,8 +839,8 @@ class RootNode extends Component {
|
|||||||
children: [
|
children: [
|
||||||
{ label: "b" },
|
{ label: "b" },
|
||||||
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
||||||
{ label: "f", children: [{ label: "g" }] }
|
{ label: "f", children: [{ label: "g" }] },
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ Here is what Owl will do:
|
|||||||
|
|
||||||
Tags are very small helpers to make it easy to write inline templates. There is
|
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,
|
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](../tooling.md#single-file-component).
|
such as a `css` tag, which will be used to write [single file components](../learning/how_to_write_sfc.md).
|
||||||
|
|
||||||
### Asynchronous Rendering
|
### Asynchronous Rendering
|
||||||
|
|
||||||
|
|||||||
+19
-2
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
The Owl framework is designed to work in many situations. However, it is
|
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
|
sometimes necessary to customize some behaviour. This is done by using the
|
||||||
global `config` object. It currently has one key:
|
global `config` object. It provides two settings:
|
||||||
|
|
||||||
- [`mode`](#mode).
|
- [`mode`](#mode) (default value: `prod`),
|
||||||
|
- [`enableTransitions`](#enabletransitions) (default value: `true`).
|
||||||
|
|
||||||
## Mode
|
## Mode
|
||||||
|
|
||||||
@@ -25,3 +26,19 @@ So, changing this setting is best done at startup.
|
|||||||
|
|
||||||
An important job done by the `dev` mode is to validate props for each component
|
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.
|
creation and update. Also, extra props will cause an error.
|
||||||
|
|
||||||
|
## `enableTransitions`
|
||||||
|
|
||||||
|
Transitions are usually nice, but they can cause issues in some specific cases,
|
||||||
|
such as automated tests. It is uncomfortable having to wait for a transition
|
||||||
|
to end before moving to the next step.
|
||||||
|
|
||||||
|
To solve this issue, Owl can be configured to ignore the `t-transition` directive.
|
||||||
|
To do that, one only needs to set the `enableTransitions` flag to false:
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.config.enableTransitions = false;
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that it suffers from the same drawback as the "dev" mode: all compiled
|
||||||
|
templates, if any, will keep their current behaviours.
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# 🦉 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`.
|
||||||
|
|
||||||
|
```
|
||||||
|
browser
|
||||||
|
Component misc
|
||||||
|
Context AsyncRoot
|
||||||
|
QWeb Portal
|
||||||
|
mount router
|
||||||
|
Store Link
|
||||||
|
useState RouteComponent
|
||||||
|
config Router
|
||||||
|
mode
|
||||||
|
core tags
|
||||||
|
EventBus css
|
||||||
|
Observer xml
|
||||||
|
hooks utils
|
||||||
|
onWillStart debounce
|
||||||
|
onMounted escape
|
||||||
|
onWillUpdateProps loadJS
|
||||||
|
onWillPatch loadFile
|
||||||
|
onPatched shallowEqual
|
||||||
|
onWillUnmount whenReady
|
||||||
|
useContext
|
||||||
|
useState
|
||||||
|
useRef
|
||||||
|
useComponent
|
||||||
|
useEnv
|
||||||
|
useSubEnv
|
||||||
|
useStore
|
||||||
|
useDispatch
|
||||||
|
useGetters
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
- [Setting an Environment](#setting-an-environment)
|
- [Setting an Environment](#setting-an-environment)
|
||||||
- [Using a sub environment](#using-a-sub-environment)
|
- [Using a sub environment](#using-a-sub-environment)
|
||||||
- [Content of an Environment](#content-of-an-environment)
|
- [Content of an Environment](#content-of-an-environment)
|
||||||
|
- [Special keys](#special-keys)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
@@ -48,15 +49,14 @@ The correct way to customize an environment is to simply set it up on the root
|
|||||||
component class, before the first component is created:
|
component class, before the first component is created:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
App.env = {
|
const env = {
|
||||||
_t: myTranslateFunction,
|
_t: myTranslateFunction,
|
||||||
user: {...},
|
user: {...},
|
||||||
services: {
|
services: {
|
||||||
...
|
...
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const app = new App();
|
mount(App, { target: document.body, env });
|
||||||
app.mount(document.body);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
It is also possible to simply share an environment between all root components,
|
It is also possible to simply share an environment between all root components,
|
||||||
@@ -93,7 +93,7 @@ Some good use cases for additional keys in the environment are:
|
|||||||
|
|
||||||
- some configuration keys,
|
- some configuration keys,
|
||||||
- session information,
|
- session information,
|
||||||
- generic services (such as doing rpcs, or accessing local storage).
|
- generic services (such as doing rpcs).
|
||||||
|
|
||||||
Doing it this way means that components are easily testable: we can simply
|
Doing it this way means that components are easily testable: we can simply
|
||||||
create a test environment with mock services.
|
create a test environment with mock services.
|
||||||
@@ -112,16 +112,25 @@ async function myEnv() {
|
|||||||
qweb: qweb,
|
qweb: qweb,
|
||||||
services: {
|
services: {
|
||||||
localStorage: localStorage,
|
localStorage: localStorage,
|
||||||
rpc: rpc
|
rpc: rpc,
|
||||||
},
|
},
|
||||||
debug: false,
|
debug: false,
|
||||||
inMobileMode: true
|
inMobileMode: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function start() {
|
async function start() {
|
||||||
App.env = await myEnv();
|
const env = await myEnv();
|
||||||
const app = new App();
|
mount(App, { target: document.body, env });
|
||||||
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. See [browser](browser.md) for more information. Note that the browser object will be removed from the environment in Owl 2.0.
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# 🦉 Error Handling 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Example](#example)
|
||||||
|
- [Reference](#reference)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
By default, whenever an error occurs in the rendering of an Owl application, we
|
||||||
|
destroy the whole application. Otherwise, we cannot offer any guarantee on the
|
||||||
|
state of the resulting component tree. It might be hopelessly corrupted, but
|
||||||
|
without any user-visible state.
|
||||||
|
|
||||||
|
Clearly, it sometimes is a little bit extreme to destroy the application. This
|
||||||
|
is why we have a builtin mechanism to handle rendering errors (and errors coming
|
||||||
|
from lifecycle hooks): the `catchError` hook.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
For example, here is how we could implement an `ErrorBoundary` component:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="ErrorBoundary">
|
||||||
|
<t t-if="state.error">
|
||||||
|
Error handled
|
||||||
|
</t>
|
||||||
|
<t t-else="">
|
||||||
|
<t t-slot="default" />
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ErrorBoundary extends Component {
|
||||||
|
state = useState({ error: false });
|
||||||
|
|
||||||
|
catchError() {
|
||||||
|
this.state.error = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Using the `ErrorBoundary` is then extremely simple:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<ErrorBoundary><SomeOtherComponent/></ErrorBoundary>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that we need to be careful here: the fallback UI should not throw any
|
||||||
|
error, otherwise we risk going into an infinite loop (also, see the page on
|
||||||
|
[slots](slots.md) for more information on the `t-slot` directive).
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
Whenever the `catchError` lifecycle hook is implemented, all errors coming from
|
||||||
|
sub components rendering and/or lifecycle method calls will be caught and given
|
||||||
|
to the `catchError` method. This allows us to properly handle the error, and to
|
||||||
|
not break the application.
|
||||||
|
|
||||||
|
There are important things to know:
|
||||||
|
|
||||||
|
- If an error that occured in the internal rendering cycle is not caught, then
|
||||||
|
Owl will destroy the full application. This is done on purpose, because Owl
|
||||||
|
cannot guarantee that the state is not corrupted from this point on.
|
||||||
|
|
||||||
|
- errors coming from event handlers are NOT managed by `catchError` or any other
|
||||||
|
owl mechanism. This is up to the application developer to properly recover
|
||||||
|
from an error
|
||||||
|
|
||||||
|
Also, it may be useful to know that whenever an error is caught, it is then
|
||||||
|
broadcasted to the application by an event on the `qweb` instance. It may be
|
||||||
|
useful, for example, to log the error somewhere.
|
||||||
|
|
||||||
|
```js
|
||||||
|
env.qweb.on("error", null, function (error) {
|
||||||
|
// do something
|
||||||
|
// react to the error
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -7,7 +7,7 @@ triggering events, and callbacks.
|
|||||||
```js
|
```js
|
||||||
const bus = new owl.core.EventBus();
|
const bus = new owl.core.EventBus();
|
||||||
|
|
||||||
bus.on("some-event", null, function(...args) {
|
bus.on("some-event", null, function (...args) {
|
||||||
console.log(...args);
|
console.log(...args);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# 🦉 Event Handling 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Event Handling](#event-handling)
|
||||||
|
- [Business DOM Events](#business-dom-events)
|
||||||
|
- [Inline Event Handlers](#inline-event-handlers)
|
||||||
|
- [Modifiers](#modifiers)
|
||||||
|
|
||||||
|
## Event Handling
|
||||||
|
|
||||||
|
In a component's template, it is useful to be able to register handlers on DOM
|
||||||
|
elements to some specific events. This is what makes a template _alive_. There
|
||||||
|
are four different use cases.
|
||||||
|
|
||||||
|
1. Register an event handler on a DOM node (_pure_ DOM event)
|
||||||
|
2. Register an event handler on a component (_pure_ DOM event)
|
||||||
|
3. Register an event handler on a DOM node (_business_ DOM event)
|
||||||
|
4. Register an event handler on a component (_business_ DOM event)
|
||||||
|
|
||||||
|
A _pure_ DOM event is directly triggered by a user interaction (e.g. a `click`).
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="someMethod">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
This will be roughly translated in javascript like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.addEventListener("click", component.someMethod.bind(component));
|
||||||
|
```
|
||||||
|
|
||||||
|
The suffix (`click` in this example) is simply the name of the actual DOM
|
||||||
|
event.
|
||||||
|
|
||||||
|
## Business DOM Events
|
||||||
|
|
||||||
|
A _business_ DOM event is triggered by a call to `trigger` on a component.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<MyComponent t-on-menu-loaded="someMethod" />
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
class MyComponent {
|
||||||
|
someWhere() {
|
||||||
|
const payload = ...;
|
||||||
|
this.trigger('menu-loaded', payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The call to `trigger` generates an `OwlEvent`, a subclass of [_CustomEvent_](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
|
||||||
|
with an additional attribute `originalComponent` (the component that triggered
|
||||||
|
the event). The generated event is of type `menu-loaded` and dispatches it on
|
||||||
|
the component's DOM element (`this.el`). The event bubbles and is cancelable.
|
||||||
|
The parent component listening to event `menu-loaded` will receive the payload
|
||||||
|
in its `someMethod` handler (in the `detail` property of the event), whenever
|
||||||
|
the event is triggered.
|
||||||
|
|
||||||
|
```js
|
||||||
|
class ParentComponent {
|
||||||
|
someMethod(ev) {
|
||||||
|
const payload = ev.detail;
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
By convention, we use KebabCase for the name of _business_ events.
|
||||||
|
|
||||||
|
The `t-on` directive allows to prebind its arguments. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="someMethod(expr)">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, `expr` is a valid Owl expression, so it could be `true` or some variable
|
||||||
|
from the rendering context.
|
||||||
|
|
||||||
|
### Type Hinting
|
||||||
|
|
||||||
|
Note that if you work with Typescript, the `trigger` method is generic on the type of the payload.
|
||||||
|
|
||||||
|
You can then describe the type of the event, so you will see typing errors...
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
this.trigger<MyCustomPayload>("my-custom-event", payload);
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
myCustomEventHandler(ev: OwlEvent<MyCustomPayload>) { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Inline Event Handlers
|
||||||
|
|
||||||
|
One can also directly specify inline statements. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="state.counter++">Increment counter</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, `state` must be defined in the rendering context (typically the component)
|
||||||
|
as it will be translated to:
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
context.state.counter++;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Warning: inline expressions are evaluated in the context of the template. This
|
||||||
|
means that they can access the component methods and properties. But if they set
|
||||||
|
a key, the inline statement will actually not modify the component, but a key in
|
||||||
|
a sub scope.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click="value = 1">Set value to 1 (does not work!!!)</button>
|
||||||
|
<button t-on-click="state.value = 1">Set state.value to 1 (work as expected)</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Modifiers
|
||||||
|
|
||||||
|
In order to remove the DOM event details from the event handlers (like calls to
|
||||||
|
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
||||||
|
specified as additional suffixes of the `t-on` directive.
|
||||||
|
|
||||||
|
| Modifier | Description |
|
||||||
|
| ---------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `.stop` | calls `event.stopPropagation()` before calling the method |
|
||||||
|
| `.prevent` | calls `event.preventDefault()` before calling the method |
|
||||||
|
| `.self` | calls the method only if the `event.target` is the element itself |
|
||||||
|
| `.capture` | bind the event handler in [capture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) mode. |
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click.stop="someMethod">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
|
||||||
|
the order may matter. For instance `t-on-click.prevent.self` will prevent all
|
||||||
|
clicks while `t-on-click.self.prevent` will only prevent clicks on the element
|
||||||
|
itself.
|
||||||
|
|
||||||
|
Finally, empty handlers are tolerated as they could be defined only to apply
|
||||||
|
modifiers. For example,
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<button t-on-click.stop="">Do something</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
This will simply stop the propagation of the event.
|
||||||
+23
-6
@@ -21,6 +21,8 @@
|
|||||||
- [`useStore`](#usestore)
|
- [`useStore`](#usestore)
|
||||||
- [`useDispatch`](#usedispatch)
|
- [`useDispatch`](#usedispatch)
|
||||||
- [`useGetters`](#usegetters)
|
- [`useGetters`](#usegetters)
|
||||||
|
- [`useComponent`](#usecomponent)
|
||||||
|
- [`useEnv`](#useenv)
|
||||||
- [Making customized hooks](#making-customized-hooks)
|
- [Making customized hooks](#making-customized-hooks)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
@@ -129,7 +131,7 @@ class SomeComponent extends Component {
|
|||||||
### One rule
|
### One rule
|
||||||
|
|
||||||
There is only one rule: every hook for a component has to be called in the
|
There is only one rule: every hook for a component has to be called in the
|
||||||
constructor (or in class fields):
|
constructor, in the _setup_ method, or in class fields:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// ok
|
// ok
|
||||||
@@ -145,6 +147,13 @@ class SomeComponent extends Component {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// also ok
|
||||||
|
class SomeComponent extends Component {
|
||||||
|
setup() {
|
||||||
|
this.state = useState({ value: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// not ok: this is executed after the constructor is called
|
// not ok: this is executed after the constructor is called
|
||||||
class SomeComponent extends Component {
|
class SomeComponent extends Component {
|
||||||
async willStart() {
|
async willStart() {
|
||||||
@@ -259,7 +268,7 @@ function useLoader() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onWillStart(() => updateRecord(component.props.id));
|
onWillStart(() => updateRecord(component.props.id));
|
||||||
onWillUpdateProps(nextProps => updateRecord(nextProps.id));
|
onWillUpdateProps((nextProps) => updateRecord(nextProps.id));
|
||||||
|
|
||||||
return record;
|
return record;
|
||||||
}
|
}
|
||||||
@@ -381,6 +390,16 @@ The `useDispatch` hook is the way for components to get a reference to the store
|
|||||||
The `useGetters` hook is the way for components to get a reference to the store
|
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.
|
getters. See the [store documentation](store.md) for more information.
|
||||||
|
|
||||||
|
### `useComponent`
|
||||||
|
|
||||||
|
The `useComponent` hook is useful as a building block for some customized hooks,
|
||||||
|
that may need a reference to the component calling them.
|
||||||
|
|
||||||
|
### `useEnv`
|
||||||
|
|
||||||
|
The `useEnv` hook is useful as a building block for some customized hooks,
|
||||||
|
that may need a reference to the env of the component calling them.
|
||||||
|
|
||||||
### Making customized hooks
|
### Making customized hooks
|
||||||
|
|
||||||
Hooks are a wonderful way to organize the code of a complex component by feature
|
Hooks are a wonderful way to organize the code of a complex component by feature
|
||||||
@@ -435,13 +454,11 @@ not the solution to every problem.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
function useRouter() {
|
function useRouter() {
|
||||||
return Component.current.env.router;
|
const env = useEnv();
|
||||||
|
return env.router;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This means that we give control to the application developer to create the
|
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
|
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.
|
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.
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ for modals (as in `bootstrap-modal`).
|
|||||||
### Usage
|
### Usage
|
||||||
|
|
||||||
The content it will teleport is defined within the `<Portal>` node and
|
The content it will teleport is defined within the `<Portal>` node and
|
||||||
internally uses the `default` [Slot](component.md#slots).
|
internally uses the `default` [Slot](slots.md).
|
||||||
|
|
||||||
This slot must contain only **one** node, which in turn can have as many children as necessary.
|
This slot must contain only **one** node, which in turn can have as many children as necessary.
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ workflow to help the user put in some data, which it could use later on.
|
|||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Component } = owl;
|
const { Component, mount } = owl;
|
||||||
const { Portal } = owl.misc;
|
const { Portal } = owl.misc;
|
||||||
|
|
||||||
class TeleportedComponent extends Component {}
|
class TeleportedComponent extends Component {}
|
||||||
@@ -51,8 +51,7 @@ class App extends Component {
|
|||||||
static components = { Portal, TeleportedComponent };
|
static components = { Portal, TeleportedComponent };
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App();
|
mount(App, { target: document.body });
|
||||||
app.mount(document.body);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
XML:
|
XML:
|
||||||
@@ -95,7 +94,7 @@ The teleported piece is updated as any other `Component`'s DOM and in the same s
|
|||||||
Namely the teleported piece will be updated in function of its parents components, and patched as
|
Namely the teleported piece will be updated in function of its parents components, and patched as
|
||||||
a normal child.
|
a normal child.
|
||||||
|
|
||||||
The [_business_ events](component.md#event-handling) triggered by a child component will be stopped
|
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
|
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.
|
`Portal`'s root node and bubble up the DOM as if it were triggered by a regular child component.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 🦉 Mounting an application 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [API](#api)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Mounting an Owl application is done by using the `mount` method (available in
|
||||||
|
`owl.mount` if you are using the iife build, or it can be directly imported
|
||||||
|
from `owl` if you are using a module system):
|
||||||
|
|
||||||
|
```js
|
||||||
|
const mount = { owl }; // if owl is available as an object
|
||||||
|
|
||||||
|
const env = { ... };
|
||||||
|
const app = await mount(MyComponent, { target: document.body, env });
|
||||||
|
```
|
||||||
|
|
||||||
|
Another example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const config = {
|
||||||
|
env: ...,
|
||||||
|
props: ...,
|
||||||
|
target: document.body,
|
||||||
|
position: "self",
|
||||||
|
};
|
||||||
|
const app = await mount(App, config);
|
||||||
|
```
|
||||||
|
|
||||||
|
A common way to initialize an application is to first setup an environment,
|
||||||
|
then to call the `mount` method.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
Mount takes two parameters:
|
||||||
|
|
||||||
|
- `C`, which should be a component class (NOT instance),
|
||||||
|
- `params`, which is an object with the following keys:
|
||||||
|
- `target (HTMLElement | DocumentFragment)`: the target of the mount operation
|
||||||
|
- `env (optional, Env)` an environment
|
||||||
|
- `position (optional, "first-child" | "last-child" | "self")` the position
|
||||||
|
where it should be mounted (see below for more informations)
|
||||||
|
- `props (optional, any)`: some initial values that are given as props. Useful
|
||||||
|
when the root component is configurable, or when testing sub components
|
||||||
|
|
||||||
|
Here are the various positions supported by Owl:
|
||||||
|
|
||||||
|
- `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`.
|
||||||
|
|
||||||
|
The `mount` method returns a promise that resolves to the instance of the created
|
||||||
|
component.
|
||||||
@@ -15,7 +15,7 @@ use cases, there is no need to directly instantiate an observer.
|
|||||||
For example, this code will display `update` in the console:
|
For example, this code will display `update` in the console:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const observer = new owl.Observer();
|
const observer = new owl.core.Observer();
|
||||||
observer.notifyCB = () => console.log("update");
|
observer.notifyCB = () => console.log("update");
|
||||||
const obj = observer.observe({ a: { b: 1 } });
|
const obj = observer.observe({ a: { b: 1 } });
|
||||||
|
|
||||||
@@ -39,14 +39,14 @@ is incremented every time the value is observed. Sometimes, it can be useful
|
|||||||
to obtain that number:
|
to obtain that number:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const observer = new owl.Observer();
|
const observer = new owl.core.Observer();
|
||||||
const obj = observer.observe({ a: { b: 1 } });
|
const obj = observer.observe({ a: { b: 1 } });
|
||||||
|
|
||||||
observer.deepRevNumber(obj.a); // 1
|
observer.revNumber(obj.a); // 1
|
||||||
obj.a.b = 2;
|
obj.a.b = 2;
|
||||||
|
|
||||||
observer.deepRevNumber(obj.a); // 2
|
observer.revNumber(obj.a); // 2
|
||||||
```
|
```
|
||||||
|
|
||||||
The `deepRevNumber` can also return 0, which indicates that the value is not
|
The `revNumber` can also return 0, which indicates that the value is not
|
||||||
observed.
|
observed.
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class Child extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component {
|
class Parent extends Component {
|
||||||
static template = xml`<div><ComponentA a="state.a" b="'string'"/></div>`;
|
static template = xml`<div><Child a="state.a" b="'string'"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ a: "fromparent" });
|
state = useState({ a: "fromparent" });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class ComponentB extends owl.Component {
|
|||||||
count: {type: Number},
|
count: {type: Number},
|
||||||
messages: {
|
messages: {
|
||||||
type: Array,
|
type: Array,
|
||||||
element: {type: Object, shape: {id: Boolean, text: 'string' }
|
element: {type: Object, shape: {id: Boolean, text: String }
|
||||||
},
|
},
|
||||||
date: Date,
|
date: Date,
|
||||||
combinedVal: [Number, Boolean]
|
combinedVal: [Number, Boolean]
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ Its API is quite simple:
|
|||||||
```
|
```
|
||||||
|
|
||||||
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
||||||
which is a virtual representation of the DOM (see [vdom doc](../architecture/vdom.md)).
|
which is a virtual representation of the DOM (see [vdom doc](../miscellaneous/vdom.md)).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const vnode = qweb.render("App", component);
|
const vnode = qweb.render("App", component);
|
||||||
@@ -114,9 +114,9 @@ For example:
|
|||||||
const translations = {
|
const translations = {
|
||||||
hello: "bonjour",
|
hello: "bonjour",
|
||||||
yes: "oui",
|
yes: "oui",
|
||||||
no: "non"
|
no: "non",
|
||||||
};
|
};
|
||||||
const translateFn = str => translations[str] || str;
|
const translateFn = (str) => translations[str] || str;
|
||||||
|
|
||||||
const qweb = new QWeb({ translateFn });
|
const qweb = new QWeb({ translateFn });
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -13,8 +13,11 @@
|
|||||||
- [Setting Variables](#setting-variables)
|
- [Setting Variables](#setting-variables)
|
||||||
- [Conditionals](#conditionals)
|
- [Conditionals](#conditionals)
|
||||||
- [Dynamic Attributes](#dynamic-attributes)
|
- [Dynamic Attributes](#dynamic-attributes)
|
||||||
|
- [Dynamic Class Attribute](#dynamic-class-attribute)
|
||||||
|
- [Dynamic Tag Names](#dynamic-tag-names)
|
||||||
- [Loops](#loops)
|
- [Loops](#loops)
|
||||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||||
|
- [Dynamic Sub Templates](#dynamic-sub-templates)
|
||||||
- [Translations](#translations)
|
- [Translations](#translations)
|
||||||
- [Debugging](#debugging)
|
- [Debugging](#debugging)
|
||||||
|
|
||||||
@@ -71,10 +74,11 @@ needs. Here is a list of all Owl specific directives:
|
|||||||
| `t-component`, `t-props` | [Defining a sub component](component.md#composition) |
|
| `t-component`, `t-props` | [Defining a sub component](component.md#composition) |
|
||||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](#loops) |
|
| `t-key` | [Defining a key (to help virtual dom reconciliation)](#loops) |
|
||||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
| `t-on-*` | [Event handling](event_handling.md) |
|
||||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
| `t-slot` | [Rendering a slot](slots.md) |
|
||||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||||
|
| `t-tag` | [Rendering nodes with dynamic tag name](#dynamic-tag-names) |
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
@@ -323,6 +327,40 @@ values) or a pair `[key, value]`. For example:
|
|||||||
<div t-att="['a', 'b']"/> <!-- <div a="b"></div> -->
|
<div t-att="['a', 'b']"/> <!-- <div a="b"></div> -->
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Dynamic class attribute
|
||||||
|
|
||||||
|
For convenience, Owl supports a special case for the `t-att-class` case: one can
|
||||||
|
use an object with keys describing the classes, and values boolean value denoting
|
||||||
|
if the class is or is not present:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-att-class="{'a': true, 'b': true}"/> <!-- result: <div class="a b"></div> -->
|
||||||
|
|
||||||
|
<div t-att-class="{'a b': true, 'c': true}"/> <!-- result: <div class="a b c"></div> -->
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that it can be combined with normal class attribute:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div class="a" t-att-class="{'b': true}"/> <!-- result: <div class="a b"></div> -->
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dynamic tag names
|
||||||
|
|
||||||
|
When writing generic components or templates, the specific concrete tag for an
|
||||||
|
HTML element is not known yet. In those situations, the `t-tag` directive is
|
||||||
|
useful. It simply evaluates dynamically an expression to use as a tag name. The
|
||||||
|
template:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<t t-tag="tag">
|
||||||
|
<span>content</span>
|
||||||
|
</t>
|
||||||
|
```
|
||||||
|
|
||||||
|
will be rendered as `<div><span>content</span></div>` if the `tag` context key
|
||||||
|
is set to `div`.
|
||||||
|
|
||||||
### Loops
|
### Loops
|
||||||
|
|
||||||
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
||||||
@@ -452,6 +490,17 @@ are all equivalent:
|
|||||||
|
|
||||||
If there is no `t-key` directive, Owl will use the index as a default key.
|
If there is no `t-key` directive, Owl will use the index as a default key.
|
||||||
|
|
||||||
|
Note: the `t-foreach` directive only accepts arrays (lists) or objects. It does
|
||||||
|
not work with other iterables, such as `Set`. However, it is only a matter of
|
||||||
|
using the `...` javascript operator. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<t t-foreach="...items" t-as="item">...</t>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `...` operator will convert the `Set` (or any other iterables) into a list,
|
||||||
|
which will work with Owl QWeb.
|
||||||
|
|
||||||
### Rendering Sub Templates
|
### Rendering Sub Templates
|
||||||
|
|
||||||
QWeb templates can be used for top level rendering, but they can also be used
|
QWeb templates can be used for top level rendering, but they can also be used
|
||||||
@@ -509,6 +558,22 @@ This can be used to define variables scoped to a sub template:
|
|||||||
<!-- "var" does not exist here -->
|
<!-- "var" does not exist here -->
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Dynamic sub templates
|
||||||
|
|
||||||
|
The `t-call` directive can also be used to dynamically call a sub template,
|
||||||
|
using string interpolation. For example:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div t-name="main-template">
|
||||||
|
<t t-call="{{template}}">
|
||||||
|
<em>content</em>
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, the name of the template is obtained from the `template` value in the
|
||||||
|
template rendering context.
|
||||||
|
|
||||||
### Translations
|
### Translations
|
||||||
|
|
||||||
By default, QWeb specify that templates should be translated. If this behaviour
|
By default, QWeb specify that templates should be translated. If this behaviour
|
||||||
@@ -532,7 +597,7 @@ The javascript QWeb implementation provides two useful debugging directives:
|
|||||||
|
|
||||||
```xml
|
```xml
|
||||||
<t t-if="a_test">
|
<t t-if="a_test">
|
||||||
<t t-debug="">
|
<t t-debug=""/>
|
||||||
</t>
|
</t>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# 🦉 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.
|
||||||
|
|
||||||
|
Slots are inserted with the `t-slot` directive:
|
||||||
|
|
||||||
|
```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).
|
||||||
|
|
||||||
|
### Dynamic Slots
|
||||||
|
|
||||||
|
The `t-slot` directive is actually able to use any expressions, using string
|
||||||
|
interplolation:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<t t-slot="{{current}}" />
|
||||||
|
```
|
||||||
+14
-14
@@ -40,14 +40,14 @@ const actions = {
|
|||||||
state.todos.push({
|
state.todos.push({
|
||||||
id: state.nextId++,
|
id: state.nextId++,
|
||||||
message,
|
message,
|
||||||
isCompleted: false
|
isCompleted: false,
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
todos: [],
|
todos: [],
|
||||||
nextId: 1
|
nextId: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
@@ -90,7 +90,7 @@ const config = {
|
|||||||
state,
|
state,
|
||||||
actions,
|
actions,
|
||||||
getters,
|
getters,
|
||||||
env
|
env,
|
||||||
};
|
};
|
||||||
const store = new Store(config);
|
const store = new Store(config);
|
||||||
```
|
```
|
||||||
@@ -110,7 +110,7 @@ const actions = {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
state.loginState = "error";
|
state.loginState = "error";
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ const actions = {
|
|||||||
state.recordId = recordId;
|
state.recordId = recordId;
|
||||||
const data = await doSomeRPC("/read/", recordId);
|
const data = await doSomeRPC("/read/", recordId);
|
||||||
state.recordData = data;
|
state.recordData = data;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -159,7 +159,7 @@ const actions = {
|
|||||||
const data = await doSomeRPC("/read/", recordId);
|
const data = await doSomeRPC("/read/", recordId);
|
||||||
state.recordId = recordId;
|
state.recordId = recordId;
|
||||||
state.recordData = data;
|
state.recordData = data;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -187,14 +187,14 @@ transform the data contained in the store.
|
|||||||
```js
|
```js
|
||||||
const getters = {
|
const getters = {
|
||||||
getPost({ state }, id) {
|
getPost({ state }, id) {
|
||||||
const post = state.posts.find(p => p.id === id);
|
const post = state.posts.find((p) => p.id === id);
|
||||||
const author = state.authors.find(a => a.id === post.id);
|
const author = state.authors.find((a) => a.id === post.id);
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
author,
|
author,
|
||||||
content: post.content
|
content: post.content,
|
||||||
};
|
};
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// somewhere else
|
// somewhere else
|
||||||
@@ -224,11 +224,11 @@ Assume we have this store:
|
|||||||
const actions = {
|
const actions = {
|
||||||
increment({ state }, val) {
|
increment({ state }, val) {
|
||||||
state.counter.value += val;
|
state.counter.value += val;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
counter: { value: 0 }
|
counter: { value: 0 },
|
||||||
};
|
};
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
```
|
```
|
||||||
@@ -245,7 +245,7 @@ A counter component can then select this value and dispatch an action like this:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
counter = useStore(state => state.counter);
|
counter = useStore((state) => state.counter);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
Tags are very small helpers intended to make it easy to write inline templates
|
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,
|
or styles. There are currently two tags: `css` and `xml`. With these functions,
|
||||||
it is possible to write [single file components](../tooling.md#single-file-component).
|
it is possible to write [single file components](../learning/how_to_write_sfc.md).
|
||||||
|
|
||||||
## XML tag
|
## XML tag
|
||||||
|
|
||||||
@@ -62,14 +62,14 @@ The CSS tag is useful to define a css stylesheet in the javascript file:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
class MyComponent extends Component {
|
class MyComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div class="my-component">some template</div>
|
<div class="my-component">some template</div>
|
||||||
`;
|
`;
|
||||||
static css`
|
static style = css`
|
||||||
.my-component {
|
.my-component {
|
||||||
color: red;
|
color: red;
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -19,20 +19,20 @@ not ready yet, resolved directly otherwise). If called with a callback as
|
|||||||
argument, it executes it as soon as the DOM ready (or directly).
|
argument, it executes it as soon as the DOM ready (or directly).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
|
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function ([templates]) {
|
||||||
const qweb = new owl.QWeb({ templates });
|
const qweb = new owl.QWeb({ templates });
|
||||||
const app = new App({ qweb });
|
const env = { qweb };
|
||||||
app.mount(document.body);
|
await mount(App, { env, target: document.body });
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
or alternatively:
|
or alternatively:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
owl.utils.whenReady(function() {
|
owl.utils.whenReady(function () {
|
||||||
const qweb = new owl.QWeb();
|
const qweb = new owl.QWeb();
|
||||||
const app = new App({ qweb });
|
const env = { qweb };
|
||||||
app.mount(document.body);
|
await mount(App, { env, target: document.body });
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
-117
@@ -1,117 +0,0 @@
|
|||||||
# 🦉 Tooling 🦉
|
|
||||||
|
|
||||||
## Content
|
|
||||||
|
|
||||||
- [Overview](#overview)
|
|
||||||
- [Playground](#playground)
|
|
||||||
- [Benchmarks](#benchmarks)
|
|
||||||
- [Single File Component](#single-file-component)
|
|
||||||
- [Debugging Script](#debugging-script)
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
To help work with/improve/learn OWL, there are a few extras tools/settings.
|
|
||||||
|
|
||||||
- development mode: enable better error reporting for the developer
|
|
||||||
- a playground application: a space to experiment and learn Owl.
|
|
||||||
- a benchmarks application: allow comparison with a few common frameworks
|
|
||||||
|
|
||||||
The two applications are available in the `tools/` folder, and can be accessed
|
|
||||||
by using a static http server. A simple python
|
|
||||||
server is available in `server.py`. There is also a npm script to start it:
|
|
||||||
`npm run tools` (and its version with a watcher: `npm run tools:watch`).
|
|
||||||
|
|
||||||
## Playground
|
|
||||||
|
|
||||||
The playground is an important application designed to help learning and
|
|
||||||
experimenting with Owl. The last published version of Owl can be tested [online](https://odoo.github.io/owl/playground/).
|
|
||||||
|
|
||||||
It is an application similar to `jsFiddle`, but specialized for Owl: there are
|
|
||||||
three tabs (`js`, `css` and `xml`), and a simple button `Run` to execute that
|
|
||||||
code in an iframe.
|
|
||||||
|
|
||||||
## Benchmarks
|
|
||||||
|
|
||||||
Note: This is more an internal tool, useful for people working on Owl.
|
|
||||||
|
|
||||||
The benchmarks application is a very small application, implemented in different
|
|
||||||
frameworks, and in different versions of Owl. This is a simple internal tool,
|
|
||||||
useful to compare various performance metrics on some tasks.
|
|
||||||
|
|
||||||
## Single File Component
|
|
||||||
|
|
||||||
It is very useful to group code by feature instead of by type of file. It makes
|
|
||||||
it easier to scale application to larger size.
|
|
||||||
|
|
||||||
To do so, Owl 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.
|
|
||||||
|
|
||||||
## Debugging Script
|
|
||||||
|
|
||||||
## Debugging
|
|
||||||
|
|
||||||
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
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
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.
|
|
||||||
+26
-21
@@ -1,22 +1,20 @@
|
|||||||
{
|
{
|
||||||
"name": "@odoo/owl",
|
"name": "@odoo/owl",
|
||||||
"version": "1.0.4",
|
"version": "1.4.5",
|
||||||
"description": "Odoo Web Library (OWL)",
|
"description": "Odoo Web Library (OWL)",
|
||||||
"main": "dist/owl.js",
|
"main": "dist/owl.cjs.js",
|
||||||
|
"browser": "dist/owl.iife.js",
|
||||||
|
"module": "dist/owl.es.js",
|
||||||
"types": "dist/types/index.d.ts",
|
"types": "dist/types/index.d.ts",
|
||||||
"files": [
|
"files": [
|
||||||
"dist/types/",
|
"dist"
|
||||||
"dist/owl.js"
|
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.15.3"
|
"node": ">=12.18.3"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
|
||||||
"build:bundle": "rollup -c",
|
"build:bundle": "rollup -c",
|
||||||
"build": "npm run build:js && npm run build:bundle",
|
"build": "npm run build:bundle",
|
||||||
"buildcommonjs": "npm run build:js && npm run build:bundle -- -f cjs",
|
|
||||||
"minify": "uglifyjs dist/owl.js -o dist/owl.min.js --compress --mangle",
|
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
||||||
@@ -24,7 +22,8 @@
|
|||||||
"pretools:watch": "npm run build",
|
"pretools:watch": "npm run build",
|
||||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
||||||
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write",
|
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write",
|
||||||
"publish": "npm run buildcommonjs && npm publish",
|
"check-formatting": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --check",
|
||||||
|
"publish": "npm run build && npm publish",
|
||||||
"release": "node tools/release.js"
|
"release": "node tools/release.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -32,32 +31,35 @@
|
|||||||
"url": "git+https://github.com/odoo/owl.git"
|
"url": "git+https://github.com/odoo/owl.git"
|
||||||
},
|
},
|
||||||
"author": "Odoo",
|
"author": "Odoo",
|
||||||
"license": "LGPL",
|
"license": "LGPL-3.0-only",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/odoo/owl/issues"
|
"url": "https://github.com/odoo/owl/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/odoo/owl#readme",
|
"homepage": "https://github.com/odoo/owl#readme",
|
||||||
"dependencies": {},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^23.3.12",
|
"@types/jest": "^27.0.1",
|
||||||
|
"@types/node": "^14.11.8",
|
||||||
"chalk": "^3.0.0",
|
"chalk": "^3.0.0",
|
||||||
"cpx": "^1.5.0",
|
"cpx": "^1.5.0",
|
||||||
|
"current-git-branch": "^1.1.0",
|
||||||
"git-rev-sync": "^1.12.0",
|
"git-rev-sync": "^1.12.0",
|
||||||
"github-api": "^3.3.0",
|
"github-api": "^3.3.0",
|
||||||
"jest": "^23.6.0",
|
"jest": "^27.1.0",
|
||||||
"jest-environment-jsdom": "^24.7.1",
|
"jest-environment-jsdom": "^27.1.0",
|
||||||
"live-server": "^1.2.1",
|
"live-server": "^1.2.1",
|
||||||
"npm-run-all": "^4.1.5",
|
"npm-run-all": "^4.1.5",
|
||||||
"prettier": "^1.19.1",
|
"prettier": "^2.0.4",
|
||||||
"rollup": "^1.6.0",
|
"rollup": "^2.56.3",
|
||||||
"rollup-plugin-typescript2": "^0.20.1",
|
"rollup-plugin-terser": "^7.0.2",
|
||||||
|
"rollup-plugin-typescript2": "^0.30.0",
|
||||||
"sass": "^1.16.1",
|
"sass": "^1.16.1",
|
||||||
"source-map-support": "^0.5.10",
|
"source-map-support": "^0.5.10",
|
||||||
"ts-jest": "^23.10.5",
|
"ts-jest": "^27.0.5",
|
||||||
"typescript": "^3.7.2",
|
"typescript": "^3.7.2",
|
||||||
"uglify-es": "^3.3.9"
|
"uglify-es": "^3.3.9"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
|
"testEnvironment": "jsdom",
|
||||||
"roots": [
|
"roots": [
|
||||||
"<rootDir>/src",
|
"<rootDir>/src",
|
||||||
"<rootDir>/tests"
|
"<rootDir>/tests"
|
||||||
@@ -74,9 +76,12 @@
|
|||||||
"jsx",
|
"jsx",
|
||||||
"json",
|
"json",
|
||||||
"node"
|
"node"
|
||||||
]
|
],
|
||||||
|
"collectCoverage": true,
|
||||||
|
"coverageReporters": ["html"]
|
||||||
},
|
},
|
||||||
"prettier": {
|
"prettier": {
|
||||||
"printWidth": 100
|
"printWidth": 100,
|
||||||
|
"endOfLine": "auto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-17
@@ -1,35 +1,22 @@
|
|||||||
# 🦉 OWL Roadmap 🦉
|
# 🦉 OWL Roadmap 🦉
|
||||||
|
|
||||||
- Current version: 1.0.4
|
- Current version: 1.4.5
|
||||||
- Status: stable
|
- Status: stable
|
||||||
|
|
||||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||||
change!
|
change!
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### December 2019
|
|
||||||
|
|
||||||
If all goes well, Owl is upgraded to beta status. From now on, no API change,
|
|
||||||
even small, is expected (but it still could happen).
|
|
||||||
|
|
||||||
### End of 2019
|
|
||||||
|
|
||||||
Release v1.0
|
|
||||||
|
|
||||||
- API should be stable,
|
|
||||||
- we will use semantic versioning,
|
|
||||||
- we will maintain a changelog and an upgrade guide.
|
|
||||||
|
|
||||||
### 1.x
|
### 1.x
|
||||||
|
|
||||||
- add chrome and firefox devtools,
|
- add chrome and firefox devtools,
|
||||||
- add support for single file components,
|
|
||||||
- fix every bugs,
|
- fix every bugs,
|
||||||
- improve documentation,
|
- improve documentation,
|
||||||
- small backward compatible improvements.
|
- small backward compatible improvements.
|
||||||
|
|
||||||
### 2.x (2021? 2022?)
|
### 2.x (2020? 2021? 2022?)
|
||||||
|
|
||||||
|
- stop support for `t-set` directive to define the content of a slot
|
||||||
|
|
||||||
Maybe:
|
Maybe:
|
||||||
|
|
||||||
|
|||||||
+66
-10
@@ -1,14 +1,70 @@
|
|||||||
import { version } from "./package.json";
|
import pkg from "./package.json";
|
||||||
import git from "git-rev-sync";
|
import git from "git-rev-sync";
|
||||||
|
import typescript from 'rollup-plugin-typescript2';
|
||||||
|
import { terser } from "rollup-plugin-terser";
|
||||||
|
|
||||||
|
const name = "owl";
|
||||||
|
const extend = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Meta data to be added on the __info__ object.
|
||||||
|
* Used to let external tools know the current owl version.
|
||||||
|
*/
|
||||||
|
const outro = `
|
||||||
|
__info__.version = '${pkg.version}';
|
||||||
|
__info__.date = '${new Date().toISOString()}';
|
||||||
|
__info__.hash = '${git.short()}';
|
||||||
|
__info__.url = 'https://github.com/odoo/owl';
|
||||||
|
`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate from a string depicting a path a new path for the minified version.
|
||||||
|
* @param {string} pkgFileName file name
|
||||||
|
*/
|
||||||
|
function generateMinifiedNameFromPkgName(pkgFileName) {
|
||||||
|
const parts = pkgFileName.split('.');
|
||||||
|
parts.splice(parts.length - 1, 0, "min");
|
||||||
|
return parts.join('.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the rollup config based on the arguments
|
||||||
|
* @param {string} format format of the bundle
|
||||||
|
* @param {string} generatedFileName generated file name
|
||||||
|
* @param {boolean} minified should it be minified
|
||||||
|
*/
|
||||||
|
function getConfigForFormat(format, generatedFileName, minified = false) {
|
||||||
|
return {
|
||||||
|
file: minified ? generateMinifiedNameFromPkgName(generatedFileName) : generatedFileName,
|
||||||
|
format: format,
|
||||||
|
name: name,
|
||||||
|
extend: extend,
|
||||||
|
outro: outro,
|
||||||
|
plugins: minified ? [terser()] : [],
|
||||||
|
indent: ' ', // indent with 4 spaces
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// rollup.config.js
|
|
||||||
export default {
|
export default {
|
||||||
input: "dist/owl/index.js",
|
input: "src/index.ts",
|
||||||
output: {
|
output: [
|
||||||
file: "dist/owl.js",
|
|
||||||
format: "iife",
|
/**
|
||||||
name: "owl",
|
* Read about module formats:
|
||||||
extend: true,
|
* https://auth0.com/blog/javascript-module-systems-showdown/
|
||||||
outro: `exports.__info__.version = '${version}';\nexports.__info__.date = '${new Date().toISOString()}';\nexports.__info__.hash = '${git.short()}';\nexports.__info__.url = 'https://github.com/odoo/owl';`
|
* https://medium.com/@kelin2025/so-you-wanna-use-es6-modules-714f48b3a953
|
||||||
}
|
*/
|
||||||
|
|
||||||
|
getConfigForFormat('esm', pkg.module),
|
||||||
|
getConfigForFormat('esm', pkg.module, true),
|
||||||
|
getConfigForFormat('cjs', pkg.main),
|
||||||
|
getConfigForFormat('cjs', pkg.main, true),
|
||||||
|
getConfigForFormat('iife', pkg.browser),
|
||||||
|
getConfigForFormat('iife', pkg.browser, true),
|
||||||
|
],
|
||||||
|
plugins: [
|
||||||
|
typescript({
|
||||||
|
useTsconfigDeclarationDir: true
|
||||||
|
}),
|
||||||
|
]
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
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"];
|
||||||
|
}
|
||||||
|
|
||||||
|
let localStorage: Window["localStorage"] | null = null;
|
||||||
|
|
||||||
|
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),
|
||||||
|
get localStorage() {
|
||||||
|
return localStorage || window.localStorage;
|
||||||
|
},
|
||||||
|
set localStorage(newLocalStorage: Window["localStorage"]) {
|
||||||
|
localStorage = newLocalStorage;
|
||||||
|
},
|
||||||
|
};
|
||||||
+190
-121
@@ -7,6 +7,7 @@ import { Fiber } from "./fiber";
|
|||||||
import "./props_validation";
|
import "./props_validation";
|
||||||
import { Scheduler, scheduler } from "./scheduler";
|
import { Scheduler, scheduler } from "./scheduler";
|
||||||
import { activateSheet } from "./styles";
|
import { activateSheet } from "./styles";
|
||||||
|
import { Browser, browser } from "../browser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Component System
|
* Owl Component System
|
||||||
@@ -34,11 +35,22 @@ import { activateSheet } from "./styles";
|
|||||||
*/
|
*/
|
||||||
export interface Env {
|
export interface Env {
|
||||||
qweb: QWeb;
|
qweb: QWeb;
|
||||||
[key: string]: any;
|
browser: Browser;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type MountPosition = "first-child" | "last-child" | "self";
|
||||||
|
|
||||||
interface MountOptions {
|
interface MountOptions {
|
||||||
position?: "first-child" | "last-child" | "self";
|
position?: MountPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enum STATUS {
|
||||||
|
CREATED,
|
||||||
|
WILLSTARTED, // willstart has been called
|
||||||
|
RENDERED, // first render is completed (so, vnode is now defined)
|
||||||
|
MOUNTED, // is ready, and in DOM. It has a valid el
|
||||||
|
UNMOUNTED, // has a valid el, but is not in DOM
|
||||||
|
DESTROYED,
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,20 +58,19 @@ interface MountOptions {
|
|||||||
* useful to typecheck and describe the internal keys used by Owl to manage the
|
* useful to typecheck and describe the internal keys used by Owl to manage the
|
||||||
* component tree.
|
* component tree.
|
||||||
*/
|
*/
|
||||||
interface Internal<T extends Env, Props> {
|
interface Internal<T extends Env> {
|
||||||
// each component has a unique id, useful mostly to handle parent/child
|
// each component has a unique id, useful mostly to handle parent/child
|
||||||
// relationships
|
// relationships
|
||||||
readonly id: number;
|
readonly id: number;
|
||||||
depth: number;
|
depth: number;
|
||||||
vnode: VNode | null;
|
vnode: VNode | null;
|
||||||
pvnode: VNode | null;
|
pvnode: VNode | null;
|
||||||
isMounted: boolean;
|
status: STATUS;
|
||||||
isDestroyed: boolean;
|
|
||||||
|
|
||||||
// parent and children keys are obviously useful to setup the parent-children
|
// parent and children keys are obviously useful to setup the parent-children
|
||||||
// relationship.
|
// relationship.
|
||||||
parent: Component<T, any> | null;
|
parent: Component<any, T> | null;
|
||||||
children: { [key: number]: Component<T, any> };
|
children: { [key: number]: Component<any, T> };
|
||||||
// children mapping: from templateID to componentID. templateID identifies a
|
// children mapping: from templateID to componentID. templateID identifies a
|
||||||
// place in a template. The t-component directive needs it to be able to get
|
// place in a template. The t-component directive needs it to be able to get
|
||||||
// the component instance back whenever the template is rerendered.
|
// the component instance back whenever the template is rerendered.
|
||||||
@@ -85,7 +96,7 @@ interface Internal<T extends Env, Props> {
|
|||||||
willStartCB: Function | null;
|
willStartCB: Function | null;
|
||||||
willUpdatePropsCB: Function | null;
|
willUpdatePropsCB: Function | null;
|
||||||
classObj: { [key: string]: boolean } | null;
|
classObj: { [key: string]: boolean } | null;
|
||||||
refs: { [key: string]: Component<T, any> | HTMLElement | undefined } | null;
|
refs: { [key: string]: Component<any, T> | HTMLElement | undefined } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const portalSymbol = Symbol("portal"); // FIXME
|
export const portalSymbol = Symbol("portal"); // FIXME
|
||||||
@@ -95,18 +106,17 @@ export const portalSymbol = Symbol("portal"); // FIXME
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
let nextId = 1;
|
let nextId = 1;
|
||||||
|
|
||||||
export class Component<T extends Env, Props extends {}> {
|
export class Component<Props extends {} = any, T extends Env = Env> {
|
||||||
readonly __owl__: Internal<Env, Props>;
|
readonly __owl__: Internal<T>;
|
||||||
static template?: string | null = null;
|
static template?: string | null = null;
|
||||||
static _template?: string | null = null;
|
static _template?: string | null = null;
|
||||||
static current: Component<any, any> | null = null;
|
static current: Component | null = null;
|
||||||
static components = {};
|
static components = {};
|
||||||
static props?: any;
|
static props?: any;
|
||||||
static defaultProps?: any;
|
static defaultProps?: any;
|
||||||
static env: any = {};
|
static env: any = {};
|
||||||
// expose scheduler s.t. it can be mocked for testing purposes
|
// expose scheduler s.t. it can be mocked for testing purposes
|
||||||
static scheduler: Scheduler = scheduler;
|
static scheduler: Scheduler = scheduler;
|
||||||
__target: HTMLElement | undefined;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `el` is the root element of the component. Note that it could be null:
|
* The `el` is the root element of the component. Note that it could be null:
|
||||||
@@ -130,7 +140,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* hand. Other components should be created automatically by the framework (with
|
* hand. Other components should be created automatically by the framework (with
|
||||||
* the t-component directive in a template)
|
* the t-component directive in a template)
|
||||||
*/
|
*/
|
||||||
constructor(parent?: Component<T, any> | null, props?: Props) {
|
constructor(parent?: Component<any, T> | null, props?: Props) {
|
||||||
Component.current = this;
|
Component.current = this;
|
||||||
|
|
||||||
let constr = this.constructor as any;
|
let constr = this.constructor as any;
|
||||||
@@ -157,17 +167,23 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
if (!this.env.qweb) {
|
if (!this.env.qweb) {
|
||||||
this.env.qweb = new QWeb();
|
this.env.qweb = new QWeb();
|
||||||
}
|
}
|
||||||
|
// TODO: remove this in owl 2.0
|
||||||
|
if (!this.env.browser) {
|
||||||
|
this.env.browser = browser;
|
||||||
|
}
|
||||||
this.env.qweb.on("update", this, () => {
|
this.env.qweb.on("update", this, () => {
|
||||||
if (this.__owl__.isMounted) {
|
switch (this.__owl__.status) {
|
||||||
this.render(true);
|
case STATUS.MOUNTED:
|
||||||
}
|
this.render(true);
|
||||||
if (this.__owl__.isDestroyed) {
|
break;
|
||||||
// this is unlikely to happen, but if a root widget is destroyed,
|
case STATUS.DESTROYED:
|
||||||
// we want to remove our subscription. The usual way to do that
|
// this is unlikely to happen, but if a root widget is destroyed,
|
||||||
// would be to perform some check in the destroy method, but since
|
// we want to remove our subscription. The usual way to do that
|
||||||
// it is very performance sensitive, and since this is a rare event,
|
// would be to perform some check in the destroy method, but since
|
||||||
// we simply do it lazily
|
// it is very performance sensitive, and since this is a rare event,
|
||||||
this.env.qweb.off("update", this);
|
// we simply do it lazily
|
||||||
|
this.env.qweb.off("update", this);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
depth = 0;
|
depth = 0;
|
||||||
@@ -180,8 +196,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
depth: depth,
|
depth: depth,
|
||||||
vnode: null,
|
vnode: null,
|
||||||
pvnode: null,
|
pvnode: null,
|
||||||
isMounted: false,
|
status: STATUS.CREATED,
|
||||||
isDestroyed: false,
|
|
||||||
parent: parent || null,
|
parent: parent || null,
|
||||||
children: {},
|
children: {},
|
||||||
cmap: {},
|
cmap: {},
|
||||||
@@ -198,13 +213,25 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
renderFn: qweb.render.bind(qweb, template),
|
renderFn: qweb.render.bind(qweb, template),
|
||||||
classObj: null,
|
classObj: null,
|
||||||
refs: null,
|
refs: null,
|
||||||
scope: null
|
scope: null,
|
||||||
};
|
};
|
||||||
if (constr.style) {
|
if (constr.style) {
|
||||||
this.__applyStyles(constr);
|
this.__applyStyles(constr);
|
||||||
}
|
}
|
||||||
|
this.setup();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* setup is run just after the component is constructed. This is the standard
|
||||||
|
* location where the component can setup its hooks. It has some advantages
|
||||||
|
* over the constructor:
|
||||||
|
* - it can be patched (useful in odoo ecosystem)
|
||||||
|
* - it does not need to propagate the arguments to the super call
|
||||||
|
*
|
||||||
|
* Note: this method should not be called manually.
|
||||||
|
*/
|
||||||
|
setup() {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* willStart is an asynchronous hook that can be implemented to perform some
|
* willStart is an asynchronous hook that can be implemented to perform some
|
||||||
* action before the initial rendering of a component.
|
* action before the initial rendering of a component.
|
||||||
@@ -299,40 +326,49 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Note that a component can be mounted an unmounted several times
|
* Note that a component can be mounted an unmounted several times
|
||||||
*/
|
*/
|
||||||
async mount(target: HTMLElement | DocumentFragment, options: MountOptions = {}): Promise<void> {
|
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 (!(target instanceof HTMLElement || target instanceof DocumentFragment)) {
|
if (!(target instanceof HTMLElement || target instanceof DocumentFragment)) {
|
||||||
let message = `Component '${this.constructor.name}' cannot be mounted: the target is not a valid DOM node.`;
|
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)`;
|
message += `\nMaybe the DOM is not ready yet? (in that case, you can use owl.utils.whenReady)`;
|
||||||
throw new Error(message);
|
throw new Error(message);
|
||||||
}
|
}
|
||||||
let inserter =
|
const position = options.position || "last-child";
|
||||||
position === "last-child"
|
const __owl__ = this.__owl__;
|
||||||
? el => target.appendChild(el)
|
const currentFiber = __owl__.currentFiber;
|
||||||
: position === "first-child"
|
|
||||||
? el => target.prepend(el)
|
switch (__owl__.status) {
|
||||||
: el => {};
|
case STATUS.CREATED: {
|
||||||
if (position === "self") {
|
const fiber = new Fiber(null, this, true, target, position);
|
||||||
this.__target = target as HTMLElement;
|
fiber.shouldPatch = false;
|
||||||
|
this.__prepareAndRender(fiber, () => {});
|
||||||
|
return scheduler.addFiber(fiber);
|
||||||
|
}
|
||||||
|
case STATUS.WILLSTARTED:
|
||||||
|
case STATUS.RENDERED:
|
||||||
|
currentFiber.target = target;
|
||||||
|
currentFiber.position = position;
|
||||||
|
return scheduler.addFiber(currentFiber);
|
||||||
|
|
||||||
|
case STATUS.UNMOUNTED: {
|
||||||
|
const fiber = new Fiber(null, this, true, target, position);
|
||||||
|
fiber.shouldPatch = false;
|
||||||
|
this.__render(fiber);
|
||||||
|
return scheduler.addFiber(fiber);
|
||||||
|
}
|
||||||
|
|
||||||
|
case STATUS.MOUNTED: {
|
||||||
|
if (position !== "self" && this.el!.parentNode !== target) {
|
||||||
|
const fiber = new Fiber(null, this, true, target, position);
|
||||||
|
fiber.shouldPatch = false;
|
||||||
|
this.__render(fiber);
|
||||||
|
return scheduler.addFiber(fiber);
|
||||||
|
} else {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case STATUS.DESTROYED:
|
||||||
|
throw new Error("Cannot mount a destroyed component");
|
||||||
}
|
}
|
||||||
const fiber = new Fiber(null, this, false, inserter);
|
|
||||||
fiber.shouldPatch = false;
|
|
||||||
if (!__owl__.vnode) {
|
|
||||||
this.__prepareAndRender(fiber, () => {});
|
|
||||||
} else {
|
|
||||||
this.__render(fiber);
|
|
||||||
}
|
|
||||||
return scheduler.addFiber(fiber);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -340,7 +376,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* to call willUnmount calls and remove the component from the DOM.
|
* to call willUnmount calls and remove the component from the DOM.
|
||||||
*/
|
*/
|
||||||
unmount() {
|
unmount() {
|
||||||
if (this.__owl__.isMounted) {
|
if (this.__owl__.status === STATUS.MOUNTED) {
|
||||||
this.__callWillUnmount();
|
this.__callWillUnmount();
|
||||||
this.el!.remove();
|
this.el!.remove();
|
||||||
}
|
}
|
||||||
@@ -357,24 +393,23 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
*/
|
*/
|
||||||
async render(force: boolean = false): Promise<void> {
|
async render(force: boolean = false): Promise<void> {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
if (!__owl__.isMounted && !__owl__.currentFiber) {
|
const currentFiber = __owl__.currentFiber;
|
||||||
// if we get here, this means that the component was either never mounted,
|
if (!__owl__.vnode && !currentFiber) {
|
||||||
// or was unmounted and some state change triggered a render. Either way,
|
|
||||||
// we do not want to actually render anything in this case.
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (__owl__.currentFiber && !__owl__.currentFiber.isRendered) {
|
if (currentFiber && !currentFiber.isRendered && !currentFiber.isCompleted) {
|
||||||
return scheduler.addFiber(__owl__.currentFiber.root);
|
return scheduler.addFiber(currentFiber.root);
|
||||||
}
|
}
|
||||||
// if we aren't mounted at this point, it implies that there is a
|
// 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
|
// currentFiber that is already rendered (isRendered is true), so we are
|
||||||
// about to be mounted
|
// about to be mounted
|
||||||
const isMounted = __owl__.isMounted;
|
const status = __owl__.status;
|
||||||
const fiber = new Fiber(null, this, force, null);
|
const fiber = new Fiber(null, this, force, null, null);
|
||||||
Promise.resolve().then(() => {
|
Promise.resolve().then(() => {
|
||||||
if (__owl__.isMounted || !isMounted) {
|
if (__owl__.status === STATUS.MOUNTED || status !== STATUS.MOUNTED) {
|
||||||
// we are mounted (__owl__.isMounted), or if we are currently being
|
if (fiber.isCompleted || fiber.isRendered) {
|
||||||
// mounted (!isMounted), so we call __render
|
return;
|
||||||
|
}
|
||||||
this.__render(fiber);
|
this.__render(fiber);
|
||||||
} else {
|
} else {
|
||||||
// we were mounted when render was called, but we aren't anymore, so we
|
// we were mounted when render was called, but we aren't anymore, so we
|
||||||
@@ -398,7 +433,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
*/
|
*/
|
||||||
destroy() {
|
destroy() {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
if (!__owl__.isDestroyed) {
|
if (__owl__.status !== STATUS.DESTROYED) {
|
||||||
const el = this.el;
|
const el = this.el;
|
||||||
this.__destroy(__owl__.parent);
|
this.__destroy(__owl__.parent);
|
||||||
if (el) {
|
if (el) {
|
||||||
@@ -422,8 +457,8 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* up to the parent DOM nodes. Thus, it must be called between mounted() and
|
* up to the parent DOM nodes. Thus, it must be called between mounted() and
|
||||||
* willUnmount().
|
* willUnmount().
|
||||||
*/
|
*/
|
||||||
trigger(eventType: string, payload?: any) {
|
trigger<T = any>(eventType: string, payload?: T) {
|
||||||
this.__trigger(this, eventType, payload);
|
this.__trigger<T>(this, eventType, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
@@ -441,15 +476,14 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Note that it does not call the __callWillUnmount method to avoid visiting
|
* Note that it does not call the __callWillUnmount method to avoid visiting
|
||||||
* all children many times.
|
* all children many times.
|
||||||
*/
|
*/
|
||||||
__destroy(parent: Component<any, any> | null) {
|
__destroy(parent: Component | null) {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
const isMounted = __owl__.isMounted;
|
if (__owl__.status === STATUS.MOUNTED) {
|
||||||
if (isMounted) {
|
|
||||||
if (__owl__.willUnmountCB) {
|
if (__owl__.willUnmountCB) {
|
||||||
__owl__.willUnmountCB();
|
__owl__.willUnmountCB();
|
||||||
}
|
}
|
||||||
this.willUnmount();
|
this.willUnmount();
|
||||||
__owl__.isMounted = false;
|
__owl__.status = STATUS.UNMOUNTED;
|
||||||
}
|
}
|
||||||
const children = __owl__.children;
|
const children = __owl__.children;
|
||||||
for (let key in children) {
|
for (let key in children) {
|
||||||
@@ -460,7 +494,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
delete parent.__owl__.children[id];
|
delete parent.__owl__.children[id];
|
||||||
__owl__.parent = null;
|
__owl__.parent = null;
|
||||||
}
|
}
|
||||||
__owl__.isDestroyed = true;
|
__owl__.status = STATUS.DESTROYED;
|
||||||
delete __owl__.vnode;
|
delete __owl__.vnode;
|
||||||
if (__owl__.currentFiber) {
|
if (__owl__.currentFiber) {
|
||||||
__owl__.currentFiber.isCompleted = true;
|
__owl__.currentFiber.isCompleted = true;
|
||||||
@@ -470,7 +504,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
__callMounted() {
|
__callMounted() {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
|
|
||||||
__owl__.isMounted = true;
|
__owl__.status = STATUS.MOUNTED;
|
||||||
__owl__.currentFiber = null;
|
__owl__.currentFiber = null;
|
||||||
this.mounted();
|
this.mounted();
|
||||||
if (__owl__.mountedCB) {
|
if (__owl__.mountedCB) {
|
||||||
@@ -484,15 +518,15 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
__owl__.willUnmountCB();
|
__owl__.willUnmountCB();
|
||||||
}
|
}
|
||||||
this.willUnmount();
|
this.willUnmount();
|
||||||
__owl__.isMounted = false;
|
__owl__.status = STATUS.UNMOUNTED;
|
||||||
if (this.__owl__.currentFiber) {
|
if (__owl__.currentFiber) {
|
||||||
this.__owl__.currentFiber.isCompleted = true;
|
__owl__.currentFiber.isCompleted = true;
|
||||||
this.__owl__.currentFiber.root.counter = 0;
|
__owl__.currentFiber.root.counter = 0;
|
||||||
}
|
}
|
||||||
const children = __owl__.children;
|
const children = __owl__.children;
|
||||||
for (let id in children) {
|
for (let id in children) {
|
||||||
const comp = children[id];
|
const comp = children[id];
|
||||||
if (comp.__owl__.isMounted) {
|
if (comp.__owl__.status === STATUS.MOUNTED) {
|
||||||
comp.__callWillUnmount();
|
comp.__callWillUnmount();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -501,12 +535,12 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Private trigger method, allows to choose the component which triggered
|
* Private trigger method, allows to choose the component which triggered
|
||||||
* the event in the first place
|
* the event in the first place
|
||||||
*/
|
*/
|
||||||
__trigger(component: Component<any, any>, eventType: string, payload?: any) {
|
__trigger<T>(component: Component, eventType: string, payload?: T) {
|
||||||
if (this.el) {
|
if (this.el) {
|
||||||
const ev = new OwlEvent(component, eventType, {
|
const ev = new OwlEvent<T>(component, eventType, {
|
||||||
bubbles: true,
|
bubbles: true,
|
||||||
cancelable: true,
|
cancelable: true,
|
||||||
detail: payload
|
detail: payload,
|
||||||
});
|
});
|
||||||
const triggerHook = this.env[portalSymbol as any];
|
const triggerHook = this.env[portalSymbol as any];
|
||||||
if (triggerHook) {
|
if (triggerHook) {
|
||||||
@@ -524,7 +558,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||||
if (shouldUpdate) {
|
if (shouldUpdate) {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null);
|
const fiber = new Fiber(parentFiber, this, parentFiber.force, null, null);
|
||||||
if (!parentFiber.child) {
|
if (!parentFiber.child) {
|
||||||
parentFiber.child = fiber;
|
parentFiber.child = fiber;
|
||||||
} else {
|
} else {
|
||||||
@@ -541,7 +575,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.willUpdateProps(nextProps),
|
this.willUpdateProps(nextProps),
|
||||||
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps)
|
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps),
|
||||||
]);
|
]);
|
||||||
if (fiber.isCompleted) {
|
if (fiber.isCompleted) {
|
||||||
return;
|
return;
|
||||||
@@ -556,20 +590,8 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* Main patching method. We call the virtual dom patch method here to convert
|
* Main patching method. We call the virtual dom patch method here to convert
|
||||||
* a virtual dom vnode into some actual dom.
|
* a virtual dom vnode into some actual dom.
|
||||||
*/
|
*/
|
||||||
__patch(vnode: VNode) {
|
__patch(target: HTMLElement | VNode | DocumentFragment, vnode: VNode) {
|
||||||
const __owl__ = this.__owl__;
|
this.__owl__.vnode = patch(target as any, vnode);
|
||||||
if (this.__target) {
|
|
||||||
if (this.__target.tagName.toLowerCase() !== vnode.sel) {
|
|
||||||
throw new Error(
|
|
||||||
`Cannot attach '${this.constructor.name}' to target node (not same tag name)`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
__owl__.vnode = patch(this.__target, vnode);
|
|
||||||
delete this.__target;
|
|
||||||
} else {
|
|
||||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
|
||||||
__owl__.vnode = patch(target, vnode);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -579,7 +601,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
*/
|
*/
|
||||||
__prepare(parentFiber: Fiber, scope: any, cb: CallableFunction): Fiber {
|
__prepare(parentFiber: Fiber, scope: any, cb: CallableFunction): Fiber {
|
||||||
this.__owl__.scope = scope;
|
this.__owl__.scope = scope;
|
||||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null);
|
const fiber = new Fiber(parentFiber, this, parentFiber.force, null, null);
|
||||||
fiber.shouldPatch = false;
|
fiber.shouldPatch = false;
|
||||||
if (!parentFiber.child) {
|
if (!parentFiber.child) {
|
||||||
parentFiber.child = fiber;
|
parentFiber.child = fiber;
|
||||||
@@ -612,9 +634,10 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
// key. So we fall back on looking for a template matching its name (or
|
// key. So we fall back on looking for a template matching its name (or
|
||||||
// one of its subclass).
|
// one of its subclass).
|
||||||
|
|
||||||
let template: string;
|
let template: string = p.name;
|
||||||
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
while (!(template in qweb.templates) && p !== Component) {
|
||||||
p = p.__proto__;
|
p = p.__proto__;
|
||||||
|
template = p.name;
|
||||||
}
|
}
|
||||||
if (p === Component) {
|
if (p === Component) {
|
||||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
||||||
@@ -624,18 +647,25 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
return p._template;
|
return p._template;
|
||||||
}
|
}
|
||||||
|
|
||||||
async __prepareAndRender(fiber: Fiber, cb: CallableFunction) {
|
async __prepareAndRender(fiber: Fiber, cb: CallableFunction) {
|
||||||
try {
|
try {
|
||||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
const proms = Promise.all([
|
||||||
|
this.willStart(),
|
||||||
|
this.__owl__.willStartCB && this.__owl__.willStartCB(),
|
||||||
|
]);
|
||||||
|
this.__owl__.status = STATUS.WILLSTARTED;
|
||||||
|
await proms;
|
||||||
|
if (this.__owl__.status === <any>STATUS.DESTROYED) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
fiber.handleError(e);
|
fiber.handleError(e);
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
if (this.__owl__.isDestroyed) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
if (!fiber.isCompleted) {
|
if (!fiber.isCompleted) {
|
||||||
this.__render(fiber);
|
this.__render(fiber);
|
||||||
|
this.__owl__.status = STATUS.RENDERED;
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -649,16 +679,35 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
try {
|
try {
|
||||||
let vnode = __owl__.renderFn!(this, {
|
let vnode = __owl__.renderFn!(this, {
|
||||||
handlers: __owl__.boundHandlers,
|
handlers: __owl__.boundHandlers,
|
||||||
fiber: fiber
|
fiber: fiber,
|
||||||
});
|
});
|
||||||
// we iterate over the children to detect those that no longer belong to the
|
// 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
|
// 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
|
// 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
|
// be notified later on (when patching), that they are removed from the DOM
|
||||||
for (let childKey in __owl__.children) {
|
for (let childKey in __owl__.children) {
|
||||||
let child = __owl__.children[childKey];
|
const child = __owl__.children[childKey];
|
||||||
if (!child.__owl__.isMounted && child.__owl__.parentLastFiberId < fiber.id) {
|
const childOwl = child.__owl__;
|
||||||
child.destroy();
|
if (childOwl.status !== STATUS.MOUNTED && childOwl.parentLastFiberId < fiber.id) {
|
||||||
|
// we only do here a "soft" destroy, meaning that we leave the child
|
||||||
|
// dom node alone, without removing it. Most of the time, it does not
|
||||||
|
// matter, because the child component is already unmounted. However,
|
||||||
|
// if some of its parent have been unmounted, the child could actually
|
||||||
|
// still be attached to its parent, and this may be important if we
|
||||||
|
// want to remount the parent, because the vdom need to match the
|
||||||
|
// actual DOM
|
||||||
|
child.__destroy(childOwl.parent);
|
||||||
|
if (childOwl.pvnode) {
|
||||||
|
// we remove the key here to make sure that the patching algorithm
|
||||||
|
// is able to make the difference between this pvnode and an eventual
|
||||||
|
// other instance of the same component
|
||||||
|
delete childOwl.pvnode.key;
|
||||||
|
// Since the component has been unmounted, we do not want to actually
|
||||||
|
// call a remove hook. This is pretty important, since the t-component
|
||||||
|
// directive actually disabled it, so the vdom algorithm will just
|
||||||
|
// not remove the child elm if we don't remove the hook.
|
||||||
|
delete childOwl.pvnode.data!.hook!.remove;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!vnode) {
|
if (!vnode) {
|
||||||
@@ -686,17 +735,6 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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).
|
* Apply default props (only top level).
|
||||||
*
|
*
|
||||||
@@ -710,3 +748,34 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface MountParameters {
|
||||||
|
env?: Env;
|
||||||
|
target: HTMLElement | DocumentFragment;
|
||||||
|
props?: any;
|
||||||
|
position?: MountOptions["position"];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Type<T> extends Function {
|
||||||
|
new (...args: any[]): T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function mount<T extends Type<Component>>(
|
||||||
|
C: T,
|
||||||
|
params: MountParameters
|
||||||
|
): Promise<InstanceType<T>> {
|
||||||
|
const { env, props, target } = params;
|
||||||
|
let origEnv = C.hasOwnProperty("env") ? (C as any).env : null;
|
||||||
|
if (env) {
|
||||||
|
((C as any) as typeof Component).env = env;
|
||||||
|
}
|
||||||
|
const component: Component = new C(null, props);
|
||||||
|
if (origEnv) {
|
||||||
|
(C as any).env = origEnv;
|
||||||
|
} else {
|
||||||
|
delete (C as any).env;
|
||||||
|
}
|
||||||
|
const position = params.position || "last-child";
|
||||||
|
await component.mount(target, { position });
|
||||||
|
return component as any;
|
||||||
|
}
|
||||||
|
|||||||
+111
-26
@@ -1,13 +1,14 @@
|
|||||||
import { QWeb } from "../qweb/index";
|
import { QWeb } from "../qweb/index";
|
||||||
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
||||||
import { makeHandlerCode, MODS_CODE } from "../qweb/extensions";
|
import { makeHandlerCode, MODS_CODE } from "../qweb/extensions";
|
||||||
|
import { STATUS } from "./component";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-component
|
// t-component
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
const T_COMPONENT_MODS_CODE = Object.assign({}, MODS_CODE, {
|
||||||
self: "if (e.target !== vn.elm) {return}"
|
self: "if (e.target !== vn.elm) {return}",
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
QWeb.utils.defineProxy = function defineProxy(target, source) {
|
||||||
@@ -18,11 +19,31 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
|||||||
},
|
},
|
||||||
set(val) {
|
set(val) {
|
||||||
source[k] = val;
|
source[k] = val;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
QWeb.utils.assignHooks = function assignHooks(dataObj, hooks) {
|
||||||
|
if ("hook" in dataObj) {
|
||||||
|
const hookObject = dataObj.hook;
|
||||||
|
for (let name in hooks) {
|
||||||
|
const current = hookObject[name];
|
||||||
|
const fn = hooks[name];
|
||||||
|
if (current) {
|
||||||
|
hookObject[name] = (...args) => {
|
||||||
|
current(...args);
|
||||||
|
fn(...args);
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
hookObject[name] = fn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dataObj.hook = hooks;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The t-component directive is certainly a complicated and hard to maintain piece
|
* The t-component directive is certainly a complicated and hard to maintain piece
|
||||||
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
* of code. To help you, fellow developer, if you have to maintain it, I offer
|
||||||
@@ -207,7 +228,9 @@ QWeb.addDirective({
|
|||||||
if (name.startsWith("t-on-")) {
|
if (name.startsWith("t-on-")) {
|
||||||
events.push([name, value]);
|
events.push([name, value]);
|
||||||
} else if (name === "t-transition") {
|
} else if (name === "t-transition") {
|
||||||
transition = value;
|
if (QWeb.enableTransitions) {
|
||||||
|
transition = value;
|
||||||
|
}
|
||||||
} else if (!name.startsWith("t-")) {
|
} else if (!name.startsWith("t-")) {
|
||||||
if (name !== "class" && name !== "style") {
|
if (name !== "class" && name !== "style") {
|
||||||
// this is a prop!
|
// this is a prop!
|
||||||
@@ -218,11 +241,22 @@ QWeb.addDirective({
|
|||||||
|
|
||||||
// computing the props string representing the props object
|
// computing the props string representing the props object
|
||||||
let propStr = Object.keys(props)
|
let propStr = Object.keys(props)
|
||||||
.map(k => k + ":" + props[k])
|
.map((k) => k + ":" + props[k])
|
||||||
.join(",");
|
.join(",");
|
||||||
let componentID = ctx.generateID();
|
let componentID = ctx.generateID();
|
||||||
|
|
||||||
const templateKey = ctx.generateTemplateKey();
|
let hasDefinedKey = false;
|
||||||
|
let templateKey;
|
||||||
|
if (node.tagName === "t" && !node.hasAttribute("t-key") && value.match(INTERP_REGEXP)) {
|
||||||
|
defineComponentKey();
|
||||||
|
const id = ctx.generateID();
|
||||||
|
// the ___ is to make sure we have no possible conflict with normal
|
||||||
|
// template keys
|
||||||
|
ctx.addLine(`let k${id} = '___' + componentKey${componentID}`);
|
||||||
|
templateKey = `k${id}`;
|
||||||
|
} else {
|
||||||
|
templateKey = ctx.generateTemplateKey();
|
||||||
|
}
|
||||||
let ref = node.getAttribute("t-ref");
|
let ref = node.getAttribute("t-ref");
|
||||||
let refExpr = "";
|
let refExpr = "";
|
||||||
let refKey: string = "";
|
let refKey: string = "";
|
||||||
@@ -260,7 +294,7 @@ QWeb.addDirective({
|
|||||||
let classDef = classAttr
|
let classDef = classAttr
|
||||||
.trim()
|
.trim()
|
||||||
.split(/\s+/)
|
.split(/\s+/)
|
||||||
.map(a => `'${a}':true`)
|
.map((a) => `'${a}':true`)
|
||||||
.join(",");
|
.join(",");
|
||||||
classObj = `_${ctx.generateID()}`;
|
classObj = `_${ctx.generateID()}`;
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||||
@@ -268,7 +302,7 @@ QWeb.addDirective({
|
|||||||
if (tattClass) {
|
if (tattClass) {
|
||||||
let tattExpr = ctx.formatExpression(tattClass);
|
let tattExpr = ctx.formatExpression(tattClass);
|
||||||
if (tattExpr[0] !== "{" || tattExpr[tattExpr.length - 1] !== "}") {
|
if (tattExpr[0] !== "{" || tattExpr[tattExpr.length - 1] !== "}") {
|
||||||
tattExpr = `utils.toObj(${tattExpr})`;
|
tattExpr = `utils.toClassObj(${tattExpr})`;
|
||||||
}
|
}
|
||||||
if (classAttr) {
|
if (classAttr) {
|
||||||
ctx.addLine(`Object.assign(${classObj}, ${tattExpr})`);
|
ctx.addLine(`Object.assign(${classObj}, ${tattExpr})`);
|
||||||
@@ -278,7 +312,9 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let eventsCode = events
|
let eventsCode = events
|
||||||
.map(function([name, value]) {
|
.map(function ([name, value]) {
|
||||||
|
const capture = name.match(/\.capture/);
|
||||||
|
name = capture ? name.replace(/\.capture/, "") : name;
|
||||||
const { event, handler } = makeHandlerCode(
|
const { event, handler } = makeHandlerCode(
|
||||||
ctx,
|
ctx,
|
||||||
name,
|
name,
|
||||||
@@ -286,12 +322,15 @@ QWeb.addDirective({
|
|||||||
false,
|
false,
|
||||||
T_COMPONENT_MODS_CODE
|
T_COMPONENT_MODS_CODE
|
||||||
);
|
);
|
||||||
|
if (capture) {
|
||||||
|
return `vn.elm.addEventListener('${event}', ${handler}, true);`;
|
||||||
|
}
|
||||||
return `vn.elm.addEventListener('${event}', ${handler});`;
|
return `vn.elm.addEventListener('${event}', ${handler});`;
|
||||||
})
|
})
|
||||||
.join("");
|
.join("");
|
||||||
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
const styleExpr = tattStyle || (styleAttr ? `'${styleAttr}'` : false);
|
||||||
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
const styleCode = styleExpr ? `vn.elm.style = ${styleExpr};` : "";
|
||||||
createHook = `vnode.data.hook = {create(_, vn){${styleCode}${eventsCode}}};`;
|
createHook = `utils.assignHooks(vnode.data, {create(_, vn){${styleCode}${eventsCode}}});`;
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
@@ -308,7 +347,7 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
if (hasDynamicProps) {
|
if (hasDynamicProps) {
|
||||||
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
||||||
ctx.addLine(`let props${componentID} = Object.assign({${propStr}}, ${dynamicProp});`);
|
ctx.addLine(`let props${componentID} = Object.assign({}, ${dynamicProp}, {${propStr}});`);
|
||||||
} else {
|
} else {
|
||||||
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
||||||
}
|
}
|
||||||
@@ -327,14 +366,14 @@ QWeb.addDirective({
|
|||||||
// SLOTS
|
// SLOTS
|
||||||
const hasSlots = node.childNodes.length;
|
const hasSlots = node.childNodes.length;
|
||||||
|
|
||||||
let scope = hasSlots ? `Object.assign(Object.create(context), scope)` : "undefined";
|
let scope = hasSlots ? `utils.combine(context, scope)` : "undefined";
|
||||||
|
|
||||||
ctx.addIf(`w${componentID}`);
|
ctx.addIf(`w${componentID}`);
|
||||||
|
|
||||||
// need to update component
|
// need to update component
|
||||||
let styleCode = "";
|
let styleCode = "";
|
||||||
if (tattStyle) {
|
if (tattStyle) {
|
||||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
styleCode = `.then(()=>{if (w${componentID}.__owl__.status === ${STATUS.DESTROYED}) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||||
}
|
}
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`w${componentID}.__updateProps(props${componentID}, extra.fiber, ${scope})${styleCode};`
|
`w${componentID}.__updateProps(props${componentID}, extra.fiber, ${scope})${styleCode};`
|
||||||
@@ -350,14 +389,17 @@ QWeb.addDirective({
|
|||||||
ctx.addElse();
|
ctx.addElse();
|
||||||
|
|
||||||
// new component
|
// new component
|
||||||
let dynamicFallback = "";
|
function defineComponentKey() {
|
||||||
if (!value.match(INTERP_REGEXP)) {
|
if (!hasDefinedKey) {
|
||||||
dynamicFallback = `|| ${ctx.formatExpression(value)}`;
|
const interpValue = ctx.interpolate(value);
|
||||||
|
ctx.addLine(`let componentKey${componentID} = ${interpValue};`);
|
||||||
|
hasDefinedKey = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const interpValue = ctx.interpolate(value);
|
defineComponentKey();
|
||||||
ctx.addLine(`let componentKey${componentID} = ${interpValue};`);
|
const contextualValue = value.match(INTERP_REGEXP) ? "false" : ctx.formatExpression(value);
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`let W${componentID} = context.constructor.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}]${dynamicFallback};`
|
`let W${componentID} = ${contextualValue} || context.constructor.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}];`
|
||||||
);
|
);
|
||||||
|
|
||||||
// maybe only do this in dev mode...
|
// maybe only do this in dev mode...
|
||||||
@@ -368,33 +410,76 @@ QWeb.addDirective({
|
|||||||
if (transition) {
|
if (transition) {
|
||||||
ctx.addLine(`const __patch${componentID} = w${componentID}.__patch;`);
|
ctx.addLine(`const __patch${componentID} = w${componentID}.__patch;`);
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`w${componentID}.__patch = fiber => {__patch${componentID}.call(w${componentID}, fiber); if(!w${componentID}.__owl__.transitionInserted){w${componentID}.__owl__.transitionInserted = true;utils.transitionInsert(w${componentID}.__owl__.vnode, '${transition}');}};`
|
`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;`);
|
ctx.addLine(`parent.__owl__.cmap[${templateKey}] = w${componentID}.__owl__.id;`);
|
||||||
|
|
||||||
if (hasSlots) {
|
if (hasSlots) {
|
||||||
const clone = <Element>node.cloneNode(true);
|
const clone = <Element>node.cloneNode(true);
|
||||||
const slotNodes = clone.querySelectorAll("[t-set]");
|
|
||||||
|
// 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 node of clone.children) {
|
||||||
|
if (node.hasAttribute("t-set") && node.hasChildNodes()) {
|
||||||
|
node.setAttribute("t-set-slot", node.getAttribute("t-set")!);
|
||||||
|
node.removeAttribute("t-set");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
|
||||||
|
const slotNames = new Set<string>();
|
||||||
const slotId = QWeb.nextSlotId++;
|
const slotId = QWeb.nextSlotId++;
|
||||||
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
||||||
if (slotNodes.length) {
|
if (slotNodes.length) {
|
||||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
||||||
const slotNode = slotNodes[i];
|
const slotNode = slotNodes[i];
|
||||||
|
// check if this is defined in a sub component (in which case it should
|
||||||
|
// be ignored)
|
||||||
|
let el = slotNode.parentElement;
|
||||||
|
let isInSubComponent = false;
|
||||||
|
while (el !== clone) {
|
||||||
|
if (
|
||||||
|
el!.hasAttribute("t-component") ||
|
||||||
|
el!.tagName[0] === el!.tagName[0].toUpperCase()
|
||||||
|
) {
|
||||||
|
isInSubComponent = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
el = el.parentElement;
|
||||||
|
}
|
||||||
|
if (isInSubComponent) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let key = slotNode.getAttribute("t-set-slot")!;
|
||||||
|
if (slotNames.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
slotNames.add(key);
|
||||||
|
slotNode.removeAttribute("t-set-slot");
|
||||||
slotNode.parentElement!.removeChild(slotNode);
|
slotNode.parentElement!.removeChild(slotNode);
|
||||||
const key = slotNode.getAttribute("t-set")!;
|
|
||||||
slotNode.removeAttribute("t-set");
|
const slotFn = qweb._compile(`slot_${key}_template`, { elem: slotNode, hasParent: true });
|
||||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
|
||||||
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (clone.childNodes.length) {
|
if (clone.childNodes.length) {
|
||||||
|
let hasContent = false;
|
||||||
const t = clone.ownerDocument!.createElement("t");
|
const t = clone.ownerDocument!.createElement("t");
|
||||||
for (let child of Object.values(clone.childNodes)) {
|
for (let child of Object.values(clone.childNodes)) {
|
||||||
|
hasContent =
|
||||||
|
hasContent || (child instanceof Text ? Boolean(child.textContent.trim().length) : true);
|
||||||
t.appendChild(child);
|
t.appendChild(child);
|
||||||
}
|
}
|
||||||
const slotFn = qweb._compile(`slot_default_template`, t, ctx);
|
if (hasContent) {
|
||||||
QWeb.slots[`${slotId}_default`] = slotFn;
|
const slotFn = qweb._compile(`slot_default_template`, { elem: t, hasParent: true });
|
||||||
|
QWeb.slots[`${slotId}_default`] = slotFn;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,5 +508,5 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`w${componentID}.__owl__.parentLastFiberId = extra.fiber.id;`);
|
ctx.addLine(`w${componentID}.__owl__.parentLastFiberId = extra.fiber.id;`);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
+122
-40
@@ -1,5 +1,5 @@
|
|||||||
import { h, VNode } from "../vdom/index";
|
import { h, VNode } from "../vdom/index";
|
||||||
import { Component } from "./component";
|
import { Component, MountPosition, STATUS } from "./component";
|
||||||
import { scheduler } from "./scheduler";
|
import { scheduler } from "./scheduler";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,11 +46,12 @@ export class Fiber {
|
|||||||
// scheduler.
|
// scheduler.
|
||||||
counter: number = 0;
|
counter: number = 0;
|
||||||
|
|
||||||
inserter: (el: HTMLElement) => void | null;
|
target: HTMLElement | DocumentFragment | null;
|
||||||
|
position: MountPosition | null;
|
||||||
|
|
||||||
scope: any;
|
scope: any;
|
||||||
|
|
||||||
component: Component<any, any>;
|
component: Component;
|
||||||
vnode: VNode | null = null;
|
vnode: VNode | null = null;
|
||||||
|
|
||||||
root: Fiber;
|
root: Fiber;
|
||||||
@@ -61,10 +62,17 @@ export class Fiber {
|
|||||||
|
|
||||||
error?: Error;
|
error?: Error;
|
||||||
|
|
||||||
constructor(parent: Fiber | null, component: Component<any, any>, force, inserter) {
|
constructor(
|
||||||
|
parent: Fiber | null,
|
||||||
|
component: Component,
|
||||||
|
force: boolean,
|
||||||
|
target: HTMLElement | DocumentFragment | null,
|
||||||
|
position: MountPosition | null
|
||||||
|
) {
|
||||||
this.component = component;
|
this.component = component;
|
||||||
this.force = force;
|
this.force = force;
|
||||||
this.inserter = inserter;
|
this.target = target;
|
||||||
|
this.position = position;
|
||||||
|
|
||||||
const __owl__ = component.__owl__;
|
const __owl__ = component.__owl__;
|
||||||
this.scope = __owl__.scope;
|
this.scope = __owl__.scope;
|
||||||
@@ -74,6 +82,7 @@ export class Fiber {
|
|||||||
|
|
||||||
let oldFiber = __owl__.currentFiber;
|
let oldFiber = __owl__.currentFiber;
|
||||||
if (oldFiber && !oldFiber.isCompleted) {
|
if (oldFiber && !oldFiber.isCompleted) {
|
||||||
|
this.force = true;
|
||||||
if (oldFiber.root === oldFiber && !parent) {
|
if (oldFiber.root === oldFiber && !parent) {
|
||||||
// both oldFiber and this fiber are root fibers
|
// both oldFiber and this fiber are root fibers
|
||||||
this._reuseFiber(oldFiber);
|
this._reuseFiber(oldFiber);
|
||||||
@@ -98,6 +107,8 @@ export class Fiber {
|
|||||||
*/
|
*/
|
||||||
_reuseFiber(oldFiber: Fiber) {
|
_reuseFiber(oldFiber: Fiber) {
|
||||||
oldFiber.cancel(); // cancel children fibers
|
oldFiber.cancel(); // cancel children fibers
|
||||||
|
oldFiber.target = this.target || oldFiber.target;
|
||||||
|
oldFiber.position = this.position || oldFiber.position;
|
||||||
oldFiber.isCompleted = false; // keep the root fiber alive
|
oldFiber.isCompleted = false; // keep the root fiber alive
|
||||||
oldFiber.isRendered = false; // the fiber has to be re-rendered
|
oldFiber.isRendered = false; // the fiber has to be re-rendered
|
||||||
if (oldFiber.child) {
|
if (oldFiber.child) {
|
||||||
@@ -179,13 +190,14 @@ export class Fiber {
|
|||||||
complete() {
|
complete() {
|
||||||
let component = this.component;
|
let component = this.component;
|
||||||
this.isCompleted = true;
|
this.isCompleted = true;
|
||||||
if (!this.inserter && !component.__owl__.isMounted) {
|
const status = component.__owl__.status;
|
||||||
|
if (status === STATUS.DESTROYED) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// build patchQueue
|
// build patchQueue
|
||||||
const patchQueue: Fiber[] = [];
|
const patchQueue: Fiber[] = [];
|
||||||
const doWork: (Fiber) => Fiber | null = function(f) {
|
const doWork: (Fiber) => Fiber | null = function (f) {
|
||||||
patchQueue.push(f);
|
patchQueue.push(f);
|
||||||
return f.child;
|
return f.child;
|
||||||
};
|
};
|
||||||
@@ -193,14 +205,16 @@ export class Fiber {
|
|||||||
const patchLen = patchQueue.length;
|
const patchLen = patchQueue.length;
|
||||||
|
|
||||||
// call willPatch hook on each fiber of patchQueue
|
// call willPatch hook on each fiber of patchQueue
|
||||||
for (let i = 0; i < patchLen; i++) {
|
if (status === STATUS.MOUNTED) {
|
||||||
const fiber = patchQueue[i];
|
for (let i = 0; i < patchLen; i++) {
|
||||||
if (fiber.shouldPatch) {
|
const fiber = patchQueue[i];
|
||||||
component = fiber.component;
|
if (fiber.shouldPatch) {
|
||||||
if (component.__owl__.willPatchCB) {
|
component = fiber.component;
|
||||||
component.__owl__.willPatchCB();
|
if (component.__owl__.willPatchCB) {
|
||||||
|
component.__owl__.willPatchCB();
|
||||||
|
}
|
||||||
|
component.willPatch();
|
||||||
}
|
}
|
||||||
component.willPatch();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,32 +222,79 @@ export class Fiber {
|
|||||||
for (let i = patchLen - 1; i >= 0; i--) {
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
const fiber = patchQueue[i];
|
const fiber = patchQueue[i];
|
||||||
component = fiber.component;
|
component = fiber.component;
|
||||||
component.__patch(fiber.vnode!);
|
if (fiber.target && i === 0) {
|
||||||
if (!fiber.shouldPatch && (!fiber.inserter || i !== 0)) {
|
let target;
|
||||||
component.__owl__.pvnode!.elm = component.__owl__.vnode!.elm;
|
if (fiber.position === "self") {
|
||||||
|
target = fiber.target;
|
||||||
|
if ((target as HTMLElement).tagName.toLowerCase() !== fiber.vnode!.sel) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot attach '${component.constructor.name}' to target node (not same tag name)`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// In self mode, we *know* we are to take possession of the target
|
||||||
|
// Hence we manually create the corresponding VNode and copy the "key" in data
|
||||||
|
const selfVnodeData = fiber.vnode!.data ? { key: fiber.vnode!.data.key } : {};
|
||||||
|
const selfVnode = h(fiber.vnode!.sel, selfVnodeData);
|
||||||
|
selfVnode.elm = target;
|
||||||
|
target = selfVnode;
|
||||||
|
} else {
|
||||||
|
target = component.__owl__.vnode || document.createElement(fiber.vnode!.sel!);
|
||||||
|
}
|
||||||
|
component.__patch(target!, fiber.vnode!);
|
||||||
|
} else {
|
||||||
|
if (fiber.shouldPatch) {
|
||||||
|
component.__patch(component.__owl__.vnode!, fiber.vnode!);
|
||||||
|
// When updating a Component's props (in directive),
|
||||||
|
// the component has a pvnode AND should be patched.
|
||||||
|
// However, its pvnode.elm may have changed if it is a High Order Component
|
||||||
|
if (component.__owl__.pvnode) {
|
||||||
|
component.__owl__.pvnode.elm = component.__owl__.vnode!.elm;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
component.__patch(document.createElement(fiber.vnode!.sel!), fiber.vnode!);
|
||||||
|
component.__owl__.pvnode!.elm = component.__owl__.vnode!.elm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const compOwl = component.__owl__;
|
||||||
|
if (fiber === compOwl.currentFiber) {
|
||||||
|
compOwl.currentFiber = null;
|
||||||
}
|
}
|
||||||
component.__owl__.currentFiber = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// insert into the DOM (mount case)
|
// insert into the DOM (mount case)
|
||||||
let inDOM = false;
|
let inDOM = false;
|
||||||
if (this.inserter) {
|
if (this.target) {
|
||||||
this.inserter(this.component.el!);
|
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);
|
inDOM = document.body.contains(this.component.el);
|
||||||
this.component.env.qweb.trigger("dom-appended");
|
this.component.env.qweb.trigger("dom-appended");
|
||||||
}
|
}
|
||||||
|
|
||||||
// call patched/mounted hook on each fiber of (reversed) patchQueue
|
// call patched/mounted hook on each fiber of (reversed) patchQueue
|
||||||
for (let i = patchLen - 1; i >= 0; i--) {
|
if (status === STATUS.MOUNTED || inDOM) {
|
||||||
const fiber = patchQueue[i];
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
component = fiber.component;
|
const fiber = patchQueue[i];
|
||||||
if (fiber.shouldPatch && !this.inserter) {
|
component = fiber.component;
|
||||||
component.patched();
|
if (fiber.shouldPatch && !this.target) {
|
||||||
if (component.__owl__.patchedCB) {
|
component.patched();
|
||||||
component.__owl__.patchedCB();
|
if (component.__owl__.patchedCB) {
|
||||||
|
component.__owl__.patchedCB();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
component.__callMounted();
|
||||||
}
|
}
|
||||||
} else if (this.inserter ? inDOM : true) {
|
}
|
||||||
component.__callMounted();
|
} else {
|
||||||
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
|
const fiber = patchQueue[i];
|
||||||
|
component = fiber.component;
|
||||||
|
component.__owl__.status = STATUS.UNMOUNTED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -242,7 +303,7 @@ export class Fiber {
|
|||||||
* Cancel a fiber and all its children.
|
* Cancel a fiber and all its children.
|
||||||
*/
|
*/
|
||||||
cancel() {
|
cancel() {
|
||||||
this._walk(f => {
|
this._walk((f) => {
|
||||||
if (!f.isRendered) {
|
if (!f.isRendered) {
|
||||||
f.root.counter--;
|
f.root.counter--;
|
||||||
}
|
}
|
||||||
@@ -265,22 +326,43 @@ export class Fiber {
|
|||||||
|
|
||||||
const qweb = component.env.qweb;
|
const qweb = component.env.qweb;
|
||||||
let root = component;
|
let root = component;
|
||||||
let canCatch = false;
|
|
||||||
while (component && !(canCatch = !!component.catchError)) {
|
|
||||||
root = component;
|
|
||||||
component = component.__owl__.parent!;
|
|
||||||
}
|
|
||||||
qweb.trigger("error", error);
|
|
||||||
|
|
||||||
if (canCatch) {
|
function handle(error) {
|
||||||
component.catchError!(error);
|
let canCatch = false;
|
||||||
} else {
|
qweb.trigger("error", error);
|
||||||
|
while (component && !(canCatch = !!component.catchError)) {
|
||||||
|
root = component;
|
||||||
|
component = component.__owl__.parent!;
|
||||||
|
}
|
||||||
|
if (canCatch) {
|
||||||
|
try {
|
||||||
|
component.catchError!(error);
|
||||||
|
} catch (e) {
|
||||||
|
root = component;
|
||||||
|
component = component.__owl__.parent!;
|
||||||
|
return handle(e);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let isHandled = handle(error);
|
||||||
|
|
||||||
|
if (!isHandled) {
|
||||||
// the 3 next lines aim to mark the root fiber as being in error, and
|
// 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
|
// to force it to end, without waiting for its children
|
||||||
this.root.counter = 0;
|
this.root.counter = 0;
|
||||||
this.root.error = error;
|
this.root.error = error;
|
||||||
scheduler.flush();
|
scheduler.flush();
|
||||||
root.destroy();
|
// at this point, the state of the application is corrupted and we could
|
||||||
|
// have a lot of issues or crashes. So we destroy the application in a try
|
||||||
|
// catch and swallow these errors because the fiber is already in error,
|
||||||
|
// and this is the actual issue that needs to be solved, not those followup
|
||||||
|
// errors.
|
||||||
|
try {
|
||||||
|
root.destroy();
|
||||||
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { QWeb } from "../qweb/index";
|
|||||||
* This is why it is only done in 'dev' mode.
|
* This is why it is only done in 'dev' mode.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
QWeb.utils.validateProps = function(Widget, props: Object) {
|
QWeb.utils.validateProps = function (Widget, props: Object) {
|
||||||
const propsDef = (<any>Widget).props;
|
const propsDef = (<any>Widget).props;
|
||||||
if (propsDef instanceof Array) {
|
if (propsDef instanceof Array) {
|
||||||
// list of strings (prop names)
|
// list of strings (prop names)
|
||||||
@@ -37,7 +37,7 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
|
|||||||
if (propsDef[propName] && !propsDef[propName].optional) {
|
if (propsDef[propName] && !propsDef[propName].optional) {
|
||||||
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
throw new Error(`Missing props '${propName}' (component '${Widget.name}')`);
|
||||||
} else {
|
} else {
|
||||||
break;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let isValid;
|
let isValid;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Fiber } from "./fiber";
|
import { Fiber } from "./fiber";
|
||||||
|
import { browser } from "../browser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Scheduler Class
|
* Owl Scheduler Class
|
||||||
@@ -19,9 +20,9 @@ interface Task {
|
|||||||
export class Scheduler {
|
export class Scheduler {
|
||||||
tasks: Task[] = [];
|
tasks: Task[] = [];
|
||||||
isRunning: boolean = false;
|
isRunning: boolean = false;
|
||||||
requestAnimationFrame: typeof window.requestAnimationFrame;
|
requestAnimationFrame: Window["requestAnimationFrame"];
|
||||||
|
|
||||||
constructor(requestAnimationFrame) {
|
constructor(requestAnimationFrame: Window["requestAnimationFrame"]) {
|
||||||
this.requestAnimationFrame = requestAnimationFrame;
|
this.requestAnimationFrame = requestAnimationFrame;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ export class Scheduler {
|
|||||||
this.isRunning = false;
|
this.isRunning = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
addFiber(fiber): Promise<void> {
|
addFiber(fiber: Fiber): Promise<void> {
|
||||||
// if the fiber was remapped into a larger rendering fiber, it may not be a
|
// 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
|
// root fiber. But we only want to register root fibers
|
||||||
fiber = fiber.root;
|
fiber = fiber.root;
|
||||||
@@ -49,7 +50,7 @@ export class Scheduler {
|
|||||||
return reject(fiber.error);
|
return reject(fiber.error);
|
||||||
}
|
}
|
||||||
resolve();
|
resolve();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
if (!this.isRunning) {
|
if (!this.isRunning) {
|
||||||
this.start();
|
this.start();
|
||||||
@@ -57,6 +58,17 @@ export class Scheduler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.
|
* Process all current tasks. This only applies to the fibers that are ready.
|
||||||
* Other tasks are left unchanged.
|
* Other tasks are left unchanged.
|
||||||
@@ -64,7 +76,7 @@ export class Scheduler {
|
|||||||
flush() {
|
flush() {
|
||||||
let tasks = this.tasks;
|
let tasks = this.tasks;
|
||||||
this.tasks = [];
|
this.tasks = [];
|
||||||
tasks = tasks.filter(task => {
|
tasks = tasks.filter((task) => {
|
||||||
if (task.fiber.isCompleted) {
|
if (task.fiber.isCompleted) {
|
||||||
task.callback();
|
task.callback();
|
||||||
return false;
|
return false;
|
||||||
@@ -98,5 +110,4 @@ export class Scheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const raf = window.requestAnimationFrame.bind(window);
|
export const scheduler = new Scheduler(browser.requestAnimationFrame);
|
||||||
export const scheduler = new Scheduler(raf);
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
export const STYLESHEETS: { [id: string]: HTMLStyleElement } = {};
|
export const STYLESHEETS: { [id: string]: HTMLStyleElement } = {};
|
||||||
|
|
||||||
export function processSheet(str: string): string {
|
export function processSheet(str: string): string {
|
||||||
const tokens = str.split(/(\{|\}|;)/).map(s => s.trim());
|
const tokens = str.split(/(\{|\}|;)/).map((s) => s.trim());
|
||||||
const selectorStack: string[][] = [];
|
const selectorStack: string[][] = [];
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
let rules: string[] = [];
|
let rules: string[] = [];
|
||||||
|
|||||||
+20
-6
@@ -1,4 +1,5 @@
|
|||||||
import { QWeb } from "./qweb/index";
|
import { QWeb } from "./qweb/index";
|
||||||
|
import { TRANSLATABLE_ATTRS } from "./qweb/qweb";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This file creates and exports the OWL 'config' object, with keys:
|
* This file creates and exports the OWL 'config' object, with keys:
|
||||||
@@ -8,9 +9,13 @@ import { QWeb } from "./qweb/index";
|
|||||||
|
|
||||||
interface Config {
|
interface Config {
|
||||||
mode: string;
|
mode: string;
|
||||||
|
enableTransitions: boolean;
|
||||||
|
translatableAttributes: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {} as Config;
|
export const config = {
|
||||||
|
translatableAttributes: TRANSLATABLE_ATTRS,
|
||||||
|
} as Config;
|
||||||
|
|
||||||
Object.defineProperty(config, "mode", {
|
Object.defineProperty(config, "mode", {
|
||||||
get() {
|
get() {
|
||||||
@@ -19,12 +24,21 @@ Object.defineProperty(config, "mode", {
|
|||||||
set(mode: string) {
|
set(mode: string) {
|
||||||
QWeb.dev = mode === "dev";
|
QWeb.dev = mode === "dev";
|
||||||
if (QWeb.dev) {
|
if (QWeb.dev) {
|
||||||
const url = `https://github.com/odoo/owl/blob/master/doc/reference/config.md#mode`;
|
console.info(`Owl is running in 'dev' mode.
|
||||||
console.warn(
|
|
||||||
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
This is not suitable for production use.
|
||||||
);
|
See https://github.com/odoo/owl/blob/master/doc/reference/config.md#mode for more information.`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`Owl is now running in 'prod' mode.`);
|
console.log(`Owl is now running in 'prod' mode.`);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Object.defineProperty(config, "enableTransitions", {
|
||||||
|
get() {
|
||||||
|
return QWeb.enableTransitions;
|
||||||
|
},
|
||||||
|
set(value: boolean) {
|
||||||
|
QWeb.enableTransitions = value;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
+7
-17
@@ -79,9 +79,9 @@ export class Context extends EventBus {
|
|||||||
async __notifyComponents() {
|
async __notifyComponents() {
|
||||||
const rev = ++this.rev;
|
const rev = ++this.rev;
|
||||||
const subscriptions = this.subscriptions.update;
|
const subscriptions = this.subscriptions.update;
|
||||||
const groups = partitionBy(subscriptions, s => (s.owner ? s.owner.__owl__.depth : -1));
|
const groups = partitionBy(subscriptions, (s) => (s.owner ? s.owner.__owl__.depth : -1));
|
||||||
for (let group of groups) {
|
for (let group of groups) {
|
||||||
const proms = group.map(sub => sub.callback.call(sub.owner, rev));
|
const proms = group.map((sub) => sub.callback.call(sub.owner, rev));
|
||||||
// at this point, each component in the current group has registered a
|
// at this point, each component in the current group has registered a
|
||||||
// top level fiber in the scheduler. It could happen that rendering these
|
// 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
|
// components is done (if they have no children). This is why we manually
|
||||||
@@ -100,11 +100,11 @@ export class Context extends EventBus {
|
|||||||
* to context state changes. The `useContext` method returns the context state
|
* to context state changes. The `useContext` method returns the context state
|
||||||
*/
|
*/
|
||||||
export function useContext(ctx: Context): any {
|
export function useContext(ctx: Context): any {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
return useContextWithCB(ctx, component, component.render.bind(component));
|
return useContextWithCB(ctx, component, component.render.bind(component));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useContextWithCB(ctx: Context, component: Component<any, any>, method): any {
|
export function useContextWithCB(ctx: Context, component: Component, method): any {
|
||||||
const __owl__ = component.__owl__;
|
const __owl__ = component.__owl__;
|
||||||
const id = __owl__.id;
|
const id = __owl__.id;
|
||||||
const mapping = ctx.mapping;
|
const mapping = ctx.mapping;
|
||||||
@@ -115,31 +115,21 @@ export function useContextWithCB(ctx: Context, component: Component<any, any>, m
|
|||||||
__owl__.observer = new Observer();
|
__owl__.observer = new Observer();
|
||||||
__owl__.observer.notifyCB = component.render.bind(component);
|
__owl__.observer.notifyCB = component.render.bind(component);
|
||||||
}
|
}
|
||||||
const currentCB = __owl__.observer.notifyCB;
|
|
||||||
__owl__.observer.notifyCB = function() {
|
|
||||||
if (ctx.rev > mapping[id]) {
|
|
||||||
// in this case, the context has been updated since we were rendering
|
|
||||||
// last, and we do not need to render here with the observer. A
|
|
||||||
// rendering is coming anyway, with the correct props.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
currentCB();
|
|
||||||
};
|
|
||||||
|
|
||||||
mapping[id] = 0;
|
mapping[id] = 0;
|
||||||
const renderFn = __owl__.renderFn;
|
const renderFn = __owl__.renderFn;
|
||||||
__owl__.renderFn = function(comp, params) {
|
__owl__.renderFn = function (comp, params) {
|
||||||
mapping[id] = ctx.rev;
|
mapping[id] = ctx.rev;
|
||||||
return renderFn(comp, params);
|
return renderFn(comp, params);
|
||||||
};
|
};
|
||||||
ctx.on("update", component, async contextRev => {
|
ctx.on("update", component, async (contextRev) => {
|
||||||
if (mapping[id] < contextRev) {
|
if (mapping[id] < contextRev) {
|
||||||
mapping[id] = contextRev;
|
mapping[id] = contextRev;
|
||||||
await method();
|
await method();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const __destroy = component.__destroy;
|
const __destroy = component.__destroy;
|
||||||
component.__destroy = parent => {
|
component.__destroy = (parent) => {
|
||||||
ctx.off("update", component);
|
ctx.off("update", component);
|
||||||
delete mapping[id];
|
delete mapping[id];
|
||||||
__destroy.call(component, parent);
|
__destroy.call(component, parent);
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export class EventBus {
|
|||||||
}
|
}
|
||||||
this.subscriptions[eventType].push({
|
this.subscriptions[eventType].push({
|
||||||
owner,
|
owner,
|
||||||
callback
|
callback,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ export class EventBus {
|
|||||||
off(eventType: string, owner: any) {
|
off(eventType: string, owner: any) {
|
||||||
const subs = this.subscriptions[eventType];
|
const subs = this.subscriptions[eventType];
|
||||||
if (subs) {
|
if (subs) {
|
||||||
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
|
this.subscriptions[eventType] = subs.filter((s) => s.owner !== owner);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,12 @@ export class Observer {
|
|||||||
notifyCB() {}
|
notifyCB() {}
|
||||||
|
|
||||||
observe<T>(value: T, parent?: any): T {
|
observe<T>(value: T, parent?: any): T {
|
||||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
if (
|
||||||
|
value === null ||
|
||||||
|
typeof value !== "object" ||
|
||||||
|
value instanceof Date ||
|
||||||
|
value instanceof Promise
|
||||||
|
) {
|
||||||
// fun fact: typeof null === 'object'
|
// fun fact: typeof null === 'object'
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
@@ -67,14 +72,14 @@ export class Observer {
|
|||||||
self.notifyCB();
|
self.notifyCB();
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const metadata = {
|
const metadata = {
|
||||||
value,
|
value,
|
||||||
proxy,
|
proxy,
|
||||||
rev: this.rev,
|
rev: this.rev,
|
||||||
parent
|
parent,
|
||||||
};
|
};
|
||||||
|
|
||||||
this.weakMap.set(value, metadata);
|
this.weakMap.set(value, metadata);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { Component } from "../component/component";
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export class OwlEvent<T> extends CustomEvent<T> {
|
export class OwlEvent<T> extends CustomEvent<T> {
|
||||||
originalComponent: Component<any, any>;
|
originalComponent: Component;
|
||||||
constructor(component, eventType, options) {
|
constructor(component, eventType, options) {
|
||||||
super(eventType, options);
|
super(eventType, options);
|
||||||
this.originalComponent = component;
|
this.originalComponent = component;
|
||||||
|
|||||||
+38
-18
@@ -1,4 +1,4 @@
|
|||||||
import { Component } from "./component/component";
|
import { Component, Env } from "./component/component";
|
||||||
import { Observer } from "./core/observer";
|
import { Observer } from "./core/observer";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -22,7 +22,7 @@ import { Observer } from "./core/observer";
|
|||||||
* trigger a rerendering of the current component.
|
* trigger a rerendering of the current component.
|
||||||
*/
|
*/
|
||||||
export function useState<T>(state: T): T {
|
export function useState<T>(state: T): T {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
const __owl__ = component.__owl__;
|
const __owl__ = component.__owl__;
|
||||||
if (!__owl__.observer) {
|
if (!__owl__.observer) {
|
||||||
__owl__.observer = new Observer();
|
__owl__.observer = new Observer();
|
||||||
@@ -36,11 +36,11 @@ export function useState<T>(state: T): T {
|
|||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
||||||
if (reverse) {
|
if (reverse) {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function() {
|
component.__owl__[method] = function () {
|
||||||
current.call(component);
|
current.call(component);
|
||||||
cb.call(component);
|
cb.call(component);
|
||||||
};
|
};
|
||||||
@@ -49,11 +49,11 @@ function makeLifecycleHook(method: string, reverse: boolean = false) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function() {
|
component.__owl__[method] = function () {
|
||||||
cb.call(component);
|
cb.call(component);
|
||||||
current.call(component);
|
current.call(component);
|
||||||
};
|
};
|
||||||
@@ -65,12 +65,12 @@ function makeLifecycleHook(method: string, reverse: boolean = false) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function makeAsyncHook(method: string) {
|
function makeAsyncHook(method: string) {
|
||||||
return function(cb) {
|
return function (cb) {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component: Component = Component.current!;
|
||||||
if (component.__owl__[method]) {
|
if (component.__owl__[method]) {
|
||||||
const current = component.__owl__[method];
|
const current = component.__owl__[method];
|
||||||
component.__owl__[method] = function(...args) {
|
component.__owl__[method] = function (...args) {
|
||||||
return Promise.all[(current.call(component, ...args), cb.call(component, ...args))];
|
return Promise.all([current.call(component, ...args), cb.call(component, ...args)]);
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
component.__owl__[method] = cb;
|
component.__owl__[method] = cb;
|
||||||
@@ -94,12 +94,12 @@ export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
|
|||||||
* The purpose of this hook is to allow components to get a reference to a sub
|
* The purpose of this hook is to allow components to get a reference to a sub
|
||||||
* html node or component.
|
* html node or component.
|
||||||
*/
|
*/
|
||||||
interface Ref {
|
interface Ref<C extends Component = Component> {
|
||||||
el: HTMLElement | null;
|
el: HTMLElement | null;
|
||||||
comp: Component<any, any> | null;
|
comp: C | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useRef(name: string): Ref {
|
export function useRef<C extends Component = Component>(name: string): Ref<C> {
|
||||||
const __owl__ = Component.current!.__owl__;
|
const __owl__ = Component.current!.__owl__;
|
||||||
return {
|
return {
|
||||||
get el(): HTMLElement | null {
|
get el(): HTMLElement | null {
|
||||||
@@ -111,13 +111,33 @@ export function useRef(name: string): Ref {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
get comp(): Component<any, any> | null {
|
get comp(): C | null {
|
||||||
const val = __owl__.refs && __owl__.refs[name];
|
const val = __owl__.refs && __owl__.refs[name];
|
||||||
return val instanceof Component ? val : null;
|
return val instanceof Component ? (val as C) : null;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// "Builder" hooks
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This hook is useful as a building block for some customized hooks, that may
|
||||||
|
* need a reference to the component calling them.
|
||||||
|
*/
|
||||||
|
export function useComponent<P, E extends Env>(): Component<P, E> {
|
||||||
|
return Component.current as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This hook is useful as a building block for some customized hooks, that may
|
||||||
|
* need a reference to the env of the component calling them.
|
||||||
|
*/
|
||||||
|
export function useEnv<E extends Env>(): E {
|
||||||
|
return Component.current.env as any;
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// useSubEnv
|
// useSubEnv
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|||||||
+4
-2
@@ -19,9 +19,10 @@ import { Link } from "./router/link";
|
|||||||
import { RouteComponent } from "./router/route_component";
|
import { RouteComponent } from "./router/route_component";
|
||||||
import { Router } from "./router/router";
|
import { Router } from "./router/router";
|
||||||
|
|
||||||
export { Component } from "./component/component";
|
export { Component, mount } from "./component/component";
|
||||||
export { QWeb };
|
export { QWeb };
|
||||||
export { config };
|
export { config };
|
||||||
|
export { browser } from "./browser";
|
||||||
|
|
||||||
export const Context = _context.Context;
|
export const Context = _context.Context;
|
||||||
export const useState = _hooks.useState;
|
export const useState = _hooks.useState;
|
||||||
@@ -35,6 +36,7 @@ export const hooks = Object.assign({}, _hooks, {
|
|||||||
useContext: _context.useContext,
|
useContext: _context.useContext,
|
||||||
useDispatch: _store.useDispatch,
|
useDispatch: _store.useDispatch,
|
||||||
useGetters: _store.useGetters,
|
useGetters: _store.useGetters,
|
||||||
useStore: _store.useStore
|
useStore: _store.useStore,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const __info__ = {};
|
export const __info__ = {};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { xml } from "../tags";
|
|||||||
* from this coordination. This is the goal of the AsyncRoot component.
|
* from this coordination. This is the goal of the AsyncRoot component.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export class AsyncRoot extends Component<any, any> {
|
export class AsyncRoot extends Component {
|
||||||
static template = xml`<t t-slot="default"/>`;
|
static template = xml`<t t-slot="default"/>`;
|
||||||
|
|
||||||
async __updateProps(nextProps, parentFiber) {
|
async __updateProps(nextProps, parentFiber) {
|
||||||
|
|||||||
+13
-9
@@ -18,12 +18,16 @@ import { useSubEnv } from "../hooks";
|
|||||||
* are re-triggered on an empty <portal> node located in the parent's DOM.
|
* are re-triggered on an empty <portal> node located in the parent's DOM.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export class Portal extends Component<any, any> {
|
interface Props {
|
||||||
|
target: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Portal extends Component<Props> {
|
||||||
static template = xml`<portal><t t-slot="default"/></portal>`;
|
static template = xml`<portal><t t-slot="default"/></portal>`;
|
||||||
static props = {
|
static props = {
|
||||||
target: {
|
target: {
|
||||||
type: String
|
type: String,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// boolean to indicate whether or not we must listen to 'dom-appended' event
|
// boolean to indicate whether or not we must listen to 'dom-appended' event
|
||||||
@@ -43,7 +47,7 @@ export class Portal extends Component<any, any> {
|
|||||||
// represents the element that is moved somewhere else
|
// represents the element that is moved somewhere else
|
||||||
portal: VNode | null = null;
|
portal: VNode | null = null;
|
||||||
// the target where we will move `portal`
|
// the target where we will move `portal`
|
||||||
target: HTMLElement | null = null;
|
target: Element | null = null;
|
||||||
|
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -51,12 +55,12 @@ export class Portal extends Component<any, any> {
|
|||||||
// put a callback in the env that is propagated to children s.t. portal can
|
// 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
|
// register an handler to those events just before children will trigger them
|
||||||
useSubEnv({
|
useSubEnv({
|
||||||
[portalSymbol]: ev => {
|
[portalSymbol]: (ev) => {
|
||||||
if (!this._handledEvents.has(ev.type)) {
|
if (!this._handledEvents.has(ev.type)) {
|
||||||
this.portal!.elm!.addEventListener(ev.type, this._handlerTunnel);
|
this.portal!.elm!.addEventListener(ev.type, this._handlerTunnel);
|
||||||
this._handledEvents.add(ev.type);
|
this._handledEvents.add(ev.type);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -120,7 +124,7 @@ export class Portal extends Component<any, any> {
|
|||||||
*
|
*
|
||||||
* @override
|
* @override
|
||||||
*/
|
*/
|
||||||
__patch(vnode) {
|
__patch(target, vnode) {
|
||||||
if (this.doTargetLookUp) {
|
if (this.doTargetLookUp) {
|
||||||
const target = document.querySelector(this.props.target);
|
const target = document.querySelector(this.props.target);
|
||||||
if (!target) {
|
if (!target) {
|
||||||
@@ -149,7 +153,7 @@ export class Portal extends Component<any, any> {
|
|||||||
this.portal = patch(portalPatch, vnode.children![0] as VNode);
|
this.portal = patch(portalPatch, vnode.children![0] as VNode);
|
||||||
vnode.children = [];
|
vnode.children = [];
|
||||||
|
|
||||||
super.__patch(vnode);
|
super.__patch(target, vnode);
|
||||||
|
|
||||||
if (shouldDeploy) {
|
if (shouldDeploy) {
|
||||||
this.__deployPortal();
|
this.__deployPortal();
|
||||||
@@ -158,7 +162,7 @@ export class Portal extends Component<any, any> {
|
|||||||
/**
|
/**
|
||||||
* Override to set the env
|
* Override to set the env
|
||||||
*/
|
*/
|
||||||
__trigger(component: Component<any, any>, eventType: string, payload?: any) {
|
__trigger(component: Component, eventType: string, payload?: any) {
|
||||||
const env = this.env;
|
const env = this.env;
|
||||||
this.env = this.parentEnv;
|
this.env = this.parentEnv;
|
||||||
super.__trigger(component, eventType, payload);
|
super.__trigger(component, eventType, payload);
|
||||||
|
|||||||
+44
-30
@@ -1,4 +1,4 @@
|
|||||||
import { CompilationContext } from "./compilation_context";
|
import { CompilationContext, INTERP_REGEXP } from "./compilation_context";
|
||||||
import { QWeb } from "./qweb";
|
import { QWeb } from "./qweb";
|
||||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||||
import { QWebVar } from "./expression_parser";
|
import { QWebVar } from "./expression_parser";
|
||||||
@@ -49,6 +49,7 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Compilatio
|
|||||||
if (ctx.escaping) {
|
if (ctx.escaping) {
|
||||||
let protectID;
|
let protectID;
|
||||||
if (value.hasBody) {
|
if (value.hasBody) {
|
||||||
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
protectID = ctx.startProtectScope();
|
protectID = ctx.startProtectScope();
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`${exprID} = ${exprID} instanceof utils.VDomArray ? utils.vDomToString(${exprID}) : ${exprID};`
|
`${exprID} = ${exprID} instanceof utils.VDomArray ? utils.vDomToString(${exprID}) : ${exprID};`
|
||||||
@@ -96,7 +97,7 @@ QWeb.addDirective({
|
|||||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
||||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -106,7 +107,7 @@ QWeb.addDirective({
|
|||||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
||||||
compileValueNode(value, node, qweb, ctx);
|
compileValueNode(value, node, qweb, ctx);
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -163,7 +164,7 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -179,7 +180,7 @@ QWeb.addDirective({
|
|||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -195,7 +196,7 @@ QWeb.addDirective({
|
|||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
@@ -208,7 +209,7 @@ QWeb.addDirective({
|
|||||||
},
|
},
|
||||||
finalize({ ctx }) {
|
finalize({ ctx }) {
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -222,77 +223,90 @@ QWeb.addDirective({
|
|||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
ctx.rootContext.shouldDefineScope = true;
|
ctx.rootContext.shouldDefineScope = true;
|
||||||
ctx.rootContext.shouldDefineUtils = 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 subTemplate = node.getAttribute("t-call")!;
|
||||||
|
const isDynamic = INTERP_REGEXP.test(subTemplate);
|
||||||
const nodeTemplate = qweb.templates[subTemplate];
|
const nodeTemplate = qweb.templates[subTemplate];
|
||||||
if (!nodeTemplate) {
|
if (!isDynamic && !nodeTemplate) {
|
||||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 2: compile target template in sub templates
|
// Step 2: compile target template in sub templates
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
if (!qweb.subTemplates[subTemplate]) {
|
let subIdstr: string;
|
||||||
qweb.subTemplates[subTemplate] = true;
|
if (isDynamic) {
|
||||||
const subTemplateFn = qweb._compile(subTemplate, nodeTemplate.elem, ctx, true);
|
const _id = ctx.generateID();
|
||||||
qweb.subTemplates[subTemplate] = subTemplateFn;
|
ctx.addLine(`let tname${_id} = ${ctx.interpolate(subTemplate)};`);
|
||||||
|
ctx.addLine(`let tid${_id} = this.subTemplates[tname${_id}];`);
|
||||||
|
ctx.addIf(`!tid${_id}`);
|
||||||
|
ctx.addLine(`tid${_id} = this.constructor.nextId++;`);
|
||||||
|
ctx.addLine(`this.subTemplates[tname${_id}] = tid${_id};`);
|
||||||
|
ctx.addLine(
|
||||||
|
`this.constructor.subTemplates[tid${_id}] = this._compile(tname${_id}, {hasParent: true, defineKey: true});`
|
||||||
|
);
|
||||||
|
ctx.closeIf();
|
||||||
|
subIdstr = `tid${_id}`;
|
||||||
|
} else {
|
||||||
|
let subId = qweb.subTemplates[subTemplate];
|
||||||
|
if (!subId) {
|
||||||
|
subId = QWeb.nextId++;
|
||||||
|
qweb.subTemplates[subTemplate] = subId;
|
||||||
|
const subTemplateFn = qweb._compile(subTemplate, { hasParent: true, defineKey: true });
|
||||||
|
QWeb.subTemplates[subId] = subTemplateFn;
|
||||||
|
}
|
||||||
|
subIdstr = `'${subId}'`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: compile t-call body if necessary
|
// Step 3: compile t-call body if necessary
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
let hasBody = node.hasChildNodes();
|
let hasBody = node.hasChildNodes();
|
||||||
let protectID;
|
const protectID = ctx.startProtectScope();
|
||||||
if (hasBody) {
|
if (hasBody) {
|
||||||
// we add a sub scope to protect the ambient scope
|
// we add a sub scope to protect the ambient scope
|
||||||
ctx.addLine(`{`);
|
ctx.addLine(`{`);
|
||||||
ctx.indent();
|
ctx.indent();
|
||||||
protectID = ctx.startProtectScope();
|
|
||||||
const nodeCopy = node.cloneNode(true) as Element;
|
const nodeCopy = node.cloneNode(true) as Element;
|
||||||
for (let attr of ["t-if", "t-else", "t-elif", "t-call"]) {
|
for (let attr of ["t-if", "t-else", "t-elif", "t-call"]) {
|
||||||
nodeCopy.removeAttribute(attr);
|
nodeCopy.removeAttribute(attr);
|
||||||
}
|
}
|
||||||
const parentNode = ctx.parentNode;
|
|
||||||
ctx.parentNode = "__0";
|
|
||||||
// this local scope is intended to trap c__0
|
// this local scope is intended to trap c__0
|
||||||
ctx.addLine(`{`);
|
ctx.addLine(`{`);
|
||||||
ctx.indent();
|
ctx.indent();
|
||||||
ctx.addLine("let c__0 = [];");
|
ctx.addLine("let c__0 = [];");
|
||||||
qweb._compileNode(nodeCopy, ctx);
|
qweb._compileNode(nodeCopy, ctx.subContext("parentNode", "__0"));
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
ctx.addLine("scope[utils.zero] = c__0;");
|
ctx.addLine("scope[utils.zero] = c__0;");
|
||||||
ctx.parentNode = parentNode;
|
|
||||||
ctx.dedent();
|
ctx.dedent();
|
||||||
ctx.addLine(`}`);
|
ctx.addLine(`}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 4: add the appropriate function call to current component
|
// Step 4: add the appropriate function call to current component
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
const callingScope = hasBody ? "scope" : "Object.assign(Object.create(context), scope)";
|
const parentComponent = ctx.rootContext.shouldDefineParent
|
||||||
const parentComponent = `utils.getComponent(context)`;
|
? `parent`
|
||||||
|
: `utils.getComponent(context)`;
|
||||||
const key = ctx.generateTemplateKey();
|
const key = ctx.generateTemplateKey();
|
||||||
const parentNode = ctx.parentNode ? `c${ctx.parentNode}` : "result";
|
const parentNode = ctx.parentNode ? `c${ctx.parentNode}` : "result";
|
||||||
const extra = `Object.assign({}, extra, {parentNode: ${parentNode}, parent: ${parentComponent}, key: ${key}})`;
|
const extra = `Object.assign({}, extra, {parentNode: ${parentNode}, parent: ${parentComponent}, key: ${key}})`;
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
ctx.addLine(`this.subTemplates['${subTemplate}'].call(this, ${callingScope}, ${extra});`);
|
ctx.addLine(`this.constructor.subTemplates[${subIdstr}].call(this, scope, ${extra});`);
|
||||||
} else {
|
} else {
|
||||||
// this is a t-call with no parentnode, we need to extract the result
|
// this is a t-call with no parentnode, we need to extract the result
|
||||||
ctx.rootContext.shouldDefineResult = true;
|
ctx.rootContext.shouldDefineResult = true;
|
||||||
ctx.addLine(`result = []`);
|
ctx.addLine(`result = []`);
|
||||||
ctx.addLine(`this.subTemplates['${subTemplate}'].call(this, ${callingScope}, ${extra});`);
|
ctx.addLine(`this.constructor.subTemplates[${subIdstr}].call(this, scope, ${extra});`);
|
||||||
ctx.addLine(`result = result[0]`);
|
ctx.addLine(`result = result[0]`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 5: restore previous scope
|
// Step 5: restore previous scope
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
if (hasBody) {
|
if (hasBody) {
|
||||||
ctx.stopProtectScope(protectID);
|
|
||||||
ctx.dedent();
|
ctx.dedent();
|
||||||
ctx.addLine(`}`);
|
ctx.addLine(`}`);
|
||||||
}
|
}
|
||||||
|
ctx.stopProtectScope(protectID);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -353,7 +367,7 @@ QWeb.addDirective({
|
|||||||
ctx.addLine("}");
|
ctx.addLine("}");
|
||||||
ctx.stopProtectScope(varsID);
|
ctx.stopProtectScope(varsID);
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -364,7 +378,7 @@ QWeb.addDirective({
|
|||||||
priority: 1,
|
priority: 1,
|
||||||
atNodeEncounter({ ctx }) {
|
atNodeEncounter({ ctx }) {
|
||||||
ctx.addLine("debugger;");
|
ctx.addLine("debugger;");
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -376,5 +390,5 @@ QWeb.addDirective({
|
|||||||
atNodeEncounter({ ctx, value }) {
|
atNodeEncounter({ ctx, value }) {
|
||||||
const expr = ctx.formatExpression(value);
|
const expr = ctx.formatExpression(value);
|
||||||
ctx.addLine(`console.log(${expr})`);
|
ctx.addLine(`console.log(${expr})`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ export class CompilationContext {
|
|||||||
const tokens = compileExprToArray(expr, this.variables);
|
const tokens = compileExprToArray(expr, this.variables);
|
||||||
const done = new Set();
|
const done = new Set();
|
||||||
return tokens
|
return tokens
|
||||||
.map(tok => {
|
.map((tok) => {
|
||||||
if (tok.varName) {
|
if (tok.varName) {
|
||||||
if (!done.has(tok.varName)) {
|
if (!done.has(tok.varName)) {
|
||||||
done.add(tok.varName);
|
done.add(tok.varName);
|
||||||
@@ -189,18 +189,19 @@ export class CompilationContext {
|
|||||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
return `(${this.formatExpression(s.slice(2, -2))})`;
|
||||||
}
|
}
|
||||||
|
|
||||||
let r = s.replace(/\{\{.*?\}\}/g, s => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
let r = s.replace(/\{\{.*?\}\}/g, (s) => "${" + this.formatExpression(s.slice(2, -2)) + "}");
|
||||||
return "`" + r + "`";
|
return "`" + r + "`";
|
||||||
}
|
}
|
||||||
startProtectScope(codeBlock?: boolean): number {
|
startProtectScope(codeBlock?: boolean): number {
|
||||||
const protectID = this.generateID();
|
const protectID = this.generateID();
|
||||||
this.rootContext.protectedScopeNumber++;
|
this.rootContext.protectedScopeNumber++;
|
||||||
this.rootContext.shouldDefineScope = true;
|
this.rootContext.shouldDefineScope = true;
|
||||||
const scopeExpr = codeBlock
|
const scopeExpr = `Object.create(scope);`;
|
||||||
? `Object.create(scope);`
|
|
||||||
: `Object.assign(Object.create(context), scope);`;
|
|
||||||
this.addLine(`let _origScope${protectID} = scope;`);
|
this.addLine(`let _origScope${protectID} = scope;`);
|
||||||
this.addLine(`scope = ${scopeExpr}`);
|
this.addLine(`scope = ${scopeExpr}`);
|
||||||
|
if (!codeBlock) {
|
||||||
|
this.addLine(`scope.__access_mode__ = 'ro';`);
|
||||||
|
}
|
||||||
return protectID;
|
return protectID;
|
||||||
}
|
}
|
||||||
stopProtectScope(protectID: number) {
|
stopProtectScope(protectID: number) {
|
||||||
|
|||||||
@@ -29,14 +29,14 @@ const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in
|
|||||||
","
|
","
|
||||||
);
|
);
|
||||||
|
|
||||||
const WORD_REPLACEMENT = {
|
const WORD_REPLACEMENT = Object.assign(Object.create(null), {
|
||||||
and: "&&",
|
and: "&&",
|
||||||
or: "||",
|
or: "||",
|
||||||
gt: ">",
|
gt: ">",
|
||||||
gte: ">=",
|
gte: ">=",
|
||||||
lt: "<",
|
lt: "<",
|
||||||
lte: "<="
|
lte: "<=",
|
||||||
};
|
});
|
||||||
|
|
||||||
export interface QWebVar {
|
export interface QWebVar {
|
||||||
id: string; // foo
|
id: string; // foo
|
||||||
@@ -57,6 +57,7 @@ type TKind =
|
|||||||
| "RIGHT_PAREN"
|
| "RIGHT_PAREN"
|
||||||
| "COMMA"
|
| "COMMA"
|
||||||
| "VALUE"
|
| "VALUE"
|
||||||
|
| "TEMPLATE_STRING"
|
||||||
| "SYMBOL"
|
| "SYMBOL"
|
||||||
| "OPERATOR"
|
| "OPERATOR"
|
||||||
| "COLON";
|
| "COLON";
|
||||||
@@ -67,9 +68,10 @@ interface Token {
|
|||||||
originalValue?: string;
|
originalValue?: string;
|
||||||
size?: number;
|
size?: number;
|
||||||
varName?: string;
|
varName?: string;
|
||||||
|
replace?: Function;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
const STATIC_TOKEN_MAP: { [key: string]: TKind } = Object.assign(Object.create(null), {
|
||||||
"{": "LEFT_BRACE",
|
"{": "LEFT_BRACE",
|
||||||
"}": "RIGHT_BRACE",
|
"}": "RIGHT_BRACE",
|
||||||
"[": "LEFT_BRACKET",
|
"[": "LEFT_BRACKET",
|
||||||
@@ -77,8 +79,8 @@ const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
|||||||
":": "COLON",
|
":": "COLON",
|
||||||
",": "COMMA",
|
",": "COMMA",
|
||||||
"(": "LEFT_PAREN",
|
"(": "LEFT_PAREN",
|
||||||
")": "RIGHT_PAREN"
|
")": "RIGHT_PAREN",
|
||||||
};
|
});
|
||||||
|
|
||||||
// note that the space after typeof is relevant. It makes sure that the formatted
|
// note that the space after typeof is relevant. It makes sure that the formatted
|
||||||
// expression has a space after typeof
|
// expression has a space after typeof
|
||||||
@@ -86,10 +88,10 @@ const OPERATORS = "...,.,===,==,+,!==,!=,!,||,&&,>=,>,<=,<,?,-,*,/,%,typeof ,=>,
|
|||||||
|
|
||||||
type Tokenizer = (expr: string) => Token | false;
|
type Tokenizer = (expr: string) => Token | false;
|
||||||
|
|
||||||
let tokenizeString: Tokenizer = function(expr) {
|
let tokenizeString: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
let start = s;
|
let start = s;
|
||||||
if (s !== "'" && s !== '"') {
|
if (s !== "'" && s !== '"' && s !== "`") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -111,10 +113,21 @@ let tokenizeString: Tokenizer = function(expr) {
|
|||||||
throw new Error("Invalid expression");
|
throw new Error("Invalid expression");
|
||||||
}
|
}
|
||||||
s += start;
|
s += start;
|
||||||
|
if (start === "`") {
|
||||||
|
return {
|
||||||
|
type: "TEMPLATE_STRING",
|
||||||
|
value: s,
|
||||||
|
replace(replacer) {
|
||||||
|
return s.replace(/\$\{(.*?)\}/g, (match, group) => {
|
||||||
|
return "${" + replacer(group) + "}";
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
return { type: "VALUE", value: s };
|
return { type: "VALUE", value: s };
|
||||||
};
|
};
|
||||||
|
|
||||||
let tokenizeNumber: Tokenizer = function(expr) {
|
let tokenizeNumber: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
if (s && s.match(/[0-9]/)) {
|
if (s && s.match(/[0-9]/)) {
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -128,7 +141,7 @@ let tokenizeNumber: Tokenizer = function(expr) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let tokenizeSymbol: Tokenizer = function(expr) {
|
let tokenizeSymbol: Tokenizer = function (expr) {
|
||||||
let s = expr[0];
|
let s = expr[0];
|
||||||
if (s && s.match(/[a-zA-Z_\$]/)) {
|
if (s && s.match(/[a-zA-Z_\$]/)) {
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -145,7 +158,7 @@ let tokenizeSymbol: Tokenizer = function(expr) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const tokenizeStatic: Tokenizer = function(expr) {
|
const tokenizeStatic: Tokenizer = function (expr) {
|
||||||
const char = expr[0];
|
const char = expr[0];
|
||||||
if (char && char in STATIC_TOKEN_MAP) {
|
if (char && char in STATIC_TOKEN_MAP) {
|
||||||
return { type: STATIC_TOKEN_MAP[char], value: char };
|
return { type: STATIC_TOKEN_MAP[char], value: char };
|
||||||
@@ -153,7 +166,7 @@ const tokenizeStatic: Tokenizer = function(expr) {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const tokenizeOperator: Tokenizer = function(expr) {
|
const tokenizeOperator: Tokenizer = function (expr) {
|
||||||
for (let op of OPERATORS) {
|
for (let op of OPERATORS) {
|
||||||
if (expr.startsWith(op)) {
|
if (expr.startsWith(op)) {
|
||||||
return { type: "OPERATOR", value: op };
|
return { type: "OPERATOR", value: op };
|
||||||
@@ -167,7 +180,7 @@ const TOKENIZERS = [
|
|||||||
tokenizeNumber,
|
tokenizeNumber,
|
||||||
tokenizeOperator,
|
tokenizeOperator,
|
||||||
tokenizeSymbol,
|
tokenizeSymbol,
|
||||||
tokenizeStatic
|
tokenizeStatic,
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -210,6 +223,10 @@ export function tokenize(expr: string): Token[] {
|
|||||||
// Expression "evaluator"
|
// Expression "evaluator"
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const isLeftSeparator = (token) => token && (token.type === "LEFT_BRACE" || token.type === "COMMA");
|
||||||
|
const isRightSeparator = (token) =>
|
||||||
|
token && (token.type === "RIGHT_BRACE" || token.type === "COMMA");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is the main function exported by this file. This is the code that will
|
* This is the main function exported by this file. This is the code that will
|
||||||
* process an expression (given as a string) and returns another expression with
|
* process an expression (given as a string) and returns another expression with
|
||||||
@@ -238,13 +255,39 @@ export function tokenize(expr: string): Token[] {
|
|||||||
export function compileExprToArray(expr: string, scope: { [key: string]: QWebVar }): Token[] {
|
export function compileExprToArray(expr: string, scope: { [key: string]: QWebVar }): Token[] {
|
||||||
scope = Object.create(scope);
|
scope = Object.create(scope);
|
||||||
const tokens = tokenize(expr);
|
const tokens = tokenize(expr);
|
||||||
for (let i = 0; i < tokens.length; i++) {
|
|
||||||
|
let i = 0;
|
||||||
|
let stack = []; // to track last opening [ or {
|
||||||
|
|
||||||
|
while (i < tokens.length) {
|
||||||
let token = tokens[i];
|
let token = tokens[i];
|
||||||
let prevToken = tokens[i - 1];
|
let prevToken = tokens[i - 1];
|
||||||
let nextToken = tokens[i + 1];
|
let nextToken = tokens[i + 1];
|
||||||
|
let groupType = stack[stack.length - 1];
|
||||||
|
|
||||||
|
switch (token.type) {
|
||||||
|
case "LEFT_BRACE":
|
||||||
|
case "LEFT_BRACKET":
|
||||||
|
stack.push(token.type);
|
||||||
|
break;
|
||||||
|
case "RIGHT_BRACE":
|
||||||
|
case "RIGHT_BRACKET":
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
|
||||||
let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value);
|
let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value);
|
||||||
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
||||||
if (prevToken) {
|
if (prevToken) {
|
||||||
|
// normalize missing tokens: {a} should be equivalent to {a:a}
|
||||||
|
if (
|
||||||
|
groupType === "LEFT_BRACE" &&
|
||||||
|
isLeftSeparator(prevToken) &&
|
||||||
|
isRightSeparator(nextToken)
|
||||||
|
) {
|
||||||
|
tokens.splice(i + 1, 0, { type: "COLON", value: ":" }, { ...token });
|
||||||
|
nextToken = tokens[i + 1];
|
||||||
|
}
|
||||||
|
|
||||||
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
||||||
isVar = false;
|
isVar = false;
|
||||||
} else if (prevToken.type === "LEFT_BRACE" || prevToken.type === "COMMA") {
|
} else if (prevToken.type === "LEFT_BRACE" || prevToken.type === "COMMA") {
|
||||||
@@ -254,6 +297,9 @@ export function compileExprToArray(expr: string, scope: { [key: string]: QWebVar
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (token.type === "TEMPLATE_STRING") {
|
||||||
|
token.value = token.replace((expr) => compileExpr(expr, scope));
|
||||||
|
}
|
||||||
if (nextToken && nextToken.type === "OPERATOR" && nextToken.value === "=>") {
|
if (nextToken && nextToken.type === "OPERATOR" && nextToken.value === "=>") {
|
||||||
if (token.type === "RIGHT_PAREN") {
|
if (token.type === "RIGHT_PAREN") {
|
||||||
let j = i - 1;
|
let j = i - 1;
|
||||||
@@ -278,12 +324,13 @@ export function compileExprToArray(expr: string, scope: { [key: string]: QWebVar
|
|||||||
token.value = `scope['${token.value}']`;
|
token.value = `scope['${token.value}']`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function compileExpr(expr: string, scope: { [key: string]: QWebVar }): string {
|
export function compileExpr(expr: string, scope: { [key: string]: QWebVar }): string {
|
||||||
return compileExprToArray(expr, scope)
|
return compileExprToArray(expr, scope)
|
||||||
.map(t => t.value)
|
.map((t) => t.value)
|
||||||
.join("");
|
.join("");
|
||||||
}
|
}
|
||||||
|
|||||||
+80
-26
@@ -1,5 +1,8 @@
|
|||||||
|
import { STATUS } from "../component/component";
|
||||||
import { VNode } from "../vdom/index";
|
import { VNode } from "../vdom/index";
|
||||||
|
import { INTERP_REGEXP } from "./compilation_context";
|
||||||
import { QWeb } from "./qweb";
|
import { QWeb } from "./qweb";
|
||||||
|
import { browser } from "../browser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl QWeb Extensions
|
* Owl QWeb Extensions
|
||||||
@@ -23,7 +26,7 @@ import { QWeb } from "./qweb";
|
|||||||
export const MODS_CODE = {
|
export const MODS_CODE = {
|
||||||
prevent: "e.preventDefault();",
|
prevent: "e.preventDefault();",
|
||||||
self: "if (e.target !== this.elm) {return}",
|
self: "if (e.target !== this.elm) {return}",
|
||||||
stop: "e.stopPropagation();"
|
stop: "e.stopPropagation();",
|
||||||
};
|
};
|
||||||
|
|
||||||
interface HandlerInfo {
|
interface HandlerInfo {
|
||||||
@@ -40,14 +43,17 @@ export function makeHandlerCode(
|
|||||||
putInCache: boolean,
|
putInCache: boolean,
|
||||||
modcodes = MODS_CODE
|
modcodes = MODS_CODE
|
||||||
): HandlerInfo {
|
): HandlerInfo {
|
||||||
const [event, ...mods] = fullName.slice(5).split(".");
|
let [event, ...mods] = fullName.slice(5).split(".");
|
||||||
|
if (mods.includes("capture")) {
|
||||||
|
event = "!" + event;
|
||||||
|
}
|
||||||
if (!event) {
|
if (!event) {
|
||||||
throw new Error("Missing event name with t-on directive");
|
throw new Error("Missing event name with t-on directive");
|
||||||
}
|
}
|
||||||
let code: string;
|
let code: string;
|
||||||
// check if it is a method with no args, a method with args or an expression
|
// check if it is a method with no args, a method with args or an expression
|
||||||
let args: string = "";
|
let args: string = "";
|
||||||
const name: string = value.replace(/\(.*\)/, function(_args) {
|
const name: string = value.replace(/\(.*\)/, function (_args) {
|
||||||
args = _args.slice(1, -1);
|
args = _args.slice(1, -1);
|
||||||
return "";
|
return "";
|
||||||
});
|
});
|
||||||
@@ -70,9 +76,10 @@ export function makeHandlerCode(
|
|||||||
// we need to capture every variable in it
|
// we need to capture every variable in it
|
||||||
putInCache = false;
|
putInCache = false;
|
||||||
code = ctx.captureExpression(value);
|
code = ctx.captureExpression(value);
|
||||||
|
code = `const res = (() => { return ${code} })(); if (typeof res === 'function') { res(e) }`;
|
||||||
}
|
}
|
||||||
const modCode = mods.map(mod => modcodes[mod]).join("");
|
const modCode = mods.map((mod) => modcodes[mod]).join("");
|
||||||
let handler = `function (e) {if (!context.__owl__.isMounted){return}${modCode}${code}}`;
|
let handler = `function (e) {if (context.__owl__.status === ${STATUS.DESTROYED}){return}${modCode}${code}}`;
|
||||||
if (putInCache) {
|
if (putInCache) {
|
||||||
const key = ctx.generateTemplateKey(event);
|
const key = ctx.generateTemplateKey(event);
|
||||||
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || ${handler};`);
|
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || ${handler};`);
|
||||||
@@ -87,7 +94,7 @@ QWeb.addDirective({
|
|||||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
||||||
const { event, handler } = makeHandlerCode(ctx, fullName, value, true);
|
const { event, handler } = makeHandlerCode(ctx, fullName, value, true);
|
||||||
ctx.addLine(`p${nodeID}.on['${event}'] = ${handler};`);
|
ctx.addLine(`p${nodeID}.on['${event}'] = ${handler};`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -102,17 +109,17 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
||||||
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
||||||
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-transition
|
// t-transition
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
QWeb.utils.nextFrame = function(cb: () => void) {
|
QWeb.utils.nextFrame = function (cb: () => void) {
|
||||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
requestAnimationFrame(() => requestAnimationFrame(cb));
|
||||||
};
|
};
|
||||||
|
|
||||||
QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
QWeb.utils.transitionInsert = function (vn: VNode, name: string) {
|
||||||
const elm = <HTMLElement>vn.elm;
|
const elm = <HTMLElement>vn.elm;
|
||||||
// remove potential duplicated vnode that is currently being removed, to
|
// remove potential duplicated vnode that is currently being removed, to
|
||||||
// prevent from having twice the same node in the DOM during an animation
|
// prevent from having twice the same node in the DOM during an animation
|
||||||
@@ -136,7 +143,7 @@ QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
QWeb.utils.transitionRemove = function(vn: VNode, name: string, rm: () => void) {
|
QWeb.utils.transitionRemove = function (vn: VNode, name: string, rm: () => void) {
|
||||||
const elm = <HTMLElement>vn.elm;
|
const elm = <HTMLElement>vn.elm;
|
||||||
elm.setAttribute("data-owl-key", vn.key!);
|
elm.setAttribute("data-owl-key", vn.key!);
|
||||||
|
|
||||||
@@ -180,12 +187,26 @@ function toMs(s: string): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function whenTransitionEnd(elm: HTMLElement, cb) {
|
function whenTransitionEnd(elm: HTMLElement, cb) {
|
||||||
|
if (!elm.parentNode) {
|
||||||
|
// if we get here, this means that the element was removed for some other
|
||||||
|
// reasons, and in that case, we don't want to work on animation since nothing
|
||||||
|
// will be displayed anyway.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const styles = window.getComputedStyle(elm);
|
const styles = window.getComputedStyle(elm);
|
||||||
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
const delays: Array<string> = (styles.transitionDelay || "").split(", ");
|
||||||
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
const durations: Array<string> = (styles.transitionDuration || "").split(", ");
|
||||||
const timeout: number = getTimeout(delays, durations);
|
const timeout: number = getTimeout(delays, durations);
|
||||||
if (timeout > 0) {
|
if (timeout > 0) {
|
||||||
elm.addEventListener("transitionend", cb, { once: true });
|
const transitionEndCB = () => {
|
||||||
|
if (!elm.parentNode) return;
|
||||||
|
cb();
|
||||||
|
browser.clearTimeout(fallbackTimeout);
|
||||||
|
elm.removeEventListener("transitionend", transitionEndCB);
|
||||||
|
};
|
||||||
|
elm.addEventListener("transitionend", transitionEndCB, { once: true });
|
||||||
|
const fallbackTimeout = browser.setTimeout(transitionEndCB, timeout + 1);
|
||||||
} else {
|
} else {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
@@ -195,16 +216,19 @@ QWeb.addDirective({
|
|||||||
name: "transition",
|
name: "transition",
|
||||||
priority: 96,
|
priority: 96,
|
||||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
atNodeCreation({ ctx, value, addNodeHook }) {
|
||||||
|
if (!QWeb.enableTransitions) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
let name = value;
|
let name = value;
|
||||||
const hooks = {
|
const hooks = {
|
||||||
insert: `utils.transitionInsert(vn, '${name}');`,
|
insert: `utils.transitionInsert(vn, '${name}');`,
|
||||||
remove: `utils.transitionRemove(vn, '${name}', rm);`
|
remove: `utils.transitionRemove(vn, '${name}', rm);`,
|
||||||
};
|
};
|
||||||
for (let hookName in hooks) {
|
for (let hookName in hooks) {
|
||||||
addNodeHook(hookName, hooks[hookName]);
|
addNodeHook(hookName, hooks[hookName]);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -215,8 +239,9 @@ QWeb.addDirective({
|
|||||||
priority: 80,
|
priority: 80,
|
||||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||||
const slotKey = ctx.generateID();
|
const slotKey = ctx.generateID();
|
||||||
|
const valueExpr = value.match(INTERP_REGEXP) ? ctx.interpolate(value) : `'${value}'`;
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + ${valueExpr}];`
|
||||||
);
|
);
|
||||||
ctx.addIf(`slot${slotKey}`);
|
ctx.addIf(`slot${slotKey}`);
|
||||||
let parentNode = `c${ctx.parentNode}`;
|
let parentNode = `c${ctx.parentNode}`;
|
||||||
@@ -241,17 +266,20 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
return true;
|
return true;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// t-model
|
// t-model
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
QWeb.utils.toNumber = function(val: string): number | string {
|
QWeb.utils.toNumber = function (val: string): number | string {
|
||||||
const n = parseFloat(val);
|
const n = parseFloat(val);
|
||||||
return isNaN(n) ? val : n;
|
return isNaN(n) ? val : n;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const hasDotAtTheEnd = /\.[\w_]+\s*$/;
|
||||||
|
const hasBracketsAtTheEnd = /\[[^\[]+\]\s*$/;
|
||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "model",
|
name: "model",
|
||||||
priority: 42,
|
priority: 42,
|
||||||
@@ -260,15 +288,41 @@ QWeb.addDirective({
|
|||||||
let handler;
|
let handler;
|
||||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
let event = fullName.includes(".lazy") ? "change" : "input";
|
||||||
|
|
||||||
// we keep here a reference to the "base expression" (if the expression
|
// First step: we need to understand the structure of the expression, and
|
||||||
// is `t-model="some.expr.value", then the base expression is "some.expr").
|
// from it, extract a base expression (that we can capture, which is
|
||||||
// This is necessary so we can capture it in the handler closure.
|
// important because it will be used in a handler later) and a formatted
|
||||||
let expr = ctx.formatExpression(value);
|
// expression (which uses the captured base expression)
|
||||||
const index = expr.lastIndexOf(".");
|
//
|
||||||
const baseExpr = expr.slice(0, index);
|
// Also, we support 2 kinds of values: some.expr.value or some.expr[value]
|
||||||
ctx.addLine(`let expr${nodeID} = ${baseExpr};`);
|
// For the first one, we have:
|
||||||
|
// - base expression = scope[some].expr
|
||||||
|
// - expression = exprX.value (where exprX is the var that captures the base expr)
|
||||||
|
// and for the expression with brackets:
|
||||||
|
// - base expression = scope[some].expr
|
||||||
|
// - expression = exprX[keyX] (where exprX is the var that captures the base expr
|
||||||
|
// and keyX captures scope[value])
|
||||||
|
let expr: string;
|
||||||
|
let baseExpr: string;
|
||||||
|
|
||||||
|
if (hasDotAtTheEnd.test(value)) {
|
||||||
|
// we manage the case where the expr has a dot: some.expr.value
|
||||||
|
const index = value.lastIndexOf(".");
|
||||||
|
baseExpr = value.slice(0, index);
|
||||||
|
ctx.addLine(`let expr${nodeID} = ${ctx.formatExpression(baseExpr)};`);
|
||||||
|
expr = `expr${nodeID}${value.slice(index)}`;
|
||||||
|
} else if (hasBracketsAtTheEnd.test(value)) {
|
||||||
|
// we manage here the case where the expr ends in a bracket expression:
|
||||||
|
// some.expr[value]
|
||||||
|
const index = value.lastIndexOf("[");
|
||||||
|
baseExpr = value.slice(0, index);
|
||||||
|
ctx.addLine(`let expr${nodeID} = ${ctx.formatExpression(baseExpr)};`);
|
||||||
|
let exprKey = value.trimRight().slice(index + 1, -1);
|
||||||
|
ctx.addLine(`let exprKey${nodeID} = ${ctx.formatExpression(exprKey)};`);
|
||||||
|
expr = `expr${nodeID}[exprKey${nodeID}]`;
|
||||||
|
} else {
|
||||||
|
throw new Error(`Invalid t-model expression: "${value}" (it should be assignable)`);
|
||||||
|
}
|
||||||
|
|
||||||
expr = `expr${nodeID}.${expr.slice(index + 1)}`;
|
|
||||||
const key = ctx.generateTemplateKey();
|
const key = ctx.generateTemplateKey();
|
||||||
if (node.tagName === "select") {
|
if (node.tagName === "select") {
|
||||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||||
@@ -295,7 +349,7 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || (${handler});`);
|
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || (${handler});`);
|
||||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers[${key}];`);
|
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers[${key}];`);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -319,5 +373,5 @@ QWeb.addDirective({
|
|||||||
if (ctx.loopNumber === 0) {
|
if (ctx.loopNumber === 0) {
|
||||||
ctx.rootContext.hasKey0 = ctx.keyStack.pop() as boolean;
|
ctx.rootContext.hasKey0 = ctx.keyStack.pop() as boolean;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
+194
-83
@@ -66,65 +66,105 @@ interface QWebConfig {
|
|||||||
// Const/global stuff/helpers
|
// Const/global stuff/helpers
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
|
export const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
|
||||||
|
|
||||||
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
|
|
||||||
|
|
||||||
const lineBreakRE = /[\r\n]/;
|
const lineBreakRE = /[\r\n]/;
|
||||||
const whitespaceRE = /\s+/g;
|
const whitespaceRE = /\s+/g;
|
||||||
|
const translationRE = /^(\s*)([\s\S]+?)(\s*)$/;
|
||||||
|
|
||||||
const NODE_HOOKS_PARAMS = {
|
const NODE_HOOKS_PARAMS = {
|
||||||
create: "(_, n)",
|
create: "(_, n)",
|
||||||
insert: "vn",
|
insert: "vn",
|
||||||
remove: "(vn, rm)",
|
remove: "(vn, rm)",
|
||||||
destroy: "()"
|
destroy: "()",
|
||||||
};
|
};
|
||||||
|
|
||||||
interface Utils {
|
interface Utils {
|
||||||
toObj(expr: any): Object;
|
toClassObj(expr: any): Object;
|
||||||
shallowEqual(p1: Object, p2: Object): boolean;
|
shallowEqual(p1: Object, p2: Object): boolean;
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isComponent(obj) {
|
function isComponent(obj): boolean {
|
||||||
return obj && obj.hasOwnProperty("__owl__");
|
return obj && obj.hasOwnProperty("__owl__");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class VDomArray extends Array {
|
||||||
|
toString() {
|
||||||
|
return vDomToString(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function vDomToString(vdom: VNode[]): string {
|
||||||
|
return vdom
|
||||||
|
.map((vnode) => {
|
||||||
|
if (vnode.sel) {
|
||||||
|
const node = document.createElement(vnode.sel);
|
||||||
|
const result = patch(node, vnode);
|
||||||
|
return (<HTMLElement>result.elm).outerHTML;
|
||||||
|
} else {
|
||||||
|
return vnode.text;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
const UTILS: Utils = {
|
const UTILS: Utils = {
|
||||||
zero: Symbol("zero"),
|
zero: Symbol("zero"),
|
||||||
toObj(expr) {
|
toClassObj(expr) {
|
||||||
|
const result = {};
|
||||||
if (typeof expr === "string") {
|
if (typeof expr === "string") {
|
||||||
|
// we transform here a list of classes into an object:
|
||||||
|
// 'hey you' becomes {hey: true, you: true}
|
||||||
expr = expr.trim();
|
expr = expr.trim();
|
||||||
if (!expr) {
|
if (!expr) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
let words = expr.split(/\s+/);
|
let words = expr.split(/\s+/);
|
||||||
let result = {};
|
|
||||||
for (let i = 0; i < words.length; i++) {
|
for (let i = 0; i < words.length; i++) {
|
||||||
result[words[i]] = true;
|
result[words[i]] = true;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
return expr;
|
// this is already an object, but we may need to split keys:
|
||||||
|
// {'a b': true, 'a c': false} should become {a: true, b: true, c: false}
|
||||||
|
for (let key in expr) {
|
||||||
|
const value = expr[key];
|
||||||
|
const words = key.split(/\s+/);
|
||||||
|
for (let word of words) {
|
||||||
|
result[word] = result[word] || value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* This method combines the current context with the variables defined in a
|
||||||
|
* scope for use in a slot.
|
||||||
|
*
|
||||||
|
* The implementation is kind of tricky because we want to preserve the
|
||||||
|
* prototype chain structure of the cloned result. So we need to traverse the
|
||||||
|
* prototype chain, cloning each level respectively.
|
||||||
|
*/
|
||||||
|
combine(context, scope) {
|
||||||
|
let clone = context;
|
||||||
|
const scopeStack = [];
|
||||||
|
while (!isComponent(scope)) {
|
||||||
|
scopeStack.push(scope);
|
||||||
|
scope = scope.__proto__;
|
||||||
|
}
|
||||||
|
while (scopeStack.length) {
|
||||||
|
let scope = scopeStack.pop();
|
||||||
|
clone = Object.create(clone);
|
||||||
|
Object.assign(clone, scope);
|
||||||
|
}
|
||||||
|
return clone;
|
||||||
},
|
},
|
||||||
shallowEqual,
|
shallowEqual,
|
||||||
addNameSpace(vnode) {
|
addNameSpace(vnode) {
|
||||||
addNS(vnode.data, vnode.children, vnode.sel);
|
addNS(vnode.data, vnode.children, vnode.sel);
|
||||||
},
|
},
|
||||||
VDomArray: class VDomArray extends Array {},
|
VDomArray,
|
||||||
vDomToString: function(vdom: VNode[]): string {
|
vDomToString,
|
||||||
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) {
|
getComponent(obj) {
|
||||||
while (obj && !isComponent(obj)) {
|
while (obj && !isComponent(obj)) {
|
||||||
obj = obj.__proto__;
|
obj = obj.__proto__;
|
||||||
@@ -133,7 +173,11 @@ const UTILS: Utils = {
|
|||||||
},
|
},
|
||||||
getScope(obj, property: string) {
|
getScope(obj, property: string) {
|
||||||
const obj0 = obj;
|
const obj0 = obj;
|
||||||
while (obj && !obj.hasOwnProperty(property)) {
|
while (
|
||||||
|
obj &&
|
||||||
|
!obj.hasOwnProperty(property) &&
|
||||||
|
!(obj.hasOwnProperty("__access_mode__") && obj.__access_mode__ === "ro")
|
||||||
|
) {
|
||||||
const newObj = obj.__proto__;
|
const newObj = obj.__proto__;
|
||||||
if (!newObj || isComponent(newObj)) {
|
if (!newObj || isComponent(newObj)) {
|
||||||
return obj0;
|
return obj0;
|
||||||
@@ -141,7 +185,7 @@ const UTILS: Utils = {
|
|||||||
obj = newObj;
|
obj = newObj;
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseXML(xml: string): Document {
|
function parseXML(xml: string): Document {
|
||||||
@@ -174,6 +218,10 @@ function parseXML(xml: string): Document {
|
|||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escapeQuotes(str: string): string {
|
||||||
|
return str.replace(/\'/g, "\\'");
|
||||||
|
}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// QWeb rendering engine
|
// QWeb rendering engine
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -187,7 +235,8 @@ export class QWeb extends EventBus {
|
|||||||
name: 1,
|
name: 1,
|
||||||
att: 1,
|
att: 1,
|
||||||
attf: 1,
|
attf: 1,
|
||||||
translation: 1
|
translation: 1,
|
||||||
|
tag: 1,
|
||||||
};
|
};
|
||||||
static DIRECTIVES: Directive[] = [];
|
static DIRECTIVES: Directive[] = [];
|
||||||
|
|
||||||
@@ -198,16 +247,19 @@ export class QWeb extends EventBus {
|
|||||||
h = h;
|
h = h;
|
||||||
// dev mode enables better error messages or more costly validations
|
// dev mode enables better error messages or more costly validations
|
||||||
static dev: boolean = false;
|
static dev: boolean = false;
|
||||||
|
static enableTransitions: boolean = true;
|
||||||
|
|
||||||
// slots contains sub templates defined with t-set inside t-component nodes, and
|
// slots contains sub templates defined with t-set inside t-component nodes, and
|
||||||
// are meant to be used by the t-slot directive.
|
// are meant to be used by the t-slot directive.
|
||||||
static slots = {};
|
static slots = {};
|
||||||
static nextSlotId = 1;
|
static nextSlotId = 1;
|
||||||
|
|
||||||
// recursiveTemplates contains sub templates called with t-call, but which
|
// subTemplates are stored in two objects: a (local) mapping from a name to an
|
||||||
// ends up in recursive situations. This is very similar to the slot situation,
|
// id, and a (global) mapping from an id to the compiled function. This is
|
||||||
// as in we need to propagate the scope.
|
// necessary to ensure that global templates can be called with more than one
|
||||||
subTemplates = {};
|
// QWeb instance.
|
||||||
|
subTemplates: { [key: string]: number } = {};
|
||||||
|
static subTemplates: { [id: number]: Function } = {};
|
||||||
|
|
||||||
isUpdating: boolean = false;
|
isUpdating: boolean = false;
|
||||||
translateFn?: QWebConfig["translateFn"];
|
translateFn?: QWebConfig["translateFn"];
|
||||||
@@ -231,7 +283,7 @@ export class QWeb extends EventBus {
|
|||||||
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
QWeb.DIRECTIVE_NAMES[directive.name] = 1;
|
||||||
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
QWeb.DIRECTIVES.sort((d1, d2) => d1.priority - d2.priority);
|
||||||
if (directive.extraNames) {
|
if (directive.extraNames) {
|
||||||
directive.extraNames.forEach(n => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
directive.extraNames.forEach((n) => (QWeb.DIRECTIVE_NAMES[n] = 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,6 +329,9 @@ export class QWeb extends EventBus {
|
|||||||
* template, with the name given by the t-name attribute.
|
* template, with the name given by the t-name attribute.
|
||||||
*/
|
*/
|
||||||
addTemplates(xmlstr: string | Document) {
|
addTemplates(xmlstr: string | Document) {
|
||||||
|
if (!xmlstr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const doc = typeof xmlstr === "string" ? parseXML(xmlstr) : xmlstr;
|
const doc = typeof xmlstr === "string" ? parseXML(xmlstr) : xmlstr;
|
||||||
const templates = doc.getElementsByTagName("templates")[0];
|
const templates = doc.getElementsByTagName("templates")[0];
|
||||||
if (!templates) {
|
if (!templates) {
|
||||||
@@ -295,11 +350,11 @@ export class QWeb extends EventBus {
|
|||||||
this._processTemplate(elem);
|
this._processTemplate(elem);
|
||||||
const template = {
|
const template = {
|
||||||
elem,
|
elem,
|
||||||
fn: function(this: QWeb, context, extra) {
|
fn: function (this: QWeb, context, extra) {
|
||||||
const compiledFunction = this._compile(name, elem);
|
const compiledFunction = this._compile(name);
|
||||||
template.fn = compiledFunction;
|
template.fn = compiledFunction;
|
||||||
return compiledFunction.call(this, context, extra);
|
return compiledFunction.call(this, context, extra);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
this.templates[name] = template;
|
this.templates[name] = template;
|
||||||
}
|
}
|
||||||
@@ -309,10 +364,10 @@ export class QWeb extends EventBus {
|
|||||||
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
|
||||||
let node = tbranch[i];
|
let node = tbranch[i];
|
||||||
let prevElem = node.previousElementSibling!;
|
let prevElem = node.previousElementSibling!;
|
||||||
let pattr = function(name) {
|
let pattr = function (name) {
|
||||||
return prevElem.getAttribute(name);
|
return prevElem.getAttribute(name);
|
||||||
};
|
};
|
||||||
let nattr = function(name) {
|
let nattr = function (name) {
|
||||||
return +!!node.getAttribute(name);
|
return +!!node.getAttribute(name);
|
||||||
};
|
};
|
||||||
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
|
||||||
@@ -322,16 +377,17 @@ export class QWeb extends EventBus {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
["t-if", "t-elif", "t-else"].map(nattr).reduce(function(a, b) {
|
["t-if", "t-elif", "t-else"].map(nattr).reduce(function (a, b) {
|
||||||
return a + b;
|
return a + b;
|
||||||
}) > 1
|
}) > 1
|
||||||
) {
|
) {
|
||||||
throw new Error("Only one conditional branching directive is allowed per node");
|
throw new Error("Only one conditional branching directive is allowed per node");
|
||||||
}
|
}
|
||||||
// All text nodes between branch nodes are removed
|
// All text (with only spaces) and comment nodes (nodeType 8) between
|
||||||
|
// branch nodes are removed
|
||||||
let textNode;
|
let textNode;
|
||||||
while ((textNode = node.previousSibling) !== prevElem) {
|
while ((textNode = node.previousSibling) !== prevElem) {
|
||||||
if (textNode.nodeValue.trim().length) {
|
if (textNode.nodeValue.trim().length && textNode.nodeType !== 8) {
|
||||||
throw new Error("text is not allowed between branching directives");
|
throw new Error("text is not allowed between branching directives");
|
||||||
}
|
}
|
||||||
textNode.remove();
|
textNode.remove();
|
||||||
@@ -400,30 +456,34 @@ export class QWeb extends EventBus {
|
|||||||
|
|
||||||
_compile(
|
_compile(
|
||||||
name: string,
|
name: string,
|
||||||
elem: Element,
|
options: {
|
||||||
parentContext?: CompilationContext,
|
elem?: Element;
|
||||||
defineKey?: boolean
|
hasParent?: boolean;
|
||||||
|
defineKey?: boolean;
|
||||||
|
} = {}
|
||||||
): CompiledTemplate {
|
): CompiledTemplate {
|
||||||
|
const elem = options.elem || this.templates[name].elem;
|
||||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
||||||
const ctx = new CompilationContext(name);
|
const ctx = new CompilationContext(name);
|
||||||
if (elem.tagName !== "t") {
|
if (elem.tagName !== "t") {
|
||||||
ctx.shouldDefineResult = false;
|
ctx.shouldDefineResult = false;
|
||||||
}
|
}
|
||||||
if (parentContext) {
|
if (options.hasParent) {
|
||||||
ctx.variables = Object.create(parentContext.variables);
|
ctx.variables = Object.create(null);
|
||||||
ctx.parentNode = parentContext.parentNode || ctx.generateID();
|
ctx.parentNode = ctx.generateID();
|
||||||
ctx.allowMultipleRoots = true;
|
ctx.allowMultipleRoots = true;
|
||||||
|
ctx.shouldDefineParent = true;
|
||||||
ctx.hasParentWidget = true;
|
ctx.hasParentWidget = true;
|
||||||
ctx.shouldDefineResult = false;
|
ctx.shouldDefineResult = false;
|
||||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
||||||
if (defineKey) {
|
if (options.defineKey) {
|
||||||
ctx.addLine(`let key0 = extra.key || "";`);
|
ctx.addLine(`let key0 = extra.key || "";`);
|
||||||
ctx.hasKey0 = true;
|
ctx.hasKey0 = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this._compileNode(elem, ctx);
|
this._compileNode(elem, ctx);
|
||||||
|
|
||||||
if (!parentContext) {
|
if (!options.hasParent) {
|
||||||
if (ctx.shouldDefineResult) {
|
if (ctx.shouldDefineResult) {
|
||||||
ctx.addLine(`return result;`);
|
ctx.addLine(`return result;`);
|
||||||
} else {
|
} else {
|
||||||
@@ -475,7 +535,8 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
if (this.translateFn) {
|
if (this.translateFn) {
|
||||||
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
||||||
text = this.translateFn(text);
|
const match = translationRE.exec(text);
|
||||||
|
text = match[1] + this.translateFn(match[2]) + match[3];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
@@ -498,10 +559,21 @@ export class QWeb extends EventBus {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (node.tagName !== "t" && node.hasAttribute("t-call")) {
|
||||||
|
const tCallNode = document.implementation.createDocument(
|
||||||
|
"http://www.w3.org/1999/xhtml",
|
||||||
|
"t",
|
||||||
|
null
|
||||||
|
).documentElement;
|
||||||
|
tCallNode.setAttribute("t-call", node.getAttribute("t-call")!);
|
||||||
|
node.removeAttribute("t-call");
|
||||||
|
node.prepend(tCallNode);
|
||||||
|
}
|
||||||
|
|
||||||
const firstLetter = node.tagName[0];
|
const firstLetter = node.tagName[0];
|
||||||
if (firstLetter === firstLetter.toUpperCase()) {
|
if (firstLetter === firstLetter.toUpperCase()) {
|
||||||
// this is a component, we modify in place the xml document to change
|
// this is a component, we modify in place the xml document to change
|
||||||
// <SomeComponent ... /> to <t t-component="SomeComponent" ... />
|
// <SomeComponent ... /> to <SomeComponent t-component="SomeComponent" ... />
|
||||||
node.setAttribute("t-component", node.tagName);
|
node.setAttribute("t-component", node.tagName);
|
||||||
} else if (node.tagName !== "t" && node.hasAttribute("t-component")) {
|
} else if (node.tagName !== "t" && node.hasAttribute("t-component")) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -528,7 +600,11 @@ export class QWeb extends EventBus {
|
|||||||
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
||||||
}
|
}
|
||||||
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
|
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
|
||||||
const tNode = document.createElement("t");
|
const tNode = document.implementation.createDocument(
|
||||||
|
"http://www.w3.org/1999/xhtml",
|
||||||
|
"t",
|
||||||
|
null
|
||||||
|
).documentElement;
|
||||||
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
|
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
|
||||||
for (let child of Array.from(node.childNodes)) {
|
for (let child of Array.from(node.childNodes)) {
|
||||||
tNode.appendChild(child);
|
tNode.appendChild(child);
|
||||||
@@ -573,7 +649,7 @@ export class QWeb extends EventBus {
|
|||||||
qweb: this,
|
qweb: this,
|
||||||
ctx,
|
ctx,
|
||||||
fullName,
|
fullName,
|
||||||
value
|
value,
|
||||||
});
|
});
|
||||||
if (isDone) {
|
if (isDone) {
|
||||||
for (let { directive, value, fullName } of finalizers) {
|
for (let { directive, value, fullName } of finalizers) {
|
||||||
@@ -584,14 +660,22 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.nodeName !== "t") {
|
if (node.nodeName !== "t" || node.hasAttribute("t-tag")) {
|
||||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
|
||||||
ctx = ctx.withParent(nodeID);
|
|
||||||
let nodeHooks = {};
|
let nodeHooks = {};
|
||||||
let addNodeHook = function(hook, handler) {
|
let addNodeHook = function (hook, handler) {
|
||||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||||
nodeHooks[hook].push(handler);
|
nodeHooks[hook].push(handler);
|
||||||
};
|
};
|
||||||
|
if (node.tagName === "select" && node.hasAttribute("t-att-value")) {
|
||||||
|
const value = node.getAttribute("t-att-value");
|
||||||
|
let exprId = ctx.generateID();
|
||||||
|
ctx.addLine(`let expr${exprId} = ${ctx.formatExpression(value)};`);
|
||||||
|
let expr = `expr${exprId}`;
|
||||||
|
node.setAttribute("t-att-value", expr);
|
||||||
|
addNodeHook("create", `n.elm.value=${expr};`);
|
||||||
|
}
|
||||||
|
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||||
|
ctx = ctx.withParent(nodeID);
|
||||||
|
|
||||||
for (let { directive, value, fullName } of validDirectives) {
|
for (let { directive, value, fullName } of validDirectives) {
|
||||||
if (directive.atNodeCreation) {
|
if (directive.atNodeCreation) {
|
||||||
@@ -602,7 +686,7 @@ export class QWeb extends EventBus {
|
|||||||
fullName,
|
fullName,
|
||||||
value,
|
value,
|
||||||
nodeID,
|
nodeID,
|
||||||
addNodeHook
|
addNodeHook,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -655,25 +739,36 @@ export class QWeb extends EventBus {
|
|||||||
const props: string[] = [];
|
const props: string[] = [];
|
||||||
const tattrs: number[] = [];
|
const tattrs: number[] = [];
|
||||||
|
|
||||||
function handleBooleanProps(key, val) {
|
function handleProperties(key, val) {
|
||||||
let isProp = false;
|
let isProp = false;
|
||||||
if (node.nodeName === "input" && key === "checked") {
|
switch (node.nodeName) {
|
||||||
let type = (<Element>node).getAttribute("type");
|
case "input":
|
||||||
if (type === "checkbox" || type === "radio") {
|
let type = (<Element>node).getAttribute("type");
|
||||||
isProp = true;
|
if (type === "checkbox" || type === "radio") {
|
||||||
}
|
if (key === "checked" || key === "indeterminate") {
|
||||||
}
|
isProp = true;
|
||||||
if (node.nodeName === "option" && key === "selected") {
|
}
|
||||||
isProp = true;
|
}
|
||||||
}
|
if (key === "value" || key === "readonly" || key === "disabled") {
|
||||||
if (key === "disabled" && DISABLED_TAGS.indexOf(node.nodeName) > -1) {
|
isProp = true;
|
||||||
isProp = true;
|
}
|
||||||
}
|
break;
|
||||||
if ((key === "readonly" && node.nodeName === "input") || node.nodeName === "textarea") {
|
case "option":
|
||||||
isProp = true;
|
isProp = key === "selected" || key === "disabled";
|
||||||
|
break;
|
||||||
|
case "textarea":
|
||||||
|
isProp = key === "readonly" || key === "disabled" || key === "value";
|
||||||
|
break;
|
||||||
|
case "select":
|
||||||
|
isProp = key === "disabled" || key === "value";
|
||||||
|
break;
|
||||||
|
case "button":
|
||||||
|
case "optgroup":
|
||||||
|
isProp = key === "disabled";
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
if (isProp) {
|
if (isProp) {
|
||||||
props.push(`${key}: _${val}`);
|
props.push(`${key}: ${val}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let classObj = "";
|
let classObj = "";
|
||||||
@@ -693,19 +788,23 @@ export class QWeb extends EventBus {
|
|||||||
if ((value = value.trim())) {
|
if ((value = value.trim())) {
|
||||||
let classDef = value
|
let classDef = value
|
||||||
.split(/\s+/)
|
.split(/\s+/)
|
||||||
.map(a => `'${a}':true`)
|
.map((a) => `'${escapeQuotes(a)}':true`)
|
||||||
.join(",");
|
.join(",");
|
||||||
classObj = `_${ctx.generateID()}`;
|
if (classObj) {
|
||||||
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
ctx.addLine(`Object.assign(${classObj}, {${classDef}})`);
|
||||||
|
} else {
|
||||||
|
classObj = `_${ctx.generateID()}`;
|
||||||
|
ctx.addLine(`let ${classObj} = {${classDef}};`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ctx.addLine(`let _${attID} = '${value}';`);
|
ctx.addLine(`let _${attID} = '${escapeQuotes(value)}';`);
|
||||||
if (!name.match(/^[a-zA-Z]+$/)) {
|
if (!name.match(/^[a-zA-Z]+$/)) {
|
||||||
// attribute contains 'non letters' => we want to quote it
|
// attribute contains 'non letters' => we want to quote it
|
||||||
name = '"' + name + '"';
|
name = '"' + name + '"';
|
||||||
}
|
}
|
||||||
attrs.push(`${name}: _${attID}`);
|
attrs.push(`${name}: _${attID}`);
|
||||||
handleBooleanProps(name, attID);
|
handleProperties(name, `_${attID}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -717,7 +816,7 @@ export class QWeb extends EventBus {
|
|||||||
|
|
||||||
if (attName === "class") {
|
if (attName === "class") {
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
formattedValue = `utils.toObj(${formattedValue})`;
|
formattedValue = `utils.toClassObj(${formattedValue})`;
|
||||||
if (classObj) {
|
if (classObj) {
|
||||||
ctx.addLine(`Object.assign(${classObj}, ${formattedValue})`);
|
ctx.addLine(`Object.assign(${classObj}, ${formattedValue})`);
|
||||||
} else {
|
} else {
|
||||||
@@ -737,12 +836,17 @@ export class QWeb extends EventBus {
|
|||||||
const attValueID = ctx.generateID();
|
const attValueID = ctx.generateID();
|
||||||
ctx.addLine(`let _${attValueID} = ${formattedValue};`);
|
ctx.addLine(`let _${attValueID} = ${formattedValue};`);
|
||||||
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
|
||||||
const attrIndex = attrs.findIndex(att => att.startsWith(attName + ":"));
|
const attrIndex = attrs.findIndex((att) => att.startsWith(attName + ":"));
|
||||||
attrs.splice(attrIndex, 1);
|
attrs.splice(attrIndex, 1);
|
||||||
}
|
}
|
||||||
ctx.addLine(`let _${attID} = ${formattedValue};`);
|
if (node.nodeName === "select" && attName === "value") {
|
||||||
attrs.push(`${attName}: _${attID}`);
|
attrs.push(`${attName}: ${v}`);
|
||||||
handleBooleanProps(attName, attID);
|
handleProperties(attName, v);
|
||||||
|
} else {
|
||||||
|
ctx.addLine(`let _${attID} = ${formattedValue};`);
|
||||||
|
attrs.push(`${attName}: _${attID}`);
|
||||||
|
handleProperties(attName, "_" + attID);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -798,7 +902,14 @@ export class QWeb extends EventBus {
|
|||||||
ctx.addLine(`}`);
|
ctx.addLine(`}`);
|
||||||
ctx.closeIf();
|
ctx.closeIf();
|
||||||
}
|
}
|
||||||
ctx.addLine(`let vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`);
|
let nodeName = `'${node.nodeName}'`;
|
||||||
|
if ((<Element>node).hasAttribute("t-tag")) {
|
||||||
|
const tagExpr = (<Element>node).getAttribute("t-tag");
|
||||||
|
(<Element>node).removeAttribute("t-tag");
|
||||||
|
nodeName = `tag${ctx.generateID()}`;
|
||||||
|
ctx.addLine(`let ${nodeName} = ${ctx.formatExpression(tagExpr)};`);
|
||||||
|
}
|
||||||
|
ctx.addLine(`let vn${nodeID} = h(${nodeName}, p${nodeID}, c${nodeID});`);
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
|
||||||
} else if (ctx.loopNumber || ctx.hasKey0) {
|
} else if (ctx.loopNumber || ctx.hasKey0) {
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ import { Destination, RouterEnv } from "./router";
|
|||||||
|
|
||||||
type Props = Destination;
|
type Props = Destination;
|
||||||
|
|
||||||
export class Link<Env extends RouterEnv> extends Component<Env, Props> {
|
export class Link<Env extends RouterEnv> extends Component<Props, Env> {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<a t-att-class="{'router-link-active': isActive }"
|
<a t-att-class="{'router-link-active': isActive }"
|
||||||
t-att-href="href"
|
t-att-href="href"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Component } from "../component/component";
|
import { Component } from "../component/component";
|
||||||
import { xml } from "../tags";
|
import { xml } from "../tags";
|
||||||
|
import { EnvWithRouter } from "./router";
|
||||||
|
|
||||||
export class RouteComponent extends Component<any, {}> {
|
export class RouteComponent extends Component<{}, EnvWithRouter> {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<t>
|
<t>
|
||||||
<t
|
<t
|
||||||
|
|||||||
+55
-36
@@ -11,6 +11,7 @@ type NavigationGuard = (info: {
|
|||||||
export interface Route {
|
export interface Route {
|
||||||
name: string;
|
name: string;
|
||||||
path: string;
|
path: string;
|
||||||
|
extractionRegExp: RegExp;
|
||||||
component?: any;
|
component?: any;
|
||||||
redirect?: Destination;
|
redirect?: Destination;
|
||||||
params: string[];
|
params: string[];
|
||||||
@@ -49,7 +50,12 @@ interface Options {
|
|||||||
mode: Router["mode"];
|
mode: Router["mode"];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface EnvWithRouter extends Env {
|
||||||
|
router: Router;
|
||||||
|
}
|
||||||
|
|
||||||
const paramRegexp = /\{\{(.*?)\}\}/;
|
const paramRegexp = /\{\{(.*?)\}\}/;
|
||||||
|
const globalParamRegexp = new RegExp(paramRegexp.source, "g");
|
||||||
|
|
||||||
export class Router {
|
export class Router {
|
||||||
currentRoute: Route | null = null;
|
currentRoute: Route | null = null;
|
||||||
@@ -60,7 +66,11 @@ export class Router {
|
|||||||
routeIds: string[];
|
routeIds: string[];
|
||||||
env: RouterEnv;
|
env: RouterEnv;
|
||||||
|
|
||||||
constructor(env: Env, routes: Partial<Route>[], options: Options = { mode: "history" }) {
|
constructor(
|
||||||
|
env: Partial<EnvWithRouter>,
|
||||||
|
routes: Partial<Route>[],
|
||||||
|
options: Options = { mode: "history" }
|
||||||
|
) {
|
||||||
env.router = this;
|
env.router = this;
|
||||||
this.mode = options.mode;
|
this.mode = options.mode;
|
||||||
this.env = env as RouterEnv;
|
this.env = env as RouterEnv;
|
||||||
@@ -79,6 +89,7 @@ export class Router {
|
|||||||
this.validateDestination(partialRoute.redirect);
|
this.validateDestination(partialRoute.redirect);
|
||||||
}
|
}
|
||||||
partialRoute.params = partialRoute.path ? findParams(partialRoute.path) : [];
|
partialRoute.params = partialRoute.path ? findParams(partialRoute.path) : [];
|
||||||
|
partialRoute.extractionRegExp = makeExtractionRegExp(partialRoute.path);
|
||||||
this.routes[partialRoute.name] = partialRoute as Route;
|
this.routes[partialRoute.name] = partialRoute as Route;
|
||||||
this.routeIds.push(partialRoute.name);
|
this.routeIds.push(partialRoute.name);
|
||||||
}
|
}
|
||||||
@@ -89,7 +100,7 @@ export class Router {
|
|||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
(this as any)._listener = ev => this._navigate(this.currentPath(), ev);
|
(this as any)._listener = (ev) => this._navigate(this.currentPath(), ev);
|
||||||
window.addEventListener("popstate", (this as any)._listener);
|
window.addEventListener("popstate", (this as any)._listener);
|
||||||
if (this.mode === "hash") {
|
if (this.mode === "hash") {
|
||||||
window.addEventListener("hashchange", (this as any)._listener);
|
window.addEventListener("hashchange", (this as any)._listener);
|
||||||
@@ -114,7 +125,10 @@ export class Router {
|
|||||||
const initialParams = this.currentParams;
|
const initialParams = this.currentParams;
|
||||||
const result = await this.matchAndApplyRules(path);
|
const result = await this.matchAndApplyRules(path);
|
||||||
if (result.type === "match") {
|
if (result.type === "match") {
|
||||||
const finalPath = this.routeToPath(result.route, result.params);
|
let finalPath = this.routeToPath(result.route, result.params);
|
||||||
|
if (path.indexOf("?") > -1) {
|
||||||
|
finalPath += "?" + path.split("?")[1];
|
||||||
|
}
|
||||||
const isPopStateEvent = ev && ev instanceof PopStateEvent;
|
const isPopStateEvent = ev && ev instanceof PopStateEvent;
|
||||||
if (!isPopStateEvent) {
|
if (!isPopStateEvent) {
|
||||||
this.setUrlFromPath(finalPath);
|
this.setUrlFromPath(finalPath);
|
||||||
@@ -162,19 +176,14 @@ export class Router {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private routeToPath(route: Route, params: RouteParams): string {
|
private routeToPath(route: Route, params: RouteParams): string {
|
||||||
const path = route.path;
|
|
||||||
const parts = path.split("/");
|
|
||||||
const l = parts.length;
|
|
||||||
for (let i = 0; i < l; i++) {
|
|
||||||
const part = parts[i];
|
|
||||||
const match = part.match(paramRegexp);
|
|
||||||
if (match) {
|
|
||||||
const key = match[1].split(".")[0];
|
|
||||||
parts[i] = <string>params[key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const prefix = this.mode === "hash" ? "#" : "";
|
const prefix = this.mode === "hash" ? "#" : "";
|
||||||
return prefix + parts.join("/");
|
return (
|
||||||
|
prefix +
|
||||||
|
route.path.replace(globalParamRegexp, (match, param) => {
|
||||||
|
const [key] = param.split(".");
|
||||||
|
return <string>params[key];
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private currentPath(): string {
|
private currentPath(): string {
|
||||||
@@ -190,7 +199,7 @@ export class Router {
|
|||||||
return {
|
return {
|
||||||
type: "match",
|
type: "match",
|
||||||
route: route,
|
route: route,
|
||||||
params: params
|
params: params,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,7 +224,7 @@ export class Router {
|
|||||||
const result = await route.beforeRouteEnter({
|
const result = await route.beforeRouteEnter({
|
||||||
env: this.env,
|
env: this.env,
|
||||||
from: this.currentRoute,
|
from: this.currentRoute,
|
||||||
to: route
|
to: route,
|
||||||
});
|
});
|
||||||
if (result === false) {
|
if (result === false) {
|
||||||
return { type: "cancelled" };
|
return { type: "cancelled" };
|
||||||
@@ -233,43 +242,53 @@ export class Router {
|
|||||||
if (route.path === "*") {
|
if (route.path === "*") {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
if (path.indexOf("?") > -1) {
|
||||||
|
path = path.split("?")[0];
|
||||||
|
}
|
||||||
if (path.startsWith("#")) {
|
if (path.startsWith("#")) {
|
||||||
path = path.slice(1);
|
path = path.slice(1);
|
||||||
}
|
}
|
||||||
const descrParts = route.path.split("/");
|
const paramsMatch = path.match(route.extractionRegExp);
|
||||||
const targetParts = path.split("/");
|
if (!paramsMatch) {
|
||||||
const l = descrParts.length;
|
|
||||||
if (l !== targetParts.length) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const result = {};
|
const result = {};
|
||||||
for (let i = 0; i < l; i++) {
|
route.params.forEach((param, index) => {
|
||||||
const descr = descrParts[i];
|
const [key, suffix] = param.split(".");
|
||||||
let target: string | number = targetParts[i];
|
const paramValue = paramsMatch[index + 1];
|
||||||
const match = descr.match(paramRegexp);
|
if (suffix === "number") {
|
||||||
if (match) {
|
return (result[key] = parseInt(paramValue, 10));
|
||||||
const [key, suffix] = match[1].split(".");
|
|
||||||
if (suffix === "number") {
|
|
||||||
target = parseInt(target, 10);
|
|
||||||
}
|
|
||||||
result[key] = target;
|
|
||||||
} else if (descr !== target) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
return (result[key] = paramValue);
|
||||||
|
});
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function findParams(str: string): string[] {
|
function findParams(str: string): string[] {
|
||||||
const globalParamRegexp = /\{\{(.*?)\}\}/g;
|
|
||||||
const result: string[] = [];
|
const result: string[] = [];
|
||||||
let m;
|
let m;
|
||||||
do {
|
do {
|
||||||
m = globalParamRegexp.exec(str);
|
m = globalParamRegexp.exec(str);
|
||||||
if (m) {
|
if (m) {
|
||||||
result.push(m[1].split(".")[0]);
|
result.push(m[1]);
|
||||||
}
|
}
|
||||||
} while (m);
|
} while (m);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escapeRegExp(str: string) {
|
||||||
|
return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeExtractionRegExp(path: string) {
|
||||||
|
// replace param strings with capture groups so that we can build a regex to match over the path
|
||||||
|
const extractionString = path
|
||||||
|
.split(paramRegexp)
|
||||||
|
.map((part, index) => {
|
||||||
|
return index % 2 ? "(.*)" : escapeRegExp(part);
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
// Example: /home/{{param1}}/{{param2}} => ^\/home\/(.*)\/(.*)$
|
||||||
|
return new RegExp(`^${extractionString}$`);
|
||||||
|
}
|
||||||
|
|||||||
+29
-15
@@ -1,5 +1,4 @@
|
|||||||
import { Component } from "./component/component";
|
import { Component, Env } from "./component/component";
|
||||||
import { Env } from "./component/component";
|
|
||||||
import { Context, useContextWithCB } from "./context";
|
import { Context, useContextWithCB } from "./context";
|
||||||
import { onWillUpdateProps } from "./hooks";
|
import { onWillUpdateProps } from "./hooks";
|
||||||
|
|
||||||
@@ -24,6 +23,10 @@ import { onWillUpdateProps } from "./hooks";
|
|||||||
// Store Definition
|
// Store Definition
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export interface EnvWithStore extends Env {
|
||||||
|
store: Store;
|
||||||
|
}
|
||||||
|
|
||||||
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
||||||
export type Getter = ({ state: any, getters }, payload?) => any;
|
export type Getter = ({ state: any, getters }, payload?) => any;
|
||||||
|
|
||||||
@@ -49,7 +52,7 @@ export class Store extends Context {
|
|||||||
if (config.getters) {
|
if (config.getters) {
|
||||||
const firstArg = {
|
const firstArg = {
|
||||||
state: this.state,
|
state: this.state,
|
||||||
getters: this.getters
|
getters: this.getters,
|
||||||
};
|
};
|
||||||
for (let g in config.getters) {
|
for (let g in config.getters) {
|
||||||
this.getters[g] = config.getters[g].bind(this, firstArg);
|
this.getters[g] = config.getters[g].bind(this, firstArg);
|
||||||
@@ -66,12 +69,17 @@ export class Store extends Context {
|
|||||||
dispatch: this.dispatch.bind(this),
|
dispatch: this.dispatch.bind(this),
|
||||||
env: this.env,
|
env: this.env,
|
||||||
state: this.state,
|
state: this.state,
|
||||||
getters: this.getters
|
getters: this.getters,
|
||||||
},
|
},
|
||||||
...payload
|
...payload
|
||||||
);
|
);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
__notifyComponents(): Promise<void> {
|
||||||
|
this.trigger("before-update");
|
||||||
|
return super.__notifyComponents();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SelectorOptions {
|
interface SelectorOptions {
|
||||||
@@ -83,7 +91,7 @@ interface SelectorOptions {
|
|||||||
const isStrictEqual = (a, b) => a === b;
|
const isStrictEqual = (a, b) => a === b;
|
||||||
|
|
||||||
export function useStore(selector, options: SelectorOptions = {}): any {
|
export function useStore(selector, options: SelectorOptions = {}): any {
|
||||||
const component: Component<any, any> = Component.current!;
|
const component = Component.current as Component<any, EnvWithStore>;
|
||||||
const componentId = component.__owl__.id;
|
const componentId = component.__owl__.id;
|
||||||
const store = options.store || (component.env.store as Store);
|
const store = options.store || (component.env.store as Store);
|
||||||
if (!(store instanceof Store)) {
|
if (!(store instanceof Store)) {
|
||||||
@@ -102,18 +110,21 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
|||||||
const newRevNumber = hashFn(result);
|
const newRevNumber = hashFn(result);
|
||||||
if ((newRevNumber > 0 && revNumber !== newRevNumber) || !isEqual(oldResult, result)) {
|
if ((newRevNumber > 0 && revNumber !== newRevNumber) || !isEqual(oldResult, result)) {
|
||||||
revNumber = newRevNumber;
|
revNumber = newRevNumber;
|
||||||
if (options.onUpdate) {
|
|
||||||
options.onUpdate(result);
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
store.updateFunctions[componentId].push(function(): boolean {
|
if (options.onUpdate) {
|
||||||
|
store.on("before-update", component, () => {
|
||||||
|
const newValue = selector(store!.state, component.props!);
|
||||||
|
options.onUpdate(newValue);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
store.updateFunctions[componentId].push(function (): boolean {
|
||||||
return selectCompareUpdate(store!.state, component.props);
|
return selectCompareUpdate(store!.state, component.props);
|
||||||
});
|
});
|
||||||
|
|
||||||
useContextWithCB(store, component, function(): Promise<void> | void {
|
useContextWithCB(store, component, function (): Promise<void> | void {
|
||||||
let shouldRender = false;
|
let shouldRender = false;
|
||||||
for (let fn of store.updateFunctions[componentId]) {
|
for (let fn of store.updateFunctions[componentId]) {
|
||||||
shouldRender = fn() || shouldRender;
|
shouldRender = fn() || shouldRender;
|
||||||
@@ -122,13 +133,16 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
|||||||
return component.render();
|
return component.render();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
onWillUpdateProps(props => {
|
onWillUpdateProps((props) => {
|
||||||
selectCompareUpdate(store.state, props);
|
selectCompareUpdate(store.state, props);
|
||||||
});
|
});
|
||||||
|
|
||||||
const __destroy = component.__destroy;
|
const __destroy = component.__destroy;
|
||||||
component.__destroy = parent => {
|
component.__destroy = (parent) => {
|
||||||
delete store.updateFunctions[componentId];
|
delete store.updateFunctions[componentId];
|
||||||
|
if (options.onUpdate) {
|
||||||
|
store.off("before-update", component);
|
||||||
|
}
|
||||||
__destroy.call(component, parent);
|
__destroy.call(component, parent);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -144,16 +158,16 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
|||||||
},
|
},
|
||||||
has(target, k) {
|
has(target, k) {
|
||||||
return k in result;
|
return k in result;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDispatch(store?: Store): Store["dispatch"] {
|
export function useDispatch(store?: Store): Store["dispatch"] {
|
||||||
store = store || (Component.current!.env.store as Store);
|
store = store || (Component.current!.env as EnvWithStore).store;
|
||||||
return store.dispatch.bind(store);
|
return store.dispatch.bind(store);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGetters(store?: Store): Store["getters"] {
|
export function useGetters(store?: Store): Store["getters"] {
|
||||||
store = store || (Component.current!.env.store as Store);
|
store = store || (Component.current!.env as EnvWithStore).store;
|
||||||
return store.getters;
|
return store.getters;
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-9
@@ -10,14 +10,16 @@
|
|||||||
* - debounce
|
* - debounce
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { browser } from "./browser";
|
||||||
|
|
||||||
export function whenReady(fn?: any) {
|
export function whenReady(fn?: any) {
|
||||||
return new Promise(function(resolve) {
|
return new Promise(function (resolve) {
|
||||||
if (document.readyState !== "loading") {
|
if (document.readyState !== "loading") {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
document.addEventListener("DOMContentLoaded", resolve, false);
|
document.addEventListener("DOMContentLoaded", resolve, false);
|
||||||
}
|
}
|
||||||
}).then(fn || function() {});
|
}).then(fn || function () {});
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadedScripts: { [key: string]: Promise<void> } = {};
|
const loadedScripts: { [key: string]: Promise<void> } = {};
|
||||||
@@ -26,14 +28,14 @@ export function loadJS(url: string): Promise<void> {
|
|||||||
if (url in loadedScripts) {
|
if (url in loadedScripts) {
|
||||||
return loadedScripts[url];
|
return loadedScripts[url];
|
||||||
}
|
}
|
||||||
const promise: Promise<void> = new Promise(function(resolve, reject) {
|
const promise: Promise<void> = new Promise(function (resolve, reject) {
|
||||||
const script = document.createElement("script");
|
const script = document.createElement("script");
|
||||||
script.type = "text/javascript";
|
script.type = "text/javascript";
|
||||||
script.src = url;
|
script.src = url;
|
||||||
script.onload = function() {
|
script.onload = function () {
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
script.onerror = function() {
|
script.onerror = function () {
|
||||||
reject(`Error loading file '${url}'`);
|
reject(`Error loading file '${url}'`);
|
||||||
};
|
};
|
||||||
const head = document.head || document.getElementsByTagName("head")[0];
|
const head = document.head || document.getElementsByTagName("head")[0];
|
||||||
@@ -44,7 +46,7 @@ export function loadJS(url: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function loadFile(url: string): Promise<string> {
|
export async function loadFile(url: string): Promise<string> {
|
||||||
const result = await fetch(url);
|
const result = await browser.fetch(url);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
throw new Error("Error while fetching xml templates");
|
throw new Error("Error while fetching xml templates");
|
||||||
}
|
}
|
||||||
@@ -73,7 +75,7 @@ export function escape(str: string | number | undefined): string {
|
|||||||
*/
|
*/
|
||||||
export function debounce(func: Function, wait: number, immediate?: boolean): Function {
|
export function debounce(func: Function, wait: number, immediate?: boolean): Function {
|
||||||
let timeout;
|
let timeout;
|
||||||
return function(this: any) {
|
return function (this: any) {
|
||||||
const context = this;
|
const context = this;
|
||||||
const args = arguments;
|
const args = arguments;
|
||||||
function later() {
|
function later() {
|
||||||
@@ -83,8 +85,8 @@ export function debounce(func: Function, wait: number, immediate?: boolean): Fun
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const callNow = immediate && !timeout;
|
const callNow = immediate && !timeout;
|
||||||
clearTimeout(timeout);
|
browser.clearTimeout(timeout);
|
||||||
timeout = setTimeout(later, wait);
|
timeout = browser.setTimeout(later, wait);
|
||||||
if (callNow) {
|
if (callNow) {
|
||||||
func.apply(context, args);
|
func.apply(context, args);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { VNode, h } from "./vdom";
|
import { VNode, h, addNS } from "./vdom";
|
||||||
|
|
||||||
const parser = new DOMParser();
|
const parser = new DOMParser();
|
||||||
|
|
||||||
@@ -13,6 +13,9 @@ export function htmlToVDOM(html: string): VNode[] {
|
|||||||
|
|
||||||
function htmlToVNode(node: ChildNode): VNode {
|
function htmlToVNode(node: ChildNode): VNode {
|
||||||
if (!(node instanceof Element)) {
|
if (!(node instanceof Element)) {
|
||||||
|
if (node instanceof Comment) {
|
||||||
|
return h("!", node.textContent);
|
||||||
|
}
|
||||||
return { text: node.textContent! } as VNode;
|
return { text: node.textContent! } as VNode;
|
||||||
}
|
}
|
||||||
const attrs = {};
|
const attrs = {};
|
||||||
@@ -23,5 +26,9 @@ function htmlToVNode(node: ChildNode): VNode {
|
|||||||
for (let c of node.childNodes) {
|
for (let c of node.childNodes) {
|
||||||
children.push(htmlToVNode(c));
|
children.push(htmlToVNode(c));
|
||||||
}
|
}
|
||||||
return h((node as Element).tagName, { attrs }, children);
|
const vnode = h((node as Element).tagName, { attrs }, children);
|
||||||
|
if (vnode.sel === "svg") {
|
||||||
|
addNS(vnode.data, (vnode as any).children, vnode.sel);
|
||||||
|
}
|
||||||
|
return vnode;
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-10
@@ -33,7 +33,7 @@ function updateProps(oldVnode: VNode, vnode: VNode): void {
|
|||||||
|
|
||||||
export const propsModule = {
|
export const propsModule = {
|
||||||
create: updateProps,
|
create: updateProps,
|
||||||
update: updateProps
|
update: updateProps,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -70,8 +70,12 @@ function handleEvent(event: Event, vnode: VNode) {
|
|||||||
on = (vnode.data as VNodeData).on;
|
on = (vnode.data as VNodeData).on;
|
||||||
|
|
||||||
// call event handler(s) if exists
|
// call event handler(s) if exists
|
||||||
if (on && on[name]) {
|
if (on) {
|
||||||
invokeHandler(on[name], vnode, event);
|
if (on[name]) {
|
||||||
|
invokeHandler(on[name], vnode, event);
|
||||||
|
} else if (on["!" + name]) {
|
||||||
|
invokeHandler(on["!" + name], vnode, event);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,13 +104,17 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
if (!on) {
|
if (!on) {
|
||||||
for (name in oldOn) {
|
for (name in oldOn) {
|
||||||
// remove listener if element was changed or existing listeners removed
|
// remove listener if element was changed or existing listeners removed
|
||||||
oldElm.removeEventListener(name, oldListener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
oldElm.removeEventListener(name, oldListener, capture);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (name in oldOn) {
|
for (name in oldOn) {
|
||||||
// remove listener if existing listener removed
|
// remove listener if existing listener removed
|
||||||
if (!on[name]) {
|
if (!on[name]) {
|
||||||
oldElm.removeEventListener(name, oldListener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
oldElm.removeEventListener(name, oldListener, capture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -123,13 +131,17 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
if (!oldOn) {
|
if (!oldOn) {
|
||||||
for (name in on) {
|
for (name in on) {
|
||||||
// add listener if element was changed or new listeners added
|
// add listener if element was changed or new listeners added
|
||||||
elm.addEventListener(name, listener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
elm.addEventListener(name, listener, capture);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (name in on) {
|
for (name in on) {
|
||||||
// add listener if new listener added
|
// add listener if new listener added
|
||||||
if (!oldOn[name]) {
|
if (!oldOn[name]) {
|
||||||
elm.addEventListener(name, listener, false);
|
const capture = name.charAt(0) === "!";
|
||||||
|
name = capture ? name.slice(1) : name;
|
||||||
|
elm.addEventListener(name, listener, capture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,7 +151,7 @@ function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
|
|||||||
export const eventListenersModule = {
|
export const eventListenersModule = {
|
||||||
create: updateEventListeners,
|
create: updateEventListeners,
|
||||||
update: updateEventListeners,
|
update: updateEventListeners,
|
||||||
destroy: updateEventListeners
|
destroy: updateEventListeners,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -198,7 +210,7 @@ function updateAttrs(oldVnode: VNode, vnode: VNode): void {
|
|||||||
|
|
||||||
export const attrsModule = {
|
export const attrsModule = {
|
||||||
create: updateAttrs,
|
create: updateAttrs,
|
||||||
update: updateAttrs
|
update: updateAttrs,
|
||||||
} as Module;
|
} as Module;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -219,7 +231,8 @@ function updateClass(oldVnode: VNode, vnode: VNode): void {
|
|||||||
elm = vnode.elm as Element;
|
elm = vnode.elm as Element;
|
||||||
|
|
||||||
for (name in oldClass) {
|
for (name in oldClass) {
|
||||||
if (name && !klass[name]) {
|
if (name && !klass[name] && !Object.prototype.hasOwnProperty.call(klass, name)) {
|
||||||
|
// was `true` and now not provided
|
||||||
elm.classList.remove(name);
|
elm.classList.remove(name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -520,7 +520,7 @@ const htmlDomApi = {
|
|||||||
parentNode,
|
parentNode,
|
||||||
nextSibling,
|
nextSibling,
|
||||||
tagName,
|
tagName,
|
||||||
setTextContent
|
setTextContent,
|
||||||
} as DOMAPI;
|
} as DOMAPI;
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -24,11 +24,11 @@ exports[`animations t-transition combined with component 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
const __patch2 = w2.__patch;
|
const __patch2 = w2.__patch;
|
||||||
w2.__patch = fiber => {__patch2.call(w2, fiber); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
@@ -69,11 +69,11 @@ exports[`animations t-transition combined with t-component and t-if 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
const __patch2 = w2.__patch;
|
const __patch2 = w2.__patch;
|
||||||
w2.__patch = fiber => {__patch2.call(w2, fiber); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
@@ -115,11 +115,11 @@ exports[`animations t-transition combined with t-component, remove and re-add be
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
const __patch2 = w2.__patch;
|
const __patch2 = w2.__patch;
|
||||||
w2.__patch = fiber => {__patch2.call(w2, fiber); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
w2.__patch = (t, vn) => {__patch2.call(w2, t, vn); if(!w2.__owl__.transitionInserted){w2.__owl__.transitionInserted = true;utils.transitionInsert(w2.__owl__.vnode, 'chimay');}};
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||||
@@ -177,3 +177,24 @@ exports[`animations t-transition, on a simple node (insert) 1`] = `
|
|||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`animations t-transition, on a simple node, not in the DOM 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('span', p1, c1);
|
||||||
|
p1.hook = {
|
||||||
|
insert: vn => {
|
||||||
|
utils.transitionInsert(vn, 'chimay');
|
||||||
|
},
|
||||||
|
remove: (vn, rm) => {
|
||||||
|
utils.transitionRemove(vn, 'chimay', rm);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
c1.push({text: \`blue\`});
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|||||||
+44
-21
@@ -1,15 +1,15 @@
|
|||||||
import { Component, Env } from "../src/component/component";
|
import { Component, Env } from "../src/component/component";
|
||||||
|
import { useRef, useState } from "../src/hooks";
|
||||||
import { QWeb } from "../src/qweb/index";
|
import { QWeb } from "../src/qweb/index";
|
||||||
import { useState, useRef } from "../src/hooks";
|
|
||||||
import { xml } from "../src/tags";
|
import { xml } from "../src/tags";
|
||||||
import {
|
import {
|
||||||
makeDeferred,
|
makeDeferred,
|
||||||
makeTestFixture,
|
|
||||||
makeTestEnv,
|
makeTestEnv,
|
||||||
|
makeTestFixture,
|
||||||
|
nextFrame,
|
||||||
patchNextFrame,
|
patchNextFrame,
|
||||||
renderToDOM,
|
renderToDOM,
|
||||||
unpatchNextFrame,
|
unpatchNextFrame,
|
||||||
nextTick
|
|
||||||
} from "./helpers";
|
} from "./helpers";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
@@ -71,7 +71,27 @@ describe("animations", () => {
|
|||||||
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
|
cb();
|
||||||
|
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
|
def.resolve();
|
||||||
|
});
|
||||||
|
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
||||||
|
fixture.appendChild(node);
|
||||||
|
|
||||||
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
|
await def; // wait for the mocked repaint to be done
|
||||||
|
node.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||||
|
expect(node.className).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-transition, on a simple node, not in the DOM", async () => {
|
||||||
|
expect.assertions(5);
|
||||||
|
qweb.addTemplate("test", `<span t-transition="chimay">blue</span>`);
|
||||||
|
|
||||||
|
let def = makeDeferred();
|
||||||
|
patchNextFrame((cb) => {
|
||||||
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -81,8 +101,10 @@ describe("animations", () => {
|
|||||||
|
|
||||||
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
expect(node.className).toBe("chimay-enter chimay-enter-active");
|
||||||
await def; // wait for the mocked repaint to be done
|
await def; // wait for the mocked repaint to be done
|
||||||
node.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
node.dispatchEvent(new Event("transitionend"));
|
||||||
expect(node.className).toBe("");
|
// we check here that the css classes have not been removed, since the
|
||||||
|
// element is not in the dom, we actually do not want to do anything.
|
||||||
|
expect(node.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("t-transition with no delay/duration", async () => {
|
test("t-transition with no delay/duration", async () => {
|
||||||
@@ -90,13 +112,14 @@ describe("animations", () => {
|
|||||||
qweb.addTemplate("test", `<span t-transition="jupiler">blue</span>`);
|
qweb.addTemplate("test", `<span t-transition="jupiler">blue</span>`);
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(node.className).toBe("");
|
expect(node.className).toBe("");
|
||||||
def.resolve();
|
def.resolve();
|
||||||
});
|
});
|
||||||
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
let node: HTMLElement = <HTMLElement>renderToDOM(qweb, "test");
|
||||||
|
fixture.appendChild(node);
|
||||||
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
expect(node.className).toBe("jupiler-enter jupiler-enter-active");
|
||||||
await def;
|
await def;
|
||||||
});
|
});
|
||||||
@@ -116,7 +139,7 @@ describe("animations", () => {
|
|||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -132,7 +155,7 @@ describe("animations", () => {
|
|||||||
// remove span from the DOM
|
// remove span from the DOM
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
widget.state.hide = true;
|
widget.state.hide = true;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-leave chimay-leave-active");
|
expect(spanNode.className).toBe("chimay-leave chimay-leave-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-leave-active chimay-leave-to");
|
expect(spanNode.className).toBe("chimay-leave-active chimay-leave-to");
|
||||||
@@ -159,7 +182,7 @@ describe("animations", () => {
|
|||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
||||||
cb();
|
cb();
|
||||||
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
expect(spanNode.className).toBe("chimay-enter-active chimay-enter-to");
|
||||||
@@ -187,7 +210,7 @@ describe("animations", () => {
|
|||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
||||||
);
|
);
|
||||||
@@ -227,7 +250,7 @@ describe("animations", () => {
|
|||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
'<div><span class="chimay-enter chimay-enter-active">blue</span></div>'
|
||||||
);
|
);
|
||||||
@@ -252,7 +275,7 @@ describe("animations", () => {
|
|||||||
// remove span from the DOM
|
// remove span from the DOM
|
||||||
def = makeDeferred();
|
def = makeDeferred();
|
||||||
widget.state.display = false;
|
widget.state.display = false;
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__3__">blue</span></div>'
|
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__3__">blue</span></div>'
|
||||||
);
|
);
|
||||||
@@ -292,7 +315,7 @@ describe("animations", () => {
|
|||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
let phase = "enter";
|
let phase = "enter";
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
let spans = fixture.querySelectorAll("span");
|
let spans = fixture.querySelectorAll("span");
|
||||||
expect(spans.length).toBe(1);
|
expect(spans.length).toBe(1);
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||||
@@ -343,7 +366,7 @@ describe("animations", () => {
|
|||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
let phase = "enter";
|
let phase = "enter";
|
||||||
patchNextFrame(cb => {
|
patchNextFrame((cb) => {
|
||||||
let spans = fixture.querySelectorAll("span");
|
let spans = fixture.querySelectorAll("span");
|
||||||
expect(spans.length).toBe(1);
|
expect(spans.length).toBe(1);
|
||||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||||
@@ -390,36 +413,36 @@ describe("animations", () => {
|
|||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
patchNextFrame(cb => cb());
|
patchNextFrame((cb) => cb());
|
||||||
|
|
||||||
const widget = new Parent();
|
const widget = new Parent();
|
||||||
await widget.mount(fixture);
|
await widget.mount(fixture);
|
||||||
|
|
||||||
widget.state.flag = true;
|
widget.state.flag = true;
|
||||||
|
|
||||||
await nextTick();
|
await nextFrame();
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||||
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
||||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||||
|
|
||||||
widget.state.flag = false;
|
widget.state.flag = false;
|
||||||
await nextTick();
|
await nextFrame();
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__3__">blue</span></div>'
|
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__3__">blue</span></div>'
|
||||||
);
|
);
|
||||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||||
|
|
||||||
widget.state.flag = true;
|
widget.state.flag = true;
|
||||||
await nextTick();
|
await nextFrame();
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
'<div><span class="chimay-enter-active chimay-enter-to" data-owl-key="__3__">blue</span></div>'
|
'<div><span class="chimay-enter-active chimay-enter-to" data-owl-key="__3__">blue</span></div>'
|
||||||
);
|
);
|
||||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(2);
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(2);
|
||||||
|
|
||||||
widget.state.flag = false;
|
widget.state.flag = false;
|
||||||
await nextTick();
|
await nextFrame();
|
||||||
widget.state.flag = true;
|
widget.state.flag = true;
|
||||||
await nextTick();
|
await nextFrame();
|
||||||
|
|
||||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(3);
|
expect(QWeb.utils.transitionInsert).toBeCalledTimes(3);
|
||||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||||
|
|||||||
@@ -20,16 +20,16 @@ exports[`class and style attributes with t-component dynamic t-att-style is prop
|
|||||||
w2 = false;
|
w2 = false;
|
||||||
}
|
}
|
||||||
if (w2) {
|
if (w2) {
|
||||||
w2.__updateProps(props2, extra.fiber, undefined).then(()=>{if (w2.__owl__.isDestroyed) {return};w2.el.style=_4;});;
|
w2.__updateProps(props2, extra.fiber, undefined).then(()=>{if (w2.__owl__.status === 5) {return};w2.el.style=_4;});;
|
||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w2.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.style = _4;}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.style = _4;}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -67,11 +67,11 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -90,7 +90,7 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let _7 = {'c':true};
|
let _7 = {'c':true};
|
||||||
Object.assign(_7, utils.toObj({d:scope['state'].d}))
|
Object.assign(_7, utils.toClassObj({d:scope['state'].d}))
|
||||||
let c8 = [], p8 = {key:8,class:_7};
|
let c8 = [], p8 = {key:8,class:_7};
|
||||||
let vn8 = h('span', p8, c8);
|
let vn8 = h('span', p8, c8);
|
||||||
return vn8;
|
return vn8;
|
||||||
@@ -112,7 +112,7 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
// Component 'Child'
|
// Component 'Child'
|
||||||
const ref4 = \`child\`;
|
const ref4 = \`child\`;
|
||||||
let _5 = {'a':true};
|
let _5 = {'a':true};
|
||||||
Object.assign(_5, utils.toObj(scope['state'].b?'b':''))
|
Object.assign(_5, utils.toClassObj(scope['state'].b?'b':''))
|
||||||
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let props2 = {};
|
let props2 = {};
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
@@ -125,11 +125,11 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {insert(vn) {context.__owl__.refs[ref4] = w2;},remove() {},destroy(vn) {w2.destroy();delete context.__owl__.refs[ref4];}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -148,7 +148,7 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let _7 = {'c':true};
|
let _7 = {'c':true};
|
||||||
Object.assign(_7, utils.toObj(scope['state'].d?'d':''))
|
Object.assign(_7, utils.toClassObj(scope['state'].d?'d':''))
|
||||||
let c8 = [], p8 = {key:8,class:_7};
|
let c8 = [], p8 = {key:8,class:_7};
|
||||||
let vn8 = h('span', p8, c8);
|
let vn8 = h('span', p8, c8);
|
||||||
return vn8;
|
return vn8;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ exports[`basic widget properties can handle empty props 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
@@ -97,7 +97,7 @@ exports[`basic widget properties reconciliation alg works for t-foreach in t-for
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey10 = \`Child\`;
|
let componentKey10 = \`Child\`;
|
||||||
let W10 = context.constructor.components[componentKey10] || QWeb.components[componentKey10]|| scope['Child'];
|
let W10 = scope['Child'] || context.constructor.components[componentKey10] || QWeb.components[componentKey10];
|
||||||
if (!W10) {throw new Error('Cannot find the definition of component \\"' + componentKey10 + '\\"')}
|
if (!W10) {throw new Error('Cannot find the definition of component \\"' + componentKey10 + '\\"')}
|
||||||
w10 = new W10(parent, props10);
|
w10 = new W10(parent, props10);
|
||||||
parent.__owl__.cmap[k11] = w10.__owl__.id;
|
parent.__owl__.cmap[k11] = w10.__owl__.id;
|
||||||
@@ -145,7 +145,7 @@ exports[`basic widget properties same t-keys in two different places 1`] = `
|
|||||||
c2.push(pvnode);
|
c2.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`Child\`;
|
let componentKey3 = \`Child\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| scope['Child'];
|
let W3 = scope['Child'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||||
@@ -175,7 +175,7 @@ exports[`basic widget properties same t-keys in two different places 1`] = `
|
|||||||
c5.push(pvnode);
|
c5.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey6 = \`Child\`;
|
let componentKey6 = \`Child\`;
|
||||||
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| scope['Child'];
|
let W6 = scope['Child'] || context.constructor.components[componentKey6] || QWeb.components[componentKey6];
|
||||||
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
||||||
w6 = new W6(parent, props6);
|
w6 = new W6(parent, props6);
|
||||||
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
||||||
@@ -218,7 +218,7 @@ exports[`basic widget properties t-key on a component with t-if, and a sibling c
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
@@ -243,7 +243,7 @@ exports[`basic widget properties t-key on a component with t-if, and a sibling c
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey4 = \`Child\`;
|
let componentKey4 = \`Child\`;
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| scope['Child'];
|
let W4 = scope['Child'] || context.constructor.components[componentKey4] || QWeb.components[componentKey4];
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||||
w4 = new W4(parent, props4);
|
w4 = new W4(parent, props4);
|
||||||
parent.__owl__.cmap['__5__'] = w4.__owl__.id;
|
parent.__owl__.cmap['__5__'] = w4.__owl__.id;
|
||||||
@@ -257,6 +257,45 @@ exports[`basic widget properties t-key on a component with t-if, and a sibling c
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`composition can switch between dynamic components without the need for a t-key 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__3\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component '{{state.child}}'
|
||||||
|
let componentKey2 = (scope['state'].child);
|
||||||
|
let k3 = '___' + componentKey2
|
||||||
|
let w2 = k3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k3]] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let W2 = false || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k3, hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`composition sub components with some state rendered in a loop 1`] = `
|
exports[`composition sub components with some state rendered in a loop 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -301,7 +340,7 @@ exports[`composition sub components with some state rendered in a loop 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey6 = \`ChildWidget\`;
|
let componentKey6 = \`ChildWidget\`;
|
||||||
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| scope['ChildWidget'];
|
let W6 = scope['ChildWidget'] || context.constructor.components[componentKey6] || QWeb.components[componentKey6];
|
||||||
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
||||||
w6 = new W6(parent, props6);
|
w6 = new W6(parent, props6);
|
||||||
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
||||||
@@ -330,7 +369,9 @@ exports[`composition t-component with dynamic value 1`] = `
|
|||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
let vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
// Component '{{state.widget}}'
|
// Component '{{state.widget}}'
|
||||||
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
let componentKey2 = (scope['state'].widget);
|
||||||
|
let k3 = '___' + componentKey2
|
||||||
|
let w2 = k3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k3]] : false;
|
||||||
let props2 = {};
|
let props2 = {};
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
w2.destroy();
|
w2.destroy();
|
||||||
@@ -341,13 +382,12 @@ exports[`composition t-component with dynamic value 1`] = `
|
|||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w2.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = (scope['state'].widget);
|
let W2 = false || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: k3, hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
@@ -368,6 +408,67 @@ exports[`composition t-component with dynamic value 2 1`] = `
|
|||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
let vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
// Component 'Widget{{state.widget}}'
|
// Component 'Widget{{state.widget}}'
|
||||||
|
let componentKey2 = \`Widget\${scope['state'].widget}\`;
|
||||||
|
let k3 = '___' + componentKey2
|
||||||
|
let w2 = k3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k3]] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let W2 = false || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k3, hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`composition t-ref on a node, and t-on-click 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
context.__owl__.refs = context.__owl__.refs || {};
|
||||||
|
let h = this.h;
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('div', p4, c4);
|
||||||
|
const ref5 = \`nibor\`;
|
||||||
|
p4.hook = {
|
||||||
|
create: (_, n) => {
|
||||||
|
context.__owl__.refs[ref5] = n.elm;
|
||||||
|
},
|
||||||
|
destroy: () => {
|
||||||
|
delete context.__owl__.refs[ref5];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
c4.push({text: \`nibor\`});
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`composition t-ref on a node, and t-on-click 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Child'
|
||||||
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let props2 = {};
|
let props2 = {};
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
@@ -379,12 +480,12 @@ exports[`composition t-component with dynamic value 2 1`] = `
|
|||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w2.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Widget\${scope['state'].widget}\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('click', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['doSomething'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -407,7 +508,7 @@ exports[`dynamic t-props basic use 1`] = `
|
|||||||
let vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
// Component 'Child'
|
// Component 'Child'
|
||||||
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
let props2 = Object.assign({}, scope['some'].obj);
|
let props2 = Object.assign({}, scope['some'].obj, {});
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
w2.destroy();
|
w2.destroy();
|
||||||
w2 = false;
|
w2 = false;
|
||||||
@@ -418,7 +519,7 @@ exports[`dynamic t-props basic use 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
@@ -458,27 +559,27 @@ exports[`other directives with t-component slot setted value (with t-set) not ac
|
|||||||
w3 = false;
|
w3 = false;
|
||||||
}
|
}
|
||||||
if (w3) {
|
if (w3) {
|
||||||
w3.__updateProps(props3, extra.fiber, Object.assign(Object.create(context), scope));
|
w3.__updateProps(props3, extra.fiber, utils.combine(context, scope));
|
||||||
let pvnode = w3.__owl__.pvnode;
|
let pvnode = w3.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`ChildWidget\`;
|
let componentKey3 = \`ChildWidget\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| scope['ChildWidget'];
|
let W3 = scope['ChildWidget'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
||||||
w3.__owl__.slotId = 1;
|
w3.__owl__.slotId = 1;
|
||||||
let fiber = w3.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w3.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w3.__owl__.pvnode = pvnode;
|
w3.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
let c5 = [], p5 = {key:5};
|
let c6 = [], p6 = {key:6};
|
||||||
let vn5 = h('p', p5, c5);
|
let vn6 = h('p', p6, c6);
|
||||||
c1.push(vn5);
|
c1.push(vn6);
|
||||||
if (scope.iter != null) {
|
if (scope.iter != null) {
|
||||||
c5.push({text: scope.iter});
|
c6.push({text: scope.iter});
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -519,7 +620,7 @@ exports[`other directives with t-component t-on expression captured in t-foreach
|
|||||||
c6.push(vn7);
|
c6.push(vn7);
|
||||||
const otherState_8 = scope['otherState'];
|
const otherState_8 = scope['otherState'];
|
||||||
const iter_8 = scope.iter;
|
const iter_8 = scope.iter;
|
||||||
p7.on['click'] = function (e) {if (!context.__owl__.isMounted){return}otherState_8.vals.push(iter_8+'_'+iter_8)};
|
p7.on['click'] = function (e) {if (context.__owl__.status === 5){return}const res = (() => { return otherState_8.vals.push(iter_8+'_'+iter_8) })(); if (typeof res === 'function') { res(e) }};
|
||||||
c7.push({text: \`expr\`});
|
c7.push({text: \`expr\`});
|
||||||
utils.getScope(scope, 'iter').iter = scope.iter+1;
|
utils.getScope(scope, 'iter').iter = scope.iter+1;
|
||||||
}
|
}
|
||||||
@@ -570,7 +671,7 @@ exports[`other directives with t-component t-on expression in t-foreach 1`] = `
|
|||||||
c6.push(vn9);
|
c6.push(vn9);
|
||||||
const otherState_10 = scope['otherState'];
|
const otherState_10 = scope['otherState'];
|
||||||
const val_10 = scope['val'];
|
const val_10 = scope['val'];
|
||||||
p9.on['click'] = function (e) {if (!context.__owl__.isMounted){return}otherState_10.vals.push(val_10)};
|
p9.on['click'] = function (e) {if (context.__owl__.status === 5){return}const res = (() => { return otherState_10.vals.push(val_10) })(); if (typeof res === 'function') { res(e) }};
|
||||||
c9.push({text: \`Expr\`});
|
c9.push({text: \`Expr\`});
|
||||||
}
|
}
|
||||||
scope = _origScope5;
|
scope = _origScope5;
|
||||||
@@ -624,7 +725,7 @@ exports[`other directives with t-component t-on expression in t-foreach with t-s
|
|||||||
const otherState_10 = scope['otherState'];
|
const otherState_10 = scope['otherState'];
|
||||||
const val_10 = scope['val'];
|
const val_10 = scope['val'];
|
||||||
const bossa_10 = scope.bossa;
|
const bossa_10 = scope.bossa;
|
||||||
p9.on['click'] = function (e) {if (!context.__owl__.isMounted){return}otherState_10.vals.push(val_10+'_'+bossa_10)};
|
p9.on['click'] = function (e) {if (context.__owl__.status === 5){return}const res = (() => { return otherState_10.vals.push(val_10+'_'+bossa_10) })(); if (typeof res === 'function') { res(e) }};
|
||||||
c9.push({text: \`Expr\`});
|
c9.push({text: \`Expr\`});
|
||||||
}
|
}
|
||||||
scope = _origScope5;
|
scope = _origScope5;
|
||||||
@@ -674,7 +775,7 @@ exports[`other directives with t-component t-on method call in t-foreach 1`] = `
|
|||||||
let vn9 = h('button', p9, c9);
|
let vn9 = h('button', p9, c9);
|
||||||
c6.push(vn9);
|
c6.push(vn9);
|
||||||
let args10 = [scope['val']];
|
let args10 = [scope['val']];
|
||||||
p9.on['click'] = function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['addVal'](...args10, e);};
|
p9.on['click'] = function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['addVal'](...args10, e);};
|
||||||
c9.push({text: \`meth call\`});
|
c9.push({text: \`meth call\`});
|
||||||
}
|
}
|
||||||
scope = _origScope5;
|
scope = _origScope5;
|
||||||
@@ -682,6 +783,44 @@ exports[`other directives with t-component t-on method call in t-foreach 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`other directives with t-component t-on with .capture modifier 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Child'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, undefined);
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Child\`;
|
||||||
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('click', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['capture'](e);}, true);}});});
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`other directives with t-component t-on with getter as handler 1`] = `
|
exports[`other directives with t-component t-on with getter as handler 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -710,11 +849,11 @@ exports[`other directives with t-component t-on with getter as handler 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`Child\`;
|
let componentKey3 = \`Child\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| scope['Child'];
|
let W3 = scope['Child'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
||||||
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['handler'](e);});}};});
|
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['handler'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w3.__owl__.pvnode = pvnode;
|
w3.__owl__.pvnode = pvnode;
|
||||||
@@ -749,11 +888,11 @@ exports[`other directives with t-component t-on with handler bound to argument 1
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](...args4, e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](...args4, e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -788,11 +927,11 @@ exports[`other directives with t-component t-on with handler bound to empty obje
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](...args4, e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](...args4, e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -827,11 +966,11 @@ exports[`other directives with t-component t-on with handler bound to empty obje
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](...args4, e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](...args4, e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -866,11 +1005,11 @@ exports[`other directives with t-component t-on with handler bound to object 1`]
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](...args4, e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](...args4, e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -909,11 +1048,11 @@ exports[`other directives with t-component t-on with inline statement 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`Child\`;
|
let componentKey3 = \`Child\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| scope['Child'];
|
let W3 = scope['Child'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
||||||
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}state_5.counter++});}};});
|
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}const res = (() => { return state_5.counter++ })(); if (typeof res === 'function') { res(e) }});}});});
|
||||||
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w3.__owl__.pvnode = pvnode;
|
w3.__owl__.pvnode = pvnode;
|
||||||
@@ -947,11 +1086,11 @@ exports[`other directives with t-component t-on with no handler (only modifiers)
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`ComponentA\`;
|
let componentKey2 = \`ComponentA\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['ComponentA'];
|
let W2 = scope['ComponentA'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -985,11 +1124,11 @@ exports[`other directives with t-component t-on with prevent and self modifiers
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}e.preventDefault();if (e.target !== vn.elm) {return}utils.getComponent(context)['onEv'](e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}e.preventDefault();if (e.target !== vn.elm) {return}utils.getComponent(context)['onEv'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -1023,11 +1162,11 @@ exports[`other directives with t-component t-on with self and prevent modifiers
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}if (e.target !== vn.elm) {return}e.preventDefault();utils.getComponent(context)['onEv'](e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}if (e.target !== vn.elm) {return}e.preventDefault();utils.getComponent(context)['onEv'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -1061,11 +1200,11 @@ exports[`other directives with t-component t-on with self modifier 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev-1', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv1'](e);});vn.elm.addEventListener('ev-2', function (e) {if (!context.__owl__.isMounted){return}if (e.target !== vn.elm) {return}utils.getComponent(context)['onEv2'](e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev-1', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv1'](e);});vn.elm.addEventListener('ev-2', function (e) {if (context.__owl__.status === 5){return}if (e.target !== vn.elm) {return}utils.getComponent(context)['onEv2'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -1099,11 +1238,11 @@ exports[`other directives with t-component t-on with stop and/or prevent modifie
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev-1', function (e) {if (!context.__owl__.isMounted){return}e.stopPropagation();utils.getComponent(context)['onEv1'](e);});vn.elm.addEventListener('ev-2', function (e) {if (!context.__owl__.isMounted){return}e.preventDefault();utils.getComponent(context)['onEv2'](e);});vn.elm.addEventListener('ev-3', function (e) {if (!context.__owl__.isMounted){return}e.stopPropagation();e.preventDefault();utils.getComponent(context)['onEv3'](e);});}};});
|
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev-1', function (e) {if (context.__owl__.status === 5){return}e.stopPropagation();utils.getComponent(context)['onEv1'](e);});vn.elm.addEventListener('ev-2', function (e) {if (context.__owl__.status === 5){return}e.preventDefault();utils.getComponent(context)['onEv2'](e);});vn.elm.addEventListener('ev-3', function (e) {if (context.__owl__.status === 5){return}e.stopPropagation();e.preventDefault();utils.getComponent(context)['onEv3'](e);});}});});
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -1155,12 +1294,16 @@ exports[`other directives with t-component t-set can't alter from within callee
|
|||||||
if (scope.iter != null) {
|
if (scope.iter != null) {
|
||||||
c2.push({text: scope.iter});
|
c2.push({text: scope.iter});
|
||||||
}
|
}
|
||||||
this.subTemplates['ChildWidget'].call(this, Object.assign(Object.create(context), scope), Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__4__'}));
|
let _origScope6 = scope;
|
||||||
let c5 = [], p5 = {key:5};
|
scope = Object.create(scope);
|
||||||
let vn5 = h('p', p5, c5);
|
scope.__access_mode__ = 'ro';
|
||||||
c1.push(vn5);
|
this.constructor.subTemplates['2'].call(this, scope, Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__7__'}));
|
||||||
|
scope = _origScope6;
|
||||||
|
let c8 = [], p8 = {key:8};
|
||||||
|
let vn8 = h('p', p8, c8);
|
||||||
|
c1.push(vn8);
|
||||||
if (scope.iter != null) {
|
if (scope.iter != null) {
|
||||||
c5.push({text: scope.iter});
|
c8.push({text: scope.iter});
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -1182,22 +1325,23 @@ exports[`other directives with t-component t-set can't alter in t-call body 1`]
|
|||||||
if (scope.iter != null) {
|
if (scope.iter != null) {
|
||||||
c2.push({text: scope.iter});
|
c2.push({text: scope.iter});
|
||||||
}
|
}
|
||||||
|
let _origScope6 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
scope.__access_mode__ = 'ro';
|
||||||
{
|
{
|
||||||
let _origScope4 = scope;
|
|
||||||
scope = Object.assign(Object.create(context), scope);
|
|
||||||
{
|
{
|
||||||
let c__0 = [];
|
let c__0 = [];
|
||||||
utils.getScope(scope, 'iter').iter = 'inCall';
|
utils.getScope(scope, 'iter').iter = 'inCall';
|
||||||
scope[utils.zero] = c__0;
|
scope[utils.zero] = c__0;
|
||||||
}
|
}
|
||||||
this.subTemplates['ChildWidget'].call(this, scope, Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__5__'}));
|
this.constructor.subTemplates['2'].call(this, scope, Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__7__'}));
|
||||||
scope = _origScope4;
|
|
||||||
}
|
}
|
||||||
let c6 = [], p6 = {key:6};
|
scope = _origScope6;
|
||||||
let vn6 = h('p', p6, c6);
|
let c8 = [], p8 = {key:8};
|
||||||
c1.push(vn6);
|
let vn8 = h('p', p8, c8);
|
||||||
|
c1.push(vn8);
|
||||||
if (scope.iter != null) {
|
if (scope.iter != null) {
|
||||||
c6.push({text: scope.iter});
|
c8.push({text: scope.iter});
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -1234,7 +1378,7 @@ exports[`other directives with t-component t-set not altered by child widget 1`]
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`ChildWidget\`;
|
let componentKey3 = \`ChildWidget\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| scope['ChildWidget'];
|
let W3 = scope['ChildWidget'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
||||||
@@ -1302,6 +1446,47 @@ exports[`other directives with t-component t-set outside modified in t-foreach 1
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`props evaluation t-set with a body expression can be used as textual prop 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let c2 = new utils.VDomArray();
|
||||||
|
c2.push({text: \`42\`});
|
||||||
|
scope.abc = c2
|
||||||
|
// Component 'Child'
|
||||||
|
let w3 = '__4__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__4__']] : false;
|
||||||
|
let props3 = {val:scope.abc};
|
||||||
|
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||||
|
w3.destroy();
|
||||||
|
w3 = false;
|
||||||
|
}
|
||||||
|
if (w3) {
|
||||||
|
w3.__updateProps(props3, extra.fiber, undefined);
|
||||||
|
let pvnode = w3.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey3 = \`Child\`;
|
||||||
|
let W3 = scope['Child'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
|
w3 = new W3(parent, props3);
|
||||||
|
parent.__owl__.cmap['__4__'] = w3.__owl__.id;
|
||||||
|
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__4__', hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w3.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`random stuff/miscellaneous can inject values in tagged templates 1`] = `
|
exports[`random stuff/miscellaneous can inject values in tagged templates 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -1311,7 +1496,11 @@ exports[`random stuff/miscellaneous can inject values in tagged templates 1`] =
|
|||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
let vn1 = h('div', p1, c1);
|
let vn1 = h('div', p1, c1);
|
||||||
this.subTemplates['__template__1'].call(this, Object.assign(Object.create(context), scope), Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__4__'}));
|
let _origScope5 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
scope.__access_mode__ = 'ro';
|
||||||
|
this.constructor.subTemplates['3'].call(this, scope, Object.assign({}, extra, {parentNode: c1, parent: utils.getComponent(context), key: '__6__'}));
|
||||||
|
scope = _origScope5;
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
@@ -1343,7 +1532,7 @@ exports[`random stuff/miscellaneous snapshotting compiled code 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`child\`;
|
let componentKey2 = \`child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['child'];
|
let W2 = scope['child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
@@ -1403,11 +1592,11 @@ exports[`random stuff/miscellaneous t-on with handler bound to dynamic argument
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey6 = \`Child\`;
|
let componentKey6 = \`Child\`;
|
||||||
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| scope['Child'];
|
let W6 = scope['Child'] || context.constructor.components[componentKey6] || QWeb.components[componentKey6];
|
||||||
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
||||||
w6 = new W6(parent, props6);
|
w6 = new W6(parent, props6);
|
||||||
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
parent.__owl__.cmap[k7] = w6.__owl__.id;
|
||||||
let fiber = w6.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['onEv'](...args8, e);});}};});
|
let fiber = w6.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; utils.assignHooks(vnode.data, {create(_, vn){vn.elm.addEventListener('ev', function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['onEv'](...args8, e);});}});});
|
||||||
let pvnode = h('dummy', {key: k7, hook: {remove() {},destroy(vn) {w6.destroy();}}});
|
let pvnode = h('dummy', {key: k7, hook: {remove() {},destroy(vn) {w6.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w6.__owl__.pvnode = pvnode;
|
w6.__owl__.pvnode = pvnode;
|
||||||
@@ -1425,16 +1614,17 @@ exports[`t-call handlers are properly bound through a t-call 1`] = `
|
|||||||
) {
|
) {
|
||||||
// Template name: \\"sub\\"
|
// Template name: \\"sub\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c2 = extra.parentNode;
|
||||||
let key0 = extra.key || \\"\\";
|
let key0 = extra.key || \\"\\";
|
||||||
let c2 = [], p2 = {key:\`\${key0}_2\`,on:{}};
|
let c3 = [], p3 = {key:\`\${key0}_3\`,on:{}};
|
||||||
let vn2 = h('p', p2, c2);
|
let vn3 = h('p', p3, c3);
|
||||||
c1.push(vn2);
|
c2.push(vn3);
|
||||||
let k3 = \`click__3__\${key0}__\`;
|
let k4 = \`click__4__\${key0}__\`;
|
||||||
extra.handlers[k3] = extra.handlers[k3] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['update'](e);};
|
extra.handlers[k4] = extra.handlers[k4] || function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['update'](e);};
|
||||||
p2.on['click'] = extra.handlers[k3];
|
p3.on['click'] = extra.handlers[k4];
|
||||||
c2.push({text: \`lucas\`});
|
c3.push({text: \`lucas\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1443,16 +1633,17 @@ exports[`t-call handlers with arguments are properly bound through a t-call 1`]
|
|||||||
) {
|
) {
|
||||||
// Template name: \\"sub\\"
|
// Template name: \\"sub\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
|
let parent = extra.parent;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c2 = extra.parentNode;
|
||||||
let key0 = extra.key || \\"\\";
|
let key0 = extra.key || \\"\\";
|
||||||
let c2 = [], p2 = {key:\`\${key0}_2\`,on:{}};
|
let c3 = [], p3 = {key:\`\${key0}_3\`,on:{}};
|
||||||
let vn2 = h('p', p2, c2);
|
let vn3 = h('p', p3, c3);
|
||||||
c1.push(vn2);
|
c2.push(vn3);
|
||||||
let args3 = [scope['a']];
|
let args4 = [scope['a']];
|
||||||
p2.on['click'] = function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['update'](...args3, e);};
|
p3.on['click'] = function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['update'](...args4, e);};
|
||||||
c2.push({text: \`lucas\`});
|
c3.push({text: \`lucas\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1465,32 +1656,32 @@ exports[`t-call parent is set within t-call 1`] = `
|
|||||||
let parent = extra.parent;
|
let parent = extra.parent;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c2 = extra.parentNode;
|
||||||
let key0 = extra.key || \\"\\";
|
let key0 = extra.key || \\"\\";
|
||||||
// Component 'Child'
|
// Component 'Child'
|
||||||
let k3 = \`__3__\${key0}__\`;
|
let k4 = \`__4__\${key0}__\`;
|
||||||
let w2 = k3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k3]] : false;
|
let w3 = k4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k4]] : false;
|
||||||
let props2 = {};
|
let props3 = {};
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||||
w2.destroy();
|
w3.destroy();
|
||||||
w2 = false;
|
w3 = false;
|
||||||
}
|
}
|
||||||
if (w2) {
|
if (w3) {
|
||||||
w2.__updateProps(props2, extra.fiber, undefined);
|
w3.__updateProps(props3, extra.fiber, undefined);
|
||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w3.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c2.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey3 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W3 = scope['Child'] || context.constructor.components[componentKey3] || QWeb.components[componentKey3];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||||
let fiber = w2.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w3.__prepare(extra.fiber, undefined, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: k3, hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: k4, hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||||
c1.push(pvnode);
|
c2.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w3.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1519,7 +1710,7 @@ exports[`t-call parent is set within t-call with no parentNode 1`] = `
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
parent.__owl__.cmap[k3] = w2.__owl__.id;
|
||||||
@@ -1584,6 +1775,33 @@ exports[`t-model directive basic use, on an input 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`t-model directive basic use, on an input with bracket expression 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let c2 = [], p2 = {key:2,on:{}};
|
||||||
|
let vn2 = h('input', p2, c2);
|
||||||
|
c1.push(vn2);
|
||||||
|
let expr2 = scope['state'];
|
||||||
|
let exprKey2 = 'text';
|
||||||
|
p2.props = {value: expr2[exprKey2]};
|
||||||
|
extra.handlers['__3__'] = extra.handlers['__3__'] || ((ev) => {expr2[exprKey2] = ev.target.value});
|
||||||
|
p2.on['input'] = extra.handlers['__3__'];
|
||||||
|
let c4 = [], p4 = {key:4};
|
||||||
|
let vn4 = h('span', p4, c4);
|
||||||
|
c1.push(vn4);
|
||||||
|
let _5 = scope['state'].text;
|
||||||
|
if (_5 != null) {
|
||||||
|
c4.push({text: _5});
|
||||||
|
}
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`t-model directive basic use, on another key in component 1`] = `
|
exports[`t-model directive basic use, on another key in component 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -1650,6 +1868,46 @@ exports[`t-model directive in a t-foreach 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`t-model directive in a t-foreach, part 2 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let _2 = scope['state'];
|
||||||
|
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
|
let _3 = _4 = _2;
|
||||||
|
if (!(_2 instanceof Array)) {
|
||||||
|
_3 = Object.keys(_2);
|
||||||
|
_4 = Object.values(_2);
|
||||||
|
}
|
||||||
|
let _length3 = _3.length;
|
||||||
|
let _origScope5 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
for (let i1 = 0; i1 < _length3; i1++) {
|
||||||
|
scope.thing_first = i1 === 0
|
||||||
|
scope.thing_last = i1 === _length3 - 1
|
||||||
|
scope.thing_index = i1
|
||||||
|
scope.thing = _3[i1]
|
||||||
|
scope.thing_value = _4[i1]
|
||||||
|
let key1 = scope['thing_index'];
|
||||||
|
let c6 = [], p6 = {key:\`\${key1}_6\`,on:{}};
|
||||||
|
let vn6 = h('input', p6, c6);
|
||||||
|
c1.push(vn6);
|
||||||
|
let expr6 = scope['state'];
|
||||||
|
let exprKey6 = scope['thing_index'];
|
||||||
|
let k7 = \`__7__\${key1}__\`;
|
||||||
|
p6.props = {value: expr6[exprKey6]};
|
||||||
|
extra.handlers[k7] = extra.handlers[k7] || ((ev) => {expr6[exprKey6] = ev.target.value});
|
||||||
|
p6.on['input'] = extra.handlers[k7];
|
||||||
|
}
|
||||||
|
scope = _origScope5;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`t-model directive on a select 1`] = `
|
exports[`t-model directive on a select 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -1734,7 +1992,7 @@ exports[`t-model directive on an input type=radio 1`] = `
|
|||||||
let _2 = 'radio';
|
let _2 = 'radio';
|
||||||
let _3 = 'one';
|
let _3 = 'one';
|
||||||
let _4 = 'One';
|
let _4 = 'One';
|
||||||
let c5 = [], p5 = {key:5,attrs:{type: _2,id: _3,value: _4},on:{}};
|
let c5 = [], p5 = {key:5,attrs:{type: _2,id: _3,value: _4},props:{value: _4},on:{}};
|
||||||
let vn5 = h('input', p5, c5);
|
let vn5 = h('input', p5, c5);
|
||||||
c1.push(vn5);
|
c1.push(vn5);
|
||||||
let expr5 = scope['state'];
|
let expr5 = scope['state'];
|
||||||
@@ -1744,7 +2002,7 @@ exports[`t-model directive on an input type=radio 1`] = `
|
|||||||
let _7 = 'radio';
|
let _7 = 'radio';
|
||||||
let _8 = 'two';
|
let _8 = 'two';
|
||||||
let _9 = 'Two';
|
let _9 = 'Two';
|
||||||
let c10 = [], p10 = {key:10,attrs:{type: _7,id: _8,value: _9},on:{}};
|
let c10 = [], p10 = {key:10,attrs:{type: _7,id: _8,value: _9},props:{value: _9},on:{}};
|
||||||
let vn10 = h('input', p10, c10);
|
let vn10 = h('input', p10, c10);
|
||||||
c1.push(vn10);
|
c1.push(vn10);
|
||||||
let expr10 = scope['state'];
|
let expr10 = scope['state'];
|
||||||
@@ -1847,7 +2105,7 @@ exports[`top level sub widgets basic use 1`] = `
|
|||||||
utils.defineProxy(vn3, pvnode);
|
utils.defineProxy(vn3, pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey1 = \`Child\`;
|
let componentKey1 = \`Child\`;
|
||||||
let W1 = context.constructor.components[componentKey1] || QWeb.components[componentKey1]|| scope['Child'];
|
let W1 = scope['Child'] || context.constructor.components[componentKey1] || QWeb.components[componentKey1];
|
||||||
if (!W1) {throw new Error('Cannot find the definition of component \\"' + componentKey1 + '\\"')}
|
if (!W1) {throw new Error('Cannot find the definition of component \\"' + componentKey1 + '\\"')}
|
||||||
w1 = new W1(parent, props1);
|
w1 = new W1(parent, props1);
|
||||||
parent.__owl__.cmap['__2__'] = w1.__owl__.id;
|
parent.__owl__.cmap['__2__'] = w1.__owl__.id;
|
||||||
@@ -1887,7 +2145,7 @@ exports[`top level sub widgets can select a sub widget 1`] = `
|
|||||||
utils.defineProxy(vn3, pvnode);
|
utils.defineProxy(vn3, pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey1 = \`Child\`;
|
let componentKey1 = \`Child\`;
|
||||||
let W1 = context.constructor.components[componentKey1] || QWeb.components[componentKey1]|| scope['Child'];
|
let W1 = scope['Child'] || context.constructor.components[componentKey1] || QWeb.components[componentKey1];
|
||||||
if (!W1) {throw new Error('Cannot find the definition of component \\"' + componentKey1 + '\\"')}
|
if (!W1) {throw new Error('Cannot find the definition of component \\"' + componentKey1 + '\\"')}
|
||||||
w1 = new W1(parent, props1);
|
w1 = new W1(parent, props1);
|
||||||
parent.__owl__.cmap['__2__'] = w1.__owl__.id;
|
parent.__owl__.cmap['__2__'] = w1.__owl__.id;
|
||||||
@@ -1914,7 +2172,7 @@ exports[`top level sub widgets can select a sub widget 1`] = `
|
|||||||
utils.defineProxy(vn6, pvnode);
|
utils.defineProxy(vn6, pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey4 = \`OtherChild\`;
|
let componentKey4 = \`OtherChild\`;
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| scope['OtherChild'];
|
let W4 = scope['OtherChild'] || context.constructor.components[componentKey4] || QWeb.components[componentKey4];
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||||
w4 = new W4(parent, props4);
|
w4 = new W4(parent, props4);
|
||||||
parent.__owl__.cmap['__5__'] = w4.__owl__.id;
|
parent.__owl__.cmap['__5__'] = w4.__owl__.id;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
|
|||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Child\`;
|
let componentKey2 = \`Child\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Child'];
|
let W2 = scope['Child'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
|||||||
@@ -19,17 +19,17 @@ exports[`t-slot directive can define and call slots 1`] = `
|
|||||||
w2 = false;
|
w2 = false;
|
||||||
}
|
}
|
||||||
if (w2) {
|
if (w2) {
|
||||||
w2.__updateProps(props2, extra.fiber, Object.assign(Object.create(context), scope));
|
w2.__updateProps(props2, extra.fiber, utils.combine(context, scope));
|
||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w2.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Dialog\`;
|
let componentKey2 = \`Dialog\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Dialog'];
|
let W2 = scope['Dialog'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
w2.__owl__.slotId = 1;
|
w2.__owl__.slotId = 1;
|
||||||
let fiber = w2.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -44,23 +44,23 @@ exports[`t-slot directive can define and call slots 2`] = `
|
|||||||
) {
|
) {
|
||||||
// Template name: \\"Dialog\\"
|
// Template name: \\"Dialog\\"
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c6 = [], p6 = {key:6};
|
let c8 = [], p8 = {key:8};
|
||||||
let vn6 = h('div', p6, c6);
|
let vn8 = h('div', p8, c8);
|
||||||
let c7 = [], p7 = {key:7};
|
|
||||||
let vn7 = h('div', p7, c7);
|
|
||||||
c6.push(vn7);
|
|
||||||
const slot8 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
|
||||||
if (slot8) {
|
|
||||||
slot8.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c7, parent: extra.parent || context}));
|
|
||||||
}
|
|
||||||
let c9 = [], p9 = {key:9};
|
let c9 = [], p9 = {key:9};
|
||||||
let vn9 = h('div', p9, c9);
|
let vn9 = h('div', p9, c9);
|
||||||
c6.push(vn9);
|
c8.push(vn9);
|
||||||
const slot10 = this.constructor.slots[context.__owl__.slotId + '_' + 'footer'];
|
const slot10 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
||||||
if (slot10) {
|
if (slot10) {
|
||||||
slot10.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
slot10.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
||||||
}
|
}
|
||||||
return vn6;
|
let c11 = [], p11 = {key:11};
|
||||||
|
let vn11 = h('div', p11, c11);
|
||||||
|
c8.push(vn11);
|
||||||
|
const slot12 = this.constructor.slots[context.__owl__.slotId + '_' + 'footer'];
|
||||||
|
if (slot12) {
|
||||||
|
slot12.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c11, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn8;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -68,12 +68,13 @@ exports[`t-slot directive can define and call slots 3`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_header_template\\"
|
// Template name: \\"slot_header_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
let c4 = [], p4 = {key:4};
|
let c5 = [], p5 = {key:5};
|
||||||
let vn4 = h('span', p4, c4);
|
let vn5 = h('span', p5, c5);
|
||||||
c1.push(vn4);
|
c4.push(vn5);
|
||||||
c4.push({text: \`header\`});
|
c5.push({text: \`header\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -81,12 +82,105 @@ exports[`t-slot directive can define and call slots 4`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_footer_template\\"
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c6 = extra.parentNode;
|
||||||
|
let c7 = [], p7 = {key:7};
|
||||||
|
let vn7 = h('span', p7, c7);
|
||||||
|
c6.push(vn7);
|
||||||
|
c7.push({text: \`footer\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Dialog'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, utils.combine(context, scope));
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Dialog\`;
|
||||||
|
let W2 = scope['Dialog'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
w2.__owl__.slotId = 1;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c8 = [], p8 = {key:8};
|
||||||
|
let vn8 = h('div', p8, c8);
|
||||||
|
let c9 = [], p9 = {key:9};
|
||||||
|
let vn9 = h('div', p9, c9);
|
||||||
|
c8.push(vn9);
|
||||||
|
const slot10 = this.constructor.slots[context.__owl__.slotId + '_' + 'header'];
|
||||||
|
if (slot10) {
|
||||||
|
slot10.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
let c11 = [], p11 = {key:11};
|
||||||
|
let vn11 = h('div', p11, c11);
|
||||||
|
c8.push(vn11);
|
||||||
|
const slot12 = this.constructor.slots[context.__owl__.slotId + '_' + 'footer'];
|
||||||
|
if (slot12) {
|
||||||
|
slot12.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c11, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn8;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 3`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_header_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
|
let h = this.h;
|
||||||
|
let c4 = extra.parentNode;
|
||||||
let c5 = [], p5 = {key:5};
|
let c5 = [], p5 = {key:5};
|
||||||
let vn5 = h('span', p5, c5);
|
let vn5 = h('span', p5, c5);
|
||||||
c1.push(vn5);
|
c4.push(vn5);
|
||||||
c5.push({text: \`footer\`});
|
c5.push({text: \`header\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive can define and call slots using old t-set keyword 4`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"slot_footer_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
|
let h = this.h;
|
||||||
|
let c6 = extra.parentNode;
|
||||||
|
let c7 = [], p7 = {key:7};
|
||||||
|
let vn7 = h('span', p7, c7);
|
||||||
|
c6.push(vn7);
|
||||||
|
c7.push({text: \`footer\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -94,12 +188,13 @@ exports[`t-slot directive content is the default slot 1`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
let c4 = [], p4 = {key:4};
|
let c5 = [], p5 = {key:5};
|
||||||
let vn4 = h('span', p4, c4);
|
let vn5 = h('span', p5, c5);
|
||||||
c1.push(vn4);
|
c4.push(vn5);
|
||||||
c4.push({text: \`sts rocks\`});
|
c5.push({text: \`sts rocks\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -120,13 +215,72 @@ exports[`t-slot directive dafault slots can define a default content 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive default slot next to named slot, with default content 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
// Component 'Dialog'
|
||||||
|
let w2 = '__3__' in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap['__3__']] : false;
|
||||||
|
let props2 = {};
|
||||||
|
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||||
|
w2.destroy();
|
||||||
|
w2 = false;
|
||||||
|
}
|
||||||
|
if (w2) {
|
||||||
|
w2.__updateProps(props2, extra.fiber, utils.combine(context, scope));
|
||||||
|
let pvnode = w2.__owl__.pvnode;
|
||||||
|
c1.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey2 = \`Dialog\`;
|
||||||
|
let W2 = scope['Dialog'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
|
w2 = new W2(parent, props2);
|
||||||
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
|
w2.__owl__.slotId = 1;
|
||||||
|
let fiber = w2.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
|
c1.push(pvnode);
|
||||||
|
w2.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w2.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`t-slot directive default slot work with text nodes 1`] = `
|
exports[`t-slot directive default slot work with text nodes 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
c1.push({text: \`sts rocks\`});
|
c4.push({text: \`sts rocks\`});
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive dynamic t-slot call 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c9 = [], p9 = {key:9,on:{}};
|
||||||
|
let vn9 = h('button', p9, c9);
|
||||||
|
extra.handlers['click__10__'] = extra.handlers['click__10__'] || function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['toggle'](e);};
|
||||||
|
p9.on['click'] = extra.handlers['click__10__'];
|
||||||
|
const slot11 = this.constructor.slots[context.__owl__.slotId + '_' + (scope['current'].slot)];
|
||||||
|
if (slot11) {
|
||||||
|
slot11.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c9, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn9;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -134,16 +288,17 @@ exports[`t-slot directive multiple roots are allowed in a default slot 1`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
let c4 = [], p4 = {key:4};
|
|
||||||
let vn4 = h('span', p4, c4);
|
|
||||||
c1.push(vn4);
|
|
||||||
c4.push({text: \`sts\`});
|
|
||||||
let c5 = [], p5 = {key:5};
|
let c5 = [], p5 = {key:5};
|
||||||
let vn5 = h('span', p5, c5);
|
let vn5 = h('span', p5, c5);
|
||||||
c1.push(vn5);
|
c4.push(vn5);
|
||||||
c5.push({text: \`rocks\`});
|
c5.push({text: \`sts\`});
|
||||||
|
let c6 = [], p6 = {key:6};
|
||||||
|
let vn6 = h('span', p6, c6);
|
||||||
|
c4.push(vn6);
|
||||||
|
c6.push({text: \`rocks\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -151,16 +306,17 @@ exports[`t-slot directive multiple roots are allowed in a named slot 1`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_content_template\\"
|
// Template name: \\"slot_content_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
let c4 = [], p4 = {key:4};
|
|
||||||
let vn4 = h('span', p4, c4);
|
|
||||||
c1.push(vn4);
|
|
||||||
c4.push({text: \`sts\`});
|
|
||||||
let c5 = [], p5 = {key:5};
|
let c5 = [], p5 = {key:5};
|
||||||
let vn5 = h('span', p5, c5);
|
let vn5 = h('span', p5, c5);
|
||||||
c1.push(vn5);
|
c4.push(vn5);
|
||||||
c5.push({text: \`rocks\`});
|
c5.push({text: \`sts\`});
|
||||||
|
let c6 = [], p6 = {key:6};
|
||||||
|
let vn6 = h('span', p6, c6);
|
||||||
|
c4.push(vn6);
|
||||||
|
c6.push({text: \`rocks\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -186,24 +342,25 @@ exports[`t-slot directive refs are properly bound in slots 1`] = `
|
|||||||
) {
|
) {
|
||||||
// Template name: \\"slot_footer_template\\"
|
// Template name: \\"slot_footer_template\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
|
let parent = extra.parent;
|
||||||
context.__owl__.refs = context.__owl__.refs || {};
|
context.__owl__.refs = context.__owl__.refs || {};
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c8 = extra.parentNode;
|
||||||
let c8 = [], p8 = {key:8,on:{}};
|
let c9 = [], p9 = {key:9,on:{}};
|
||||||
let vn8 = h('button', p8, c8);
|
let vn9 = h('button', p9, c9);
|
||||||
c1.push(vn8);
|
c8.push(vn9);
|
||||||
extra.handlers['click__9__'] = extra.handlers['click__9__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['doSomething'](e);};
|
extra.handlers['click__10__'] = extra.handlers['click__10__'] || function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['doSomething'](e);};
|
||||||
p8.on['click'] = extra.handlers['click__9__'];
|
p9.on['click'] = extra.handlers['click__10__'];
|
||||||
const ref10 = \`myButton\`;
|
const ref11 = \`myButton\`;
|
||||||
p8.hook = {
|
p9.hook = {
|
||||||
create: (_, n) => {
|
create: (_, n) => {
|
||||||
context.__owl__.refs[ref10] = n.elm;
|
context.__owl__.refs[ref11] = n.elm;
|
||||||
},
|
},
|
||||||
destroy: () => {
|
destroy: () => {
|
||||||
delete context.__owl__.refs[ref10];
|
delete context.__owl__.refs[ref11];
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
c8.push({text: \`do something\`});
|
c9.push({text: \`do something\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -212,14 +369,15 @@ exports[`t-slot directive slots are rendered with proper context 1`] = `
|
|||||||
) {
|
) {
|
||||||
// Template name: \\"slot_footer_template\\"
|
// Template name: \\"slot_footer_template\\"
|
||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
|
let parent = extra.parent;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c8 = extra.parentNode;
|
||||||
let c8 = [], p8 = {key:8,on:{}};
|
let c9 = [], p9 = {key:9,on:{}};
|
||||||
let vn8 = h('button', p8, c8);
|
let vn9 = h('button', p9, c9);
|
||||||
c1.push(vn8);
|
c8.push(vn9);
|
||||||
extra.handlers['click__9__'] = extra.handlers['click__9__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['doSomething'](e);};
|
extra.handlers['click__10__'] = extra.handlers['click__10__'] || function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['doSomething'](e);};
|
||||||
p8.on['click'] = extra.handlers['click__9__'];
|
p9.on['click'] = extra.handlers['click__10__'];
|
||||||
c8.push({text: \`do something\`});
|
c9.push({text: \`do something\`});
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -229,14 +387,14 @@ exports[`t-slot directive slots are rendered with proper context, part 2 1`] = `
|
|||||||
// Template name: \\"Link\\"
|
// Template name: \\"Link\\"
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let _11 = scope['props'].to;
|
let _12 = scope['props'].to;
|
||||||
let c12 = [], p12 = {key:12,attrs:{href: _11}};
|
let c13 = [], p13 = {key:13,attrs:{href: _12}};
|
||||||
let vn12 = h('a', p12, c12);
|
let vn13 = h('a', p13, c13);
|
||||||
const slot13 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
const slot14 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
if (slot13) {
|
if (slot14) {
|
||||||
slot13.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c12, parent: extra.parent || context}));
|
slot14.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c13, parent: extra.parent || context}));
|
||||||
}
|
}
|
||||||
return vn12;
|
return vn13;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -283,17 +441,17 @@ exports[`t-slot directive slots are rendered with proper context, part 2 2`] = `
|
|||||||
w8 = false;
|
w8 = false;
|
||||||
}
|
}
|
||||||
if (w8) {
|
if (w8) {
|
||||||
w8.__updateProps(props8, extra.fiber, Object.assign(Object.create(context), scope));
|
w8.__updateProps(props8, extra.fiber, utils.combine(context, scope));
|
||||||
let pvnode = w8.__owl__.pvnode;
|
let pvnode = w8.__owl__.pvnode;
|
||||||
c7.push(pvnode);
|
c7.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey8 = \`Link\`;
|
let componentKey8 = \`Link\`;
|
||||||
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| scope['Link'];
|
let W8 = scope['Link'] || context.constructor.components[componentKey8] || QWeb.components[componentKey8];
|
||||||
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
||||||
w8 = new W8(parent, props8);
|
w8 = new W8(parent, props8);
|
||||||
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
||||||
w8.__owl__.slotId = 1;
|
w8.__owl__.slotId = 1;
|
||||||
let fiber = w8.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w8.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
||||||
c7.push(pvnode);
|
c7.push(pvnode);
|
||||||
w8.__owl__.pvnode = pvnode;
|
w8.__owl__.pvnode = pvnode;
|
||||||
@@ -309,13 +467,14 @@ exports[`t-slot directive slots are rendered with proper context, part 2 3`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c7 = extra.parentNode;
|
let c10 = extra.parentNode;
|
||||||
c7.push({text: \`User \`});
|
c10.push({text: \`User \`});
|
||||||
let _10 = scope['user'].name;
|
let _11 = scope['user'].name;
|
||||||
if (_10 != null) {
|
if (_11 != null) {
|
||||||
c7.push({text: _10});
|
c10.push({text: _11});
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
@@ -326,14 +485,14 @@ exports[`t-slot directive slots are rendered with proper context, part 3 1`] = `
|
|||||||
// Template name: \\"Link\\"
|
// Template name: \\"Link\\"
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let _10 = scope['props'].to;
|
let _12 = scope['props'].to;
|
||||||
let c11 = [], p11 = {key:11,attrs:{href: _10}};
|
let c13 = [], p13 = {key:13,attrs:{href: _12}};
|
||||||
let vn11 = h('a', p11, c11);
|
let vn13 = h('a', p13, c13);
|
||||||
const slot12 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
const slot14 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
if (slot12) {
|
if (slot14) {
|
||||||
slot12.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c11, parent: extra.parent || context}));
|
slot14.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c13, parent: extra.parent || context}));
|
||||||
}
|
}
|
||||||
return vn11;
|
return vn13;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -381,17 +540,17 @@ exports[`t-slot directive slots are rendered with proper context, part 3 2`] = `
|
|||||||
w8 = false;
|
w8 = false;
|
||||||
}
|
}
|
||||||
if (w8) {
|
if (w8) {
|
||||||
w8.__updateProps(props8, extra.fiber, Object.assign(Object.create(context), scope));
|
w8.__updateProps(props8, extra.fiber, utils.combine(context, scope));
|
||||||
let pvnode = w8.__owl__.pvnode;
|
let pvnode = w8.__owl__.pvnode;
|
||||||
c7.push(pvnode);
|
c7.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey8 = \`Link\`;
|
let componentKey8 = \`Link\`;
|
||||||
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| scope['Link'];
|
let W8 = scope['Link'] || context.constructor.components[componentKey8] || QWeb.components[componentKey8];
|
||||||
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
||||||
w8 = new W8(parent, props8);
|
w8 = new W8(parent, props8);
|
||||||
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
||||||
w8.__owl__.slotId = 1;
|
w8.__owl__.slotId = 1;
|
||||||
let fiber = w8.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w8.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
||||||
c7.push(pvnode);
|
c7.push(pvnode);
|
||||||
w8.__owl__.pvnode = pvnode;
|
w8.__owl__.pvnode = pvnode;
|
||||||
@@ -407,11 +566,13 @@ exports[`t-slot directive slots are rendered with proper context, part 3 3`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c7 = extra.parentNode;
|
let c10 = extra.parentNode;
|
||||||
if (scope.userdescr != null) {
|
let _11 = scope['userdescr'];
|
||||||
c7.push({text: scope.userdescr});
|
if (_11 != null) {
|
||||||
|
c10.push({text: _11});
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
@@ -436,17 +597,17 @@ exports[`t-slot directive slots are rendered with proper context, part 4 1`] = `
|
|||||||
w2 = false;
|
w2 = false;
|
||||||
}
|
}
|
||||||
if (w2) {
|
if (w2) {
|
||||||
w2.__updateProps(props2, extra.fiber, Object.assign(Object.create(context), scope));
|
w2.__updateProps(props2, extra.fiber, utils.combine(context, scope));
|
||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w2.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`Link\`;
|
let componentKey2 = \`Link\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| scope['Link'];
|
let W2 = scope['Link'] || context.constructor.components[componentKey2] || QWeb.components[componentKey2];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w2 = new W2(parent, props2);
|
||||||
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
parent.__owl__.cmap['__3__'] = w2.__owl__.id;
|
||||||
w2.__owl__.slotId = 1;
|
w2.__owl__.slotId = 1;
|
||||||
let fiber = w2.__prepare(extra.fiber, Object.assign(Object.create(context), scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
let fiber = w2.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
let pvnode = h('dummy', {key: '__3__', hook: {remove() {},destroy(vn) {w2.destroy();}}});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w2.__owl__.pvnode = pvnode;
|
||||||
@@ -460,15 +621,120 @@ exports[`t-slot directive slots are rendered with proper context, part 4 2`] = `
|
|||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
// Template name: \\"slot_default_template\\"
|
// Template name: \\"slot_default_template\\"
|
||||||
|
let parent = extra.parent;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let c1 = extra.parentNode;
|
let c4 = extra.parentNode;
|
||||||
if (scope.userdescr != null) {
|
let _5 = scope['userdescr'];
|
||||||
c1.push({text: scope.userdescr});
|
if (_5 != null) {
|
||||||
|
c4.push({text: _5});
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive slots in t-foreach in t-foreach 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__2\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let QWeb = this.constructor;
|
||||||
|
let parent = context;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let vn1 = h('div', p1, c1);
|
||||||
|
let _2 = scope['tree'];
|
||||||
|
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
|
let _3 = _4 = _2;
|
||||||
|
if (!(_2 instanceof Array)) {
|
||||||
|
_3 = Object.keys(_2);
|
||||||
|
_4 = Object.values(_2);
|
||||||
|
}
|
||||||
|
let _length3 = _3.length;
|
||||||
|
let _origScope5 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
for (let i1 = 0; i1 < _length3; i1++) {
|
||||||
|
scope.node1_first = i1 === 0
|
||||||
|
scope.node1_last = i1 === _length3 - 1
|
||||||
|
scope.node1_index = i1
|
||||||
|
scope.node1 = _3[i1]
|
||||||
|
scope.node1_value = _4[i1]
|
||||||
|
let key1 = scope['node1'].key;
|
||||||
|
let c6 = [], p6 = {key:\`\${key1}_6\`};
|
||||||
|
let vn6 = h('div', p6, c6);
|
||||||
|
c1.push(vn6);
|
||||||
|
let _7 = scope['node1'].value;
|
||||||
|
if (_7 != null) {
|
||||||
|
c6.push({text: _7});
|
||||||
|
}
|
||||||
|
let c8 = [], p8 = {key:\`\${key1}_8\`};
|
||||||
|
let vn8 = h('ul', p8, c8);
|
||||||
|
c1.push(vn8);
|
||||||
|
let _9 = scope['node1'].nodes;
|
||||||
|
if (!_9) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
|
let _10 = _11 = _9;
|
||||||
|
if (!(_9 instanceof Array)) {
|
||||||
|
_10 = Object.keys(_9);
|
||||||
|
_11 = Object.values(_9);
|
||||||
|
}
|
||||||
|
let _length10 = _10.length;
|
||||||
|
let _origScope12 = scope;
|
||||||
|
scope = Object.create(scope);
|
||||||
|
for (let i2 = 0; i2 < _length10; i2++) {
|
||||||
|
scope.node2_first = i2 === 0
|
||||||
|
scope.node2_last = i2 === _length10 - 1
|
||||||
|
scope.node2_index = i2
|
||||||
|
scope.node2 = _10[i2]
|
||||||
|
scope.node2_value = _11[i2]
|
||||||
|
let key2 = scope['node2'].key;
|
||||||
|
// Component 'Child'
|
||||||
|
let k14 = \`__14__\${key1}__\${key2}__\`;
|
||||||
|
let w13 = k14 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k14]] : false;
|
||||||
|
let props13 = {};
|
||||||
|
if (w13 && w13.__owl__.currentFiber && !w13.__owl__.vnode) {
|
||||||
|
w13.destroy();
|
||||||
|
w13 = false;
|
||||||
|
}
|
||||||
|
if (w13) {
|
||||||
|
w13.__updateProps(props13, extra.fiber, utils.combine(context, scope));
|
||||||
|
let pvnode = w13.__owl__.pvnode;
|
||||||
|
c8.push(pvnode);
|
||||||
|
} else {
|
||||||
|
let componentKey13 = \`Child\`;
|
||||||
|
let W13 = scope['Child'] || context.constructor.components[componentKey13] || QWeb.components[componentKey13];
|
||||||
|
if (!W13) {throw new Error('Cannot find the definition of component \\"' + componentKey13 + '\\"')}
|
||||||
|
w13 = new W13(parent, props13);
|
||||||
|
parent.__owl__.cmap[k14] = w13.__owl__.id;
|
||||||
|
w13.__owl__.slotId = 1;
|
||||||
|
let fiber = w13.__prepare(extra.fiber, utils.combine(context, scope), () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
|
let pvnode = h('dummy', {key: k14, hook: {remove() {},destroy(vn) {w13.destroy();}}});
|
||||||
|
c8.push(pvnode);
|
||||||
|
w13.__owl__.pvnode = pvnode;
|
||||||
|
}
|
||||||
|
w13.__owl__.parentLastFiberId = extra.fiber.id;
|
||||||
|
}
|
||||||
|
scope = _origScope12;
|
||||||
|
}
|
||||||
|
scope = _origScope5;
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`t-slot directive t-set t-value in a slot 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"__template__1\\"
|
||||||
|
let h = this.h;
|
||||||
|
let c5 = [], p5 = {key:5};
|
||||||
|
let vn5 = h('span', p5, c5);
|
||||||
|
const slot6 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
|
if (slot6) {
|
||||||
|
slot6.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c5, parent: extra.parent || context}));
|
||||||
|
}
|
||||||
|
return vn5;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`t-slot directive template can just return a slot 1`] = `
|
exports[`t-slot directive template can just return a slot 1`] = `
|
||||||
"function anonymous(context, extra
|
"function anonymous(context, extra
|
||||||
) {
|
) {
|
||||||
@@ -476,12 +742,12 @@ exports[`t-slot directive template can just return a slot 1`] = `
|
|||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let result;
|
let result;
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
const slot6 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
const slot7 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
if (slot6) {
|
if (slot7) {
|
||||||
let children7= []
|
let children8= []
|
||||||
result = {}
|
result = {}
|
||||||
slot6.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: children7, parent: extra.parent || context}));
|
slot7.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: children8, parent: extra.parent || context}));
|
||||||
utils.defineProxy(result, children7[0]);
|
utils.defineProxy(result, children8[0]);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}"
|
}"
|
||||||
|
|||||||
+465
-73
@@ -1,4 +1,4 @@
|
|||||||
import { Component, Env } from "../../src/component/component";
|
import { Component, Env, STATUS } from "../../src/component/component";
|
||||||
import { useState } from "../../src/hooks";
|
import { useState } from "../../src/hooks";
|
||||||
import { xml } from "../../src/tags";
|
import { xml } from "../../src/tags";
|
||||||
import { makeDeferred, makeTestEnv, makeTestFixture, nextMicroTick, nextTick } from "../helpers";
|
import { makeDeferred, makeTestEnv, makeTestFixture, nextMicroTick, nextTick } from "../helpers";
|
||||||
@@ -25,35 +25,35 @@ afterEach(() => {
|
|||||||
fixture.remove();
|
fixture.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
function children(w: Component<any, any>): Component<any, any>[] {
|
function children(w: Component): Component[] {
|
||||||
const childrenMap = w.__owl__.children;
|
const childrenMap = w.__owl__.children;
|
||||||
return Object.keys(childrenMap).map(id => childrenMap[id]);
|
return Object.keys(childrenMap).map((id) => childrenMap[id]);
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("async rendering", () => {
|
describe("async rendering", () => {
|
||||||
test("destroying a widget before start is over", async () => {
|
test("destroying a widget before start is over", async () => {
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
class W extends Component<any, any> {
|
class W extends Component {
|
||||||
static template = xml`<div/>`;
|
static template = xml`<div/>`;
|
||||||
willStart(): Promise<void> {
|
willStart(): Promise<void> {
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const w = new W();
|
const w = new W();
|
||||||
|
expect(w.__owl__.status).toBe(STATUS.CREATED);
|
||||||
w.mount(fixture);
|
w.mount(fixture);
|
||||||
expect(w.__owl__.isDestroyed).toBe(false);
|
expect(w.__owl__.status).toBe(STATUS.WILLSTARTED);
|
||||||
expect(w.__owl__.isMounted).toBe(false);
|
|
||||||
w.destroy();
|
w.destroy();
|
||||||
|
expect(w.__owl__.status).toBe(STATUS.DESTROYED);
|
||||||
def.resolve();
|
def.resolve();
|
||||||
await nextTick();
|
await nextTick();
|
||||||
expect(w.__owl__.isDestroyed).toBe(true);
|
expect(w.__owl__.status).toBe(STATUS.DESTROYED);
|
||||||
expect(w.__owl__.isMounted).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("destroying/recreating a subwidget with different props (if start is not over)", async () => {
|
test("destroying/recreating a subwidget with different props (if start is not over)", async () => {
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
let n = 0;
|
let n = 0;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span>child:<t t-esc="props.val"/></span>`;
|
static template = xml`<span>child:<t t-esc="props.val"/></span>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -63,7 +63,7 @@ describe("async rendering", () => {
|
|||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class W extends Component<any, any> {
|
class W extends Component {
|
||||||
static template = xml`<div><t t-if="state.val > 1"><Child val="state.val"/></t></div>`;
|
static template = xml`<div><t t-if="state.val > 1"><Child val="state.val"/></t></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ val: 1 });
|
state = useState({ val: 1 });
|
||||||
@@ -90,7 +90,7 @@ describe("async rendering", () => {
|
|||||||
let defB = makeDeferred();
|
let defB = makeDeferred();
|
||||||
let nbRenderings: number = 0;
|
let nbRenderings: number = 0;
|
||||||
|
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
static template = xml`<span><t t-esc="getValue()"/></span>`;
|
static template = xml`<span><t t-esc="getValue()"/></span>`;
|
||||||
willStart(): Promise<void> {
|
willStart(): Promise<void> {
|
||||||
return defA;
|
return defA;
|
||||||
@@ -101,13 +101,13 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ChildB extends Component<any, any> {
|
class ChildB extends Component {
|
||||||
static template = xml`<span>b</span>`;
|
static template = xml`<span>b</span>`;
|
||||||
willStart(): Promise<void> {
|
willStart(): Promise<void> {
|
||||||
return defB;
|
return defB;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.flagA"><ChildA /></t>
|
<t t-if="state.flagA"><ChildA /></t>
|
||||||
@@ -139,20 +139,20 @@ describe("async rendering", () => {
|
|||||||
let defA = makeDeferred();
|
let defA = makeDeferred();
|
||||||
let defB = makeDeferred();
|
let defB = makeDeferred();
|
||||||
|
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
static template = xml`<span>a<t t-esc="props.val"/></span>`;
|
static template = xml`<span>a<t t-esc="props.val"/></span>`;
|
||||||
willUpdateProps(): Promise<void> {
|
willUpdateProps(): Promise<void> {
|
||||||
return defA;
|
return defA;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ChildB extends Component<any, any> {
|
class ChildB extends Component {
|
||||||
static template = xml`<span>b<t t-esc="props.val"/></span>`;
|
static template = xml`<span>b<t t-esc="props.val"/></span>`;
|
||||||
willStart(): Promise<void> {
|
willStart(): Promise<void> {
|
||||||
return defB;
|
return defB;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<ChildA val="state.valA"/>
|
<ChildA val="state.valA"/>
|
||||||
@@ -182,20 +182,20 @@ describe("async rendering", () => {
|
|||||||
let defA = makeDeferred();
|
let defA = makeDeferred();
|
||||||
let defB = makeDeferred();
|
let defB = makeDeferred();
|
||||||
|
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
static template = xml`<span>a<t t-esc="props.val"/></span>`;
|
static template = xml`<span>a<t t-esc="props.val"/></span>`;
|
||||||
willUpdateProps(): Promise<void> {
|
willUpdateProps(): Promise<void> {
|
||||||
return defA;
|
return defA;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ChildB extends Component<any, any> {
|
class ChildB extends Component {
|
||||||
static template = xml`<span>b<t t-esc="props.val"/></span>`;
|
static template = xml`<span>b<t t-esc="props.val"/></span>`;
|
||||||
willStart(): Promise<void> {
|
willStart(): Promise<void> {
|
||||||
return defB;
|
return defB;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<ChildA val="state.valA"/>
|
<ChildA val="state.valA"/>
|
||||||
@@ -224,7 +224,7 @@ describe("async rendering", () => {
|
|||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
const defs = [makeDeferred(), makeDeferred()];
|
const defs = [makeDeferred(), makeDeferred()];
|
||||||
let index = 0;
|
let index = 0;
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
willUpdateProps(): Promise<void> {
|
willUpdateProps(): Promise<void> {
|
||||||
return defs[index++];
|
return defs[index++];
|
||||||
@@ -234,7 +234,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><ChildA val="state.valA"/></div>`;
|
static template = xml`<div><ChildA val="state.valA"/></div>`;
|
||||||
static components = { ChildA };
|
static components = { ChildA };
|
||||||
state = useState({ valA: 1 });
|
state = useState({ valA: 1 });
|
||||||
@@ -258,7 +258,7 @@ describe("async rendering", () => {
|
|||||||
|
|
||||||
test("update a sub-component twice in the same frame, 2", async () => {
|
test("update a sub-component twice in the same frame, 2", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
static template = xml`<span><t t-esc="val()"/></span>`;
|
static template = xml`<span><t t-esc="val()"/></span>`;
|
||||||
patched() {
|
patched() {
|
||||||
steps.push("patched");
|
steps.push("patched");
|
||||||
@@ -269,7 +269,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><ChildA val="state.valA"/></div>`;
|
static template = xml`<div><ChildA val="state.valA"/></div>`;
|
||||||
static components = { ChildA };
|
static components = { ChildA };
|
||||||
state = useState({ valA: 1 });
|
state = useState({ valA: 1 });
|
||||||
@@ -302,9 +302,9 @@ describe("async rendering", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("components in a node in a t-foreach ", async () => {
|
test("components in a node in a t-foreach ", async () => {
|
||||||
class Child extends Component<any, any> {}
|
class Child extends Component {}
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
|
|
||||||
get items() {
|
get items() {
|
||||||
@@ -335,7 +335,7 @@ describe("async rendering", () => {
|
|||||||
test("properly behave when destroyed/unmounted while rendering ", async () => {
|
test("properly behave when destroyed/unmounted while rendering ", async () => {
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
|
|
||||||
class SubChild extends Component<any, any> {
|
class SubChild extends Component {
|
||||||
static template = xml`<div/>`;
|
static template = xml`<div/>`;
|
||||||
willPatch() {
|
willPatch() {
|
||||||
throw new Error("Should not happen!");
|
throw new Error("Should not happen!");
|
||||||
@@ -348,12 +348,12 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div><SubChild /></div>`;
|
static template = xml`<div><SubChild /></div>`;
|
||||||
static components = { SubChild };
|
static components = { SubChild };
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><t t-if="state.flag"><Child val="state.val"/></t></div>`;
|
static template = xml`<div><t t-if="state.flag"><Child val="state.val"/></t></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ flag: true, val: "Framboise Lindemans" });
|
state = useState({ flag: true, val: "Framboise Lindemans" });
|
||||||
@@ -396,18 +396,18 @@ describe("async rendering", () => {
|
|||||||
`);
|
`);
|
||||||
|
|
||||||
let destroyCount = 0;
|
let destroyCount = 0;
|
||||||
class ChildA extends Component<any, any> {
|
class ChildA extends Component {
|
||||||
destroy() {
|
destroy() {
|
||||||
destroyCount++;
|
destroyCount++;
|
||||||
super.destroy();
|
super.destroy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ChildB extends Component<any, any> {
|
class ChildB extends Component {
|
||||||
willStart(): any {
|
willStart(): any {
|
||||||
return new Promise(function() {});
|
return new Promise(function () {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { ChildA, ChildB };
|
static components = { ChildA, ChildB };
|
||||||
state = useState({ valA: 1, valB: 2, flag: false });
|
state = useState({ valA: 1, valB: 2, flag: false });
|
||||||
}
|
}
|
||||||
@@ -426,11 +426,11 @@ describe("async rendering", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("rendering component again in next microtick", async () => {
|
test("rendering component again in next microtick", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div t-name="Child">Child</div>`;
|
static template = xml`<div t-name="Child">Child</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<button t-on-click="onClick">Click</button>
|
<button t-on-click="onClick">Click</button>
|
||||||
@@ -458,7 +458,7 @@ describe("async rendering", () => {
|
|||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
let stateB;
|
let stateB;
|
||||||
|
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="someValue()"/></span>`;
|
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="someValue()"/></span>`;
|
||||||
someValue() {
|
someValue() {
|
||||||
return this.props.fromB;
|
return this.props.fromB;
|
||||||
@@ -469,7 +469,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentC.prototype.someValue = jest.fn(ComponentC.prototype.someValue);
|
ComponentC.prototype.someValue = jest.fn(ComponentC.prototype.someValue);
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
||||||
state = useState({ fromB: "b" });
|
state = useState({ fromB: "b" });
|
||||||
@@ -480,7 +480,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -514,14 +514,14 @@ describe("async rendering", () => {
|
|||||||
const defs = [makeDeferred(), makeDeferred()];
|
const defs = [makeDeferred(), makeDeferred()];
|
||||||
let index = 0;
|
let index = 0;
|
||||||
let stateB;
|
let stateB;
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromB"/></span>`;
|
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromB"/></span>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return defs[index++];
|
return defs[index++];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
state = useState({ fromB: "b" });
|
state = useState({ fromB: "b" });
|
||||||
@@ -532,7 +532,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static template = xml`<div><t t-esc="state.fromA"/><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><t t-esc="state.fromA"/><ComponentB fromA="state.fromA"/></div>`;
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -564,14 +564,14 @@ describe("async rendering", () => {
|
|||||||
const defs = [makeDeferred(), makeDeferred()];
|
const defs = [makeDeferred(), makeDeferred()];
|
||||||
let index = 0;
|
let index = 0;
|
||||||
let stateB;
|
let stateB;
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromB"/></span>`;
|
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromB"/></span>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return defs[index++];
|
return defs[index++];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
static template = xml`<p><ComponentC fromA="props.fromA" fromB="state.fromB" /></p>`;
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
state = useState({ fromB: "b" });
|
state = useState({ fromB: "b" });
|
||||||
@@ -582,7 +582,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -616,7 +616,7 @@ describe("async rendering", () => {
|
|||||||
let index = 0;
|
let index = 0;
|
||||||
let stateC;
|
let stateC;
|
||||||
|
|
||||||
class ComponentD extends Component<any, any> {
|
class ComponentD extends Component {
|
||||||
static template = xml`<i><t t-esc="props.fromA"/><t t-esc="someValue()"/></i>`;
|
static template = xml`<i><t t-esc="props.fromA"/><t t-esc="someValue()"/></i>`;
|
||||||
someValue() {
|
someValue() {
|
||||||
return this.props.fromC;
|
return this.props.fromC;
|
||||||
@@ -627,7 +627,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentD.prototype.someValue = jest.fn(ComponentD.prototype.someValue);
|
ComponentD.prototype.someValue = jest.fn(ComponentD.prototype.someValue);
|
||||||
|
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><ComponentD fromA="props.fromA" fromC="state.fromC" /></span>`;
|
static template = xml`<span><ComponentD fromA="props.fromA" fromC="state.fromC" /></span>`;
|
||||||
static components = { ComponentD };
|
static components = { ComponentD };
|
||||||
state = useState({ fromC: "c" });
|
state = useState({ fromC: "c" });
|
||||||
@@ -637,7 +637,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><ComponentC fromA="props.fromA" /></p>`;
|
static template = xml`<p><ComponentC fromA="props.fromA" /></p>`;
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
|
|
||||||
@@ -646,7 +646,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -686,7 +686,7 @@ describe("async rendering", () => {
|
|||||||
let index = 0;
|
let index = 0;
|
||||||
let stateC;
|
let stateC;
|
||||||
|
|
||||||
class ComponentD extends Component<any, any> {
|
class ComponentD extends Component {
|
||||||
static template = xml`<i><t t-esc="props.fromA"/><t t-esc="someValue()"/></i>`;
|
static template = xml`<i><t t-esc="props.fromA"/><t t-esc="someValue()"/></i>`;
|
||||||
someValue() {
|
someValue() {
|
||||||
return this.props.fromC;
|
return this.props.fromC;
|
||||||
@@ -697,7 +697,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentD.prototype.someValue = jest.fn(ComponentD.prototype.someValue);
|
ComponentD.prototype.someValue = jest.fn(ComponentD.prototype.someValue);
|
||||||
|
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><ComponentD fromA="props.fromA" fromC="state.fromC" /></span>`;
|
static template = xml`<span><ComponentD fromA="props.fromA" fromC="state.fromC" /></span>`;
|
||||||
static components = { ComponentD };
|
static components = { ComponentD };
|
||||||
state = useState({ fromC: "c" });
|
state = useState({ fromC: "c" });
|
||||||
@@ -707,7 +707,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><ComponentC fromA="props.fromA" /></p>`;
|
static template = xml`<p><ComponentC fromA="props.fromA" /></p>`;
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
|
|
||||||
@@ -716,7 +716,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -754,7 +754,7 @@ describe("async rendering", () => {
|
|||||||
const defsB = [makeDeferred(), makeDeferred()];
|
const defsB = [makeDeferred(), makeDeferred()];
|
||||||
let index = 0;
|
let index = 0;
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><t t-esc="someValue()" /></p>`;
|
static template = xml`<p><t t-esc="someValue()" /></p>`;
|
||||||
someValue() {
|
someValue() {
|
||||||
return this.props.fromA;
|
return this.props.fromA;
|
||||||
@@ -765,7 +765,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -799,7 +799,7 @@ describe("async rendering", () => {
|
|||||||
const defsB = [makeDeferred(), makeDeferred()];
|
const defsB = [makeDeferred(), makeDeferred()];
|
||||||
let index = 0;
|
let index = 0;
|
||||||
|
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><t t-esc="someValue()" /></p>`;
|
static template = xml`<p><t t-esc="someValue()" /></p>`;
|
||||||
someValue() {
|
someValue() {
|
||||||
return this.props.fromA;
|
return this.props.fromA;
|
||||||
@@ -810,7 +810,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -841,7 +841,7 @@ describe("async rendering", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("concurrent renderings scenario 7", async () => {
|
test("concurrent renderings scenario 7", async () => {
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><t t-esc="props.fromA" /><t t-esc="someValue()" /></p>`;
|
static template = xml`<p><t t-esc="props.fromA" /><t t-esc="someValue()" /></p>`;
|
||||||
state = useState({ fromB: "b" });
|
state = useState({ fromB: "b" });
|
||||||
someValue() {
|
someValue() {
|
||||||
@@ -853,7 +853,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
ComponentB.prototype.someValue = jest.fn(ComponentB.prototype.someValue);
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -874,7 +874,7 @@ describe("async rendering", () => {
|
|||||||
test("concurrent renderings scenario 8", async () => {
|
test("concurrent renderings scenario 8", async () => {
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
let stateB;
|
let stateB;
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><t t-esc="props.fromA" /><t t-esc="state.fromB" /></p>`;
|
static template = xml`<p><t t-esc="props.fromA" /><t t-esc="state.fromB" /></p>`;
|
||||||
state = useState({ fromB: "b" });
|
state = useState({ fromB: "b" });
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
@@ -886,7 +886,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
static template = xml`<div><ComponentB fromA="state.fromA"/></div>`;
|
||||||
state = useState({ fromA: 1 });
|
state = useState({ fromA: 1 });
|
||||||
@@ -925,10 +925,10 @@ describe("async rendering", () => {
|
|||||||
// re-rendering
|
// re-rendering
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
let stateC;
|
let stateC;
|
||||||
class ComponentD extends Component<any, any> {
|
class ComponentD extends Component {
|
||||||
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromC"/></span>`;
|
static template = xml`<span><t t-esc="props.fromA"/><t t-esc="props.fromC"/></span>`;
|
||||||
}
|
}
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<p><ComponentD fromA="props.fromA" fromC="state.fromC" /></p>`;
|
static template = xml`<p><ComponentD fromA="props.fromA" fromC="state.fromC" /></p>`;
|
||||||
static components = { ComponentD };
|
static components = { ComponentD };
|
||||||
state = useState({ fromC: "b1" });
|
state = useState({ fromC: "b1" });
|
||||||
@@ -938,13 +938,13 @@ describe("async rendering", () => {
|
|||||||
stateC = this.state;
|
stateC = this.state;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<b><t t-esc="props.fromA"/></b>`;
|
static template = xml`<b><t t-esc="props.fromA"/></b>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-esc="state.fromA"/>
|
<t t-esc="state.fromA"/>
|
||||||
@@ -991,14 +991,14 @@ describe("async rendering", () => {
|
|||||||
const defB = makeDeferred();
|
const defB = makeDeferred();
|
||||||
const defC = makeDeferred();
|
const defC = makeDeferred();
|
||||||
let stateB;
|
let stateB;
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><t t-esc="props.value"/></span>`;
|
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||||
willStart() {
|
willStart() {
|
||||||
return defC;
|
return defC;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ComponentC.prototype.__render = jest.fn(ComponentC.prototype.__render);
|
ComponentC.prototype.__render = jest.fn(ComponentC.prototype.__render);
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static template = xml`<p><ComponentC t-if="state.hasChild" value="props.value"/></p>`;
|
static template = xml`<p><ComponentC t-if="state.hasChild" value="props.value"/></p>`;
|
||||||
state = useState({ hasChild: false });
|
state = useState({ hasChild: false });
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
@@ -1010,7 +1010,7 @@ describe("async rendering", () => {
|
|||||||
return defB;
|
return defB;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static template = xml`<div><ComponentB value="state.value"/></div>`;
|
static template = xml`<div><ComponentB value="state.value"/></div>`;
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
@@ -1042,7 +1042,7 @@ describe("async rendering", () => {
|
|||||||
// remapped to the promise of the ambient rendering)
|
// remapped to the promise of the ambient rendering)
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
let child;
|
let child;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/>|<t t-esc="val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/>|<t t-esc="val"/></span>`;
|
||||||
val = 3;
|
val = 3;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
@@ -1051,7 +1051,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child val="state.valA"/></div>`;
|
static template = xml`<div><Child val="state.valA"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ valA: 1 });
|
state = useState({ valA: 1 });
|
||||||
@@ -1079,14 +1079,14 @@ describe("async rendering", () => {
|
|||||||
// rendered but not completed yet)
|
// rendered but not completed yet)
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child val="state.val"/></div>`;
|
static template = xml`<div><Child val="state.val"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ val: 1 });
|
state = useState({ val: 1 });
|
||||||
@@ -1117,7 +1117,7 @@ describe("async rendering", () => {
|
|||||||
|
|
||||||
test("concurrent renderings scenario 13", async () => {
|
test("concurrent renderings scenario 13", async () => {
|
||||||
let lastChild;
|
let lastChild;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="state.val"/></span>`;
|
static template = xml`<span><t t-esc="state.val"/></span>`;
|
||||||
state = useState({ val: 0 });
|
state = useState({ val: 0 });
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -1129,7 +1129,7 @@ describe("async rendering", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<Child/>
|
<Child/>
|
||||||
@@ -1152,8 +1152,244 @@ describe("async rendering", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div><span>0</span><span>1</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>0</span><span>1</span></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("concurrent renderings scenario 14", async () => {
|
||||||
|
let b: B | undefined = undefined;
|
||||||
|
let c: C | undefined = undefined;
|
||||||
|
class C extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<p>
|
||||||
|
<span t-esc="props.fromA"/>
|
||||||
|
<span t-esc="props.fromB"/>
|
||||||
|
<span t-esc="state.fromC"/>
|
||||||
|
</p>`;
|
||||||
|
|
||||||
|
state = useState({ fromC: 3 });
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
c = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class B extends Component {
|
||||||
|
static template = xml`<p><C fromB="state.fromB" fromA="props.fromA"/></p>`;
|
||||||
|
static components = { C };
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
b = this;
|
||||||
|
}
|
||||||
|
state = useState({ fromB: 2 });
|
||||||
|
}
|
||||||
|
class A extends Component {
|
||||||
|
static template = xml`<p><B fromA="state.fromA"/></p>`;
|
||||||
|
static components = { B };
|
||||||
|
state = useState({ fromA: 1 });
|
||||||
|
}
|
||||||
|
const a = new A();
|
||||||
|
await a.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering of the whole tree
|
||||||
|
a.state.fromA += 10;
|
||||||
|
// wait enough for the whole tree to be re-rendered, but not patched yet
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering from C, which will remap its new fiber
|
||||||
|
c!.state.fromC += 10;
|
||||||
|
// trigger a re-rendering from B, which will remap its new fiber as well
|
||||||
|
b!.state.fromB += 10;
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
// at this point, all re-renderings should have been done correctly, and
|
||||||
|
// the root fiber (A) counter should have been reset to 0, so the DOM should
|
||||||
|
// have been patched with the updated version of each component
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>11</span><span>12</span><span>13</span></p></p></p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("concurrent renderings scenario 15", async () => {
|
||||||
|
let b: B | undefined = undefined;
|
||||||
|
let c: C | undefined = undefined;
|
||||||
|
class C extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<p>
|
||||||
|
<span t-esc="props.fromA"/>
|
||||||
|
<span t-esc="props.fromB"/>
|
||||||
|
<span t-esc="state.fromC"/>
|
||||||
|
</p>`;
|
||||||
|
|
||||||
|
state = useState({ fromC: 3 });
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
c = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class B extends Component {
|
||||||
|
static template = xml`<p><C fromB="state.fromB" fromA="props.fromA"/></p>`;
|
||||||
|
static components = { C };
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
b = this;
|
||||||
|
}
|
||||||
|
state = useState({ fromB: 2 });
|
||||||
|
}
|
||||||
|
class A extends Component {
|
||||||
|
static template = xml`<p><B fromA="state.fromA"/></p>`;
|
||||||
|
static components = { B };
|
||||||
|
state = useState({ fromA: 1 });
|
||||||
|
}
|
||||||
|
const a = new A();
|
||||||
|
await a.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering of the whole tree
|
||||||
|
a.state.fromA += 10;
|
||||||
|
// wait enough for the whole tree to be re-rendered, but not patched yet
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering from C, which will remap its new fiber
|
||||||
|
c!.state.fromC += 10;
|
||||||
|
// trigger a re-rendering from B, which will remap its new fiber as well
|
||||||
|
b!.state.fromB += 10;
|
||||||
|
|
||||||
|
// simulate a flush (nothing should have changed as no fiber should have its
|
||||||
|
// counter to 0)
|
||||||
|
Component.scheduler.flush();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// wait a bit and simulate another flush (we expect nothing to change as well)
|
||||||
|
await nextMicroTick();
|
||||||
|
Component.scheduler.flush();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>11</span><span>12</span><span>13</span></p></p></p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("concurrent renderings scenario 16", async () => {
|
||||||
|
expect.assertions(4);
|
||||||
|
let b: B | undefined = undefined;
|
||||||
|
let c: C | undefined = undefined;
|
||||||
|
class D extends Component {
|
||||||
|
static template = xml`<ul>DDD</ul>`;
|
||||||
|
async willStart() {
|
||||||
|
await nextTick();
|
||||||
|
await nextTick();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class C extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<p>
|
||||||
|
<span t-esc="props.fromA"/>
|
||||||
|
<span t-esc="props.fromB"/>
|
||||||
|
<span t-esc="state.fromC"/>
|
||||||
|
<D t-if="state.fromC === 13"/>
|
||||||
|
</p>`;
|
||||||
|
static components = { D };
|
||||||
|
state = { fromC: 3 }; // not reactive
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
c = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class B extends Component {
|
||||||
|
static template = xml`<p><C fromB="state.fromB" fromA="props.fromA"/></p>`;
|
||||||
|
static components = { C };
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
b = this;
|
||||||
|
}
|
||||||
|
state = useState({ fromB: 2 });
|
||||||
|
}
|
||||||
|
class A extends Component {
|
||||||
|
static template = xml`<p><B fromA="state.fromA"/></p>`;
|
||||||
|
static components = { B };
|
||||||
|
state = useState({ fromA: 1 });
|
||||||
|
}
|
||||||
|
const a = new A();
|
||||||
|
await a.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering of the whole tree
|
||||||
|
a.state.fromA += 10;
|
||||||
|
// wait enough for the whole tree to be re-rendered, but not patched yet
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
|
||||||
|
// trigger a re-rendering from C, which will remap its new fiber
|
||||||
|
c!.state.fromC += 10;
|
||||||
|
const prom = c!.render().then(() => {
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>11</span><span>12</span><span>13</span><ul>DDD</ul></p></p></p>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
// trigger a re-rendering from B, which will remap its new fiber as well
|
||||||
|
b!.state.fromB += 10;
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
// at this point, C rendering is still pending, and nothing should have been
|
||||||
|
// updated yet.
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<p><p><p><span>1</span><span>2</span><span>3</span></p></p></p>"
|
||||||
|
);
|
||||||
|
await prom;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("concurrent renderings scenario 17", async () => {
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<span><t t-esc="state.value"/></span>`;
|
||||||
|
state = useState({ value: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<span>1</span>");
|
||||||
|
|
||||||
|
parent.state.value = 2;
|
||||||
|
parent.__owl__.currentFiber!.cancel();
|
||||||
|
|
||||||
|
parent.state.value = 3; // update value directly
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<span>3</span>");
|
||||||
|
|
||||||
|
parent.state.value = 4; // update value after a tick
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<span>4</span>");
|
||||||
|
});
|
||||||
|
|
||||||
test("change state and call manually render: no unnecessary rendering", async () => {
|
test("change state and call manually render: no unnecessary rendering", async () => {
|
||||||
class Widget extends Component<any, any> {
|
class Widget extends Component {
|
||||||
static template = xml`<div><t t-esc="state.val"/></div>`;
|
static template = xml`<div><t t-esc="state.val"/></div>`;
|
||||||
state = useState({ val: 1 });
|
state = useState({ val: 1 });
|
||||||
}
|
}
|
||||||
@@ -1169,4 +1405,160 @@ describe("async rendering", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div>2</div>");
|
expect(fixture.innerHTML).toBe("<div>2</div>");
|
||||||
expect(Widget.prototype.__render).toHaveBeenCalledTimes(2);
|
expect(Widget.prototype.__render).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("components with shouldUpdate=false", async () => {
|
||||||
|
const state = { p: 1, cc: 10 };
|
||||||
|
|
||||||
|
class ChildChild extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
child child: <t t-esc="state.cc"/>
|
||||||
|
</div>`;
|
||||||
|
state = state;
|
||||||
|
shouldUpdate() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static components = { ChildChild };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
child
|
||||||
|
<ChildChild/>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
shouldUpdate() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let parent: any;
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
parent: <t t-esc="state.p"/>
|
||||||
|
<Child/>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
state = state;
|
||||||
|
constructor(a, b) {
|
||||||
|
super(a, b);
|
||||||
|
parent = this;
|
||||||
|
}
|
||||||
|
shouldUpdate() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static components = { Parent };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Parent/>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
var div = document.createElement("div");
|
||||||
|
fixture.appendChild(div);
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div></div><div><div> parent: 1<div> child <div> child child: 10</div></div></div></div>"
|
||||||
|
);
|
||||||
|
app.mount(div);
|
||||||
|
|
||||||
|
// wait for rendering from second mount to go through parent
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
state.cc++;
|
||||||
|
state.p++;
|
||||||
|
parent.render();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><div><div> parent: 2<div> child <div> child child: 11</div></div></div></div></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("components with shouldUpdate=false, part 2", async () => {
|
||||||
|
const state = { p: 1, cc: 10 };
|
||||||
|
let shouldUpdate = true;
|
||||||
|
|
||||||
|
class ChildChild extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
child child: <t t-esc="state.cc"/>
|
||||||
|
</div>`;
|
||||||
|
state = state;
|
||||||
|
shouldUpdate() {
|
||||||
|
return shouldUpdate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static components = { ChildChild };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
child
|
||||||
|
<ChildChild/>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
shouldUpdate() {
|
||||||
|
return shouldUpdate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let parent: any;
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
parent: <t t-esc="state.p"/>
|
||||||
|
<Child/>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
state = state;
|
||||||
|
constructor(a, b) {
|
||||||
|
super(a, b);
|
||||||
|
parent = this;
|
||||||
|
}
|
||||||
|
shouldUpdate() {
|
||||||
|
return shouldUpdate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static components = { Parent };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Parent/>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><div> parent: 1<div> child <div> child child: 10</div></div></div></div>"
|
||||||
|
);
|
||||||
|
|
||||||
|
state.cc++;
|
||||||
|
state.p++;
|
||||||
|
app.render();
|
||||||
|
|
||||||
|
// wait for rendering to go through child
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
shouldUpdate = false;
|
||||||
|
parent.render();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><div> parent: 2<div> child <div> child child: 11</div></div></div></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,10 +28,10 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("class and style attributes with t-component", () => {
|
describe("class and style attributes with t-component", () => {
|
||||||
test("class is properly added on widget root el", async () => {
|
test("class is properly added on widget root el", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div class="c"/>`;
|
static template = xml`<div class="c"/>`;
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static template = xml`<div><Child class="a b"/></div>`;
|
static template = xml`<div><Child class="a b"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -41,10 +41,10 @@ describe("class and style attributes with t-component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("empty class attribute is not added on widget root el", async () => {
|
test("empty class attribute is not added on widget root el", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span/>`;
|
static template = xml`<span/>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child class=""/></div>`;
|
static template = xml`<div><Child class=""/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -54,10 +54,10 @@ describe("class and style attributes with t-component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("t-att-class is properly added/removed on widget root el", async () => {
|
test("t-att-class is properly added/removed on widget root el", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div class="c"/>`;
|
static template = xml`<div class="c"/>`;
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static template = xml`<div><Child t-att-class="{a:state.a, b:state.b}"/></div>`;
|
static template = xml`<div><Child t-att-class="{a:state.a, b:state.b}"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ a: true, b: false });
|
state = useState({ a: true, b: false });
|
||||||
@@ -80,8 +80,8 @@ describe("class and style attributes with t-component", () => {
|
|||||||
<Child class="a b c d"/>
|
<Child class="a b c d"/>
|
||||||
</div>`
|
</div>`
|
||||||
);
|
);
|
||||||
class Child extends Component<any, any> {}
|
class Child extends Component {}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
env.qweb.addTemplate("Child", `<div/>`);
|
env.qweb.addTemplate("Child", `<div/>`);
|
||||||
@@ -99,10 +99,10 @@ describe("class and style attributes with t-component", () => {
|
|||||||
<span t-name="Child" class="c" t-att-class="{ d: state.d }"/>
|
<span t-name="Child" class="c" t-att-class="{ d: state.d }"/>
|
||||||
</templates>`);
|
</templates>`);
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
state = useState({ d: true });
|
state = useState({ d: true });
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ b: true });
|
state = useState({ b: true });
|
||||||
child = useRef("child");
|
child = useRef("child");
|
||||||
@@ -141,10 +141,10 @@ describe("class and style attributes with t-component", () => {
|
|||||||
<span t-name="Child" class="c" t-att-class="state.d ? 'd' : ''"/>
|
<span t-name="Child" class="c" t-att-class="state.d ? 'd' : ''"/>
|
||||||
</templates>`);
|
</templates>`);
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
state = useState({ d: true });
|
state = useState({ d: true });
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ b: true });
|
state = useState({ b: true });
|
||||||
child = useRef("child");
|
child = useRef("child");
|
||||||
@@ -180,7 +180,7 @@ describe("class and style attributes with t-component", () => {
|
|||||||
<div t-name="App" t-att-class="{ c: state.c }" />
|
<div t-name="App" t-att-class="{ c: state.c }" />
|
||||||
</templates>`);
|
</templates>`);
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
state = useState({ c: true });
|
state = useState({ c: true });
|
||||||
mounted() {
|
mounted() {
|
||||||
this.el!.classList.add("user");
|
this.el!.classList.add("user");
|
||||||
@@ -207,11 +207,11 @@ describe("class and style attributes with t-component", () => {
|
|||||||
</div>`
|
</div>`
|
||||||
);
|
);
|
||||||
|
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`<div/>`;
|
static template = xml`<div/>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static components = { child: SomeComponent };
|
static components = { child: SomeComponent };
|
||||||
}
|
}
|
||||||
const widget = new ParentWidget();
|
const widget = new ParentWidget();
|
||||||
@@ -228,11 +228,11 @@ describe("class and style attributes with t-component", () => {
|
|||||||
</div>`
|
</div>`
|
||||||
);
|
);
|
||||||
|
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`<div/>`;
|
static template = xml`<div/>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static components = { child: SomeComponent };
|
static components = { child: SomeComponent };
|
||||||
state = useState({ style: "font-size: 20px" });
|
state = useState({ style: "font-size: 20px" });
|
||||||
}
|
}
|
||||||
@@ -250,10 +250,10 @@ describe("class and style attributes with t-component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("error in subcomponent with class", async () => {
|
test("error in subcomponent with class", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div t-esc="this.will.crash"/>`;
|
static template = xml`<div t-esc="this.will.crash"/>`;
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static template = xml`<div><Child class="a"/></div>`;
|
static template = xml`<div><Child class="a"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -265,7 +265,8 @@ describe("class and style attributes with t-component", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'crash'\)|Cannot read property 'crash' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
expect(fixture.innerHTML).toBe("");
|
expect(fixture.innerHTML).toBe("");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+750
-335
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
|||||||
import { Component, Env } from "../../src/component/component";
|
import { Component, Env, mount, STATUS } from "../../src/component/component";
|
||||||
import { useState } from "../../src/hooks";
|
import { useState } from "../../src/hooks";
|
||||||
import { xml } from "../../src/tags";
|
import { xml } from "../../src/tags";
|
||||||
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
||||||
@@ -41,10 +41,10 @@ describe("component error handling (catchError)", () => {
|
|||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
const handler = jest.fn();
|
const handler = jest.fn();
|
||||||
env.qweb.on("error", null, handler);
|
env.qweb.on("error", null, handler);
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.error">Error handled</t>
|
<t t-if="state.error">Error handled</t>
|
||||||
@@ -56,7 +56,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<ErrorBoundary><ErrorComponent flag="state.flag"/></ErrorBoundary>
|
<ErrorBoundary><ErrorComponent flag="state.flag"/></ErrorBoundary>
|
||||||
@@ -83,11 +83,11 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
|
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
static template = xml`<div>hey<t t-esc="props.flag and state.this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><ErrorComponent flag="state.flag"/></div>`;
|
static template = xml`<div><ErrorComponent flag="state.flag"/></div>`;
|
||||||
static components = { ErrorComponent };
|
static components = { ErrorComponent };
|
||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
@@ -95,7 +95,9 @@ describe("component error handling (catchError)", () => {
|
|||||||
try {
|
try {
|
||||||
await super.render();
|
await super.render();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
expect(e.message).toBe("Cannot read property 'this' of undefined");
|
expect(e.message).toMatch(
|
||||||
|
/Cannot read properties of undefined \(reading 'this'\)|Cannot read property 'this' of undefined/
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,7 +110,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
|
|
||||||
expect(console.error).toBeCalledTimes(0);
|
expect(console.error).toBeCalledTimes(0);
|
||||||
console.error = consoleError;
|
console.error = consoleError;
|
||||||
expect(app.__owl__.isDestroyed).toBe(true);
|
expect(app.__owl__.status).toBe(STATUS.DESTROYED);
|
||||||
expect(handler).toBeCalledTimes(1);
|
expect(handler).toBeCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -117,10 +119,10 @@ describe("component error handling (catchError)", () => {
|
|||||||
env.qweb.on("error", null, handler);
|
env.qweb.on("error", null, handler);
|
||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.error">Error handled</t>
|
<t t-if="state.error">Error handled</t>
|
||||||
@@ -132,7 +134,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
@@ -153,10 +155,10 @@ describe("component error handling (catchError)", () => {
|
|||||||
env.qweb.on("error", null, handler);
|
env.qweb.on("error", null, handler);
|
||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
static template = xml`<div>hey<t t-esc="state.this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.error">Error handled</t>
|
<t t-if="state.error">Error handled</t>
|
||||||
@@ -168,7 +170,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<ErrorBoundary t-if="state.flag"><ErrorComponent /></ErrorBoundary>
|
<ErrorBoundary t-if="state.flag"><ErrorComponent /></ErrorBoundary>
|
||||||
@@ -203,20 +205,20 @@ describe("component error handling (catchError)", () => {
|
|||||||
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
</templates>`);
|
</templates>`);
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
constructor(parent) {
|
constructor(parent) {
|
||||||
super(parent);
|
super(parent);
|
||||||
throw new Error("NOOOOO");
|
throw new Error("NOOOOO");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
state = useState({ error: false });
|
state = useState({ error: false });
|
||||||
|
|
||||||
catchError() {
|
catchError() {
|
||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { ErrorBoundary, ErrorComponent };
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
}
|
}
|
||||||
const app = new App();
|
const app = new App();
|
||||||
@@ -231,7 +233,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
test("can catch an error in the willStart call", async () => {
|
test("can catch an error in the willStart call", async () => {
|
||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div t-name="ErrorComponent">Some text</div>`;
|
static template = xml`<div t-name="ErrorComponent">Some text</div>`;
|
||||||
async willStart() {
|
async willStart() {
|
||||||
// we wait a little bit to be in a different stack frame
|
// we wait a little bit to be in a different stack frame
|
||||||
@@ -239,7 +241,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
throw new Error("NOOOOO");
|
throw new Error("NOOOOO");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.error">Error handled</t>
|
<t t-if="state.error">Error handled</t>
|
||||||
@@ -251,7 +253,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><ErrorBoundary><ErrorComponent /></ErrorBoundary></div>`;
|
static template = xml`<div><ErrorBoundary><ErrorComponent /></ErrorBoundary></div>`;
|
||||||
static components = { ErrorBoundary, ErrorComponent };
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
}
|
}
|
||||||
@@ -277,19 +279,19 @@ describe("component error handling (catchError)", () => {
|
|||||||
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
<ErrorBoundary><ErrorComponent /></ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
</templates>`);
|
</templates>`);
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
mounted() {
|
mounted() {
|
||||||
throw new Error("NOOOOO");
|
throw new Error("NOOOOO");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
state = useState({ error: false });
|
state = useState({ error: false });
|
||||||
|
|
||||||
catchError() {
|
catchError() {
|
||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { ErrorBoundary, ErrorComponent };
|
static components = { ErrorBoundary, ErrorComponent };
|
||||||
}
|
}
|
||||||
const app = new App();
|
const app = new App();
|
||||||
@@ -304,13 +306,13 @@ describe("component error handling (catchError)", () => {
|
|||||||
// we do not catch error in willPatch anymore
|
// we do not catch error in willPatch anymore
|
||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn();
|
console.error = jest.fn();
|
||||||
class ErrorComponent extends Component<any, any> {
|
class ErrorComponent extends Component {
|
||||||
static template = xml`<div><t t-esc="props.message"/></div>`;
|
static template = xml`<div><t t-esc="props.message"/></div>`;
|
||||||
willPatch() {
|
willPatch() {
|
||||||
throw new Error("NOOOOO");
|
throw new Error("NOOOOO");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ErrorBoundary extends Component<any, any> {
|
class ErrorBoundary extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.error">Error handled</t>
|
<t t-if="state.error">Error handled</t>
|
||||||
@@ -322,7 +324,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
this.state.error = true;
|
this.state.error = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<span><t t-esc="state.message"/></span>
|
<span><t t-esc="state.message"/></span>
|
||||||
@@ -347,7 +349,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
// we do not catch error in willPatch anymore
|
// we do not catch error in willPatch anymore
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,7 +361,8 @@ describe("component error handling (catchError)", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'crash'\)|Cannot read property 'crash' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
|
|
||||||
expect(console.error).toBeCalledTimes(0);
|
expect(console.error).toBeCalledTimes(0);
|
||||||
console.error = consoleError;
|
console.error = consoleError;
|
||||||
@@ -369,7 +372,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div>abc</div>`;
|
static template = xml`<div>abc</div>`;
|
||||||
mounted() {
|
mounted() {
|
||||||
throw new Error("boom");
|
throw new Error("boom");
|
||||||
@@ -395,7 +398,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><t t-esc="val"/></div>`;
|
static template = xml`<div><t t-esc="val"/></div>`;
|
||||||
val = 3;
|
val = 3;
|
||||||
willPatch() {
|
willPatch() {
|
||||||
@@ -424,7 +427,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><t t-esc="val"/></div>`;
|
static template = xml`<div><t t-esc="val"/></div>`;
|
||||||
val = 3;
|
val = 3;
|
||||||
patched() {
|
patched() {
|
||||||
@@ -453,10 +456,10 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
// we do not catch error in willPatch anymore
|
// we do not catch error in willPatch anymore
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
static template = xml`<div><t t-esc="this.will.crash"/></div>`;
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><Child/></div>`;
|
static template = xml`<div><Child/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -469,7 +472,8 @@ describe("component error handling (catchError)", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'crash'\)|Cannot read property 'crash' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
|
|
||||||
expect(console.error).toBeCalledTimes(0);
|
expect(console.error).toBeCalledTimes(0);
|
||||||
console.error = consoleError;
|
console.error = consoleError;
|
||||||
@@ -479,7 +483,7 @@ describe("component error handling (catchError)", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
// we do not catch error in willPatch anymore
|
// we do not catch error in willPatch anymore
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><t t-if="flag" t-esc="this.will.crash"/></div>`;
|
static template = xml`<div><t t-if="flag" t-esc="this.will.crash"/></div>`;
|
||||||
flag = false;
|
flag = false;
|
||||||
}
|
}
|
||||||
@@ -495,17 +499,18 @@ describe("component error handling (catchError)", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'crash'\)|Cannot read property 'crash' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
|
|
||||||
expect(console.error).toBeCalledTimes(0);
|
expect(console.error).toBeCalledTimes(0);
|
||||||
console.error = consoleError;
|
console.error = consoleError;
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a rendering error will reject the render promise (with sub components)", async () => {
|
test("a rendering error will reject the render promise (with sub components)", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span></span>`;
|
static template = xml`<span></span>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child/><t t-esc="x.y"/></div>`;
|
static template = xml`<div><Child/><t t-esc="x.y"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -518,6 +523,94 @@ describe("component error handling (catchError)", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'y' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'y'\)|Cannot read property 'y' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("simple catchError", async () => {
|
||||||
|
class Boom extends Component {
|
||||||
|
static template = xml`<div t-esc="a.b.c"/>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="error">Error</t>
|
||||||
|
<t t-else="">
|
||||||
|
<Boom />
|
||||||
|
</t>
|
||||||
|
</div>`;
|
||||||
|
static components = { Boom };
|
||||||
|
|
||||||
|
error = false;
|
||||||
|
|
||||||
|
catchError(error) {
|
||||||
|
this.error = error;
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await mount(Parent, { target: fixture });
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Error</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("catchError in catchError", async () => {
|
||||||
|
class Boom extends Component {
|
||||||
|
static template = xml`<div t-esc="a.b.c"/>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Boom />
|
||||||
|
</div>`;
|
||||||
|
static components = { Boom };
|
||||||
|
|
||||||
|
catchError(error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<t t-if="error">Error</t>
|
||||||
|
<t t-else="">
|
||||||
|
<Child />
|
||||||
|
</t>
|
||||||
|
</div>`;
|
||||||
|
static components = { Child };
|
||||||
|
|
||||||
|
error = false;
|
||||||
|
|
||||||
|
catchError(error) {
|
||||||
|
this.error = error;
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await mount(Parent, { target: fixture });
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Error</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("errors in mounted and in willUnmount", async () => {
|
||||||
|
expect.assertions(1);
|
||||||
|
class Example extends Component {
|
||||||
|
static template = xml`<div/>`;
|
||||||
|
val;
|
||||||
|
mounted() {
|
||||||
|
throw new Error("Error in mounted");
|
||||||
|
this.val = { foo: "bar" };
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
console.log(this.val.foo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mount(Example, { target: fixture });
|
||||||
|
} catch (e) {
|
||||||
|
expect(e.message).toBe("Error in mounted");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ afterEach(() => {
|
|||||||
QWeb.dev = dev;
|
QWeb.dev = dev;
|
||||||
});
|
});
|
||||||
|
|
||||||
class Widget extends Component<any, any> {}
|
class Widget extends Component {}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Tests
|
// Tests
|
||||||
@@ -92,11 +92,11 @@ describe("props validation", () => {
|
|||||||
{ type: String, ok: "1", ko: 1 },
|
{ type: String, ok: "1", ko: 1 },
|
||||||
{ type: Object, ok: {}, ko: "1" },
|
{ type: Object, ok: {}, ko: "1" },
|
||||||
{ type: Date, ok: new Date(), ko: "1" },
|
{ type: Date, ok: new Date(), ko: "1" },
|
||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" },
|
||||||
];
|
];
|
||||||
|
|
||||||
let props;
|
let props;
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
get p() {
|
get p() {
|
||||||
return props.p;
|
return props.p;
|
||||||
@@ -149,18 +149,18 @@ describe("props validation", () => {
|
|||||||
{ type: String, ok: "1", ko: 1 },
|
{ type: String, ok: "1", ko: 1 },
|
||||||
{ type: Object, ok: {}, ko: "1" },
|
{ type: Object, ok: {}, ko: "1" },
|
||||||
{ type: Date, ok: new Date(), ko: "1" },
|
{ type: Date, ok: new Date(), ko: "1" },
|
||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" },
|
||||||
];
|
];
|
||||||
|
|
||||||
let props;
|
let props;
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
get p() {
|
get p() {
|
||||||
return props.p;
|
return props.p;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (let test of Tests) {
|
for (let test of Tests) {
|
||||||
let TestWidget = class extends Component<any, any> {
|
let TestWidget = class extends Component {
|
||||||
static props = { p: { type: test.type } };
|
static props = { p: { type: test.type } };
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
};
|
};
|
||||||
@@ -200,11 +200,11 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate a prop with multiple types", async () => {
|
test("can validate a prop with multiple types", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: [String, Boolean] };
|
static props = { p: [String, Boolean] };
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -244,11 +244,11 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an optional props", async () => {
|
test("can validate an optional props", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: String, optional: true } };
|
static props = { p: { type: String, optional: true } };
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -288,11 +288,11 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with given primitive type", async () => {
|
test("can validate an array with given primitive type", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: String } };
|
static props = { p: { type: Array, element: String } };
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -340,11 +340,11 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with multiple sub element types", async () => {
|
test("can validate an array with multiple sub element types", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: [String, Boolean] } };
|
static props = { p: { type: Array, element: [String, Boolean] } };
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -393,13 +393,13 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an object with simple shape", async () => {
|
test("can validate an object with simple shape", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: { type: Object, shape: { id: Number, url: String } }
|
p: { type: Object, shape: { id: Number, url: String } },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -451,19 +451,19 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate recursively complicated prop def", async () => {
|
test("can validate recursively complicated prop def", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: {
|
p: {
|
||||||
type: Object,
|
type: Object,
|
||||||
shape: {
|
shape: {
|
||||||
id: Number,
|
id: Number,
|
||||||
url: [Boolean, { type: Array, element: Number }]
|
url: [Boolean, { type: Array, element: Number }],
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
get p() {
|
get p() {
|
||||||
@@ -503,17 +503,17 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate optional attributes in nested sub props", () => {
|
test("can validate optional attributes in nested sub props", () => {
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component {
|
||||||
static props = {
|
static props = {
|
||||||
myprop: {
|
myprop: {
|
||||||
type: Array,
|
type: Array,
|
||||||
element: {
|
element: {
|
||||||
type: Object,
|
type: Object,
|
||||||
shape: {
|
shape: {
|
||||||
num: { type: Number, optional: true }
|
num: { type: Number, optional: true },
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let error;
|
let error;
|
||||||
@@ -536,11 +536,11 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate with a custom validator", () => {
|
test("can validate with a custom validator", () => {
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component {
|
||||||
static props = {
|
static props = {
|
||||||
size: {
|
size: {
|
||||||
validate: e => ["small", "medium", "large"].includes(e)
|
validate: (e) => ["small", "medium", "large"].includes(e),
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let error;
|
let error;
|
||||||
@@ -561,13 +561,13 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can validate with a custom validator, and a type", () => {
|
test("can validate with a custom validator, and a type", () => {
|
||||||
const validator = jest.fn(n => 0 <= n && n <= 10);
|
const validator = jest.fn((n) => 0 <= n && n <= 10);
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component {
|
||||||
static props = {
|
static props = {
|
||||||
n: {
|
n: {
|
||||||
type: Number,
|
type: Number,
|
||||||
validate: validator
|
validate: validator,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let error;
|
let error;
|
||||||
@@ -738,7 +738,7 @@ describe("props validation", () => {
|
|||||||
|
|
||||||
test("props are validated whenever component is updated", async () => {
|
test("props are validated whenever component is updated", async () => {
|
||||||
let error;
|
let error;
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static props = { p: { type: Number } };
|
static props = { p: { type: Number } };
|
||||||
static template = xml`<div><t t-esc="props.p"/></div>`;
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
|
||||||
@@ -750,7 +750,7 @@ describe("props validation", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
state: any = useState({ p: 1 });
|
state: any = useState({ p: 1 });
|
||||||
@@ -767,12 +767,12 @@ describe("props validation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("default values are applied before validating props at update", async () => {
|
test("default values are applied before validating props at update", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static props = { p: { type: Number } };
|
static props = { p: { type: Number } };
|
||||||
static template = xml`<div><t t-esc="props.p"/></div>`;
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
static defaultProps = { p: 4 };
|
static defaultProps = { p: 4 };
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
state: any = useState({ p: 1 });
|
state: any = useState({ p: 1 });
|
||||||
@@ -786,15 +786,40 @@ describe("props validation", () => {
|
|||||||
await nextTick();
|
await nextTick();
|
||||||
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("mix of optional and mandatory", async () => {
|
||||||
|
class Child extends Component {
|
||||||
|
static props = {
|
||||||
|
optional: { type: String, optional: true },
|
||||||
|
mandatory: Number,
|
||||||
|
};
|
||||||
|
static template = xml` <div><t t-esc="props.mandatory"/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component {
|
||||||
|
static components = { Child };
|
||||||
|
static template = xml`<div><Child/></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new App(undefined, {});
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'mandatory' (component 'Child')");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("default props", () => {
|
describe("default props", () => {
|
||||||
test("can set default values", async () => {
|
test("can set default values", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static defaultProps = { p: 4 };
|
static defaultProps = { p: 4 };
|
||||||
static template = xml`<div><t t-esc="props.p"/></div>`;
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><TestWidget /></div>`;
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
}
|
}
|
||||||
|
|||||||
+583
-86
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,7 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("styles and component", () => {
|
describe("styles and component", () => {
|
||||||
test("can define an inline stylesheet", async () => {
|
test("can define an inline stylesheet", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div class="app">text</div>`;
|
static template = xml`<div class="app">text</div>`;
|
||||||
static style = css`
|
static style = css`
|
||||||
.app {
|
.app {
|
||||||
@@ -54,7 +54,7 @@ describe("styles and component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("inherited components properly apply css", async () => {
|
test("inherited components properly apply css", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div class="app">text</div>`;
|
static template = xml`<div class="app">text</div>`;
|
||||||
static style = css`
|
static style = css`
|
||||||
.app {
|
.app {
|
||||||
@@ -86,7 +86,7 @@ describe("styles and component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("get a meaningful error message if css helper is missing", async () => {
|
test("get a meaningful error message if css helper is missing", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div class="app">text</div>`;
|
static template = xml`<div class="app">text</div>`;
|
||||||
static style = `.app {color: red;}`;
|
static style = `.app {color: red;}`;
|
||||||
}
|
}
|
||||||
@@ -103,7 +103,7 @@ describe("styles and component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("inline stylesheets are processed", async () => {
|
test("inline stylesheets are processed", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div class="app">text</div>`;
|
static template = xml`<div class="app">text</div>`;
|
||||||
static style = css`
|
static style = css`
|
||||||
.app {
|
.app {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Component, Env } from "../../src/component/component";
|
import { Component, Env, mount } from "../../src/component/component";
|
||||||
import { useState } from "../../src/hooks";
|
import { useState } from "../../src/hooks";
|
||||||
import { xml } from "../../src/tags";
|
import { xml } from "../../src/tags";
|
||||||
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick, nextMicroTick } from "../helpers";
|
||||||
|
import { scheduler } from "../../src/component/scheduler";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Setup and helpers
|
// Setup and helpers
|
||||||
@@ -27,28 +28,46 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("mount targets", () => {
|
describe("mount targets", () => {
|
||||||
test("can attach a component to an existing node (if same tagname)", async () => {
|
test("can attach a component to an existing node (if same tagname)", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div>app</div>`;
|
static template = xml`<div t-att-class="state.customClass">app<p>another tag</p></div>`;
|
||||||
|
state = useState({ customClass: "custom" });
|
||||||
}
|
}
|
||||||
const div = document.createElement("div");
|
const div = document.createElement("div");
|
||||||
|
div.classList.add("arbitrary");
|
||||||
|
div.innerHTML = `<p>pre-existing</p>`;
|
||||||
fixture.appendChild(div);
|
fixture.appendChild(div);
|
||||||
|
|
||||||
const app = new App();
|
const app = await mount(App, { target: div, position: "self" });
|
||||||
await app.mount(div, { position: "self" });
|
|
||||||
expect(fixture.innerHTML).toBe("<div>app</div>");
|
expect(fixture.innerHTML).toBe(
|
||||||
|
`<div class="arbitrary custom"><p>pre-existing</p>app<p>another tag</p></div>`
|
||||||
|
);
|
||||||
|
expect(div).toBe(app.el);
|
||||||
|
|
||||||
|
app.state.customClass = "custom2";
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
`<div class="arbitrary custom2"><p>pre-existing</p>app<p>another tag</p></div>`
|
||||||
|
);
|
||||||
|
expect(div).toBe(app.el);
|
||||||
|
|
||||||
|
app.unmount();
|
||||||
|
// This assert is a best guess
|
||||||
|
// The use case it covers was not really thought through
|
||||||
|
// and may change in the future
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("cannot attach a component to an existing node (if not same tagname)", async () => {
|
test("cannot attach a component to an existing node (if not same tagname)", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<span>app</span>`;
|
static template = xml`<span>app</span>`;
|
||||||
}
|
}
|
||||||
const div = document.createElement("div");
|
const div = document.createElement("div");
|
||||||
fixture.appendChild(div);
|
fixture.appendChild(div);
|
||||||
|
|
||||||
const app = new App();
|
|
||||||
let error;
|
let error;
|
||||||
try {
|
try {
|
||||||
await app.mount(div, { position: "self" });
|
await mount(App, { target: div, position: "self" });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
@@ -57,38 +76,35 @@ describe("mount targets", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can mount a component (with position='first-child')", async () => {
|
test("can mount a component (with position='first-child')", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div>app</div>`;
|
static template = xml`<div>app</div>`;
|
||||||
}
|
}
|
||||||
const span = document.createElement("span");
|
const span = document.createElement("span");
|
||||||
fixture.appendChild(span);
|
fixture.appendChild(span);
|
||||||
|
|
||||||
const app = new App();
|
await mount(App, { target: fixture, position: "first-child" });
|
||||||
await app.mount(fixture, { position: "first-child" });
|
|
||||||
expect(fixture.innerHTML).toBe("<div>app</div><span></span>");
|
expect(fixture.innerHTML).toBe("<div>app</div><span></span>");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can mount a component (with position='last-child')", async () => {
|
test("can mount a component (with position='last-child')", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div>app</div>`;
|
static template = xml`<div>app</div>`;
|
||||||
}
|
}
|
||||||
const span = document.createElement("span");
|
const span = document.createElement("span");
|
||||||
fixture.appendChild(span);
|
fixture.appendChild(span);
|
||||||
|
|
||||||
const app = new App();
|
await mount(App, { target: fixture, position: "last-child" });
|
||||||
await app.mount(fixture, { position: "last-child" });
|
|
||||||
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("default mount option is 'last-child'", async () => {
|
test("default mount option is 'last-child'", async () => {
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div>app</div>`;
|
static template = xml`<div>app</div>`;
|
||||||
}
|
}
|
||||||
const span = document.createElement("span");
|
const span = document.createElement("span");
|
||||||
fixture.appendChild(span);
|
fixture.appendChild(span);
|
||||||
|
|
||||||
const app = new App();
|
await mount(App, { target: fixture });
|
||||||
await app.mount(fixture);
|
|
||||||
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
expect(fixture.innerHTML).toBe("<span></span><div>app</div>");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -96,7 +112,7 @@ describe("mount targets", () => {
|
|||||||
describe("unmounting and remounting", () => {
|
describe("unmounting and remounting", () => {
|
||||||
test("widget can be unmounted and remounted", async () => {
|
test("widget can be unmounted and remounted", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
class MyWidget extends Component<any, any> {
|
class MyWidget extends Component {
|
||||||
static template = xml`<div>Hey</div>`;
|
static template = xml`<div>Hey</div>`;
|
||||||
async willStart() {
|
async willStart() {
|
||||||
steps.push("willstart");
|
steps.push("willstart");
|
||||||
@@ -112,8 +128,7 @@ describe("unmounting and remounting", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new MyWidget();
|
const w = await mount(MyWidget, { target: fixture });
|
||||||
await w.mount(fixture);
|
|
||||||
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
expect(steps).toEqual(["willstart", "mounted"]);
|
expect(steps).toEqual(["willstart", "mounted"]);
|
||||||
|
|
||||||
@@ -128,7 +143,7 @@ describe("unmounting and remounting", () => {
|
|||||||
|
|
||||||
test("widget can be mounted twice without ill effect", async () => {
|
test("widget can be mounted twice without ill effect", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
class MyWidget extends Component<any, any> {
|
class MyWidget extends Component {
|
||||||
static template = xml`<div>Hey</div>`;
|
static template = xml`<div>Hey</div>`;
|
||||||
async willStart() {
|
async willStart() {
|
||||||
steps.push("willstart");
|
steps.push("willstart");
|
||||||
@@ -141,8 +156,7 @@ describe("unmounting and remounting", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new MyWidget();
|
const w = await mount(MyWidget, { target: fixture });
|
||||||
await w.mount(fixture);
|
|
||||||
await w.mount(fixture);
|
await w.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
expect(steps).toEqual(["willstart", "mounted"]);
|
expect(steps).toEqual(["willstart", "mounted"]);
|
||||||
@@ -151,7 +165,7 @@ describe("unmounting and remounting", () => {
|
|||||||
test("state changes in willUnmount do not trigger rerender", async () => {
|
test("state changes in willUnmount do not trigger rerender", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<span><t t-esc="props.val"/><t t-esc="state.n"/></span>
|
<span><t t-esc="props.val"/><t t-esc="state.n"/></span>
|
||||||
`;
|
`;
|
||||||
@@ -172,7 +186,7 @@ describe("unmounting and remounting", () => {
|
|||||||
this.state.n = 3;
|
this.state.n = 3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<Child t-if="state.flag" val="state.val"/>
|
<Child t-if="state.flag" val="state.val"/>
|
||||||
@@ -182,8 +196,7 @@ describe("unmounting and remounting", () => {
|
|||||||
state = useState({ val: 1, flag: true });
|
state = useState({ val: 1, flag: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new Parent();
|
const widget = await mount(Parent, { target: fixture });
|
||||||
await widget.mount(fixture);
|
|
||||||
expect(steps).toEqual(["render"]);
|
expect(steps).toEqual(["render"]);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||||
widget.state.flag = false;
|
widget.state.flag = false;
|
||||||
@@ -193,7 +206,7 @@ describe("unmounting and remounting", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("state changes in willUnmount will be applied on remount", async () => {
|
test("state changes in willUnmount will be applied on remount", async () => {
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div><t t-esc="state.val"/></div>
|
<div><t t-esc="state.val"/></div>
|
||||||
`;
|
`;
|
||||||
@@ -216,7 +229,7 @@ describe("unmounting and remounting", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("sub component is still active after being unmounted and remounted", async () => {
|
test("sub component is still active after being unmounted and remounted", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<p t-on-click="state.value++">
|
<p t-on-click="state.value++">
|
||||||
<t t-esc="state.value"/>
|
<t t-esc="state.value"/>
|
||||||
@@ -225,7 +238,7 @@ describe("unmounting and remounting", () => {
|
|||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
static template = xml`<div><Child/></div>`;
|
static template = xml`<div><Child/></div>`;
|
||||||
}
|
}
|
||||||
@@ -248,7 +261,7 @@ describe("unmounting and remounting", () => {
|
|||||||
|
|
||||||
test("change state just before mounting component", async () => {
|
test("change state just before mounting component", async () => {
|
||||||
const steps: number[] = [];
|
const steps: number[] = [];
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div><t t-esc="state.val"/></div>
|
<div><t t-esc="state.val"/></div>
|
||||||
`;
|
`;
|
||||||
@@ -278,7 +291,7 @@ describe("unmounting and remounting", () => {
|
|||||||
|
|
||||||
test("change state while mounting component", async () => {
|
test("change state while mounting component", async () => {
|
||||||
const steps: number[] = [];
|
const steps: number[] = [];
|
||||||
class TestWidget extends Component<any, any> {
|
class TestWidget extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div><t t-esc="state.val"/></div>
|
<div><t t-esc="state.val"/></div>
|
||||||
`;
|
`;
|
||||||
@@ -310,12 +323,60 @@ describe("unmounting and remounting", () => {
|
|||||||
expect(steps).toEqual([2, 2, 3]);
|
expect(steps).toEqual([2, 2, 3]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("change state and render while mounted in detached dom", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="state.val"/></div>`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const detachedDiv = document.createElement("div");
|
||||||
|
const app = await mount(App, { target: detachedDiv });
|
||||||
|
|
||||||
|
expect(detachedDiv.innerHTML).toBe("<div>1</div>");
|
||||||
|
app.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(detachedDiv.innerHTML).toBe("<div>2</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("change state and render while not mounted ", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="state.val"/></div>`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App(null);
|
||||||
|
|
||||||
|
app.state.val = 2; // will call the render method (before being mounted)
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
await app.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div>2</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroy and change state after mounted in detached dom", async () => {
|
||||||
|
class App extends Component {
|
||||||
|
static template = xml`<div><t t-esc="state.val"/></div>`;
|
||||||
|
state = useState({ val: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const detachedDiv = document.createElement("div");
|
||||||
|
const app = await mount(App, { target: detachedDiv });
|
||||||
|
|
||||||
|
expect(detachedDiv.innerHTML).toBe("<div>1</div>");
|
||||||
|
|
||||||
|
app.destroy();
|
||||||
|
app.state.val = 2;
|
||||||
|
await nextTick();
|
||||||
|
expect(detachedDiv.innerHTML).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
test("change state while component is unmounted", async () => {
|
test("change state while component is unmounted", async () => {
|
||||||
let child;
|
let child;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span t-esc="state.val"/>`;
|
static template = xml`<span t-esc="state.val"/>`;
|
||||||
state = useState({
|
state = useState({
|
||||||
val: "C1"
|
val: "C1",
|
||||||
});
|
});
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -323,7 +384,7 @@ describe("unmounting and remounting", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
static template = xml`<div><t t-esc="state.val"/><Child/></div>`;
|
static template = xml`<div><t t-esc="state.val"/><Child/></div>`;
|
||||||
state = useState({ val: "P1" });
|
state = useState({ val: "P1" });
|
||||||
@@ -343,9 +404,43 @@ describe("unmounting and remounting", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div>P2<span>C2</span></div>");
|
expect(fixture.innerHTML).toBe("<div>P2<span>C2</span></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("change state while component is mounted in a fragment", async () => {
|
||||||
|
class Child1 extends Component {
|
||||||
|
static template = xml`<span>C1</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Child2 extends Component {
|
||||||
|
static template = xml`<span>C2</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static components = { Child1, Child2 };
|
||||||
|
static template = xml`
|
||||||
|
<div>
|
||||||
|
<Child1 t-if="child == 'c1'"/>
|
||||||
|
<Child2 t-if="child == 'c2'"/>
|
||||||
|
</div>`;
|
||||||
|
child: string | false = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fragment = document.createDocumentFragment();
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fragment);
|
||||||
|
expect(parent.el.outerHTML).toBe("<div></div>");
|
||||||
|
|
||||||
|
parent.child = "c1";
|
||||||
|
parent.render();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
parent.child = "c2";
|
||||||
|
await parent.mount(fixture);
|
||||||
|
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>C2</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
test("unmount component during a re-rendering", async () => {
|
test("unmount component during a re-rendering", async () => {
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return def;
|
return def;
|
||||||
@@ -353,7 +448,7 @@ describe("unmounting and remounting", () => {
|
|||||||
}
|
}
|
||||||
Child.prototype.__render = jest.fn(Child.prototype.__render);
|
Child.prototype.__render = jest.fn(Child.prototype.__render);
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child val="state.val"/></div>`;
|
static template = xml`<div><Child val="state.val"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ val: 1 });
|
state = useState({ val: 1 });
|
||||||
@@ -378,18 +473,8 @@ describe("unmounting and remounting", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("widget can be mounted on different target", async () => {
|
test("widget can be mounted on different target", async () => {
|
||||||
const steps: string[] = [];
|
class MyWidget extends Component {
|
||||||
class MyWidget extends Component<any, any> {
|
|
||||||
static template = xml`<div>Hey</div>`;
|
static template = xml`<div>Hey</div>`;
|
||||||
async willStart() {
|
|
||||||
steps.push("willstart");
|
|
||||||
}
|
|
||||||
mounted() {
|
|
||||||
steps.push("mounted");
|
|
||||||
}
|
|
||||||
willUnmount() {
|
|
||||||
steps.push("willunmount");
|
|
||||||
}
|
|
||||||
patched() {
|
patched() {
|
||||||
throw new Error("patched should not be called");
|
throw new Error("patched should not be called");
|
||||||
}
|
}
|
||||||
@@ -406,4 +491,242 @@ describe("unmounting and remounting", () => {
|
|||||||
await w.mount(span);
|
await w.mount(span);
|
||||||
expect(fixture.innerHTML).toBe("<div></div><span><div>Hey</div></span>");
|
expect(fixture.innerHTML).toBe("<div></div><span><div>Hey</div></span>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("widget can be mounted on different target, another situation", async () => {
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const div = document.createElement("div");
|
||||||
|
const span = document.createElement("span");
|
||||||
|
fixture.appendChild(div);
|
||||||
|
fixture.appendChild(span);
|
||||||
|
const w = new MyWidget();
|
||||||
|
|
||||||
|
w.mount(div).catch(() => steps.push("1 catch"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span></span>");
|
||||||
|
|
||||||
|
w.mount(span).then(() => steps.push("2 resolved"));
|
||||||
|
|
||||||
|
// we wait two microticks because this is the number of internal promises
|
||||||
|
// that need to be resolved/rejected, and because we want to prove here
|
||||||
|
// that the first mount operation is cancelled immediately, and not after
|
||||||
|
// one full tick.
|
||||||
|
await nextMicroTick();
|
||||||
|
await nextMicroTick();
|
||||||
|
expect(steps).toEqual([]);
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span></span>");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["2 resolved"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div></div><span><div>Hey</div></span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("component can be mounted on same target, another situation", async () => {
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
async willStart() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
throw new Error("patched should not be called");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const w = new MyWidget();
|
||||||
|
|
||||||
|
w.mount(fixture).then(() => steps.push("1 resolved"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
w.mount(fixture).then(() => steps.push("2 resolved"));
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual([]);
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div>Hey</div>");
|
||||||
|
expect(steps).toEqual(["1 resolved", "2 resolved"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("mounting a destroyed widget", async () => {
|
||||||
|
class MyWidget extends Component {
|
||||||
|
static template = xml`<div>Hey</div>`;
|
||||||
|
}
|
||||||
|
const w = new MyWidget();
|
||||||
|
w.destroy(); // because, why not
|
||||||
|
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(scheduler.tasks.length).toBe(0);
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Cannot mount a destroyed component");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C1 };
|
||||||
|
static template = xml`<div><div><C1 t-props="state" t-if="state.a"/></div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("first");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 2", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C1 };
|
||||||
|
static template = xml`<div><div><C1 t-props="state" t-if="state.a"/>some text</div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("firstsome text");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixedsome text");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 3", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class C2 extends Component {
|
||||||
|
static template = xml`<C1 a="props.a"/>`;
|
||||||
|
static components = { C1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C2 };
|
||||||
|
static template = xml`<div><div><C2 t-props="state" t-if="state.a"/></div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("first");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("destroying a sub-component cleans itself from parent's vnode, part 4", async () => {
|
||||||
|
class C1 extends Component {
|
||||||
|
static template = xml`<div><div><t t-esc="props.a"/></div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class C2 extends Component {
|
||||||
|
static template = xml`<C1 a="props.a"/>`;
|
||||||
|
static components = { C1 };
|
||||||
|
}
|
||||||
|
class P extends Component {
|
||||||
|
static components = { C2 };
|
||||||
|
static template = xml`<div><div><C2 t-props="state" t-if="state.a"/>some text</div></div>`;
|
||||||
|
state = {
|
||||||
|
a: "first",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parent = new P();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.textContent).toBe("firstsome text");
|
||||||
|
parent.unmount();
|
||||||
|
parent.state.a = "";
|
||||||
|
parent.mount(fixture);
|
||||||
|
parent.state.a = "fixed";
|
||||||
|
await parent.render();
|
||||||
|
expect(fixture.textContent).toBe("fixedsome text");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("remounting component tree where a component implement shouldupdate", async () => {
|
||||||
|
let state: any;
|
||||||
|
const steps = [];
|
||||||
|
class Child extends Component {
|
||||||
|
static template = xml`<div><t t-esc="state.word"/><t t-esc="props.name"/></div>`;
|
||||||
|
|
||||||
|
state = useState({ word: "hello" });
|
||||||
|
|
||||||
|
constructor(parent, props) {
|
||||||
|
super(parent, props);
|
||||||
|
state = this.state;
|
||||||
|
}
|
||||||
|
patched() {
|
||||||
|
steps.push("patched");
|
||||||
|
}
|
||||||
|
mounted() {
|
||||||
|
steps.push("mounted");
|
||||||
|
}
|
||||||
|
willUnmount() {
|
||||||
|
steps.push("willUnmount");
|
||||||
|
}
|
||||||
|
shouldUpdate() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component {
|
||||||
|
static template = xml`<div><Child name="state.name"/></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
state = useState({ name: "World" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = await mount(Parent, { target: fixture });
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>helloWorld</div></div>");
|
||||||
|
|
||||||
|
parent.unmount();
|
||||||
|
expect(fixture.innerHTML).toBe("");
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>helloWorld</div></div>");
|
||||||
|
|
||||||
|
state.word = "test";
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>testWorld</div></div>");
|
||||||
|
expect(steps).toEqual(["mounted", "willUnmount", "mounted", "patched"]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+41
-22
@@ -32,7 +32,7 @@ describe("Context", () => {
|
|||||||
test("very simple use, with initial value", async () => {
|
test("very simple use, with initial value", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Test extends Component<any, any> {
|
class Test extends Component {
|
||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ describe("Context", () => {
|
|||||||
test("useContext hook is reactive, for one component", async () => {
|
test("useContext hook is reactive, for one component", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Test extends Component<any, any> {
|
class Test extends Component {
|
||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
@@ -59,11 +59,11 @@ describe("Context", () => {
|
|||||||
test("two components can subscribe to same context", async () => {
|
test("two components can subscribe to same context", async () => {
|
||||||
const testContext = new Context({ value: 123 });
|
const testContext = new Context({ value: 123 });
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><Child /></div>`;
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -80,7 +80,7 @@ describe("Context", () => {
|
|||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
async render() {
|
async render() {
|
||||||
@@ -90,7 +90,7 @@ describe("Context", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><Child /></div>`;
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -111,13 +111,13 @@ describe("Context", () => {
|
|||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class SlowComp extends Component<any, any> {
|
class SlowComp extends Component {
|
||||||
static template = xml`<p><t t-esc="props.value"/></p>`;
|
static template = xml`<p><t t-esc="props.value"/></p>`;
|
||||||
willUpdateProps() {
|
willUpdateProps() {
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><SlowComp value="contextObj.value"/></span>`;
|
static template = xml`<span><SlowComp value="contextObj.value"/></span>`;
|
||||||
static components = { SlowComp };
|
static components = { SlowComp };
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
@@ -128,12 +128,12 @@ describe("Context", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><Child /></div>`;
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
|
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><Child /><Parent /></div>`;
|
static template = xml`<div><Child /><Parent /></div>`;
|
||||||
static components = { Child, Parent };
|
static components = { Child, Parent };
|
||||||
}
|
}
|
||||||
@@ -166,7 +166,7 @@ describe("Context", () => {
|
|||||||
const testContext = new Context({ a: 1, b: 2 });
|
const testContext = new Context({ a: 1, b: 2 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj1.a"/><t t-esc="contextObj2.b"/></span>`;
|
static template = xml`<span><t t-esc="contextObj1.a"/><t t-esc="contextObj2.b"/></span>`;
|
||||||
contextObj1 = useContext(testContext);
|
contextObj1 = useContext(testContext);
|
||||||
contextObj2 = useContext(testContext);
|
contextObj2 = useContext(testContext);
|
||||||
@@ -175,7 +175,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /></div>`;
|
static template = xml`<div><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
@@ -193,7 +193,7 @@ describe("Context", () => {
|
|||||||
const testContext = new Context({ a: 123, b: 321 });
|
const testContext = new Context({ a: 123, b: 321 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
__render(fiber) {
|
__render(fiber) {
|
||||||
@@ -201,7 +201,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child /><t t-esc="contextObj.b"/></div>`;
|
static template = xml`<div><Child /><t t-esc="contextObj.b"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
@@ -227,7 +227,7 @@ describe("Context", () => {
|
|||||||
const testContext = new Context({ a: 123 });
|
const testContext = new Context({ a: 123 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
__render(fiber) {
|
__render(fiber) {
|
||||||
@@ -235,7 +235,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -263,14 +263,14 @@ describe("Context", () => {
|
|||||||
test("destroyed component before being mounted is inactive", async () => {
|
test("destroyed component before being mounted is inactive", async () => {
|
||||||
const testContext = new Context({ a: 123 });
|
const testContext = new Context({ a: 123 });
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
willStart() {
|
willStart() {
|
||||||
return makeDeferred();
|
return makeDeferred();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -289,11 +289,30 @@ describe("Context", () => {
|
|||||||
expect(testContext.subscriptions.update.length).toBe(0);
|
expect(testContext.subscriptions.update.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("concurrent renderings", async () => {
|
test.skip("concurrent renderings", async () => {
|
||||||
|
/**
|
||||||
|
* Note: this test is interesting, but sadly just an incomplete attempt at
|
||||||
|
* protecting users against themselves. With the context API, it is not
|
||||||
|
* possible for the framework to protect completely against crashes. Maybe
|
||||||
|
* like in this case, when a component is in a simple hierarchy where all
|
||||||
|
* renderings come from the context changes, but in a real case, where some
|
||||||
|
* code can trigger a rendering independently, it is insufficient.
|
||||||
|
*
|
||||||
|
* The main problem is that the sub component depends on some external state,
|
||||||
|
* which may be modified, and then incompatible with the component actual
|
||||||
|
* state (for example, if the sub component has an id key related to some
|
||||||
|
* object that has been removed from the context).
|
||||||
|
*
|
||||||
|
* For now, sadly, the only solution is that components that depends on external
|
||||||
|
* state should guarantee their own integrity themselves. Then maybe this
|
||||||
|
* could be solved at the level of a state management solution that has a
|
||||||
|
* more advanced API, to let components determine if they should be updated
|
||||||
|
* or not (so, something slightly more advanced that the useStore hook).
|
||||||
|
*/
|
||||||
const testContext = new Context({ x: { n: 1 }, key: "x" });
|
const testContext = new Context({ x: { n: 1 }, key: "x" });
|
||||||
const def = makeDeferred();
|
const def = makeDeferred();
|
||||||
let stateC;
|
let stateC;
|
||||||
class ComponentC extends Component<any, any> {
|
class ComponentC extends Component {
|
||||||
static template = xml`<span><t t-esc="context[props.key].n"/><t t-esc="state.x"/></span>`;
|
static template = xml`<span><t t-esc="context[props.key].n"/><t t-esc="state.x"/></span>`;
|
||||||
context = useContext(testContext);
|
context = useContext(testContext);
|
||||||
state = useState({ x: "a" });
|
state = useState({ x: "a" });
|
||||||
@@ -303,7 +322,7 @@ describe("Context", () => {
|
|||||||
stateC = this.state;
|
stateC = this.state;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ComponentB extends Component<any, any> {
|
class ComponentB extends Component {
|
||||||
static components = { ComponentC };
|
static components = { ComponentC };
|
||||||
static template = xml`<p><ComponentC key="props.key"/></p>`;
|
static template = xml`<p><ComponentC key="props.key"/></p>`;
|
||||||
|
|
||||||
@@ -311,7 +330,7 @@ describe("Context", () => {
|
|||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ComponentA extends Component<any, any> {
|
class ComponentA extends Component {
|
||||||
static components = { ComponentB };
|
static components = { ComponentB };
|
||||||
static template = xml`<div><ComponentB key="context.key"/></div>`;
|
static template = xml`<div><ComponentB key="context.key"/></div>`;
|
||||||
context = useContext(testContext);
|
context = useContext(testContext);
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ describe("event bus behaviour", () => {
|
|||||||
expect.assertions(1);
|
expect.assertions(1);
|
||||||
const bus = new EventBus();
|
const bus = new EventBus();
|
||||||
const owner = {};
|
const owner = {};
|
||||||
bus.on("event", owner, function(this: any) {
|
bus.on("event", owner, function (this: any) {
|
||||||
expect(this).toBe(owner);
|
expect(this).toBe(owner);
|
||||||
});
|
});
|
||||||
bus.trigger("event");
|
bus.trigger("event");
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ describe("observer", () => {
|
|||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
expect(obj2).toEqual({
|
expect(obj2).toEqual({
|
||||||
a: 2
|
a: 2,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ describe("observer", () => {
|
|||||||
expect(observer.rev).toBe(5);
|
expect(observer.rev).toBe(5);
|
||||||
expect(obj).toEqual({
|
expect(obj).toEqual({
|
||||||
a: null,
|
a: null,
|
||||||
b: undefined
|
b: undefined,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -68,6 +68,23 @@ describe("observer", () => {
|
|||||||
expect(obj.date).not.toBe(date);
|
expect(obj.date).not.toBe(date);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("properly handle promises (i.e.: treat them like primitive values", async () => {
|
||||||
|
const observer = new Observer();
|
||||||
|
let resolved = false;
|
||||||
|
const prom = new Promise((r) => r());
|
||||||
|
const obj: any = observer.observe({ prom });
|
||||||
|
expect(obj.prom).toBeInstanceOf(Promise);
|
||||||
|
|
||||||
|
obj.prom.then(() => (resolved = true));
|
||||||
|
|
||||||
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
|
|
||||||
|
expect(resolved).toBe(false);
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(resolved).toBe(true);
|
||||||
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
test("can change values in array", () => {
|
test("can change values in array", () => {
|
||||||
const observer = new Observer();
|
const observer = new Observer();
|
||||||
const obj: any = observer.observe({ arr: [1, 2] });
|
const obj: any = observer.observe({ arr: [1, 2] });
|
||||||
|
|||||||
+14
-14
@@ -1,4 +1,4 @@
|
|||||||
import { Env, Component } from "../src/component/component";
|
import { Env, Component, STATUS } from "../src/component/component";
|
||||||
import { scheduler } from "../src/component/scheduler";
|
import { scheduler } from "../src/component/scheduler";
|
||||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||||
import { CompilationContext } from "../src/qweb/compilation_context";
|
import { CompilationContext } from "../src/qweb/compilation_context";
|
||||||
@@ -6,12 +6,7 @@ import { patch } from "../src/vdom";
|
|||||||
import "../src/qweb/base_directives";
|
import "../src/qweb/base_directives";
|
||||||
import "../src/qweb/extensions";
|
import "../src/qweb/extensions";
|
||||||
import "../src/component/directive";
|
import "../src/component/directive";
|
||||||
|
import { browser } from "../src/browser";
|
||||||
// modifies scheduler to make it faster to test components
|
|
||||||
scheduler.requestAnimationFrame = function(callback: FrameRequestCallback) {
|
|
||||||
setTimeout(callback, 1);
|
|
||||||
return 1;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Some static cleanup
|
// Some static cleanup
|
||||||
let nextSlotId;
|
let nextSlotId;
|
||||||
@@ -42,9 +37,13 @@ export function nextMicroTick(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function nextTick(): Promise<void> {
|
export async function nextTick(): Promise<void> {
|
||||||
return new Promise(function(resolve) {
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
setTimeout(() => scheduler.requestAnimationFrame(() => resolve()));
|
await new Promise((resolve) => scheduler.requestAnimationFrame(resolve));
|
||||||
});
|
}
|
||||||
|
|
||||||
|
export async function nextFrame(): Promise<void> {
|
||||||
|
await new Promise((resolve) => scheduler.requestAnimationFrame(resolve));
|
||||||
|
await new Promise((resolve) => scheduler.requestAnimationFrame(resolve));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeTestFixture() {
|
export function makeTestFixture() {
|
||||||
@@ -75,7 +74,8 @@ export function makeDeferred(): Deferred {
|
|||||||
|
|
||||||
export function makeTestEnv(): Env {
|
export function makeTestEnv(): Env {
|
||||||
return {
|
return {
|
||||||
qweb: new QWeb()
|
qweb: new QWeb(),
|
||||||
|
browser: browser,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +92,7 @@ export function renderToDOM(
|
|||||||
if (!context.__owl__) {
|
if (!context.__owl__) {
|
||||||
// we add `__owl__` to better simulate a component as context. This is
|
// we add `__owl__` to better simulate a component as context. This is
|
||||||
// particularly important for event handlers added with the `t-on` directive.
|
// particularly important for event handlers added with the `t-on` directive.
|
||||||
context.__owl__ = { isMounted: true };
|
context.__owl__ = { status: STATUS.MOUNTED };
|
||||||
}
|
}
|
||||||
const vnode = qweb.render(template, context, extra);
|
const vnode = qweb.render(template, context, extra);
|
||||||
|
|
||||||
@@ -132,7 +132,7 @@ export function renderToString(
|
|||||||
// is useful for animations tests, as we hook before repaints to trigger
|
// is useful for animations tests, as we hook before repaints to trigger
|
||||||
// animations (thanks to requestAnimationFrame). Patching nextFrame allows to
|
// animations (thanks to requestAnimationFrame). Patching nextFrame allows to
|
||||||
// simulate calls to this hook. One must not forget to unpatch afterwards.
|
// simulate calls to this hook. One must not forget to unpatch afterwards.
|
||||||
let nextFrame = QWeb.utils.nextFrame;
|
let _nextFrame = QWeb.utils.nextFrame;
|
||||||
export function patchNextFrame(f: Function) {
|
export function patchNextFrame(f: Function) {
|
||||||
QWeb.utils.nextFrame = (cb: () => void) => {
|
QWeb.utils.nextFrame = (cb: () => void) => {
|
||||||
setTimeout(() => f(cb));
|
setTimeout(() => f(cb));
|
||||||
@@ -140,7 +140,7 @@ export function patchNextFrame(f: Function) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function unpatchNextFrame() {
|
export function unpatchNextFrame() {
|
||||||
QWeb.utils.nextFrame = nextFrame;
|
QWeb.utils.nextFrame = _nextFrame;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function editInput(input: HTMLInputElement | HTMLTextAreaElement, value: string) {
|
export async function editInput(input: HTMLInputElement | HTMLTextAreaElement, value: string) {
|
||||||
|
|||||||
+96
-41
@@ -9,8 +9,10 @@ import {
|
|||||||
onWillPatch,
|
onWillPatch,
|
||||||
onWillStart,
|
onWillStart,
|
||||||
onWillUpdateProps,
|
onWillUpdateProps,
|
||||||
|
useEnv,
|
||||||
useSubEnv,
|
useSubEnv,
|
||||||
useExternalListener
|
useExternalListener,
|
||||||
|
useComponent,
|
||||||
} from "../src/hooks";
|
} from "../src/hooks";
|
||||||
import { xml } from "../src/tags";
|
import { xml } from "../src/tags";
|
||||||
|
|
||||||
@@ -42,7 +44,7 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("hooks", () => {
|
describe("hooks", () => {
|
||||||
test("can use a state hook", async () => {
|
test("can use a state hook", async () => {
|
||||||
class Counter extends Component<any, any> {
|
class Counter extends Component {
|
||||||
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
||||||
counter = useState({ value: 42 });
|
counter = useState({ value: 42 });
|
||||||
}
|
}
|
||||||
@@ -64,7 +66,7 @@ describe("hooks", () => {
|
|||||||
steps.push("willunmount");
|
steps.push("willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@@ -73,8 +75,6 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
const component = new MyComponent();
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("mounted");
|
|
||||||
expect(component).not.toHaveProperty("willUnmount");
|
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
expect(steps).toEqual(["mounted"]);
|
expect(steps).toEqual(["mounted"]);
|
||||||
component.unmount();
|
component.unmount();
|
||||||
@@ -92,7 +92,7 @@ describe("hooks", () => {
|
|||||||
steps.push("willunmount");
|
steps.push("willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -100,7 +100,7 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -126,7 +126,7 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount");
|
steps.push("hook:willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@@ -157,7 +157,7 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount");
|
steps.push("hook:willunmount");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -171,7 +171,7 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -197,7 +197,7 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willunmount" + i);
|
steps.push("hook:willunmount" + i);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@@ -214,12 +214,12 @@ describe("hooks", () => {
|
|||||||
"hook:mounted1",
|
"hook:mounted1",
|
||||||
"hook:mounted2",
|
"hook:mounted2",
|
||||||
"hook:willunmount2",
|
"hook:willunmount2",
|
||||||
"hook:willunmount1"
|
"hook:willunmount1",
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("useRef hook", async () => {
|
test("useRef hook", async () => {
|
||||||
class Counter extends Component<any, any> {
|
class Counter extends Component {
|
||||||
static template = xml`<div><button t-ref="button"><t t-esc="value"/></button></div>`;
|
static template = xml`<div><button t-ref="button"><t t-esc="value"/></button></div>`;
|
||||||
button = useRef("button");
|
button = useRef("button");
|
||||||
value = 0;
|
value = 0;
|
||||||
@@ -241,7 +241,7 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
test("useRef hook is null if ref is removed ", async () => {
|
test("useRef hook is null if ref is removed ", async () => {
|
||||||
expect.assertions(4);
|
expect.assertions(4);
|
||||||
class TestRef extends Component<any, any> {
|
class TestRef extends Component {
|
||||||
static template = xml`<div><span t-if="state.flag" t-ref="span">owl</span></div>`;
|
static template = xml`<div><span t-if="state.flag" t-ref="span">owl</span></div>`;
|
||||||
spanRef = useRef("span");
|
spanRef = useRef("span");
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
@@ -261,13 +261,13 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("t-refs on widget are components", async () => {
|
test("t-refs on widget are components", async () => {
|
||||||
class WidgetB extends Component<any, any> {
|
class WidgetB extends Component {
|
||||||
static template = xml`<div>b</div>`;
|
static template = xml`<div>b</div>`;
|
||||||
}
|
}
|
||||||
class WidgetC extends Component<any, any> {
|
class WidgetC extends Component {
|
||||||
static template = xml`<div class="outer-div">Hello<WidgetB t-ref="mywidgetb" /></div>`;
|
static template = xml`<div class="outer-div">Hello<WidgetB t-ref="mywidgetb" /></div>`;
|
||||||
static components = { WidgetB };
|
static components = { WidgetB };
|
||||||
ref = useRef("mywidgetb");
|
ref = useRef<WidgetB>("mywidgetb");
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new WidgetC();
|
const widget = new WidgetC();
|
||||||
@@ -280,11 +280,11 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
test("t-refs are bound at proper timing", async () => {
|
test("t-refs are bound at proper timing", async () => {
|
||||||
expect.assertions(2);
|
expect.assertions(2);
|
||||||
class Widget extends Component<any, any> {
|
class Widget extends Component {
|
||||||
static template = xml`<div>widget</div>`;
|
static template = xml`<div>widget</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-foreach="state.list" t-as="elem" t-ref="child" t-key="elem" t-component="Widget"/>
|
<t t-foreach="state.list" t-as="elem" t-ref="child" t-key="elem" t-component="Widget"/>
|
||||||
@@ -309,10 +309,10 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
test("t-refs are bound at proper timing (2)", async () => {
|
test("t-refs are bound at proper timing (2)", async () => {
|
||||||
expect.assertions(10);
|
expect.assertions(10);
|
||||||
class Widget extends Component<any, any> {
|
class Widget extends Component {
|
||||||
static template = xml`<div>widget</div>`;
|
static template = xml`<div>widget</div>`;
|
||||||
}
|
}
|
||||||
class ParentWidget extends Component<any, any> {
|
class ParentWidget extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if="state.child1" t-ref="child1" t-component="Widget"/>
|
<t t-if="state.child1" t-ref="child1" t-component="Widget"/>
|
||||||
@@ -369,7 +369,7 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
@@ -381,8 +381,6 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
const component = new MyComponent();
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("patched");
|
|
||||||
expect(component).not.toHaveProperty("willPatch");
|
|
||||||
expect(steps).toEqual([]);
|
expect(steps).toEqual([]);
|
||||||
|
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
@@ -403,7 +401,7 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willPatch");
|
steps.push("hook:willPatch");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
@@ -437,7 +435,7 @@ describe("hooks", () => {
|
|||||||
steps.push("hook:willPatch" + i);
|
steps.push("hook:willPatch" + i);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -473,7 +471,7 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test("simple input", async () => {
|
test("simple input", async () => {
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<input t-ref="input1"/>
|
<input t-ref="input1"/>
|
||||||
@@ -494,7 +492,7 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("input in a t-if", async () => {
|
test("input in a t-if", async () => {
|
||||||
class SomeComponent extends Component<any, any> {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<input t-ref="input1"/>
|
<input t-ref="input1"/>
|
||||||
@@ -520,8 +518,21 @@ describe("hooks", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("can use useEnv", async () => {
|
||||||
|
expect.assertions(1);
|
||||||
|
class TestComponent extends Component {
|
||||||
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
expect(useEnv()).toBe(env);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const component = new TestComponent();
|
||||||
|
await component.mount(fixture);
|
||||||
|
});
|
||||||
|
|
||||||
test("can use sub env", async () => {
|
test("can use sub env", async () => {
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@@ -535,8 +546,21 @@ describe("hooks", () => {
|
|||||||
expect(component.env).toHaveProperty("val");
|
expect(component.env).toHaveProperty("val");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("can use useComponent", async () => {
|
||||||
|
expect.assertions(1);
|
||||||
|
class TestComponent extends Component {
|
||||||
|
static template = xml`<div></div>`;
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
expect(useComponent()).toBe(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const component = new TestComponent();
|
||||||
|
await component.mount(fixture);
|
||||||
|
});
|
||||||
|
|
||||||
test("parent and child env", async () => {
|
test("parent and child env", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -544,7 +568,7 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -559,23 +583,42 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
test("can use onWillStart, onWillUpdateProps", async () => {
|
test("can use onWillStart, onWillUpdateProps", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
|
async function slow(): Promise<string> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
resolve("slow");
|
||||||
|
}, 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
function useMyHook() {
|
function useMyHook() {
|
||||||
onWillStart(() => {
|
onWillStart(async () => {
|
||||||
|
steps.push(await slow());
|
||||||
steps.push("onWillStart");
|
steps.push("onWillStart");
|
||||||
});
|
});
|
||||||
onWillUpdateProps(nextProps => {
|
onWillUpdateProps(async (nextProps) => {
|
||||||
expect(nextProps).toEqual({ value: 2 });
|
expect(nextProps).toEqual({ value: 2 });
|
||||||
|
steps.push(await slow());
|
||||||
steps.push("onWillUpdateProps");
|
steps.push("onWillUpdateProps");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
function use2ndHook() {
|
||||||
|
onWillStart(() => {
|
||||||
|
steps.push("on2ndStart");
|
||||||
|
});
|
||||||
|
onWillUpdateProps((nextProps) => {
|
||||||
|
expect(nextProps).toEqual({ value: 2 });
|
||||||
|
steps.push("on2ndUpdate");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
class MyComponent extends Component {
|
||||||
static template = xml`<span><t t-esc="props.value"/></span>`;
|
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
|
use2ndHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><MyComponent value="state.value"/></div>`;
|
static template = xml`<div><MyComponent value="state.value"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
@@ -583,21 +626,33 @@ describe("hooks", () => {
|
|||||||
|
|
||||||
const app = new App();
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(app).not.toHaveProperty("willStart");
|
|
||||||
expect(app).not.toHaveProperty("willUpdateProps");
|
|
||||||
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
||||||
expect(steps).toEqual(["onWillStart"]);
|
|
||||||
|
// NOTE: 'on2ndStart' appears first in the list even though
|
||||||
|
// the 'use2ndHook' is declared after 'useMyHook'. This is
|
||||||
|
// because Promise.all is used to call the callbacks specified
|
||||||
|
// in the hooks, which runs them simultaneously.
|
||||||
|
// Additionally, 'slow' should be listed before 'onWillStart'
|
||||||
|
// because call to `slow` is awaited.
|
||||||
|
expect(steps).toEqual(["on2ndStart", "slow", "onWillStart"]);
|
||||||
|
|
||||||
app.state.value = 2;
|
app.state.value = 2;
|
||||||
await nextTick();
|
await nextTick();
|
||||||
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
|
||||||
expect(steps).toEqual(["onWillStart", "onWillUpdateProps"]);
|
expect(steps).toEqual([
|
||||||
|
"on2ndStart",
|
||||||
|
"slow",
|
||||||
|
"onWillStart",
|
||||||
|
"on2ndUpdate",
|
||||||
|
"slow",
|
||||||
|
"onWillUpdateProps",
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("useExternalListener", async () => {
|
test("useExternalListener", async () => {
|
||||||
let n = 0;
|
let n = 0;
|
||||||
|
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component {
|
||||||
static template = xml`<span><t t-esc="props.value"/></span>`;
|
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
@@ -607,7 +662,7 @@ describe("hooks", () => {
|
|||||||
n++;
|
n++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ afterEach(() => {
|
|||||||
describe("Asyncroot", () => {
|
describe("Asyncroot", () => {
|
||||||
test("delayed component with AsyncRoot component", async () => {
|
test("delayed component with AsyncRoot component", async () => {
|
||||||
let def;
|
let def;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
}
|
}
|
||||||
class AsyncChild extends Child {
|
class AsyncChild extends Child {
|
||||||
@@ -35,7 +35,7 @@ describe("Asyncroot", () => {
|
|||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<button t-on-click="updateApp">Update App State</button>
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
@@ -74,7 +74,7 @@ describe("Asyncroot", () => {
|
|||||||
|
|
||||||
test("fast component with AsyncRoot", async () => {
|
test("fast component with AsyncRoot", async () => {
|
||||||
let def;
|
let def;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
}
|
}
|
||||||
class AsyncChild extends Child {
|
class AsyncChild extends Child {
|
||||||
@@ -83,7 +83,7 @@ describe("Asyncroot", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<button t-on-click="updateApp">Update App State</button>
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
@@ -122,7 +122,7 @@ describe("Asyncroot", () => {
|
|||||||
|
|
||||||
test("asyncroot component: mixed re-renderings", async () => {
|
test("asyncroot component: mixed re-renderings", async () => {
|
||||||
let def;
|
let def;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<span t-on-click="increment">
|
<span t-on-click="increment">
|
||||||
<t t-esc="state.val"/>/<t t-esc="props.val"/>
|
<t t-esc="state.val"/>/<t t-esc="props.val"/>
|
||||||
@@ -138,7 +138,7 @@ describe("Asyncroot", () => {
|
|||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<button t-on-click="updateApp">Update App State</button>
|
<button t-on-click="updateApp">Update App State</button>
|
||||||
|
|||||||
+51
-50
@@ -36,7 +36,7 @@ describe("Portal: Props validation", () => {
|
|||||||
test("target is mandatory", async () => {
|
test("target is mandatory", async () => {
|
||||||
const dev = QWeb.dev;
|
const dev = QWeb.dev;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -61,7 +61,7 @@ describe("Portal: Props validation", () => {
|
|||||||
test("target is not list", async () => {
|
test("target is not list", async () => {
|
||||||
const dev = QWeb.dev;
|
const dev = QWeb.dev;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -88,7 +88,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
test("basic use of portal", async () => {
|
test("basic use of portal", async () => {
|
||||||
const dev = QWeb.dev;
|
const dev = QWeb.dev;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -113,7 +113,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("conditional use of Portal", async () => {
|
test("conditional use of Portal", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -148,10 +148,10 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("conditional use of Portal (with sub Component)", async () => {
|
test("conditional use of Portal (with sub Component)", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<div><t t-esc="props.val"/></div>`;
|
static template = xml`<div><t t-esc="props.val"/></div>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -190,7 +190,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("with target in template (before portal)", async () => {
|
test("with target in template (before portal)", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -210,7 +210,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("with target in template (after portal)", async () => {
|
test("with target in template (after portal)", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -233,7 +233,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -260,7 +260,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
|
|
||||||
test("portal with child and props", async () => {
|
test("portal with child and props", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||||
mounted() {
|
mounted() {
|
||||||
steps.push("mounted");
|
steps.push("mounted");
|
||||||
@@ -271,7 +271,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
expect(outside.innerHTML).toBe("<span>2</span>");
|
expect(outside.innerHTML).toBe("<span>2</span>");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -298,7 +298,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -326,7 +326,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -354,7 +354,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -379,7 +379,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("portal with dynamic body", async () => {
|
test("portal with dynamic body", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -405,7 +405,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
const consoleError = console.error;
|
const consoleError = console.error;
|
||||||
console.error = jest.fn(() => {});
|
console.error = jest.fn(() => {});
|
||||||
|
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -439,7 +439,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
test("lifecycle hooks of portal sub component are properly called", async () => {
|
test("lifecycle hooks of portal sub component are properly called", async () => {
|
||||||
const steps: any[] = [];
|
const steps: any[] = [];
|
||||||
|
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span t-esc="props.val"/>`;
|
static template = xml`<span t-esc="props.val"/>`;
|
||||||
mounted() {
|
mounted() {
|
||||||
steps.push("child:mounted");
|
steps.push("child:mounted");
|
||||||
@@ -454,7 +454,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
steps.push("child:willUnmount");
|
steps.push("child:willUnmount");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -486,7 +486,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
"parent:mounted",
|
"parent:mounted",
|
||||||
"parent:willPatch",
|
"parent:willPatch",
|
||||||
"child:mounted",
|
"child:mounted",
|
||||||
"parent:patched"
|
"parent:patched",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
parent.state.val = 2;
|
parent.state.val = 2;
|
||||||
@@ -499,7 +499,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
"parent:willPatch",
|
"parent:willPatch",
|
||||||
"child:willPatch",
|
"child:willPatch",
|
||||||
"child:patched",
|
"child:patched",
|
||||||
"parent:patched"
|
"parent:patched",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
parent.state.hasChild = false;
|
parent.state.hasChild = false;
|
||||||
@@ -515,16 +515,16 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
"parent:patched",
|
"parent:patched",
|
||||||
"parent:willPatch",
|
"parent:willPatch",
|
||||||
"child:willUnmount",
|
"child:willUnmount",
|
||||||
"parent:patched"
|
"parent:patched",
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("portal destroys on crash", async () => {
|
test("portal destroys on crash", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span t-esc="props.error and this.will.crash" />`;
|
static template = xml`<span t-esc="props.error and this.will.crash" />`;
|
||||||
state = {};
|
state = {};
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -546,11 +546,12 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
error = e;
|
error = e;
|
||||||
}
|
}
|
||||||
expect(error).toBeDefined();
|
expect(error).toBeDefined();
|
||||||
expect(error.message).toBe("Cannot read property 'crash' of undefined");
|
const regexp = /Cannot read properties of undefined \(reading 'crash'\)|Cannot read property 'crash' of undefined/g;
|
||||||
|
expect(error.message).toMatch(regexp);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("portal manual unmount", async () => {
|
test("portal manual unmount", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -577,7 +578,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
|
|
||||||
test("portal manual unmount with subcomponent", async () => {
|
test("portal manual unmount with subcomponent", async () => {
|
||||||
expect.assertions(9);
|
expect.assertions(9);
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`<span>gloria</span>`;
|
static template = xml`<span>gloria</span>`;
|
||||||
mounted() {
|
mounted() {
|
||||||
expect(outside.contains(this.el)).toBeTruthy();
|
expect(outside.contains(this.el)).toBeTruthy();
|
||||||
@@ -586,7 +587,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
expect(outside.contains(this.el)).toBeTruthy();
|
expect(outside.contains(this.el)).toBeTruthy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -614,7 +615,7 @@ describe("Portal: Basic use and DOM placement", () => {
|
|||||||
|
|
||||||
describe("Portal: Events handling", () => {
|
describe("Portal: Events handling", () => {
|
||||||
test("events triggered on movable pure node are handled", async () => {
|
test("events triggered on movable pure node are handled", async () => {
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal };
|
static components = { Portal };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -638,8 +639,8 @@ describe("Portal: Events handling", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("events triggered on movable owl components are redirected", async () => {
|
test("events triggered on movable owl components are redirected", async () => {
|
||||||
let childInst: Component<any, any> | null = null;
|
let childInst: Component | null = null;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<span t-on-custom="_onCustom" t-esc="props.val"/>`;
|
<span t-on-custom="_onCustom" t-esc="props.val"/>`;
|
||||||
|
|
||||||
@@ -652,7 +653,7 @@ describe("Portal: Events handling", () => {
|
|||||||
this.trigger("custom-portal");
|
this.trigger("custom-portal");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div t-on-custom-portal="_onCustomPortal">
|
<div t-on-custom-portal="_onCustomPortal">
|
||||||
@@ -677,8 +678,8 @@ describe("Portal: Events handling", () => {
|
|||||||
|
|
||||||
test("events triggered on contained movable owl components are redirected", async () => {
|
test("events triggered on contained movable owl components are redirected", async () => {
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
let childInst: Component<any, any> | null = null;
|
let childInst: Component | null = null;
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<span t-on-custom="_onCustom"/>`;
|
<span t-on-custom="_onCustom"/>`;
|
||||||
|
|
||||||
@@ -691,7 +692,7 @@ describe("Portal: Events handling", () => {
|
|||||||
this.trigger("custom-portal");
|
this.trigger("custom-portal");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div t-on-custom="_handled" t-on-custom-portal="_handled">
|
<div t-on-custom="_handled" t-on-custom-portal="_handled">
|
||||||
@@ -717,9 +718,9 @@ describe("Portal: Events handling", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("Dom events are not mapped", async () => {
|
test("Dom events are not mapped", async () => {
|
||||||
let childInst: Component<any, any> | null = null;
|
let childInst: Component | null = null;
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<button>child</button>`;
|
<button>child</button>`;
|
||||||
|
|
||||||
@@ -728,7 +729,7 @@ describe("Portal: Events handling", () => {
|
|||||||
childInst = this;
|
childInst = this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div t-on-click="_handled">
|
<div t-on-click="_handled">
|
||||||
@@ -741,7 +742,7 @@ describe("Portal: Events handling", () => {
|
|||||||
steps.push(ev.type as string);
|
steps.push(ev.type as string);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const bodyListener = ev => {
|
const bodyListener = (ev) => {
|
||||||
steps.push(`body: ${ev.type}`);
|
steps.push(`body: ${ev.type}`);
|
||||||
};
|
};
|
||||||
document.body.addEventListener("click", bodyListener);
|
document.body.addEventListener("click", bodyListener);
|
||||||
@@ -760,22 +761,22 @@ describe("Portal: Events handling", () => {
|
|||||||
fixture.appendChild(outside2);
|
fixture.appendChild(outside2);
|
||||||
|
|
||||||
const steps: Array<string> = [];
|
const steps: Array<string> = [];
|
||||||
let childInst: Component<any, any> | null = null;
|
let childInst: Component | null = null;
|
||||||
class Child2 extends Component<any, any> {
|
class Child2 extends Component {
|
||||||
static template = xml`<div>child2</div>`;
|
static template = xml`<div>child2</div>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
childInst = this;
|
childInst = this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static components = { Portal, Child2 };
|
static components = { Portal, Child2 };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<Portal target="'#outside2'">
|
<Portal target="'#outside2'">
|
||||||
<Child2 />
|
<Child2 />
|
||||||
</Portal>`;
|
</Portal>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div t-on-custom='_handled'>
|
<div t-on-custom='_handled'>
|
||||||
@@ -797,11 +798,11 @@ describe("Portal: Events handling", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("portal's parent's env is not polluted", async () => {
|
test("portal's parent's env is not polluted", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<button>child</button>`;
|
<button>child</button>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
@@ -818,22 +819,22 @@ describe("Portal: Events handling", () => {
|
|||||||
|
|
||||||
test("Portal composed with t-slot", async () => {
|
test("Portal composed with t-slot", async () => {
|
||||||
const steps: Array<string> = [];
|
const steps: Array<string> = [];
|
||||||
let childInst: Component<any, any> | null = null;
|
let childInst: Component | null = null;
|
||||||
class Child2 extends Component<any, any> {
|
class Child2 extends Component {
|
||||||
static template = xml`<div>child2</div>`;
|
static template = xml`<div>child2</div>`;
|
||||||
constructor(parent, props) {
|
constructor(parent, props) {
|
||||||
super(parent, props);
|
super(parent, props);
|
||||||
childInst = this;
|
childInst = this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static components = { Portal, Child2 };
|
static components = { Portal, Child2 };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<Portal target="'#outside'">
|
<Portal target="'#outside'">
|
||||||
<t t-slot="default"/>
|
<t t-slot="default"/>
|
||||||
</Portal>`;
|
</Portal>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Child, Child2 };
|
static components = { Child, Child2 };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div t-on-custom='_handled'>
|
<div t-on-custom='_handled'>
|
||||||
@@ -857,11 +858,11 @@ describe("Portal: Events handling", () => {
|
|||||||
|
|
||||||
describe("Portal: UI/UX", () => {
|
describe("Portal: UI/UX", () => {
|
||||||
test("focus is kept across re-renders", async () => {
|
test("focus is kept across re-renders", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<input id="target-me" t-att-placeholder="props.val"/>`;
|
<input id="target-me" t-att-placeholder="props.val"/>`;
|
||||||
}
|
}
|
||||||
class Parent extends Component<any, any> {
|
class Parent extends Component {
|
||||||
static components = { Portal, Child };
|
static components = { Portal, Child };
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
|||||||
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
|
exports[`qweb t-att t-att-class with multiple classes 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _1 = utils.toClassObj({'a b c':scope['value']});
|
||||||
|
let c2 = [], p2 = {key:2,class:_1};
|
||||||
|
let vn2 = h('div', p2, c2);
|
||||||
|
return vn2;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-att t-att-class with multiple classes 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _3 = utils.toClassObj({['a b c']:scope['value']});
|
||||||
|
let c4 = [], p4 = {key:4,class:_3};
|
||||||
|
let vn4 = h('div', p4, c4);
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-att t-att-class with multiple classes, some of which are duplicate 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _1 = utils.toClassObj({'a b c':scope['value'],'a b d':!scope['value']});
|
||||||
|
let c2 = [], p2 = {key:2,class:_1};
|
||||||
|
let vn2 = h('div', p2, c2);
|
||||||
|
return vn2;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-att t-att-class with multiple classes, some of which are duplicate 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let utils = this.constructor.utils;
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let h = this.h;
|
||||||
|
let _3 = utils.toClassObj({'a b c':scope['value'],'a b d':!scope['value']});
|
||||||
|
let c4 = [], p4 = {key:4,class:_3};
|
||||||
|
let vn4 = h('div', p4, c4);
|
||||||
|
return vn4;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
|
exports[`qweb t-tag simple usecases 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let result;
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let tag2 = 'div';
|
||||||
|
let vn1 = h(tag2, p1, c1);
|
||||||
|
result = vn1;
|
||||||
|
return result;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-tag simple usecases 2`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let result;
|
||||||
|
let h = this.h;
|
||||||
|
let c3 = [], p3 = {key:3};
|
||||||
|
let tag4 = scope['tag'];
|
||||||
|
let vn3 = h(tag4, p3, c3);
|
||||||
|
result = vn3;
|
||||||
|
c3.push({text: \`text\`});
|
||||||
|
return result;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-tag with multiple attributes 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let result;
|
||||||
|
let h = this.h;
|
||||||
|
let _2 = {'blueberry':true};
|
||||||
|
let _3 = 'raspberry';
|
||||||
|
let c4 = [], p4 = {key:4,attrs:{taste: _3},class:_2};
|
||||||
|
let tag5 = scope['tag'];
|
||||||
|
let vn4 = h(tag5, p4, c4);
|
||||||
|
result = vn4;
|
||||||
|
c4.push({text: \`gooseberry\`});
|
||||||
|
return result;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`qweb t-tag with multiple child nodes 1`] = `
|
||||||
|
"function anonymous(context, extra
|
||||||
|
) {
|
||||||
|
// Template name: \\"test\\"
|
||||||
|
let scope = Object.create(context);
|
||||||
|
let result;
|
||||||
|
let h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
let tag2 = scope['tag'];
|
||||||
|
let vn1 = h(tag2, p1, c1);
|
||||||
|
result = vn1;
|
||||||
|
c1.push({text: \` pear \`});
|
||||||
|
let c3 = [], p3 = {key:3};
|
||||||
|
let vn3 = h('span', p3, c3);
|
||||||
|
c1.push(vn3);
|
||||||
|
c3.push({text: \`apple\`});
|
||||||
|
c1.push({text: \` strawberry \`});
|
||||||
|
return result;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
+371
-56
@@ -1,4 +1,5 @@
|
|||||||
import { QWeb } from "../../src/qweb/index";
|
import { QWeb } from "../../src/qweb/index";
|
||||||
|
import { config } from "../../src/index";
|
||||||
import { nextTick, normalize, renderToDOM, renderToString, trim } from "../helpers";
|
import { nextTick, normalize, renderToDOM, renderToString, trim } from "../helpers";
|
||||||
import { patch } from "../../src/vdom";
|
import { patch } from "../../src/vdom";
|
||||||
|
|
||||||
@@ -13,6 +14,7 @@ let qweb: QWeb;
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
QWeb.TEMPLATES = {};
|
QWeb.TEMPLATES = {};
|
||||||
|
QWeb.nextId = 1;
|
||||||
qweb = new QWeb();
|
qweb = new QWeb();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -31,6 +33,21 @@ describe("static templates", () => {
|
|||||||
expect(renderToString(qweb, "test", { text: "hello vdom" })).toBe("hello vdom");
|
expect(renderToString(qweb, "test", { text: "hello vdom" })).toBe("hello vdom");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("inline template string in t-esc", () => {
|
||||||
|
qweb.addTemplate("test", '<t><t t-esc="`text`"/></t>');
|
||||||
|
expect(renderToString(qweb, "test")).toBe("text");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("inline template string with content in t-esc", () => {
|
||||||
|
qweb.addTemplate("test", '<t><t t-set="v" t-value="1"/><t t-esc="`text${v}`"/></t>');
|
||||||
|
expect(renderToString(qweb, "test")).toBe("text1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("inline template string with variable in context", () => {
|
||||||
|
qweb.addTemplate("test", '<t><t t-esc="`text ${v}`"/></t>');
|
||||||
|
expect(renderToString(qweb, "test", { v: "from context" })).toBe("text from context");
|
||||||
|
});
|
||||||
|
|
||||||
test("simple string, with some dynamic value", () => {
|
test("simple string, with some dynamic value", () => {
|
||||||
qweb.addTemplate("test", '<t>hello <t t-esc="text"/></t>');
|
qweb.addTemplate("test", '<t>hello <t t-esc="text"/></t>');
|
||||||
expect(renderToString(qweb, "test", { text: "vdom" })).toBe("hello vdom");
|
expect(renderToString(qweb, "test", { text: "vdom" })).toBe("hello vdom");
|
||||||
@@ -51,6 +68,16 @@ describe("static templates", () => {
|
|||||||
expect(renderToString(qweb, "test")).toBe(`<div class="abc">word</div>`);
|
expect(renderToString(qweb, "test")).toBe(`<div class="abc">word</div>`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("div with a class attribute with a quote", () => {
|
||||||
|
qweb.addTemplate("test", `<div class="a'bc">word</div>`);
|
||||||
|
expect(renderToString(qweb, "test")).toBe(`<div class="a'bc">word</div>`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("div with an arbitrary attribute with a quote", () => {
|
||||||
|
qweb.addTemplate("test", `<div abc="a'bc">word</div>`);
|
||||||
|
expect(renderToString(qweb, "test")).toBe(`<div abc="a'bc">word</div>`);
|
||||||
|
});
|
||||||
|
|
||||||
test("div with a empty class attribute", () => {
|
test("div with a empty class attribute", () => {
|
||||||
qweb.addTemplate("test", `<div class="">word</div>`);
|
qweb.addTemplate("test", `<div class="">word</div>`);
|
||||||
expect(renderToString(qweb, "test")).toBe(`<div>word</div>`);
|
expect(renderToString(qweb, "test")).toBe(`<div>word</div>`);
|
||||||
@@ -65,6 +92,19 @@ describe("static templates", () => {
|
|||||||
qweb.addTemplate("test", "<div>hello <!-- comment-->owl</div>");
|
qweb.addTemplate("test", "<div>hello <!-- comment-->owl</div>");
|
||||||
expect(renderToString(qweb, "test")).toBe("<div>hello <!-- comment-->owl</div>");
|
expect(renderToString(qweb, "test")).toBe("<div>hello <!-- comment-->owl</div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("properly handle comments between t-if/t-else", () => {
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<span t-if="true">true</span>
|
||||||
|
<!-- comment-->
|
||||||
|
<span t-else="">owl</span>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
expect(renderToString(qweb, "test")).toBe("<div><span>true</span></div>");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("error handling", () => {
|
describe("error handling", () => {
|
||||||
@@ -172,7 +212,7 @@ describe("t-esc", () => {
|
|||||||
v2: undefined,
|
v2: undefined,
|
||||||
v3: null,
|
v3: null,
|
||||||
v4: 0,
|
v4: 0,
|
||||||
v5: ""
|
v5: "",
|
||||||
};
|
};
|
||||||
expect(renderToString(qweb, "test", vals)).toBe(
|
expect(renderToString(qweb, "test", vals)).toBe(
|
||||||
"<div><p>false</p><p></p><p></p><p>0</p><p></p></div>"
|
"<div><p>false</p><p></p><p></p><p>0</p><p></p></div>"
|
||||||
@@ -184,6 +224,13 @@ describe("t-esc", () => {
|
|||||||
const result = renderToString(qweb, "test", { state: { list: [1, 2] } });
|
const result = renderToString(qweb, "test", { state: { list: [1, 2] } });
|
||||||
expect(result).toBe("<span>1,2</span>");
|
expect(result).toBe("<span>1,2</span>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("t-esc inside t-call, with t-set outside", () => {
|
||||||
|
qweb.addTemplate("main", `<div><t t-set="v">Hi</t><t t-call="sub"/></div>`);
|
||||||
|
qweb.addTemplate("sub", `<span t-esc="v"/>`);
|
||||||
|
const result = renderToString(qweb, "main");
|
||||||
|
expect(result).toBe("<div><span>Hi</span></div>");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("t-raw", () => {
|
describe("t-raw", () => {
|
||||||
@@ -208,6 +255,13 @@ describe("t-raw", () => {
|
|||||||
"<span><span>hello</span><ok>world</ok></span>"
|
"<span><span>hello</span><ok>world</ok></span>"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("t-raw with comment", () => {
|
||||||
|
qweb.addTemplate("test", `<span><t t-raw="var"/></span>`);
|
||||||
|
expect(renderToString(qweb, "test", { var: "<p>text<!-- top secret --></p>" })).toBe(
|
||||||
|
"<span><p>text<!-- top secret --></p></span>"
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("t-set", () => {
|
describe("t-set", () => {
|
||||||
@@ -463,7 +517,7 @@ describe("t-if", () => {
|
|||||||
cond3: false,
|
cond3: false,
|
||||||
cond4: false,
|
cond4: false,
|
||||||
m: 5,
|
m: 5,
|
||||||
n: 2
|
n: 2,
|
||||||
};
|
};
|
||||||
expect(normalize(renderToString(qweb, "test", context))).toBe("<div>andormgtnlt</div>");
|
expect(normalize(renderToString(qweb, "test", context))).toBe("<div>andormgtnlt</div>");
|
||||||
});
|
});
|
||||||
@@ -602,7 +656,7 @@ describe("attributes", () => {
|
|||||||
test("object", () => {
|
test("object", () => {
|
||||||
qweb.addTemplate("test", `<div t-att="value"/>`);
|
qweb.addTemplate("test", `<div t-att="value"/>`);
|
||||||
const result = renderToString(qweb, "test", {
|
const result = renderToString(qweb, "test", {
|
||||||
value: { a: 1, b: 2, c: 3 }
|
value: { a: 1, b: 2, c: 3 },
|
||||||
});
|
});
|
||||||
expect(result).toBe(`<div a="1" b="2" c="3"></div>`);
|
expect(result).toBe(`<div a="1" b="2" c="3"></div>`);
|
||||||
});
|
});
|
||||||
@@ -661,7 +715,7 @@ describe("attributes", () => {
|
|||||||
const result = renderToString(qweb, "test", {
|
const result = renderToString(qweb, "test", {
|
||||||
value1: 0,
|
value1: 0,
|
||||||
value2: 1,
|
value2: 1,
|
||||||
value3: 2
|
value3: 2,
|
||||||
});
|
});
|
||||||
expect(result).toBe(`<div foo="a 0 is 1 of 2 ]"></div>`);
|
expect(result).toBe(`<div foo="a 0 is 1 of 2 ]"></div>`);
|
||||||
});
|
});
|
||||||
@@ -680,7 +734,7 @@ describe("attributes", () => {
|
|||||||
const result = renderToString(qweb, "test", {
|
const result = renderToString(qweb, "test", {
|
||||||
bar: 0,
|
bar: 0,
|
||||||
baz: 1,
|
baz: 1,
|
||||||
qux: { qux: "<>" }
|
qux: { qux: "<>" },
|
||||||
});
|
});
|
||||||
const expected = '<div foo="<foo" bar="0" baz="<1>" qux="<>"></div>';
|
const expected = '<div foo="<foo" bar="0" baz="<1>" qux="<>"></div>';
|
||||||
expect(result).toBe(expected);
|
expect(result).toBe(expected);
|
||||||
@@ -692,6 +746,12 @@ describe("attributes", () => {
|
|||||||
expect(result).toBe(`<div class="hello world"></div>`);
|
expect(result).toBe(`<div class="hello world"></div>`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("class and t-att-class should combine together", () => {
|
||||||
|
qweb.addTemplate("test", `<div t-att-class="value" class="hello" />`);
|
||||||
|
const result = renderToString(qweb, "test", { value: "world" });
|
||||||
|
expect(result).toBe(`<div class="world hello"></div>`);
|
||||||
|
});
|
||||||
|
|
||||||
test("class and t-attf-class with ternary operation", () => {
|
test("class and t-attf-class with ternary operation", () => {
|
||||||
qweb.addTemplate("test", `<div class="hello" t-attf-class="{{value ? 'world' : ''}}"/>`);
|
qweb.addTemplate("test", `<div class="hello" t-attf-class="{{value ? 'world' : ''}}"/>`);
|
||||||
const result = renderToString(qweb, "test", { value: true });
|
const result = renderToString(qweb, "test", { value: true });
|
||||||
@@ -711,7 +771,7 @@ describe("t-call (template calling", () => {
|
|||||||
qweb.addTemplate("caller", '<div><t t-call="_basic-callee"/></div>');
|
qweb.addTemplate("caller", '<div><t t-call="_basic-callee"/></div>');
|
||||||
const expected = "<div><span>ok</span></div>";
|
const expected = "<div><span>ok</span></div>";
|
||||||
expect(renderToString(qweb, "caller")).toBe(expected);
|
expect(renderToString(qweb, "caller")).toBe(expected);
|
||||||
expect(qweb.subTemplates["_basic-callee"].toString()).toMatchSnapshot();
|
expect(qweb.subTemplates["_basic-callee"]).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("basic caller, no parent node", () => {
|
test("basic caller, no parent node", () => {
|
||||||
@@ -719,7 +779,7 @@ describe("t-call (template calling", () => {
|
|||||||
qweb.addTemplate("caller", '<t t-call="_basic-callee"/>');
|
qweb.addTemplate("caller", '<t t-call="_basic-callee"/>');
|
||||||
const expected = "<div>ok</div>";
|
const expected = "<div>ok</div>";
|
||||||
expect(renderToString(qweb, "caller")).toBe(expected);
|
expect(renderToString(qweb, "caller")).toBe(expected);
|
||||||
expect(qweb.subTemplates["_basic-callee"].toString()).toMatchSnapshot();
|
expect(qweb.subTemplates["_basic-callee"]).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("t-call with t-if", () => {
|
test("t-call with t-if", () => {
|
||||||
@@ -727,13 +787,14 @@ describe("t-call (template calling", () => {
|
|||||||
qweb.addTemplate("caller", '<div><t t-if="flag" t-call="sub"/></div>');
|
qweb.addTemplate("caller", '<div><t t-if="flag" t-call="sub"/></div>');
|
||||||
const expected = "<div><span>ok</span></div>";
|
const expected = "<div><span>ok</span></div>";
|
||||||
expect(renderToString(qweb, "caller", { flag: true })).toBe(expected);
|
expect(renderToString(qweb, "caller", { flag: true })).toBe(expected);
|
||||||
expect(qweb.subTemplates["sub"].toString()).toMatchSnapshot();
|
expect(qweb.subTemplates["sub"]).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("t-call not allowed on a non t node", () => {
|
test("t-call allowed on a non t node", () => {
|
||||||
qweb.addTemplate("_basic-callee", "<t>ok</t>");
|
qweb.addTemplate("_basic-callee", "<span>ok</span>");
|
||||||
qweb.addTemplate("caller", '<div t-call="_basic-callee"/>');
|
qweb.addTemplate("caller", '<div t-call="_basic-callee"/>');
|
||||||
expect(() => renderToString(qweb, "caller")).toThrow("Invalid tag");
|
const expected = "<div><span>ok</span></div>";
|
||||||
|
expect(renderToString(qweb, "caller")).toBe(expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("with unused body", () => {
|
test("with unused body", () => {
|
||||||
@@ -862,7 +923,8 @@ describe("t-call (template calling", () => {
|
|||||||
`);
|
`);
|
||||||
const expected = "<div><span>hey</span></div>";
|
const expected = "<div><span>hey</span></div>";
|
||||||
expect(renderToString(qweb, "recursive")).toBe(expected);
|
expect(renderToString(qweb, "recursive")).toBe(expected);
|
||||||
const recursiveFn = Object.values(qweb.subTemplates)[0] as any;
|
const subId = qweb.subTemplates["recursive"];
|
||||||
|
const recursiveFn = QWeb.subTemplates[subId] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -890,7 +952,8 @@ describe("t-call (template calling", () => {
|
|||||||
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
|
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
|
||||||
expected
|
expected
|
||||||
);
|
);
|
||||||
const recursiveFn = Object.values(qweb.subTemplates)[0] as any;
|
const subId = qweb.subTemplates["nodeTemplate"];
|
||||||
|
const recursiveFn = QWeb.subTemplates[subId] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -917,7 +980,41 @@ describe("t-call (template calling", () => {
|
|||||||
const expected =
|
const expected =
|
||||||
"<div><div><p>a</p><div><p>b</p><div><p>d</p></div></div><div><p>c</p></div></div></div>";
|
"<div><div><p>a</p><div><p>b</p><div><p>d</p></div></div><div><p>c</p></div></div></div>";
|
||||||
expect(renderToString(qweb, "Parent", { root }, { fiber: {} })).toBe(expected);
|
expect(renderToString(qweb, "Parent", { root }, { fiber: {} })).toBe(expected);
|
||||||
const recursiveFn = Object.values(qweb.subTemplates)[0] as any;
|
const subId = qweb.subTemplates["nodeTemplate"];
|
||||||
|
const recursiveFn = QWeb.subTemplates[subId] as any;
|
||||||
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("recursive template, part 4: with t-set recursive index", () => {
|
||||||
|
qweb.addTemplates(`
|
||||||
|
<templates>
|
||||||
|
<div t-name="Parent">
|
||||||
|
<t t-call="nodeTemplate">
|
||||||
|
<t t-set="recursive_idx" t-value="1"/>
|
||||||
|
<t t-set="node" t-value="root"/>
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
<div t-name="nodeTemplate">
|
||||||
|
<t t-set="recursive_idx" t-value="recursive_idx + 1"/>
|
||||||
|
<p><t t-esc="node.val"/> <t t-esc="recursive_idx"/></p>
|
||||||
|
<t t-foreach="node.children or []" t-as="subtree">
|
||||||
|
<t t-call="nodeTemplate">
|
||||||
|
<t t-set="node" t-value="subtree"/>
|
||||||
|
</t>
|
||||||
|
</t>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</templates>
|
||||||
|
`);
|
||||||
|
const root = {
|
||||||
|
val: "a",
|
||||||
|
children: [{ val: "b", children: [{ val: "c", children: [{ val: "d" }] }] }],
|
||||||
|
};
|
||||||
|
const expected =
|
||||||
|
"<div><div><p>a 2</p><div><p>b 3</p><div><p>c 4</p><div><p>d 5</p></div></div></div></div></div>";
|
||||||
|
expect(renderToString(qweb, "Parent", { root })).toBe(expected);
|
||||||
|
const subId = qweb.subTemplates["nodeTemplate"];
|
||||||
|
const recursiveFn = QWeb.subTemplates[subId] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -989,6 +1086,52 @@ describe("t-call (template calling", () => {
|
|||||||
const context = { list: [{ val: 1 }, { val: 2 }, { val: 3 }] };
|
const context = { list: [{ val: 1 }, { val: 2 }, { val: 3 }] };
|
||||||
expect(trim(renderToString(qweb, "wrapper", context))).toBe(expected);
|
expect(trim(renderToString(qweb, "wrapper", context))).toBe(expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("two different QWeb instances, and shared templates", () => {
|
||||||
|
QWeb.registerTemplate("sub", `<span>ok</span>`);
|
||||||
|
QWeb.registerTemplate("main", `<div><t t-call="sub"/></div>`);
|
||||||
|
|
||||||
|
const qweb1 = new QWeb();
|
||||||
|
const qweb2 = new QWeb();
|
||||||
|
|
||||||
|
expect(renderToString(qweb1, "main")).toBe("<div><span>ok</span></div>");
|
||||||
|
expect(renderToString(qweb2, "main")).toBe("<div><span>ok</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-call with t-set inside and body text content", () => {
|
||||||
|
qweb.addTemplate("sub", `<p><t t-esc="val"/></p>`);
|
||||||
|
qweb.addTemplate(
|
||||||
|
"main",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<t t-call="sub">
|
||||||
|
<t t-set="val">yip yip</t>
|
||||||
|
</t>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
const expected = "<div><p>yip yip</p></div>";
|
||||||
|
expect(renderToString(qweb, "main")).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-call with body content as root of a template", () => {
|
||||||
|
qweb.addTemplate("antony", `<foo><t t-raw="0"/></foo>`);
|
||||||
|
qweb.addTemplate("main", `<t><t t-call="antony"><p>antony</p></t></t>`);
|
||||||
|
const expected = "<foo><p>antony</p></foo>";
|
||||||
|
expect(renderToString(qweb, "main")).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dynamic t-call", () => {
|
||||||
|
qweb.addTemplate("foo", `<foo><t t-esc="val"/></foo>`);
|
||||||
|
qweb.addTemplate("bar", `<bar><t t-esc="val"/></bar>`);
|
||||||
|
qweb.addTemplate("main", `<div><t t-call="{{template}}"/></div>`);
|
||||||
|
const expected = "<div><foo>foo</foo></div>";
|
||||||
|
expect(renderToString(qweb, "main", { template: "foo", val: "foo" })).toBe(expected);
|
||||||
|
const expected2 = "<div><bar>quux</bar></div>";
|
||||||
|
expect(renderToString(qweb, "main", { template: "bar", val: "quux" })).toBe(expected2);
|
||||||
|
// duplicate call because there was a specific bug with some id that was
|
||||||
|
// incremented each rendering.
|
||||||
|
expect(renderToString(qweb, "main", { template: "bar", val: "quux" })).toBe(expected2);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("foreach", () => {
|
describe("foreach", () => {
|
||||||
@@ -1079,6 +1222,63 @@ describe("foreach", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("t-call without body in t-foreach in t-foreach", () => {
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test_called",
|
||||||
|
`<t>
|
||||||
|
<t t-set="c" t-value="'x' + '_' + a + '_'+ b" />
|
||||||
|
[<t t-esc="a" />]
|
||||||
|
[<t t-esc="b" />]
|
||||||
|
[<t t-esc="c" />]
|
||||||
|
</t>`
|
||||||
|
);
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`<div>
|
||||||
|
<t t-foreach="numbers" t-as="a">
|
||||||
|
<t t-foreach="letters" t-as="b">
|
||||||
|
<t t-call="test_called" />
|
||||||
|
</t>
|
||||||
|
<span t-esc="c"/>
|
||||||
|
</t>
|
||||||
|
<span>[<t t-esc="a" />][<t t-esc="b" />][<t t-esc="c" />]</span>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
const context = { numbers: [1, 2, 3], letters: ["a", "b"] };
|
||||||
|
expect(renderToString(qweb, "test", context)).toBe(
|
||||||
|
"<div> [1] [a] [x_1_a] [1] [b] [x_1_b] <span></span> [2] [a] [x_2_a] [2] [b] [x_2_b] <span></span> [3] [a] [x_3_a] [3] [b] [x_3_b] <span></span><span>[][][]</span></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-call with body in t-foreach in t-foreach", () => {
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test_called",
|
||||||
|
`<t>
|
||||||
|
[<t t-esc="a" />]
|
||||||
|
[<t t-esc="b" />]
|
||||||
|
[<t t-esc="c" />]
|
||||||
|
</t>`
|
||||||
|
);
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`<div>
|
||||||
|
<t t-foreach="numbers" t-as="a">
|
||||||
|
<t t-foreach="letters" t-as="b">
|
||||||
|
<t t-call="test_called" >
|
||||||
|
<t t-set="c" t-value="'x' + '_' + a + '_'+ b" />
|
||||||
|
</t>
|
||||||
|
</t>
|
||||||
|
<span t-esc="c"/>
|
||||||
|
</t>
|
||||||
|
<span>[<t t-esc="a" />][<t t-esc="b" />][<t t-esc="c" />]</span>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
const context = { numbers: [1, 2, 3], letters: ["a", "b"] };
|
||||||
|
expect(renderToString(qweb, "test", context)).toBe(
|
||||||
|
"<div> [1] [a] [x_1_a] [1] [b] [x_1_b] <span></span> [2] [a] [x_2_a] [2] [b] [x_2_b] <span></span> [3] [a] [x_3_a] [3] [b] [x_3_b] <span></span><span>[][][]</span></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("throws error if invalid loop expression", () => {
|
test("throws error if invalid loop expression", () => {
|
||||||
qweb.addTemplate(
|
qweb.addTemplate(
|
||||||
"test",
|
"test",
|
||||||
@@ -1174,7 +1374,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
add() {
|
add() {
|
||||||
a = 3;
|
a = 3;
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1197,7 +1397,7 @@ describe("t-on", () => {
|
|||||||
},
|
},
|
||||||
handleDblClick() {
|
handleDblClick() {
|
||||||
steps.push("dblclick");
|
steps.push("dblclick");
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1217,7 +1417,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
add(n) {
|
add(n) {
|
||||||
a = a + n;
|
a = a + n;
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1234,7 +1434,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
add({ val }) {
|
add({ val }) {
|
||||||
a = a + val;
|
a = a + val;
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1251,7 +1451,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
doSomething(arg) {
|
doSomething(arg) {
|
||||||
expect(arg).toEqual({});
|
expect(arg).toEqual({});
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1267,7 +1467,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
doSomething(arg) {
|
doSomething(arg) {
|
||||||
expect(arg).toEqual({});
|
expect(arg).toEqual({});
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1289,7 +1489,7 @@ describe("t-on", () => {
|
|||||||
{
|
{
|
||||||
activate(action) {
|
activate(action) {
|
||||||
expect(action).toBe("someval");
|
expect(action).toBe("someval");
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{ handlers: [] }
|
{ handlers: [] }
|
||||||
);
|
);
|
||||||
@@ -1302,7 +1502,7 @@ describe("t-on", () => {
|
|||||||
let owner = {
|
let owner = {
|
||||||
add() {
|
add() {
|
||||||
expect(this).toBe(owner);
|
expect(this).toBe(owner);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
(<HTMLElement>node).click();
|
(<HTMLElement>node).click();
|
||||||
@@ -1312,8 +1512,8 @@ describe("t-on", () => {
|
|||||||
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
|
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
|
||||||
let owner = {
|
let owner = {
|
||||||
state: {
|
state: {
|
||||||
counter: 0
|
counter: 0,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.counter).toBe(0);
|
expect(owner.state.counter).toBe(0);
|
||||||
@@ -1326,10 +1526,10 @@ describe("t-on", () => {
|
|||||||
let owner = {
|
let owner = {
|
||||||
state: {
|
state: {
|
||||||
counter: 0,
|
counter: 0,
|
||||||
incrementCounter: inc => {
|
incrementCounter: (inc) => {
|
||||||
owner.state.counter += inc;
|
owner.state.counter += inc;
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.counter).toBe(0);
|
expect(owner.state.counter).toBe(0);
|
||||||
@@ -1341,8 +1541,8 @@ describe("t-on", () => {
|
|||||||
qweb.addTemplate("test", `<button t-on-click="state.flag = !state.flag">Toggle</button>`);
|
qweb.addTemplate("test", `<button t-on-click="state.flag = !state.flag">Toggle</button>`);
|
||||||
let owner = {
|
let owner = {
|
||||||
state: {
|
state: {
|
||||||
flag: true
|
flag: true,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.flag).toBe(true);
|
expect(owner.state.flag).toBe(true);
|
||||||
@@ -1359,8 +1559,8 @@ describe("t-on", () => {
|
|||||||
return n + 1;
|
return n + 1;
|
||||||
},
|
},
|
||||||
state: {
|
state: {
|
||||||
n: 11
|
n: 11,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.n).toBe(11);
|
expect(owner.state.n).toBe(11);
|
||||||
@@ -1376,7 +1576,7 @@ describe("t-on", () => {
|
|||||||
let owner = {
|
let owner = {
|
||||||
update() {
|
update() {
|
||||||
expect(this).toBe(owner);
|
expect(this).toBe(owner);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const node = renderToDOM(qweb, "main", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "main", owner, { handlers: [] });
|
||||||
@@ -1393,7 +1593,7 @@ describe("t-on", () => {
|
|||||||
expect(this).toBe(owner);
|
expect(this).toBe(owner);
|
||||||
expect(val).toBe(444);
|
expect(val).toBe(444);
|
||||||
},
|
},
|
||||||
value: 444
|
value: 444,
|
||||||
};
|
};
|
||||||
|
|
||||||
const node = renderToDOM(qweb, "main", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "main", owner, { handlers: [] });
|
||||||
@@ -1422,7 +1622,7 @@ describe("t-on", () => {
|
|||||||
onClickPreventedAndStopped(e) {
|
onClickPreventedAndStopped(e) {
|
||||||
expect(e.defaultPrevented).toBe(true);
|
expect(e.defaultPrevented).toBe(true);
|
||||||
expect(e.cancelBubble).toBe(true);
|
expect(e.cancelBubble).toBe(true);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
|
|
||||||
@@ -1448,7 +1648,7 @@ describe("t-on", () => {
|
|||||||
},
|
},
|
||||||
onClickSelf(e) {
|
onClickSelf(e) {
|
||||||
steps.push("onClickSelf");
|
steps.push("onClickSelf");
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
|
|
||||||
@@ -1472,10 +1672,10 @@ describe("t-on", () => {
|
|||||||
);
|
);
|
||||||
let steps: boolean[] = [];
|
let steps: boolean[] = [];
|
||||||
let owner = {
|
let owner = {
|
||||||
onClick() {}
|
onClick() {},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
(<HTMLElement>node).addEventListener("click", function(e) {
|
(<HTMLElement>node).addEventListener("click", function (e) {
|
||||||
steps.push(e.defaultPrevented);
|
steps.push(e.defaultPrevented);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1497,10 +1697,10 @@ describe("t-on", () => {
|
|||||||
);
|
);
|
||||||
let steps: boolean[] = [];
|
let steps: boolean[] = [];
|
||||||
let owner = {
|
let owner = {
|
||||||
onClick() {}
|
onClick() {},
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
(<HTMLElement>node).addEventListener("click", function(e) {
|
(<HTMLElement>node).addEventListener("click", function (e) {
|
||||||
steps.push(e.defaultPrevented);
|
steps.push(e.defaultPrevented);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1528,13 +1728,13 @@ describe("t-on", () => {
|
|||||||
const owner = {
|
const owner = {
|
||||||
projects: [
|
projects: [
|
||||||
{ id: 1, name: "Project 1" },
|
{ id: 1, name: "Project 1" },
|
||||||
{ id: 2, name: "Project 2" }
|
{ id: 2, name: "Project 2" },
|
||||||
],
|
],
|
||||||
|
|
||||||
onEdit(projectId, ev) {
|
onEdit(projectId, ev) {
|
||||||
expect(ev.defaultPrevented).toBe(true);
|
expect(ev.defaultPrevented).toBe(true);
|
||||||
steps.push(projectId);
|
steps.push(projectId);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
@@ -1559,7 +1759,7 @@ describe("t-on", () => {
|
|||||||
);
|
);
|
||||||
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
|
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
|
||||||
|
|
||||||
node.addEventListener("click", e => {
|
node.addEventListener("click", (e) => {
|
||||||
expect(e.defaultPrevented).toBe(true);
|
expect(e.defaultPrevented).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1575,7 +1775,7 @@ describe("t-on", () => {
|
|||||||
text: "Click here",
|
text: "Click here",
|
||||||
onClick() {
|
onClick() {
|
||||||
steps.push("onClick");
|
steps.push("onClick");
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
@@ -1594,7 +1794,7 @@ describe("t-on", () => {
|
|||||||
html: "Click <b>here</b>",
|
html: "Click <b>here</b>",
|
||||||
onClick() {
|
onClick() {
|
||||||
steps.push("onClick");
|
steps.push("onClick");
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
@@ -1604,6 +1804,31 @@ describe("t-on", () => {
|
|||||||
|
|
||||||
expect(steps).toEqual(["onClick"]);
|
expect(steps).toEqual(["onClick"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("t-on with .capture modifier", () => {
|
||||||
|
expect.assertions(2);
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`<div t-on-click.capture="onCapture">
|
||||||
|
<button t-on-click="doSomething">Button</button>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
|
||||||
|
const steps: string[] = [];
|
||||||
|
const owner = {
|
||||||
|
onCapture() {
|
||||||
|
steps.push("captured");
|
||||||
|
},
|
||||||
|
doSomething() {
|
||||||
|
steps.push("normal");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
|
|
||||||
|
const button = (<HTMLElement>node).getElementsByTagName("button")[0];
|
||||||
|
button.click();
|
||||||
|
expect(steps).toEqual(["captured", "normal"]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("t-ref", () => {
|
describe("t-ref", () => {
|
||||||
@@ -1639,8 +1864,7 @@ describe("t-ref", () => {
|
|||||||
|
|
||||||
describe("loading templates", () => {
|
describe("loading templates", () => {
|
||||||
test("can initialize qweb with a string", () => {
|
test("can initialize qweb with a string", () => {
|
||||||
const templates = `
|
const templates = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<templates id="template" xml:space="preserve">
|
<templates id="template" xml:space="preserve">
|
||||||
<div t-name="hey">jupiler</div>
|
<div t-name="hey">jupiler</div>
|
||||||
</templates>`;
|
</templates>`;
|
||||||
@@ -1649,8 +1873,7 @@ describe("loading templates", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("can load a few templates from a xml string", () => {
|
test("can load a few templates from a xml string", () => {
|
||||||
const data = `
|
const data = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<templates id="template" xml:space="preserve">
|
<templates id="template" xml:space="preserve">
|
||||||
|
|
||||||
<t t-name="items"><li>ok</li><li>foo</li></t>
|
<t t-name="items"><li>ok</li><li>foo</li></t>
|
||||||
@@ -1669,7 +1892,7 @@ describe("loading templates", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("special cases for some boolean html attributes/properties", () => {
|
describe("special cases for some specific html attributes/properties", () => {
|
||||||
test("input type= checkbox, with t-att-checked", () => {
|
test("input type= checkbox, with t-att-checked", () => {
|
||||||
qweb.addTemplate("test", `<input type="checkbox" t-att-checked="flag"/>`);
|
qweb.addTemplate("test", `<input type="checkbox" t-att-checked="flag"/>`);
|
||||||
const result = renderToString(qweb, "test", { flag: true });
|
const result = renderToString(qweb, "test", { flag: true });
|
||||||
@@ -1696,6 +1919,76 @@ describe("special cases for some boolean html attributes/properties", () => {
|
|||||||
);
|
);
|
||||||
renderToString(qweb, "test", { flag: true });
|
renderToString(qweb, "test", { flag: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("input with t-att-value", () => {
|
||||||
|
// render input with initial value
|
||||||
|
qweb.addTemplate("test", `<input t-att-value="v"/>`);
|
||||||
|
const vnode1 = qweb.render("test", { v: "zucchini" });
|
||||||
|
const vnode2 = patch(document.createElement("input"), vnode1);
|
||||||
|
let elm = vnode2.elm as HTMLInputElement;
|
||||||
|
expect(elm.value).toBe("zucchini");
|
||||||
|
|
||||||
|
// change value manually in input, to simulate user input
|
||||||
|
elm.value = "tomato";
|
||||||
|
expect(elm.value).toBe("tomato");
|
||||||
|
|
||||||
|
// rerender with a different value, and patch actual dom, to check that
|
||||||
|
// input value was properly reset by owl
|
||||||
|
const vnode3 = qweb.render("test", { v: "potato" });
|
||||||
|
patch(vnode2, vnode3);
|
||||||
|
expect(elm.value).toBe("potato");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("input of type checkbox with t-att-indeterminate", () => {
|
||||||
|
qweb.addTemplate("test", `<input type="checkbox" t-att-indeterminate="v"/>`);
|
||||||
|
const vnode1 = qweb.render("test", { v: true });
|
||||||
|
const vnode2 = patch(document.createElement("input"), vnode1);
|
||||||
|
let elm = vnode2.elm as HTMLInputElement;
|
||||||
|
expect(elm.indeterminate).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("textarea with t-att-value", () => {
|
||||||
|
// render input with initial value
|
||||||
|
qweb.addTemplate("test", `<textarea t-att-value="v"/>`);
|
||||||
|
const vnode1 = qweb.render("test", { v: "zucchini" });
|
||||||
|
const vnode2 = patch(document.createElement("textarea"), vnode1);
|
||||||
|
let elm = vnode2.elm as HTMLInputElement;
|
||||||
|
expect(elm.value).toBe("zucchini");
|
||||||
|
|
||||||
|
// change value manually in textarea, to simulate user textarea
|
||||||
|
elm.value = "tomato";
|
||||||
|
expect(elm.value).toBe("tomato");
|
||||||
|
|
||||||
|
// rerender with a different value, and patch actual dom, to check that
|
||||||
|
// textarea value was properly reset by owl
|
||||||
|
const vnode3 = qweb.render("test", { v: "potato" });
|
||||||
|
patch(vnode2, vnode3);
|
||||||
|
expect(elm.value).toBe("potato");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("select with t-att-value", () => {
|
||||||
|
const template = `
|
||||||
|
<select t-att-value="value">
|
||||||
|
<option value="potato">Potato</option>
|
||||||
|
<option value="tomato">Tomato</option>
|
||||||
|
<option value="onion">Onion</option>
|
||||||
|
</select>`;
|
||||||
|
qweb.addTemplate("test", template);
|
||||||
|
const vnode1 = qweb.render("test", { value: "tomato" });
|
||||||
|
const vnode2 = patch(document.createElement("select"), vnode1);
|
||||||
|
let elm = vnode2.elm as HTMLSelectElement;
|
||||||
|
expect(elm.value).toBe("tomato");
|
||||||
|
|
||||||
|
elm.value = "potato";
|
||||||
|
expect(elm.value).toBe("potato");
|
||||||
|
|
||||||
|
// rerender with a different value, and patch actual dom, to check that
|
||||||
|
// select value was properly reset by owl
|
||||||
|
const vnode3 = qweb.render("test", { value: "onion" });
|
||||||
|
patch(vnode2, vnode3);
|
||||||
|
expect(elm.value).toBe("onion");
|
||||||
|
expect(qweb.templates.test.fn.toString()).toMatchSnapshot();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("whitespace handling", () => {
|
describe("whitespace handling", () => {
|
||||||
@@ -1760,7 +2053,7 @@ describe("t-key", () => {
|
|||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
renderToString(qweb, "test", {
|
renderToString(qweb, "test", {
|
||||||
beers: [{ id: 12, name: "Chimay Rouge" }]
|
beers: [{ id: 12, name: "Chimay Rouge" }],
|
||||||
})
|
})
|
||||||
).toMatchSnapshot();
|
).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
@@ -1873,9 +2166,9 @@ describe("properly support svg", () => {
|
|||||||
describe("translation support", () => {
|
describe("translation support", () => {
|
||||||
test("can translate node content", () => {
|
test("can translate node content", () => {
|
||||||
const translations = {
|
const translations = {
|
||||||
word: "mot"
|
word: "mot",
|
||||||
};
|
};
|
||||||
const translateFn = expr => translations[expr] || expr;
|
const translateFn = (expr) => translations[expr] || expr;
|
||||||
const qweb = new QWeb({ translateFn });
|
const qweb = new QWeb({ translateFn });
|
||||||
qweb.addTemplate("test", "<div>word</div>");
|
qweb.addTemplate("test", "<div>word</div>");
|
||||||
expect(renderToString(qweb, "test")).toBe("<div>mot</div>");
|
expect(renderToString(qweb, "test")).toBe("<div>mot</div>");
|
||||||
@@ -1883,9 +2176,9 @@ describe("translation support", () => {
|
|||||||
|
|
||||||
test("does not translate node content if disabled", () => {
|
test("does not translate node content if disabled", () => {
|
||||||
const translations = {
|
const translations = {
|
||||||
word: "mot"
|
word: "mot",
|
||||||
};
|
};
|
||||||
const translateFn = expr => translations[expr] || expr;
|
const translateFn = (expr) => translations[expr] || expr;
|
||||||
const qweb = new QWeb({ translateFn });
|
const qweb = new QWeb({ translateFn });
|
||||||
qweb.addTemplate(
|
qweb.addTemplate(
|
||||||
"test",
|
"test",
|
||||||
@@ -1900,9 +2193,9 @@ describe("translation support", () => {
|
|||||||
|
|
||||||
test("some attributes are translated", () => {
|
test("some attributes are translated", () => {
|
||||||
const translations = {
|
const translations = {
|
||||||
word: "mot"
|
word: "mot",
|
||||||
};
|
};
|
||||||
const translateFn = expr => translations[expr] || expr;
|
const translateFn = (expr) => translations[expr] || expr;
|
||||||
const qweb = new QWeb({ translateFn });
|
const qweb = new QWeb({ translateFn });
|
||||||
qweb.addTemplate(
|
qweb.addTemplate(
|
||||||
"test",
|
"test",
|
||||||
@@ -1919,6 +2212,28 @@ describe("translation support", () => {
|
|||||||
'<div><p label="mot">mot</p><p title="mot">mot</p><p placeholder="mot">mot</p><p alt="mot">mot</p><p something="word">mot</p></div>'
|
'<div><p label="mot">mot</p><p title="mot">mot</p><p placeholder="mot">mot</p><p alt="mot">mot</p><p something="word">mot</p></div>'
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("can add additional attributes to the list of translatable attributes", () => {
|
||||||
|
const translations = {
|
||||||
|
word: "mot",
|
||||||
|
};
|
||||||
|
const translateFn = (expr) => translations[expr] || expr;
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
config.translatableAttributes.push("potato");
|
||||||
|
qweb.addTemplate("test", `<div tomato="word" potato="word">text</div>`);
|
||||||
|
expect(renderToString(qweb, "test")).toBe('<div tomato="word" potato="mot">text</div>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("translation is done on the trimmed text, with extra spaces readded after", () => {
|
||||||
|
const translations = {
|
||||||
|
word: "mot",
|
||||||
|
};
|
||||||
|
const translateFn = jest.fn((expr) => translations[expr] || expr);
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
qweb.addTemplate("test", "<div> word </div>");
|
||||||
|
expect(renderToString(qweb, "test")).toBe("<div> mot </div>");
|
||||||
|
expect(translateFn).toHaveBeenCalledWith("word");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("t-key tests", () => {
|
describe("t-key tests", () => {
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ describe("tokenizer", () => {
|
|||||||
|
|
||||||
expect(tokenize("{}")).toEqual([
|
expect(tokenize("{}")).toEqual([
|
||||||
{ type: "LEFT_BRACE", value: "{" },
|
{ type: "LEFT_BRACE", value: "{" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("{ }}")).toEqual([
|
expect(tokenize("{ }}")).toEqual([
|
||||||
{ type: "LEFT_BRACE", value: "{" },
|
{ type: "LEFT_BRACE", value: "{" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" },
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("a")).toEqual([{ type: "SYMBOL", value: "a" }]);
|
expect(tokenize("a")).toEqual([{ type: "SYMBOL", value: "a" }]);
|
||||||
expect(tokenize("true")).toEqual([{ type: "SYMBOL", value: "true" }]);
|
expect(tokenize("true")).toEqual([{ type: "SYMBOL", value: "true" }]);
|
||||||
@@ -25,15 +25,15 @@ describe("tokenizer", () => {
|
|||||||
{ type: "SYMBOL", value: "a" },
|
{ type: "SYMBOL", value: "a" },
|
||||||
{ type: "COLON", value: ":" },
|
{ type: "COLON", value: ":" },
|
||||||
{ type: "VALUE", value: "2" },
|
{ type: "VALUE", value: "2" },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("a,")).toEqual([
|
expect(tokenize("a,")).toEqual([
|
||||||
{ type: "SYMBOL", value: "a" },
|
{ type: "SYMBOL", value: "a" },
|
||||||
{ type: "COMMA", value: "," }
|
{ type: "COMMA", value: "," },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("][")).toEqual([
|
expect(tokenize("][")).toEqual([
|
||||||
{ type: "RIGHT_BRACKET", value: "]" },
|
{ type: "RIGHT_BRACKET", value: "]" },
|
||||||
{ type: "LEFT_BRACKET", value: "[" }
|
{ type: "LEFT_BRACKET", value: "[" },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -44,23 +44,23 @@ describe("tokenizer", () => {
|
|||||||
{ type: "OPERATOR", value: "<" },
|
{ type: "OPERATOR", value: "<" },
|
||||||
{ type: "OPERATOR", value: ">" },
|
{ type: "OPERATOR", value: ">" },
|
||||||
{ type: "OPERATOR", value: "!==" },
|
{ type: "OPERATOR", value: "!==" },
|
||||||
{ type: "OPERATOR", value: "!=" }
|
{ type: "OPERATOR", value: "!=" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize("typeof a")).toEqual([
|
expect(tokenize("typeof a")).toEqual([
|
||||||
{ type: "OPERATOR", value: "typeof " },
|
{ type: "OPERATOR", value: "typeof " },
|
||||||
{ type: "SYMBOL", value: "a" }
|
{ type: "SYMBOL", value: "a" },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(tokenize("a...1")).toEqual([
|
expect(tokenize("a...1")).toEqual([
|
||||||
{ type: "SYMBOL", value: "a" },
|
{ type: "SYMBOL", value: "a" },
|
||||||
{ type: "OPERATOR", value: "..." },
|
{ type: "OPERATOR", value: "..." },
|
||||||
{ type: "VALUE", value: "1" }
|
{ type: "VALUE", value: "1" },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
expect(tokenize("a in b")).toEqual([
|
expect(tokenize("a in b")).toEqual([
|
||||||
{ type: "SYMBOL", value: "a" },
|
{ type: "SYMBOL", value: "a" },
|
||||||
{ type: "OPERATOR", value: "in " },
|
{ type: "OPERATOR", value: "in " },
|
||||||
{ type: "SYMBOL", value: "b" }
|
{ type: "SYMBOL", value: "b" },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ describe("tokenizer", () => {
|
|||||||
expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]);
|
expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]);
|
||||||
expect(tokenize('"hello ged"}')).toEqual([
|
expect(tokenize('"hello ged"}')).toEqual([
|
||||||
{ type: "VALUE", value: '"hello ged"' },
|
{ type: "VALUE", value: '"hello ged"' },
|
||||||
{ type: "RIGHT_BRACE", value: "}" }
|
{ type: "RIGHT_BRACE", value: "}" },
|
||||||
]);
|
]);
|
||||||
expect(tokenize('"hello \\"ged\\""')).toEqual([{ type: "VALUE", value: '"hello \\"ged\\""' }]);
|
expect(tokenize('"hello \\"ged\\""')).toEqual([{ type: "VALUE", value: '"hello \\"ged\\""' }]);
|
||||||
});
|
});
|
||||||
@@ -196,4 +196,31 @@ describe("expression evaluation", () => {
|
|||||||
expect(compileExpr("f(...state.list)", {})).toBe("scope['f'](...scope['state'].list)");
|
expect(compileExpr("f(...state.list)", {})).toBe("scope['f'](...scope['state'].list)");
|
||||||
expect(compileExpr("f([...list])", {})).toBe("scope['f']([...scope['list']])");
|
expect(compileExpr("f([...list])", {})).toBe("scope['f']([...scope['list']])");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("works with builtin properties", () => {
|
||||||
|
expect(compileExpr("state.constructor.name", {})).toBe("scope['state'].constructor.name");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("works with shortcut object key description", () => {
|
||||||
|
expect(compileExpr("{a}", {})).toBe("{a:scope['a']}");
|
||||||
|
expect(compileExpr("{a,b}", {})).toBe("{a:scope['a'],b:scope['b']}");
|
||||||
|
expect(compileExpr("{a,b:3,c}", {})).toBe("{a:scope['a'],b:3,c:scope['c']}");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("works with short object description and lists ", () => {
|
||||||
|
expect(compileExpr("[a, b]", {})).toBe("[scope['a'],scope['b']]");
|
||||||
|
expect(compileExpr("[a, b, c]", {})).toBe("[scope['a'],scope['b'],scope['c']]");
|
||||||
|
expect(compileExpr("[a, {b, c},d]", {})).toBe(
|
||||||
|
"[scope['a'],{b:scope['b'],c:scope['c']},scope['d']]"
|
||||||
|
);
|
||||||
|
expect(compileExpr("{a:[b, {c, d: e}]}", {})).toBe(
|
||||||
|
"{a:[scope['b'],{c:scope['c'],d:scope['e']}]}"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("template strings", () => {
|
||||||
|
expect(compileExpr("`hey`", {})).toBe("`hey`");
|
||||||
|
expect(compileExpr("`hey ${you}`", {})).toBe("`hey ${scope['you']}`");
|
||||||
|
expect(compileExpr("`hey ${1 + 2}`", {})).toBe("`hey ${1+2}`");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { QWeb } from "../../src/qweb/index";
|
||||||
|
import { renderToString } from "../helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function render(template, context = {}) {
|
||||||
|
const qweb = new QWeb();
|
||||||
|
qweb.addTemplate("test", template);
|
||||||
|
return renderToString(qweb, "test", context);
|
||||||
|
}
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("qweb t-att", () => {
|
||||||
|
test("t-att-class with multiple classes", () => {
|
||||||
|
expect(render(`<div t-att-class="{'a b c': value}" />`, { value: true })).toBe(
|
||||||
|
'<div class="a b c"></div>'
|
||||||
|
);
|
||||||
|
expect(render(`<div t-att-class="{['a b c']: value}" />`, { value: true })).toBe(
|
||||||
|
'<div class="a b c"></div>'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("t-att-class with multiple classes, some of which are duplicate", () => {
|
||||||
|
expect(render(`<div t-att-class="{'a b c': value, 'a b d': !value}" />`, { value: true })).toBe(
|
||||||
|
'<div class="a b c"></div>'
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
render(`<div t-att-class="{'a b c': value, 'a b d': !value}" />`, { value: false })
|
||||||
|
).toBe('<div class="a b d"></div>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { QWeb } from "../../src/qweb/index";
|
||||||
|
import { renderToString } from "../helpers";
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Setup and helpers
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function render(template, context = {}) {
|
||||||
|
const qweb = new QWeb();
|
||||||
|
qweb.addTemplate("test", template);
|
||||||
|
return renderToString(qweb, "test", context);
|
||||||
|
}
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("qweb t-tag", () => {
|
||||||
|
test("simple usecases", () => {
|
||||||
|
expect(render(`<t t-tag="'div'"></t>`)).toBe("<div></div>");
|
||||||
|
expect(render(`<t t-tag="tag">text</t>`, { tag: "span" })).toBe("<span>text</span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with multiple child nodes", () => {
|
||||||
|
const template = `
|
||||||
|
<t t-tag="tag">
|
||||||
|
pear
|
||||||
|
<span>apple</span>
|
||||||
|
strawberry
|
||||||
|
</t>`;
|
||||||
|
expect(render(template, { tag: "div" })).toBe(
|
||||||
|
"<div> pear <span>apple</span> strawberry </div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with multiple attributes", () => {
|
||||||
|
const template = `
|
||||||
|
<t t-tag="tag" class="blueberry" taste="raspberry">gooseberry</t>`;
|
||||||
|
const expected = `<div taste=\"raspberry\" class=\"blueberry\">gooseberry</div>`;
|
||||||
|
expect(render(template, { tag: "div" })).toBe(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,16 +7,16 @@ exports[`Link component can render simple cases 1`] = `
|
|||||||
let utils = this.constructor.utils;
|
let utils = this.constructor.utils;
|
||||||
let scope = Object.create(context);
|
let scope = Object.create(context);
|
||||||
let h = this.h;
|
let h = this.h;
|
||||||
let _4 = utils.toObj({'router-link-active':scope['isActive']});
|
let _5 = utils.toClassObj({'router-link-active':scope['isActive']});
|
||||||
let _5 = scope['href'];
|
let _6 = scope['href'];
|
||||||
let c6 = [], p6 = {key:6,attrs:{href: _5},class:_4,on:{}};
|
let c7 = [], p7 = {key:7,attrs:{href: _6},class:_5,on:{}};
|
||||||
let vn6 = h('a', p6, c6);
|
let vn7 = h('a', p7, c7);
|
||||||
extra.handlers['click__7__'] = extra.handlers['click__7__'] || function (e) {if (!context.__owl__.isMounted){return}utils.getComponent(context)['navigate'](e);};
|
extra.handlers['click__8__'] = extra.handlers['click__8__'] || function (e) {if (context.__owl__.status === 5){return}utils.getComponent(context)['navigate'](e);};
|
||||||
p6.on['click'] = extra.handlers['click__7__'];
|
p7.on['click'] = extra.handlers['click__8__'];
|
||||||
const slot8 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
const slot9 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||||
if (slot8) {
|
if (slot9) {
|
||||||
slot8.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c6, parent: extra.parent || context}));
|
slot9.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: c7, parent: extra.parent || context}));
|
||||||
}
|
}
|
||||||
return vn6;
|
return vn7;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ exports[`RouteComponent can render simple cases 1`] = `
|
|||||||
let w4 = k5 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k5]] : false;
|
let w4 = k5 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k5]] : false;
|
||||||
let vn6 = {};
|
let vn6 = {};
|
||||||
result = vn6;
|
result = vn6;
|
||||||
let props4 = Object.assign({}, scope['env'].router.currentParams);
|
let props4 = Object.assign({}, scope['env'].router.currentParams, {});
|
||||||
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
||||||
w4.destroy();
|
w4.destroy();
|
||||||
w4 = false;
|
w4 = false;
|
||||||
@@ -29,7 +29,7 @@ exports[`RouteComponent can render simple cases 1`] = `
|
|||||||
utils.defineProxy(vn6, pvnode);
|
utils.defineProxy(vn6, pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey4 = \`routeComponent\`;
|
let componentKey4 = \`routeComponent\`;
|
||||||
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| scope['routeComponent'];
|
let W4 = scope['routeComponent'] || context.constructor.components[componentKey4] || QWeb.components[componentKey4];
|
||||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||||
w4 = new W4(parent, props4);
|
w4 = new W4(parent, props4);
|
||||||
parent.__owl__.cmap[k5] = w4.__owl__.id;
|
parent.__owl__.cmap[k5] = w4.__owl__.id;
|
||||||
|
|||||||
@@ -31,13 +31,13 @@ describe("Link component", () => {
|
|||||||
</div>
|
</div>
|
||||||
</templates>
|
</templates>
|
||||||
`);
|
`);
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { Link: Link };
|
static components = { Link: Link };
|
||||||
}
|
}
|
||||||
|
|
||||||
const routes = [
|
const routes = [
|
||||||
{ name: "about", path: "/about" },
|
{ name: "about", path: "/about" },
|
||||||
{ name: "users", path: "/users" }
|
{ name: "users", path: "/users" },
|
||||||
];
|
];
|
||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
@@ -65,13 +65,13 @@ describe("Link component", () => {
|
|||||||
</div>
|
</div>
|
||||||
</templates>
|
</templates>
|
||||||
`);
|
`);
|
||||||
class App extends Component<any, any> {
|
class App extends Component {
|
||||||
static components = { Link: Link };
|
static components = { Link: Link };
|
||||||
}
|
}
|
||||||
|
|
||||||
const routes = [
|
const routes = [
|
||||||
{ name: "about", path: "/about" },
|
{ name: "about", path: "/about" },
|
||||||
{ name: "users", path: "/users" }
|
{ name: "users", path: "/users" },
|
||||||
];
|
];
|
||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
@@ -80,8 +80,8 @@ describe("Link component", () => {
|
|||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
|
|
||||||
expect(window.location.pathname).toBe("/users");
|
expect(window.location.pathname).toBe("/users");
|
||||||
var evt = new MouseEvent("click", {
|
var evt = new MouseEvent("contextmenu", {
|
||||||
button: 1
|
button: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
fixture.querySelector("a")!.dispatchEvent(evt);
|
fixture.querySelector("a")!.dispatchEvent(evt);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user