mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
108 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f0b5a55ad1 | |||
| 690d8edf67 | |||
| 3c38bbc076 | |||
| 9c5cad15c1 | |||
| 2bed1cfbd1 | |||
| caa9ac5cb2 | |||
| 67349eb0f0 | |||
| 1ca401811f | |||
| 2beb12678e | |||
| 0ea1091692 | |||
| 71827c3ba8 | |||
| c2f42d3b82 | |||
| a3317ab997 | |||
| 403935a41e | |||
| 39af9ec938 | |||
| 13128ed425 | |||
| be556a970e | |||
| da6c24bbca | |||
| f6d6da8393 | |||
| 918945c11e | |||
| 29c2c5b9c9 | |||
| 1bb4577ec1 | |||
| 0aeebd7b6e | |||
| 4bc49e7241 | |||
| 2b5783d9bd | |||
| 1f40f113aa | |||
| 9e65b0686f | |||
| 1d72164015 | |||
| 2825a5a55d | |||
| d40ff53f5a | |||
| 23246c42aa | |||
| 895fe7c60f | |||
| 19b10f7c1d | |||
| 0788d9fe75 | |||
| 4a346d0615 | |||
| 1337aa0107 | |||
| 3e8f60cefa | |||
| 41b0618c93 | |||
| 0928c189f4 | |||
| 2f27768be2 | |||
| aa1b0f502d | |||
| da1824f4dd | |||
| 07dac970f7 | |||
| 5f6f081ae2 | |||
| 1c3c2e5c51 | |||
| 17ce73e6a9 | |||
| cedb1f411f | |||
| e7516be95c | |||
| 683993dbc4 | |||
| 50d569411c | |||
| c3453d35b9 | |||
| b0dd0252a4 | |||
| e2b2e54e29 | |||
| 766c378ac9 | |||
| 022b29b6a0 | |||
| 367725d194 | |||
| e82ed7dc8c | |||
| 63c3d4f6b0 | |||
| b859fcb8f0 | |||
| 3005756d89 | |||
| f6820bb8ac | |||
| 090880f478 | |||
| 5cdaa7b473 | |||
| 91b9e78182 | |||
| 5335fb8fba | |||
| 4513e3f31c | |||
| ecf12f6eee | |||
| 82a6961b3a | |||
| 78a4550ebb | |||
| cc82b3ffcd | |||
| bbbaf95c8e | |||
| caa63628dc | |||
| 7a49b9d94e | |||
| 01eb338e69 | |||
| 3048c6f961 | |||
| 8edc637033 | |||
| c9910077a4 | |||
| 6bf70f016c | |||
| 905619f80f | |||
| 14ceb382ef | |||
| 9846b2e997 | |||
| cfc2fb2ba2 | |||
| d57017b6ed | |||
| 5bf7a5c671 | |||
| 9b589af75a | |||
| 471fd49063 | |||
| 4fc3423682 | |||
| ffb3263c79 | |||
| e1acf66143 | |||
| 2a40907e35 | |||
| 1c0dd79955 | |||
| 9fad164c79 | |||
| 53a8841914 | |||
| 19f0863aa3 | |||
| 28f7b44f9e | |||
| fe46a6ccee | |||
| 3c23a7b246 | |||
| c52799de2c | |||
| 4edb90f44b | |||
| 0c1a7aabae | |||
| cfdce29ce7 | |||
| b344d73e07 | |||
| 4cd08d25c8 | |||
| f9861040c8 | |||
| 40d8090232 | |||
| 55be6437f1 | |||
| 6ff4dd74bf | |||
| 3628b49c37 |
@@ -0,0 +1,14 @@
|
||||
|
||||
Most of the files are
|
||||
|
||||
Copyright (c) 2004-2015 Odoo S.A.
|
||||
|
||||
Many files also contain contributions from third
|
||||
parties. In this case the original copyright of
|
||||
the contributions can be traced through the
|
||||
history of the source version control system.
|
||||
|
||||
When that is not the case, the files contain a prominent
|
||||
notice stating the original copyright and applicable
|
||||
license, or come with their own dedicated COPYRIGHT
|
||||
and/or LICENSE file.
|
||||
@@ -1,20 +1,71 @@
|
||||
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">Odoo Web Library</a> 🦉</h1>
|
||||
|
||||
_A web framework for structured, dynamic and maintainable applications_
|
||||
_A no nonsense web framework for structured, dynamic and maintainable applications_
|
||||
|
||||
## Project Overview
|
||||
|
||||
The Odoo Web Library (OWL) is a small (~16kb gzipped) UI framework intended to be the basis for
|
||||
the [Odoo](https://www.odoo.com/) Web Client, and hopefully many other Odoo
|
||||
related projects. OWL's main features are:
|
||||
The Odoo Web Library (OWL) is a smallish (~18kb gzipped) UI framework intended to
|
||||
be the basis for the [Odoo](https://www.odoo.com/) Web Client. Owl is a modern
|
||||
framework, written in Typescript, taking the best ideas from React and Vue in a
|
||||
simple and consistent way. Owl's main features are:
|
||||
|
||||
- a _declarative component system_, (template based, with asynchronous rendering and a virtual dom)
|
||||
- a store implementation (for state management)
|
||||
- a declarative component system,
|
||||
- a reactivity system based on hooks,
|
||||
- a store implementation (for state management),
|
||||
- a small frontend router
|
||||
|
||||
**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.
|
||||
Owl components are defined with ES6 classes, they use QWeb templates, an underlying
|
||||
virtual dom, integrates beautifully with hooks, and the rendering is asynchronous.
|
||||
|
||||
## OWL's Design Principles
|
||||
**Try it online!** An online playground is available at [https://odoo.github.io/owl/playground](https://odoo.github.io/owl/playground) to let you experiment with the Owl framework. There
|
||||
are some code examples to showcase some interesting features.
|
||||
|
||||
Owl is currently mostly stable. Possible future changes are explained in the
|
||||
[roadmap](roadmap.md).
|
||||
|
||||
## Example
|
||||
|
||||
Here is a short example to illustrate interactive components:
|
||||
|
||||
```javascript
|
||||
import { Component, QWeb, useState } from "owl";
|
||||
import { xml } from "owl/tags";
|
||||
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
class App extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span>Hello Owl</span>
|
||||
<Counter />
|
||||
</div>`;
|
||||
|
||||
static components = { Counter };
|
||||
}
|
||||
|
||||
const app = new App({ qweb: new QWeb() });
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
Note that the counter component is made reactive with the [`useState`](doc/hooks.md#usestate)
|
||||
hook. Also, all examples here uses the `xml` helper to define inline templates.
|
||||
But this is not mandatory, many applications will load templates separately.
|
||||
|
||||
More interesting examples can be found on the
|
||||
[playground](https://odoo.github.io/owl/playground) application.
|
||||
|
||||
## Design Principles
|
||||
|
||||
OWL is designed to be used in highly dynamic applications where changing
|
||||
requirements are common and code needs to be maintained by large teams.
|
||||
@@ -31,72 +82,191 @@ requirements are common and code needs to be maintained by large teams.
|
||||
it is not ok to use standard web tools based on `npm`.
|
||||
|
||||
Owl is not designed to be fast nor small (even though it is quite good on those
|
||||
two topics). It is a no nonsense framework to build applications. There is only
|
||||
two topics). It is a no nonsense framework to build applications. There is only
|
||||
one way to define components (with classes).
|
||||
|
||||
If you are interested in a comparison with React or Vue, you will
|
||||
find some more information [here](doc/comparison.md).
|
||||
|
||||
## Example
|
||||
## Documentation
|
||||
|
||||
Here is a short example to illustrate interactive components:
|
||||
A complete documentation for Owl can be found here:
|
||||
|
||||
```xml
|
||||
<templates>
|
||||
<button t-name="Counter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>
|
||||
</templates>
|
||||
```
|
||||
- [Main documentation page](doc/readme.md).
|
||||
|
||||
```javascript
|
||||
class Counter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
The most important sections are:
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
- [Quick Start](doc/quick_start.md)
|
||||
- [Component](doc/component.md)
|
||||
- [Hooks](doc/hooks.md)
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const counter = new Counter({ qweb });
|
||||
counter.mount(document.body);
|
||||
```
|
||||
|
||||
Note that we assume here that the xml templates are available in the `TEMPLATES`
|
||||
string. More interesting examples can be found on the
|
||||
[playground](https://odoo.github.io/owl/playground) application.
|
||||
Found an issue in the documentation? A broken link? Some outdated information?
|
||||
Submit a PR!
|
||||
|
||||
## Installing/Building
|
||||
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
- [owl-0.19.0.js](https://github.com/odoo/owl/releases/download/v0.19.0/owl.js)
|
||||
- [owl-0.19.0.min.js](https://github.com/odoo/owl/releases/download/v0.19.0/owl.min.js)
|
||||
- [owl-0.24.0.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.js)
|
||||
- [owl-0.24.0.min.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.min.js)
|
||||
|
||||
Some npm scripts are available:
|
||||
|
||||
| Command | Description |
|
||||
| --------------------- | ---------------------------------------------------------------------------- |
|
||||
| `npm install` | install every dependency required for this project |
|
||||
| `npm run build` | build a bundle of _owl_ in the _/dist/_ folder |
|
||||
| `npm run minify` | minify the prebuilt owl.js file |
|
||||
| `npm run test` | run all tests |
|
||||
| `npm run test:watch` | run all tests, and keep a watcher |
|
||||
| `npm run tools` | build tools applications, start a static server (see [here](doc/tooling.md)) |
|
||||
| `npm run tools:watch` | same as `tools`, but with a watcher to rebuild owl |
|
||||
| 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 |
|
||||
|
||||
## Documentation
|
||||
## Quick Overview
|
||||
|
||||
The complete documentation can be found [here](doc/readme.md). The most important sections are:
|
||||
Owl components in an application are used to define a (dynamic) tree of components.
|
||||
|
||||
- [Quick Start](doc/quick_start.md)
|
||||
- [Component](doc/component.md)
|
||||
- [QWeb](doc/qweb.md)
|
||||
```
|
||||
Root
|
||||
/ \
|
||||
A B
|
||||
/ \
|
||||
C D
|
||||
```
|
||||
|
||||
Found an issue in the documentation? A broken link? Some outdated information?
|
||||
Submit a PR!
|
||||
**Environment:** the root component is special: it is created with an environment,
|
||||
which should contain a `QWeb` instance. The environment is then automatically
|
||||
propagated to each sub components (and accessible in the `this.env` property).
|
||||
|
||||
```js
|
||||
const env = { qweb: new QWeb() };
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
The environment is mostly static. Each application is free to add anything to
|
||||
the environment, which is very useful, since this can be accessed by each sub
|
||||
component. Some good use case for that is some configuration keys, session
|
||||
information or generic services (such as doing rpcs, or accessing local storage).
|
||||
Doing it this way means that components are easily testable: we can simply
|
||||
create a test environment with mock services.
|
||||
|
||||
**State:** each component can manage its own local state. It is a simple ES6
|
||||
class, there are no special rules:
|
||||
|
||||
```js
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
state = { value: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The example above shows a component with a local state. Note that since there
|
||||
is nothing magical to the `state` object, we need to manually call the `render`
|
||||
function whenever we update it. This can quickly become annoying (and not
|
||||
efficient if we do it too much). There is a better way: using the `useState`
|
||||
hook, which transforms an object into a reactive version of itself:
|
||||
|
||||
```js
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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/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
|
||||
|
||||
OWL is [GPL licensed](./LICENSE).
|
||||
OWL is [LGPL licensed](./LICENSE).
|
||||
|
||||
+4
-5
@@ -30,7 +30,7 @@ btn {
|
||||
}
|
||||
```
|
||||
|
||||
will produce a nice flash effect whenever the user click (or activate with the
|
||||
will produce a nice flash effect whenever the user clicks (or activates with the
|
||||
keyboard) the button.
|
||||
|
||||
## CSS Transitions
|
||||
@@ -47,7 +47,7 @@ the lifetime of a node. Since this is not easy to do by hand, Owl `t-transition`
|
||||
directive is there to help.
|
||||
|
||||
Whenever a node has a `t-transition` directive, with a `name` value, the following
|
||||
will happen:
|
||||
sequence of events will happen:
|
||||
|
||||
At node insertion:
|
||||
|
||||
@@ -91,6 +91,5 @@ The `t-transition` directive can be applied on a node element or on a component.
|
||||
|
||||
Notes:
|
||||
|
||||
- more information on animations are available [here](animations.md).
|
||||
- Owl does not support more than one transition on a single node, so the
|
||||
`t-transition` expression must be a single value (i.e. no space allowed)
|
||||
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).
|
||||
|
||||
+132
-24
@@ -3,7 +3,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.
|
||||
|
||||
In this page, we try to highlight some of these differences. Obviously, some
|
||||
In this page, we try to highlight some of these differences. Obviously, a lot of
|
||||
effort was done to be fair. However, if you disagree with some of the points
|
||||
discussed, feel free to open an issue/submit a PR to correct this text.
|
||||
|
||||
@@ -16,6 +16,7 @@ discussed, feel free to open an issue/submit a PR to correct this text.
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
- [Reactiveness](#reactiveness)
|
||||
- [State Management](#state-management)
|
||||
- [Hooks](#hooks)
|
||||
|
||||
## Size
|
||||
|
||||
@@ -24,22 +25,38 @@ than React and Vue. Also, jQuery is not the same kind of framework, but it is in
|
||||
|
||||
| Framework | Size (minified, gzipped) |
|
||||
| ------------------------ | ------------------------ |
|
||||
| OWL | 16kb |
|
||||
| OWL | 18kb |
|
||||
| Vue + VueX | 30kb |
|
||||
| Vue + VueX + Vue Router | 39kb |
|
||||
| React + ReactDOM + Redux | 40kb |
|
||||
| jQuery | 30kb |
|
||||
|
||||
Note that those comparisons are not entirely fair, because we do not compare
|
||||
the same exact set of features. For example, VueX and Vue Router support more
|
||||
advanced use cases.
|
||||
|
||||
## Class Based
|
||||
|
||||
Both React and Vue moved away from defining components with classes. They prefer
|
||||
Both React and Vue moved away from defining components with classes. They prefer
|
||||
a more functional approach, in particular, with the new `hooks` mechanisms.
|
||||
|
||||
This has some advantages and disadvantages. But the end result is that React
|
||||
and Vue both offers multiple different ways of defining new components. In
|
||||
This has some advantages and disadvantages. But the end result is that React
|
||||
and Vue both offers multiple different ways of defining new components. In
|
||||
contrast, Owl has only one mechanism: class-based components. We believe that Owl
|
||||
components are fast enough for all our usecases, and making it as simple as
|
||||
possible for developers is more valuable (for us).
|
||||
|
||||
Also, functions or class based components are more than just syntax. Functions
|
||||
comes with a mindset of composition and class are about inheritance. Clearly,
|
||||
both of these are important mechanisms for reusing code. Also, one does not
|
||||
exclude the other.
|
||||
|
||||
It certainly looks like the world of UI frameworks is moving toward composition,
|
||||
for many very good reasons. Owl is still good at composition (for example,
|
||||
Owl supports slots, which is the primary mechanism to make generic reusable
|
||||
components). But it can also use inheritance (and this is very important since
|
||||
templates can also be inherited with `xpaths` transformations).
|
||||
|
||||
## Tooling/Build step
|
||||
|
||||
OWL is designed to be easy to use in a standalone way. For various reasons,
|
||||
@@ -50,13 +67,23 @@ be used by simply adding a script tag to a page.
|
||||
<script src="owl.min.js" />
|
||||
```
|
||||
|
||||
In comparison, React encourages using JSX,
|
||||
which necessitate a build step, and most Vue applications uses single file
|
||||
components, which also necessitate a build step.
|
||||
In comparison, React encourages using JSX, which necessitate a build step, and
|
||||
most Vue applications uses single file components, which also necessitate a build step.
|
||||
|
||||
On the flipside, external tooling may make it harder to use in some case, but it
|
||||
also brings a lot of benefits. And React/Vue have both a large ecosystem.
|
||||
|
||||
Note that since Owl is not dependant on any external tool nor libraries, it is
|
||||
very easy to integrate into any build toolchain. Also, since we cannot rely on
|
||||
additional tools, we made a lot of effort to make the most of the web platform.
|
||||
|
||||
For example, Owl uses the standard `xml` parser that comes with every browser.
|
||||
Because of that, Owl did not have to write its own template parser. Another
|
||||
example is the [`xml`](tags.md#xml-tag) tag helper function, which makes use of
|
||||
native template literals to allow in a natural way to write `xml` templates
|
||||
directly in the javascript code. This can be easily integrated with editor
|
||||
plugins to have autocompletion inside the template.
|
||||
|
||||
## Templating
|
||||
|
||||
OWL uses its own QWeb engine, which compiles templates on the
|
||||
@@ -79,7 +106,8 @@ into javascript functions. Note that Vue has a separate build which includes the
|
||||
template compiler.
|
||||
|
||||
In contrast, most React applications do not use a templating language, but write
|
||||
some JSX code, which is precompiled into plain JavaScript by a build step.
|
||||
some JSX code, which is precompiled into plain JavaScript by a build step. This
|
||||
example is done with the (kind of outdated) React class system:
|
||||
|
||||
```jsx
|
||||
class Clock extends React.Component {
|
||||
@@ -98,6 +126,20 @@ This has the advantage of having the full power of Javascript, but is less
|
||||
structured than a template language. Note that the tooling is quite impressive:
|
||||
there is a syntax highlighter for jsx here on github!
|
||||
|
||||
By comparison, here is the equivalent Owl component, written with the
|
||||
[`xml`](tags.md#xml-tag) tag helper:
|
||||
|
||||
```js
|
||||
class Clock extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<h1>Hello, world!</h1>
|
||||
<h2>It is {props.date.toLocaleTimeString()}.</h2>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
```
|
||||
|
||||
## Asynchronous Rendering
|
||||
|
||||
This is actually a big difference between OWL and React/Vue: components in OWL
|
||||
@@ -127,12 +169,14 @@ This may be dangerous (to stop the rendering waiting for the network), but it is
|
||||
extremely powerful as well, as demonstrated by the Odoo Web Client.
|
||||
|
||||
Lazy loading static libraries can obviously be done with React/Vue, but it is
|
||||
more convoluted.
|
||||
more convoluted. For example, in Vue, you need to use a dynamic import keyword
|
||||
that needs to be transpiled at build time in order for the component to be loaded
|
||||
asynchronously (see [the documentation](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components)).
|
||||
|
||||
## Reactiveness
|
||||
|
||||
React has a simple model: whenever the state changes, it is
|
||||
replaced with a new state (via the setState method). Then, the DOM is patched.
|
||||
replaced with a new state (via the `setState` method). Then, the DOM is patched.
|
||||
This is simple, efficient, and a little bit awkward to write.
|
||||
|
||||
Vue is a little bit different: it replace magically the properties in the state
|
||||
@@ -207,30 +251,94 @@ 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
|
||||
mutations), and like VueX, it keeps track of the state changes. However, it does
|
||||
not notify a component when the state changes. Instead, components need to connect
|
||||
to the store like in redux, by inheriting the `ConnectedComponent` class.
|
||||
to the store like in redux, with the `useStore` hook (see the [store documentation](store.md#connecting-a-component)).
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter += val;
|
||||
state.counter.value += val;
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: 0
|
||||
counter: { value: 0 }
|
||||
};
|
||||
const store = new owl.Store({ state, actions });
|
||||
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
increment() {
|
||||
this.env.store.dispatch("increment");
|
||||
}
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="counter.value"/>]
|
||||
</button>`;
|
||||
counter = useStore(state => state.counter);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
```
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
[Hooks](https://reactjs.org/docs/hooks-intro.html#motivation) recently took over
|
||||
the React world. They solve a lot of seemingly unconnected problems: attach
|
||||
reusable behavior to a component, in a composable way, extract stateful logic
|
||||
from a component or reuse stateful logic between component, without changing your
|
||||
component hierarchy.
|
||||
|
||||
Here is an example of the React `useState` hook:
|
||||
|
||||
```js
|
||||
import React, { useState } from "react";
|
||||
|
||||
function Example() {
|
||||
// Declare a new state variable, which we'll call "count"
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>You clicked {count} times</p>
|
||||
<button onClick={() => setCount(count + 1)}>Click me</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Because of the way React designed the hooks API, they only work for functional
|
||||
components. But in that case, they really are powerful. Every major React library
|
||||
is in the process of redesigning their API with hooks (for example,
|
||||
[Redux](https://react-redux.js.org/next/api/hooks)).
|
||||
|
||||
Vue 2 does not have hooks, but the Vue project is working on its next version,
|
||||
which will feature its new [composition API](https://vue-composition-api-rfc.netlify.com/).
|
||||
This work is based on the new ideas introduced by React hooks.
|
||||
|
||||
From the way React and Vue introduce their hooks, it may look like hooks are not
|
||||
compatible with class components. However, this is not the case, as shown by
|
||||
Owl [hooks](hooks.md). They are inspired by both React and Vue. For example,
|
||||
the `useState` hook is named after React, but its API is closer to the `reactive`
|
||||
Vue hook.
|
||||
|
||||
Here is what the `Counter` example above look like in Owl:
|
||||
|
||||
```js
|
||||
import { Component, Owl } from "owl";
|
||||
import { xml } from "owl/tags";
|
||||
|
||||
class Example extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<p>You clicked {count.value} times</p>
|
||||
<button t-on-click="increment">Click me</button>
|
||||
</div>`;
|
||||
|
||||
count = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Since the Owl framework had hooks from early in its life, its main APIs
|
||||
are designed to be interacted with hooks from the start. For example, the
|
||||
`Context` and `Store` abstractions.
|
||||
|
||||
+353
-130
@@ -5,6 +5,7 @@
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [Reactive System](#reactive-system)
|
||||
- [Properties](#properties)
|
||||
- [Static Properties](#static-properties)
|
||||
- [Methods](#methods)
|
||||
@@ -15,19 +16,20 @@
|
||||
- [Event Handling](#event-handling)
|
||||
- [Form Input Bindings](#form-input-bindings)
|
||||
- [`t-key` Directive](#t-key-directive)
|
||||
- [`t-mounted` Directive](#t-mounted-directive)
|
||||
- [Semantics](#semantics)
|
||||
- [Props Validation](#props-validation)
|
||||
- [References](#references)
|
||||
- [Slots](#slots)
|
||||
- [Asynchronous Rendering](#asynchronous-rendering)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Functional Components](#functional-components)
|
||||
- [SVG components](#svg-components)
|
||||
|
||||
## Overview
|
||||
|
||||
OWL components are the building blocks for user interface. They are designed to be:
|
||||
|
||||
1. **declarative:** the user interface should be described in term of the state
|
||||
1. **declarative:** the user interface should be described in terms of the state
|
||||
of the application, not as a sequence of imperative steps.
|
||||
|
||||
2. **composable:** each component can seamlessly be created in a parent component by
|
||||
@@ -45,16 +47,15 @@ exclusively done by a [QWeb](qweb.md) template (which needs to be preloaded in Q
|
||||
Rendering a component generates a virtual dom representation
|
||||
of the component, which is then patched to the DOM, in order to apply the changes in an efficient way.
|
||||
|
||||
OWL components observe their states, and rerender themselves whenever it is
|
||||
changed. This is done by an [observer](observer.md).
|
||||
|
||||
## Example
|
||||
|
||||
Let us have a look at a simple component:
|
||||
|
||||
```javascript
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class ClickCounter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
@@ -71,23 +72,95 @@ class ClickCounter extends owl.Component {
|
||||
Note that this code is written in ESNext style, so it will only run on the
|
||||
latest browsers without a transpilation step.
|
||||
|
||||
This example show how a component should be defined: it simply subclasses the
|
||||
Component class. If no `template` key is defined, then
|
||||
This example shows how a component should be defined: it simply subclasses the
|
||||
Component class. If no static `template` key is defined, then
|
||||
Owl will use the component's name as template name. Here,
|
||||
a state object is defined. It is not mandatory to use the state object, but it
|
||||
is certainly encouraged. The state object is [observed](observer.md), and any
|
||||
change to it will cause a rerendering.
|
||||
a state object is defined, by using the `useState` hook. It is not mandatory to use the state object, but it is certainly encouraged. The result of the `useState` call is
|
||||
[observed](observer.md), and any change to it will cause a rerendering.
|
||||
|
||||
## Reference
|
||||
|
||||
An Owl component is a small class which represent a component or some UI element.
|
||||
An Owl component is a small class which represents a component or some UI element.
|
||||
It exists in the context of an environment (`env`), which is propagated from a
|
||||
parent to its children. The environment needs to have a QWeb instance, which
|
||||
will be used to render the component template.
|
||||
|
||||
Be aware that the name of the component may be significant: if a component does
|
||||
not define a `template` key, then Owl will lookup in QWeb to
|
||||
find a template with the component name (or one of its ancestor).
|
||||
find a template with the component name (or one of its ancestors).
|
||||
|
||||
### Reactive system
|
||||
|
||||
OWL components are normal javascript classes. So, changing a component internal
|
||||
state does nothing more:
|
||||
|
||||
```js
|
||||
class Counter extends Component {
|
||||
static template = xml`<div t-on-click="increment"><t t-esc="state.value"/></div>`;
|
||||
state = { value: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Clicking on the `Counter` component defined above will call the `increment`
|
||||
method, but it will not rerender the component. To fix that, one could add an
|
||||
explicit call to `render` in `increment`:
|
||||
|
||||
```js
|
||||
increment() {
|
||||
this.state.value++;
|
||||
this.render();
|
||||
}
|
||||
```
|
||||
|
||||
However, it may be simple in this case, but it quickly become cumbersome, as a
|
||||
component get more complex, and its internal state is modified by more than one
|
||||
method.
|
||||
|
||||
A better way is to use the reactive system: by using the `useState` hook (see the
|
||||
[hooks](hooks.md) section for more details), one can make Owl react to state
|
||||
changes. The `useState` hook generates a proxy version of an object
|
||||
(this is done by an [observer](observer.md)), which allows the component to
|
||||
react to any change. So, the `Counter` example above can be improved like this:
|
||||
|
||||
```js
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`<div t-on-click="increment"><t t-esc="state.value"/></div>`;
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Obviously, we can call the `useState` hook more than once:
|
||||
|
||||
```js
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-on-click="increment(counter1)"><t t-esc="counter1.value"/></span>
|
||||
<span t-on-click="increment(counter2)"><t t-esc="counter2.value"/></span>
|
||||
</div>`;
|
||||
counter1 = useState({ value: 0 });
|
||||
counter2 = useState({ value: 0 });
|
||||
|
||||
increment(counter) {
|
||||
counter.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that hooks are subject to one important [rule](hooks.md#one-rule): they need
|
||||
to be called in the constructor.
|
||||
|
||||
### Properties
|
||||
|
||||
@@ -96,24 +169,40 @@ find a template with the component name (or one of its ancestor).
|
||||
|
||||
- **`env`** (Object): the component environment, which contains a QWeb instance.
|
||||
|
||||
- **`template`** (string, optional): if given, this is the name of the QWeb template that will render
|
||||
the component.
|
||||
- **`props`** (Object): this is an object containing all the properties given by
|
||||
the parent to a child component. For example, in the following situation,
|
||||
the parent component gives a `user` and a `color` value to the `ChildComponent`.
|
||||
|
||||
- **`state`** (Object): this is the location of the component's state, if there is
|
||||
any. After the willStart method, the `state` property is observed, and each
|
||||
change will cause the component to rerender itself.
|
||||
```xml
|
||||
<div>
|
||||
<ChildComponent user="state.user" color="color">
|
||||
</div>
|
||||
```
|
||||
|
||||
- **`props`** (Object): this is an object given (in the constructor) by the parent
|
||||
to configure the component. It can be dynamically changed later by the parent,
|
||||
in some case. Note that `props` are owned by the parent, not by the component.
|
||||
As such, it should not ever be modified by the component!!
|
||||
Note that `props` are owned by the parent, not by the component.
|
||||
As such, it should not ever be modified by the component (otherwise you risk
|
||||
unintended effects, since the parent may not be aware of the change)!!
|
||||
|
||||
- **`refs`** (Object): the `refs` object contains all references to sub DOM nodes
|
||||
or sub components defined by a `t-ref` directive in the component's template.
|
||||
The `props` can be modified dynamically by the parent. In that case, the
|
||||
component will go through the following lifecycle methods: `willUpdateProps`,
|
||||
`willPatch` and `patched`.
|
||||
|
||||
### Static Properties
|
||||
|
||||
- **`props`** (Object, optional): if given, this is an object that describes the
|
||||
- **`template`** (string, optional): if given, this is the name of the QWeb template that will render the component. Note that there is a helper `xml` to
|
||||
make it easy to define an inline template.
|
||||
|
||||
* **`components`** (Object, optional): if given, this is an object that contains
|
||||
the classes of any sub components needed by the template. This is the main way
|
||||
used by Owl to be able to create sub components.
|
||||
|
||||
```js
|
||||
class ParentComponent extends owl.Component {
|
||||
static components = { SubComponent };
|
||||
}
|
||||
```
|
||||
|
||||
* **`props`** (Object, optional): if given, this is an object that describes the
|
||||
type and shape of the (actual) props given to the component. If Owl mode is
|
||||
`dev`, this will be used to validate the props each time the component is
|
||||
created/updated. See [Props Validation](#props-validation) for more information.
|
||||
@@ -127,7 +216,7 @@ find a template with the component name (or one of its ancestor).
|
||||
}
|
||||
```
|
||||
|
||||
* **`defaultProps`** (Object, optional): if given, this object define default
|
||||
- **`defaultProps`** (Object, optional): if given, this object define default
|
||||
values for (top-level) props. Whenever `props` are given to the object, they
|
||||
will be altered to add default value (if missing). Note that it does not
|
||||
change the initial object, a new object will be created instead.
|
||||
@@ -140,6 +229,11 @@ find a template with the component name (or one of its ancestor).
|
||||
}
|
||||
```
|
||||
|
||||
There is another static property defined on the `Component` class: `current`.
|
||||
This property is set to the currently being defined component (in the constructor).
|
||||
This is the way [hooks](hooks.md) are able to get a reference to the target
|
||||
component.
|
||||
|
||||
### Methods
|
||||
|
||||
We explain here all the public methods of the `Component` class.
|
||||
@@ -155,7 +249,7 @@ We explain here all the public methods of the `Component` class.
|
||||
we know that its state (or something in the environment, or ...) has changed.
|
||||
In that case, it should simply set to `true`.
|
||||
|
||||
- **`unmount()`**: in case a component need 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
|
||||
useful to the underlying component system.
|
||||
|
||||
@@ -173,11 +267,6 @@ We explain here all the public methods of the `Component` class.
|
||||
always return true. This is an optimization, similar to React's `shouldComponentUpdate`. Most of the time, this should not be used, but it
|
||||
can be useful if we are handling large number of components.
|
||||
|
||||
- **`updateEnv(nextEnv)`**: update the environment of a component and all its
|
||||
children. This forces a complete rerender. For example, this could be useful
|
||||
if we have a `isMobile` key in the environment, to decide if we want a mobile
|
||||
interface or a destkop one.
|
||||
|
||||
- **`destroy()`**. As its name suggests, this method will remove the component,
|
||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||
removing the parent/children relationship. This method should almost never be
|
||||
@@ -226,7 +315,7 @@ component.
|
||||
```javascript
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = {someValue: true};
|
||||
this.state = useState({someValue: true});
|
||||
this.template = 'mytemplate';
|
||||
}
|
||||
```
|
||||
@@ -236,7 +325,7 @@ implemented in most cases:
|
||||
|
||||
```javascript
|
||||
class ClickCounter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
state = useState({ value: 0 });
|
||||
|
||||
...
|
||||
}
|
||||
@@ -261,9 +350,6 @@ At this point, the component is not yet rendered. Note that a slow `willStart` m
|
||||
interface. Therefore, some care should be made to make this method as
|
||||
fast as possible.
|
||||
|
||||
After the `willStart` method is completed, the state will be observed with a
|
||||
new `Observer`. Then, the component will be rendered by `QWeb`.
|
||||
|
||||
#### `mounted()`
|
||||
|
||||
`mounted` is called each time a component is attached to the
|
||||
@@ -277,10 +363,9 @@ always be unmounted at some point in the future.
|
||||
The mounted method will be called recursively on each of its children. First,
|
||||
the parent, then all its children.
|
||||
|
||||
Note that the state is now observed. It is however allowed (but not encouraged)
|
||||
to modify the state in the `mounted` hook. Doing so will cause a rerender,
|
||||
which will not be perceptible by the user, but will slightly slow down the
|
||||
component.
|
||||
It is allowed (but not encouraged) to modify the state in the `mounted` hook.
|
||||
Doing so will cause a rerender, which will not be perceptible by the user, but
|
||||
will slightly slow down the component.
|
||||
|
||||
#### `willUpdateProps(nextProps)`
|
||||
|
||||
@@ -305,14 +390,11 @@ It is not called on the initial render. This is useful to read some
|
||||
information from the DOM. For example, the current position of the
|
||||
scrollbar.
|
||||
|
||||
Note that modifying the state object is not allowed here. This method is called just
|
||||
Note that modifying the state is not allowed here. This method is called just
|
||||
before an actual DOM patch, and is only intended to be used to save some local
|
||||
DOM state. Also, it will not be called if the component is not in the DOM (this can
|
||||
happen with components with `t-keepalive`).
|
||||
|
||||
The return value of this method will be given as the first argument of the
|
||||
corresponding `patched` call.
|
||||
|
||||
#### `patched(snapshot)`
|
||||
|
||||
This hook is called whenever a component did actually update its DOM (most
|
||||
@@ -323,11 +405,9 @@ with the DOM (for example, through an external library) whenever the
|
||||
component was patched. Note that this hook will not be called if the compoent is
|
||||
not in the DOM (this can happen with components with `t-keepalive`).
|
||||
|
||||
The `snapshot` parameter is the result of the previous `willPatch` call.
|
||||
|
||||
Updating the compoent state in this hook is possible, but not encouraged.
|
||||
One need to be careful, because updates here will cause rerender, which in
|
||||
turn will cause other calls to patched. So, we need to be particularly
|
||||
Updating the component state in this hook is possible, but not encouraged.
|
||||
One needs to be careful, because updates here will create an additional rendering, which in
|
||||
turn will cause other calls to the `patched` method. So, we need to be particularly
|
||||
careful at avoiding endless cycles.
|
||||
|
||||
#### `willUnmount()`
|
||||
@@ -350,7 +430,7 @@ This is the opposite method of `mounted`.
|
||||
|
||||
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
|
||||
[error handling](#error-handling)
|
||||
[error handling](#error-handling).
|
||||
|
||||
### Root Component
|
||||
|
||||
@@ -387,9 +467,9 @@ easy to test a component.
|
||||
Updating the environment is not as simple as changing a component's state: its
|
||||
content is not observed, so updates will not be reflected immediately in the
|
||||
user interface. There is however a mechanism to force root widgets to rerender
|
||||
themselves whenever the environment is modified: one only needs to trigger the
|
||||
`update` event on the QWeb instance. For example, a responsive environment
|
||||
could be programmed like this:
|
||||
themselves whenever the environment is modified: one only needs to call the
|
||||
`forceUpdate` method on the QWeb instance. For example, a responsive environment
|
||||
could be done like this:
|
||||
|
||||
```js
|
||||
function setupResponsivePlugin(env) {
|
||||
@@ -398,7 +478,7 @@ function setupResponsivePlugin(env) {
|
||||
const updateEnv = owl.utils.debounce(() => {
|
||||
if (env.isMobile !== isMobile()) {
|
||||
env.isMobile = !env.isMobile;
|
||||
env.qweb.trigger("update");
|
||||
env.qweb.forceUpdate();
|
||||
}
|
||||
}, 15);
|
||||
window.addEventListener("resize", updateEnv);
|
||||
@@ -420,7 +500,7 @@ to be capitalized.
|
||||
|
||||
```js
|
||||
class ParentComponent extends owl.Component {
|
||||
components = { MyComponent: MyComponent};
|
||||
static components = { MyComponent: MyComponent};
|
||||
...
|
||||
}
|
||||
```
|
||||
@@ -432,7 +512,8 @@ dynamic. If it is necessary to give a string, this can be done by quoting it:
|
||||
`someString="'somevalue'"`.
|
||||
|
||||
Note that the rendering context for the template is the component itself. This means
|
||||
that the template can access `state`, `props`, `env`, or any methods defined in the component.
|
||||
that the template can access `state` (if it exists), `props`, `env`, or any
|
||||
methods defined in the component.
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
@@ -442,16 +523,16 @@ that the template can access `state`, `props`, `env`, or any methods defined in
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
components = { ChildComponent };
|
||||
state = { val: 4 };
|
||||
static components = { ChildComponent };
|
||||
state = useState({ val: 4 });
|
||||
}
|
||||
```
|
||||
|
||||
Whenever the template is rendered, it will automatically create the subcomponent
|
||||
`ChildComponent` at the correct place. It needs to find the reference to the
|
||||
actual component class in the special `components` key, or the class registered in
|
||||
actual component class in the special static `components` key, or the class registered in
|
||||
QWeb's global registry (see `register` function of QWeb). It first looks inside
|
||||
the local `components` key, then fallbacks on the global registry.
|
||||
the static `components` key, then fallbacks on the global registry.
|
||||
|
||||
_Props_: In this example, the child component will receive the object `{count: 4}` in its
|
||||
constructor. This will be assigned to the `props` variable, which can be accessed
|
||||
@@ -461,7 +542,8 @@ the sub component will also be updated automatically.
|
||||
Note that there are some restrictions on prop names: `class`, `style` and any
|
||||
string which starts with `t-` are not allowed.
|
||||
|
||||
The `t-component` directive can also be used to accept dynamic values with string interpolation (like the [`t-attf-`](qweb.md#dynamic-attributes) directive):
|
||||
It is not common, but sometimes we need a dynamic component name and/or dynamic props. In this case,
|
||||
the `t-component` directive can also be used to accept dynamic values with string interpolation (like the [`t-attf-`](qweb.md#dynamic-attributes) directive):
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
@@ -471,11 +553,51 @@ The `t-component` directive can also be used to accept dynamic values with strin
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
components = { ChildComponent1, ChildComponent2 };
|
||||
static components = { ChildComponent1, ChildComponent2 };
|
||||
state = { id: 1 };
|
||||
}
|
||||
```
|
||||
|
||||
And the `t-props` directive can be used to specify totally dynamic props:
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<Child t-props="some.obj"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
static components = { Child };
|
||||
some = { obj: { a: 1, b: 2 } };
|
||||
}
|
||||
```
|
||||
|
||||
There is an even more dynamic way to use `t-component`: its value can be an
|
||||
expression evaluating to an actual component class. In that case, this is the
|
||||
class that will be used to create the component:
|
||||
|
||||
```js
|
||||
class A extends Component<any, any, any> {
|
||||
static template = xml`<span>child a</span>`;
|
||||
}
|
||||
class B extends Component<any, any, any> {
|
||||
static template = xml`<span>child b</span>`;
|
||||
}
|
||||
class App extends Component<any, any, any> {
|
||||
static template = xml`<t t-component="myComponent" t-key="state.child"/>`;
|
||||
|
||||
state = { child: "a" };
|
||||
|
||||
get myComponent() {
|
||||
return this.state.child === "a" ? A : B;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the component `App` selects dynamically the concrete sub
|
||||
component class.
|
||||
|
||||
**CSS and style:** there is some specific support to allow the parent to declare
|
||||
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||
root component element.
|
||||
@@ -555,6 +677,29 @@ to event `menu-loaded` will receive the payload in its `someMethod` handler
|
||||
|
||||
By convention, we use KebabCase for the name of _business_ events.
|
||||
|
||||
|
||||
The `t-on` directive allows to prebind some arguments. For example,
|
||||
|
||||
```xml
|
||||
<button t-on-click="someMethod(expr)">Do something</button>
|
||||
```
|
||||
|
||||
Here, `expr` is a valid Owl expression, so it could be `true` or some variable
|
||||
from the rendering context.
|
||||
|
||||
One can also directly specify inline statements. For example,
|
||||
|
||||
```xml
|
||||
<button t-on-click="state.counter++">Increment counter</button>
|
||||
```
|
||||
|
||||
Here, `state` must be defined in the rendering context (typically the component)
|
||||
as it will be translated to:
|
||||
```js
|
||||
button.addEventListener("click", () => { component.state.counter++; });
|
||||
```
|
||||
|
||||
|
||||
In order to remove the DOM event details from the event handlers (like calls to
|
||||
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
||||
specified as additional suffixes of the `t-on` directive.
|
||||
@@ -574,14 +719,14 @@ 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.
|
||||
|
||||
The `t-on` directive also allows to prebind some arguments. For example,
|
||||
Finally, empty handlers are tolerated as they could be defined only to apply
|
||||
modifiers. For example,
|
||||
|
||||
```xml
|
||||
<button t-on-click="someMethod(expr)">Do something</button>
|
||||
<button t-on-click.stop="">Do something</button>
|
||||
```
|
||||
|
||||
Here, `expr` is a valid Owl expression, so it could be `true` or some variable
|
||||
from the rendering context.
|
||||
This will simply stop the propagation of the event.
|
||||
|
||||
### Form Input Bindings
|
||||
|
||||
@@ -591,7 +736,7 @@ form!). A possible way to do this is to do it by hand:
|
||||
|
||||
```js
|
||||
class Form extends owl.Component {
|
||||
state = { text: "" };
|
||||
state = useState({ text: "" });
|
||||
|
||||
_updateInputValue(event) {
|
||||
this.state.text = event.target.value;
|
||||
@@ -611,8 +756,9 @@ plumbing code is slightly different if you need to interact with a checkbox,
|
||||
or with radio buttons, or with select tags.
|
||||
|
||||
To help with this situation, Owl has a builtin directive `t-model`: its value
|
||||
is the (top-level) name in the state object. With the `t-model` directive, we
|
||||
can write a shorter code, equivalent to the previous example:
|
||||
should be an observed value in the component (usually `state.someValue`). With
|
||||
the `t-model` directive, we can write a shorter code, equivalent to the previous
|
||||
example:
|
||||
|
||||
```js
|
||||
class Form extends owl.Component {
|
||||
@@ -622,7 +768,7 @@ class Form extends owl.Component {
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<input t-model="text" />
|
||||
<input t-model="state.text" />
|
||||
<span t-esc="state.text" />
|
||||
</div>
|
||||
```
|
||||
@@ -632,11 +778,11 @@ The `t-model` directive works with `<input>`, `<input type="checkbox">`,
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div>Text in an input: <input t-model="someVal"/></div>
|
||||
<div>Textarea: <textarea t-model="otherVal"/></div>
|
||||
<div>Boolean value: <input type="checkbox" t-model="someFlag"/></div>
|
||||
<div>Text in an input: <input t-model="state.someVal"/></div>
|
||||
<div>Textarea: <textarea t-model="state.otherVal"/></div>
|
||||
<div>Boolean value: <input type="checkbox" t-model="state.someFlag"/></div>
|
||||
<div>Selection:
|
||||
<select t-model="color">
|
||||
<select t-model="state.color">
|
||||
<option value="">Select a color</option>
|
||||
<option value="red">Red</option>
|
||||
<option value="blue">Blue</option>
|
||||
@@ -645,11 +791,11 @@ The `t-model` directive works with `<input>`, `<input type="checkbox">`,
|
||||
<div>
|
||||
Selection with radio buttons:
|
||||
<span>
|
||||
<input type="radio" name="color" id="red" value="red" t-model="color"/>
|
||||
<input type="radio" name="color" id="red" value="red" t-model="state.color"/>
|
||||
<label for="red">Red</label>
|
||||
</span>
|
||||
<span>
|
||||
<input type="radio" name="color" id="blue" value="blue" t-model="color" />
|
||||
<input type="radio" name="color" id="blue" value="blue" t-model="state.color" />
|
||||
<label for="blue">Blue</label>
|
||||
</span>
|
||||
</div>
|
||||
@@ -661,13 +807,13 @@ Like event handling, the `t-model` directive accepts some modifiers:
|
||||
| Modifier | Description |
|
||||
| --------- | -------------------------------------------------------------------- |
|
||||
| `.lazy` | update the value on the `change` event (default is on `input` event) |
|
||||
| `.number` | tries to parse the value to a number (using `parseFloat`) |
|
||||
| `.number` | try to parse the value to a number (using `parseFloat`) |
|
||||
| `.trim` | trim the resulting value |
|
||||
|
||||
For example:
|
||||
|
||||
```xml
|
||||
<input t-model.lazy="someVal" />
|
||||
<input t-model.lazy="state.someVal" />
|
||||
```
|
||||
|
||||
These modifiers can be combined. For instance, `t-model.lazy.number` will only
|
||||
@@ -677,9 +823,10 @@ Note: the online playground has an example to show how it works.
|
||||
|
||||
### `t-key` Directive
|
||||
|
||||
Even though Owl tries to be as declarative as possible, some DOM state is still
|
||||
locked inside the DOM: for example, the scrolling state, the current user selection,
|
||||
the focused element or the state of an input. This is why we use a virtual dom
|
||||
Even though Owl tries to be as declarative as possible, the DOM does not fully
|
||||
expose its state declaratively in the DOM tree. For example, the scrolling state,
|
||||
the current user selection, the focused element or the state of an input are not
|
||||
set as attribute in the DOM tree. This is why we use a virtual dom
|
||||
algorithm to keep the actual DOM node as much as possible. However, this is
|
||||
sometimes not enough, and we need to help Owl decide if an element is actually
|
||||
the same, or is different. The `t-key` directive is used to give an identity to an element.
|
||||
@@ -699,24 +846,6 @@ There are three main use cases:
|
||||
- _animations_: give a different identity to a component. Ex: thread id with
|
||||
animations on add/remove message.
|
||||
|
||||
### `t-mounted` Directive
|
||||
|
||||
The `t-mounted` directive allows to register a callback to execute whenever the node
|
||||
is inserted into the DOM.
|
||||
|
||||
```xml
|
||||
<div><input t-ref="someInput" t-mounted="focusMe"/></div>
|
||||
```
|
||||
|
||||
```js
|
||||
class MyComponent extends owl.Component {
|
||||
...
|
||||
focusMe() {
|
||||
this.refs.someInput.focus();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Semantics
|
||||
|
||||
We give here an informal description of the way components are created/updated
|
||||
@@ -809,7 +938,7 @@ Here is what Owl will do:
|
||||
As an application becomes complex, it may be quite unsafe to define props in an informal way. This leads to two issues:
|
||||
|
||||
- hard to tell how a component should be used, by looking at its code.
|
||||
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parent.
|
||||
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parents.
|
||||
|
||||
A props type system would solve both issues, by describing the types and shapes
|
||||
of the props. Here is how it works in Owl:
|
||||
@@ -901,44 +1030,60 @@ Examples:
|
||||
|
||||
### References
|
||||
|
||||
The `t-ref` directive helps a component keep reference to some inside part of it.
|
||||
Like the `t-on` directive, it can work either on a DOM node, or on a component:
|
||||
The `useRef` hook is useful when we need a way to interact with some inside part
|
||||
of a component, rendered by Owl. It can work either on a DOM node, or on a component,
|
||||
tagged by the `t-ref` directive. See the [hooks section](hooks.md#useref) for
|
||||
more detail.
|
||||
|
||||
As a short example, here is how we could set the focus on a given input:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-ref="someDiv"/>
|
||||
<SubComponent t-ref="someComponent"/>
|
||||
<input t-ref="input"/>
|
||||
<button t-on-click="focusInput">Click</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
In this example, the component will be able to access the `div` and the component
|
||||
inside the special `refs` variable:
|
||||
|
||||
```js
|
||||
this.refs.someDiv;
|
||||
this.refs.someComponent;
|
||||
import { useRef } from "owl/hooks";
|
||||
|
||||
class SomeComponent extends Component {
|
||||
inputRef = useRef("input");
|
||||
|
||||
focusInput() {
|
||||
this.inputRef.el.focus();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is useful for various usecases: for example, integrating with an external
|
||||
library that needs to render itself inside an actual DOM node. Or for calling
|
||||
some method on a sub component.
|
||||
|
||||
Note: if used on a component, the reference will be set in the `refs`
|
||||
variable between `willPatch` and `patched`.
|
||||
|
||||
The `t-ref` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](qweb.md#dynamic-attributes) and
|
||||
`t-component` directives). For example, if we have
|
||||
`id` set to 44 in the rendering context,
|
||||
The `useRef` hook can also be used to get a reference to an instance of a sub
|
||||
component rendered by Owl. In that case, we need to access it with the `comp`
|
||||
property instead of `el`:
|
||||
|
||||
```xml
|
||||
<div t-ref="component_{{id}}"/>
|
||||
<div>
|
||||
<SubComponent t-ref="sub"/>
|
||||
<button t-on-click="doSomething">Click</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
this.refs.component_44;
|
||||
import { useRef } from "owl/hooks";
|
||||
|
||||
class SomeComponent extends Component {
|
||||
static components = { SubComponent };
|
||||
subRef = useRef("sub");
|
||||
|
||||
doSomething() {
|
||||
this.subRef.comp.doSomeThingElse();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that these two examples uses the suffix `ref` to name the reference. This
|
||||
is not mandatory, but it is a useful convention, so we do not forget to access
|
||||
it with the `el` or `comp` suffix.
|
||||
|
||||
### Slots
|
||||
|
||||
To make generic components, it is useful to be able for a parent component to _inject_
|
||||
@@ -1018,9 +1163,9 @@ Here are a few tips on how to work with asynchronous components:
|
||||
synchronous renderings
|
||||
3. Lazy loading external libraries is a good use case for async rendering. This
|
||||
is mostly fine, because we can assume that it will only takes a fraction of a
|
||||
second, and only once (see `owl.utils.loadJS`)
|
||||
4. For all the other cases, the `t-asyncroot` directive (to use alongside
|
||||
`t-component`) is there to help you. When this directive is met, a new rendering
|
||||
second, and only once (see [`owl.utils.loadJS`](utils.md#loadjs))
|
||||
4. For all the other cases, the [`AsyncRoot`](misc.md#asyncroot) component is there to help you. When
|
||||
this component is met, a new rendering
|
||||
sub tree is created, such that the rendering of that component (and its
|
||||
children) is not tied to the rendering of the rest of the interface. It can
|
||||
be used on an asynchronous component, to prevent it from delaying the
|
||||
@@ -1032,7 +1177,9 @@ Here are a few tips on how to work with asynchronous components:
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<SyncChild />
|
||||
<AsyncChild t-asyncroot="1"/>
|
||||
<AsyncRoot>
|
||||
<AsyncChild/>
|
||||
</AsyncRoot>
|
||||
</div>
|
||||
```
|
||||
|
||||
@@ -1049,7 +1196,7 @@ 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 allow us to properly handle the error, and to
|
||||
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:
|
||||
@@ -1066,8 +1213,8 @@ For example, here is how we could implement an `ErrorBoundary` component:
|
||||
```
|
||||
|
||||
```js
|
||||
class ErrorBoundary extends Widget {
|
||||
state = { error: false };
|
||||
class ErrorBoundary extends Component {
|
||||
state = useState({ error: false });
|
||||
|
||||
catchError() {
|
||||
this.state.error = true;
|
||||
@@ -1094,3 +1241,79 @@ env.qweb.on("error", null, function(error) {
|
||||
// react to the error
|
||||
});
|
||||
```
|
||||
|
||||
### Functional Components
|
||||
|
||||
Owl does not exactly have functional components. However, there is an extremely
|
||||
close alternative: calling sub templates.
|
||||
|
||||
A stateless functional component in react is usually some kind of function that
|
||||
maps props to a virtual dom (often with `jsx`). So, basically, almost like a
|
||||
template rendered with `props`. In Owl, this can be done by
|
||||
simply defining a template, that will access the `props` object:
|
||||
|
||||
```js
|
||||
const Welcome = xml`<h1>Hello, {props.name}</h1>`;
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<t t-call=${Welcome}/>
|
||||
<div>something</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
```
|
||||
|
||||
The way this works is that sub templates are inlined, and have access to the
|
||||
ambient context. They can therefore access `props`, and any other part of the
|
||||
caller component.
|
||||
|
||||
### SVG Components
|
||||
|
||||
Owl components can be used to generate dynamic SVG graphs:
|
||||
|
||||
```js
|
||||
class Node extends Component {
|
||||
static template = xml`
|
||||
<g>
|
||||
<circle t-att-cx="props.x" t-att-cy="props.y" r="4" fill="black"/>
|
||||
<text t-att-x="props.x - 5" t-att-y="props.y + 18"><t t-esc="props.node.label"/></text>
|
||||
<t t-set="childx" t-value="props.x + 100"/>
|
||||
<t t-set="height" t-value="props.height/(props.node.children || []).length"/>
|
||||
<t t-foreach="props.node.children || []" t-as="child">
|
||||
<t t-set="childy" t-value="props.y + child_index*height"/>
|
||||
<line t-att-x1="props.x" t-att-y1="props.y" t-att-x2="childx" t-att-y2="childy" stroke="black" />
|
||||
<Node x="childx" y="childy" node="child" height="height"/>
|
||||
</t>
|
||||
</g>
|
||||
`;
|
||||
static components = { Node };
|
||||
}
|
||||
|
||||
class RootNode extends Component {
|
||||
static template = xml`
|
||||
<svg height="180">
|
||||
<Node node="graph" x="10" y="20" height="180"/>
|
||||
</svg>
|
||||
`;
|
||||
static components = { Node };
|
||||
graph = {
|
||||
label: "a",
|
||||
children: [
|
||||
{ label: "b" },
|
||||
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
|
||||
{ label: "f", children: [{ label: "g" }] }
|
||||
]
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This `RootNode` component will then display a live SVG representation of the
|
||||
graph described by the `graph` property. Note that there is a recursive structure
|
||||
here: the `Node` component uses itself as a subcomponent.
|
||||
|
||||
Note that since SVG needs to be handled in a specific way (its namespace needs
|
||||
to be properly set), there is a small constraint for Owl components: if an owl
|
||||
component is supposed to be a part of an svg graph, then its root node needs to
|
||||
be a `g` tag, so Owl can properly set the namespace.
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# 🦉 Context 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example](#example)
|
||||
- [Reference](#reference)
|
||||
- [`Context`](#context)
|
||||
- [`useContext`](#usecontext)
|
||||
|
||||
## Overview
|
||||
|
||||
The `Context` object provides a way to share data between an arbitrary number
|
||||
of components. Usually, data is passed from a parent to its children component,
|
||||
but when we have to deal with some mostly global information, this can be
|
||||
annoying, since each component will need to pass the information to each children,
|
||||
even though some or most of them will not use the information.
|
||||
|
||||
With a `Context` object, each component can subscribe (with the `useContext` hook)
|
||||
to its state, and will be updated whenever the context state is updated.
|
||||
|
||||
## Example
|
||||
|
||||
Assume that we have an application with various components which needs to render
|
||||
differently depending on the size of the device. Here is how we could proceed
|
||||
to make sure that the information is properly shared. First, let us create a
|
||||
context, and add it to the environment:
|
||||
|
||||
```js
|
||||
const deviceContext = new Context({ isMobile: true });
|
||||
const env = {
|
||||
qweb: new QWeb(TEMPLATES),
|
||||
deviceContext
|
||||
};
|
||||
```
|
||||
|
||||
If we want to make it completely responsive, we need to update its value whenever
|
||||
the size of the screen is updated:
|
||||
|
||||
```js
|
||||
const isMobile = () => window.innerWidth <= 768;
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
owl.utils.debounce(() => {
|
||||
const state = deviceContext.state;
|
||||
if (state.isMobile !== isMobile()) {
|
||||
state.isMobile = !state.isMobile;
|
||||
}
|
||||
}, 15)
|
||||
);
|
||||
```
|
||||
|
||||
Then, each component that want can subscribe and render differently depending on the
|
||||
fact that we are in a mobile or desktop mode.
|
||||
|
||||
```js
|
||||
class SomeComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<t t-if=device.isMobile>
|
||||
some simplified user interface
|
||||
</t>
|
||||
<t t-else="1">
|
||||
some more sopthisticated user interface
|
||||
</t>
|
||||
`;
|
||||
device = useContext(this.env.deviceContext);
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
### `Context`
|
||||
|
||||
A `Context` object should be created with a state object:
|
||||
|
||||
```js
|
||||
const someContext = new Context({ some: "key" });
|
||||
```
|
||||
|
||||
Its state is now available in the `state` key:
|
||||
|
||||
```js
|
||||
someContext.state.some = "other key";
|
||||
```
|
||||
|
||||
This is the way some global code (such as the responsive code above) should
|
||||
read and update the context state. However, components should not ever read the
|
||||
context state directly from the context, they should instead use the `useContext`
|
||||
hook to properly register themselves to state changes.
|
||||
|
||||
Note that the `Context` hook is different from the React version. For example,
|
||||
there is no concept of provider/consumer. So, the `Context` feature does not
|
||||
by itself allow the use of a different context state depending on the component
|
||||
place in the component tree. However, this functionality can be obtained, if
|
||||
necessary, with the use of sub environment.
|
||||
|
||||
### `useContext`
|
||||
|
||||
The `useContext` hook is the normal way for a component to register themselve
|
||||
to context state changes. The `useContext` method returns the context state:
|
||||
|
||||
```js
|
||||
device = useContext(this.env.deviceContext);
|
||||
```
|
||||
|
||||
It is a simple observed state (with an owl `Observer`), which contains the shared
|
||||
information.
|
||||
+1
-1
@@ -5,7 +5,7 @@ parts of the code. Owl has a very simple bus class, which manages subscriptions,
|
||||
triggering events, and callbacks.
|
||||
|
||||
```js
|
||||
const bus = new owl.EventBus();
|
||||
const bus = new owl.core.EventBus();
|
||||
|
||||
bus.on("some-event", null, function(...args) {
|
||||
console.log(...args);
|
||||
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
# 🦉 Hooks 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Example: Mouse Position](#example-mouse-position)
|
||||
- [Example: Autofocus](#example-autofocus)
|
||||
- [Reference](#reference)
|
||||
- [One Rule](#one-rule)
|
||||
- [`useState`](#usestate)
|
||||
- [`onMounted`](#onmounted)
|
||||
- [`onWillUnmount`](#onwillunmount)
|
||||
- [`onWillPatch`](#onwillpatch)
|
||||
- [`onPatched`](#onpatched)
|
||||
- [`onWillStart`](#onwillstart)
|
||||
- [`onWillUpdateProps`](#onwillupdateprops)
|
||||
- [`useContext`](#usecontext)
|
||||
- [`useRef`](#useref)
|
||||
- [`useSubEnv`](#usesubenv)
|
||||
- [`useStore`](#usestore)
|
||||
- [`useDispatch`](#usedispatch)
|
||||
- [`useGetters`](#usegetters)
|
||||
- [Making customized hooks](#making-customized-hooks)
|
||||
|
||||
## Overview
|
||||
|
||||
Hooks were popularised by React as a way to solve the following issues:
|
||||
|
||||
- help reusing stateful logic between components
|
||||
- help organizing code by feature in complex components
|
||||
- use state in functional components, without writing a class.
|
||||
|
||||
Owl hooks serve the same purpose, except that they work for class components
|
||||
(note: React hooks do not work on class components, and maybe because of that,
|
||||
there seems to be the misconception that hooks are in opposition to class. This
|
||||
is clearly not true, as shown by Owl hooks).
|
||||
|
||||
Hooks work beautifully with Owl components: they solve the problems mentioned
|
||||
above, and in particular, they are the perfect way to make your component
|
||||
reactive.
|
||||
|
||||
## Example: mouse position
|
||||
|
||||
Here is the classical example of a non trivial hook to track the mouse position.
|
||||
|
||||
```js
|
||||
const { useState, onMounted, onWillUnmount } = owl.hooks;
|
||||
|
||||
// We define here a custom behaviour: this hook tracks the state of the mouse
|
||||
// position
|
||||
function useMouse() {
|
||||
const position = useState({ x: 0, y: 0 });
|
||||
|
||||
function update(e) {
|
||||
position.x = e.clientX;
|
||||
position.y = e.clientY;
|
||||
}
|
||||
onMounted(() => {
|
||||
window.addEventListener("mousemove", update);
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
window.removeEventListener("mousemove", update);
|
||||
});
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
static template = xml`
|
||||
<div t-name="App">
|
||||
<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>
|
||||
</div>`;
|
||||
|
||||
// this hooks is bound to the 'mouse' property.
|
||||
mouse = useMouse();
|
||||
}
|
||||
```
|
||||
|
||||
Note that we use the prefix `use` for hooks, just like in React. This is just
|
||||
a convention.
|
||||
|
||||
## Example: autofocus
|
||||
|
||||
Hooks can be combined to create the desired effect. For example, the following
|
||||
hook combines the `useRef` hook with the `onPatched` and `onMounted` functions
|
||||
to create an easy way to focus an input whenever it appears in the DOM:
|
||||
|
||||
```js
|
||||
function useAutofocus(name) {
|
||||
let ref = useRef(name);
|
||||
let isInDom = false;
|
||||
function updateFocus() {
|
||||
if (!isInDom && ref.el) {
|
||||
isInDom = true;
|
||||
ref.el.focus();
|
||||
} else if (isInDom && !ref.el) {
|
||||
isInDom = false;
|
||||
}
|
||||
}
|
||||
onPatched(updateFocus);
|
||||
onMounted(updateFocus);
|
||||
}
|
||||
```
|
||||
|
||||
This hook takes the name of a valid `t-ref` directive, which should be present
|
||||
in the template. It then checks whenever the component is mounted or patched if
|
||||
the reference is not valid, and in this case, it will focus the node element.
|
||||
This hook can be used like this:
|
||||
|
||||
```js
|
||||
class SomeComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<input />
|
||||
<input t-ref="myinput"/>
|
||||
</div>`;
|
||||
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
useAutofocus("myinput");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
### One rule
|
||||
|
||||
There is only one rule: every hook for a component has to be called in the
|
||||
constructor (or in class fields):
|
||||
|
||||
```js
|
||||
// ok
|
||||
class SomeComponent extends Component {
|
||||
state = useState({ value: 0 });
|
||||
}
|
||||
|
||||
// also ok
|
||||
class SomeComponent extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
// not ok: this is executed after the constructor is called
|
||||
class SomeComponent extends Component {
|
||||
async willStart() {
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In a hook, the `Component.current` static property is the reference to the
|
||||
component instance that is currently being created. Hooks need to be called in
|
||||
the constructor to ensure that this reference is properly set.
|
||||
|
||||
### `useState`
|
||||
|
||||
The `useState` hook is certainly the most important hook for Owl components:
|
||||
this is what allows a component to be reactive, to react to state change.
|
||||
|
||||
The `useState` hook has to be given an object or an array, and will return
|
||||
an observed version of it (using a `Proxy`).
|
||||
|
||||
```javascript
|
||||
const { useState } = owl.hooks;
|
||||
|
||||
class Counter extends owl.Component {
|
||||
static template = xml`
|
||||
<button t-on-click="increment">
|
||||
Click Me! [<t t-esc="state.value"/>]
|
||||
</button>`;
|
||||
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `onMounted`
|
||||
|
||||
`onMounted` is not a user hook, but is a building block designed to help make useful
|
||||
abstractions. `onMounted` registers a callback, which will be called when the component
|
||||
is mounted (see example on top of this page).
|
||||
|
||||
### `onWillUnmount`
|
||||
|
||||
`onWillUnmount` is not a user hook, but is a building block designed to help make useful
|
||||
abstractions. `onWillUnmount` registers a callback, which will be called when the component
|
||||
is unmounted (see example on top of this page).
|
||||
|
||||
### `onWillPatch`
|
||||
|
||||
`onWillPatch` is not a user hook, but is a building block designed to help make useful
|
||||
abstractions. `onWillPatch` registers a callback, which will be called just
|
||||
before the component patched.
|
||||
|
||||
### `onPatched`
|
||||
|
||||
`onPatched` is not a user hook, but is a building block designed to help make useful
|
||||
abstractions. `onPatched` registers a callback, which will be called just
|
||||
after the component patched.
|
||||
|
||||
### `onWillStart`
|
||||
|
||||
`onWillStart` is an asynchronous hook. This means that the function registered
|
||||
in the hook will be run just before the component is first rendered and can return a
|
||||
promise, to express the fact that it is an asynchronous operation.
|
||||
|
||||
Note that if there are more than one `onWillStart` registered callback, then they
|
||||
will all be run in parallel.
|
||||
|
||||
It can be used to load some initial data. For example, the following hook will
|
||||
automatically load some data from the server, and return an object that will
|
||||
be ready whenever the component is rendered:
|
||||
|
||||
```js
|
||||
function useLoader() {
|
||||
const component = Component.current;
|
||||
const record = useState({});
|
||||
onWillStart(async () => {
|
||||
const recordId = component.props.id;
|
||||
Object.assign(record, await fetchSomeRecord(recordId));
|
||||
});
|
||||
return record;
|
||||
}
|
||||
```
|
||||
|
||||
Note that this example does not update the record value whenever props are
|
||||
updated. For that situation, we need to use the `onWillUpdateProps` hook.
|
||||
|
||||
### `onWillUpdateProps`
|
||||
|
||||
Just like `onWillStart`, `onWillUpdateProps` is an asynchronous hook. It is
|
||||
designed to be run whenever the component props are updated. This could be
|
||||
useful to perform some asynchronous task such as fetching updated data.
|
||||
|
||||
```js
|
||||
function useLoader() {
|
||||
const component = Component.current;
|
||||
const record = useState({});
|
||||
|
||||
async function updateRecord(id) {
|
||||
Object.assign(record, await fetchSomeRecord(id));
|
||||
}
|
||||
|
||||
onWillStart(() => updateRecord(component.props.id));
|
||||
onWillUpdateProps(nextProps => updateRecord(nextProps.id));
|
||||
|
||||
return record;
|
||||
}
|
||||
```
|
||||
|
||||
Note that if there are more than one `onWillUpdateProps` registered callback,
|
||||
then they will all be run in parallel.
|
||||
|
||||
### `useContext`
|
||||
|
||||
See [`useContext`](context.md#usecontext) for reference documentation.
|
||||
|
||||
### `useRef`
|
||||
|
||||
The `useRef` hook is useful when we need a way to interact with some inside part
|
||||
of a component, rendered by Owl. It can work either on a DOM node, or on a component,
|
||||
tagged by the `t-ref` directive:
|
||||
|
||||
```xml
|
||||
<div>
|
||||
<div t-ref="someDiv"/>
|
||||
<SubComponent t-ref="someComponent"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
In this example, the component will be able to access the `div` and the component
|
||||
`SubComponent` using the `useRef` hook:
|
||||
|
||||
```js
|
||||
class Parent extends Component {
|
||||
subRef = useRef("someComponent");
|
||||
divRef = useRef("someDiv");
|
||||
|
||||
someMethod() {
|
||||
// here, if component is mounted, refs are active:
|
||||
// - this.divRef.el is the div HTMLElement
|
||||
// - this.subRef.comp is the instance of the sub component
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
As shown by the example above, html elements are accessed by using the `el`
|
||||
key, and components references are accessed with `comp`.
|
||||
|
||||
Note: if used on a component, the reference will be set in the `refs`
|
||||
variable between `willPatch` and `patched`.
|
||||
|
||||
The `t-ref` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](qweb.md#dynamic-attributes) and
|
||||
`t-component` directives). For example,
|
||||
|
||||
```xml
|
||||
<div t-ref="component_{{someCondition ? '1' : '2'}}"/>
|
||||
```
|
||||
|
||||
Here, the references need to be set like this:
|
||||
|
||||
```js
|
||||
this.ref1 = useRef("component_1");
|
||||
this.ref2 = useRef("component_2");
|
||||
```
|
||||
|
||||
References are only guaranteed to be active while the parent component is mounted.
|
||||
If this is not the case, accessing `el` or `comp` on it will return `null`.
|
||||
|
||||
### `useSubEnv`
|
||||
|
||||
The environment is sometimes useful to share some common information between
|
||||
all components. But sometimes, we want to _scope_ that knowledge to a subtree.
|
||||
|
||||
For example, if we have a form view component, maybe we would like to make some
|
||||
`model` object available to all sub components, but not to the whole application.
|
||||
This is where the `useSubEnv` hook may be useful: it lets a component add some
|
||||
information to the environment in a way that only the component and its children
|
||||
can access it:
|
||||
|
||||
```js
|
||||
class FormComponent extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
const model = makeModel();
|
||||
useSubEnv({ model });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `useSubEnv` takes one argument: an object which contains some key/value that
|
||||
will be added to the parent environment. Note that it will extend, not replace
|
||||
the parent environment. And of course, the parent environment will not be
|
||||
affected.
|
||||
|
||||
### `useStore`
|
||||
|
||||
The `useStore` hook is the entry point for a component to connect to the store.
|
||||
See the [store documentation](store.md) for more information.
|
||||
|
||||
### `useDispatch`
|
||||
|
||||
The `useDispatch` hook is the way for components to get a reference to the store
|
||||
`dispatch` function. See the [store documentation](store.md) for more information.
|
||||
|
||||
### `useGetters`
|
||||
|
||||
The `useGetters` hook is the way for components to get a reference to the store
|
||||
getters. See the [store documentation](store.md) for more information.
|
||||
|
||||
### Making customized hooks
|
||||
|
||||
Hooks are a wonderful way to organize the code of a complex component by feature
|
||||
instead of by lifecycle methods. They are like mixins, except that they can be
|
||||
easily composed together.
|
||||
|
||||
But, like every good things in life, hooks should be used with moderation. They are
|
||||
not the solution to every problem.
|
||||
|
||||
- they may be overkill: if your component needs to perform some action specific
|
||||
to itself (so, the specific code does not need to be shared), there is nothing
|
||||
wrong with a simple class method:
|
||||
|
||||
```js
|
||||
// maybe overkill
|
||||
class A extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
useMySpecificHook();
|
||||
}
|
||||
}
|
||||
|
||||
// ok
|
||||
class B extends Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.performSpecificTask();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that the second solution is easier to extend in sub components.
|
||||
|
||||
- they may be harder to test: if a customized hook injects some external side
|
||||
effect dependency, then it is harder to test without doing some non obvious
|
||||
manipulation. For example, assume that we want to give a reference to a
|
||||
router in a `useRouter` hook. We could do this:
|
||||
|
||||
```js
|
||||
const router = new Router(...);
|
||||
|
||||
function useRouter() {
|
||||
return router;
|
||||
}
|
||||
```
|
||||
|
||||
As you can see, this does not _hook_ into the internal of the component. It
|
||||
simply returns a global object, which is difficult to mock.
|
||||
|
||||
A better way would be to do something like this: get the reference from the
|
||||
environment.
|
||||
|
||||
```js
|
||||
function useRouter() {
|
||||
return Component.current.env.router;
|
||||
}
|
||||
```
|
||||
|
||||
This means that we give control to the application developer to create the
|
||||
router, which is good, so they can set it up, subclass it, ... And then, to
|
||||
test our components, we can just add a mock router in the environment.
|
||||
|
||||
Note: the code above makes use of the `Component.current` property. This is the
|
||||
way hooks are able to get a reference to the component currently being created.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# 🦉 Miscellaneous 🦉
|
||||
|
||||
## `AsyncRoot`
|
||||
|
||||
When this component is used, a new rendering sub tree is created, such that the
|
||||
rendering of that component (and its children) is not tied to the rendering of
|
||||
the rest of the interface. It can be used on an asynchronous component, to
|
||||
prevent it from delaying the rendering of the whole interface, or on a
|
||||
synchronous one, such that its rendering isn't delayed by other (asynchronous)
|
||||
components. Note that this directive has no effect on the first rendering, but
|
||||
only on subsequent ones (triggered by state or props changes).
|
||||
|
||||
```xml
|
||||
<div t-name="ParentComponent">
|
||||
<SyncChild />
|
||||
<AsyncRoot>
|
||||
<AsyncChild/>
|
||||
</AsyncRoot>
|
||||
</div>
|
||||
```
|
||||
|
||||
The `AsyncRoot` assumes that there is exactly one root node inside it. It can
|
||||
be a dom node or a component.
|
||||
+32
-30
@@ -1,50 +1,52 @@
|
||||
# 🦉 Observer 🦉
|
||||
|
||||
Owl need to be able to react to state changes. For example, whenever the state
|
||||
of a component is changed, we need to rerender it. To help with that, we have
|
||||
an Observer class. Its job is to observe some object state, and react to any
|
||||
change. To do that, it recursively replace all keys of the observed state by
|
||||
getters and setters.
|
||||
Owl needs to be able to react to state changes. For example, whenever the state
|
||||
of a component is changed, Owl needs to rerender it. To help with that, there is
|
||||
an Observer class. Its job is to observe the state of an object (or array), and
|
||||
to react to any change. The observer is implemented with the native `Proxy`
|
||||
object. Note that this means that it will not work on older browsers.
|
||||
|
||||
Note that the `Observer` is used by the `useState` and `useContext` hooks. This
|
||||
is the way most Owl applications will create observers. For the majority of
|
||||
use cases, there is no need to directly instantiate an observer.
|
||||
|
||||
## Example
|
||||
|
||||
For example, this code will display `update` in the console:
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
observer.notifyCB = () => console.log("update");
|
||||
observer.observe(obj);
|
||||
const obj = observer.observe({ a: { b: 1 } });
|
||||
|
||||
const obj = { a: { b: 1 } };
|
||||
obj.a.b = 2;
|
||||
```
|
||||
|
||||
## Technical Limitations
|
||||
This example shows that an observer can observe nested properties.
|
||||
|
||||
Since the observer uses getters and setters, it is actually unable to react to
|
||||
changes in three situations:
|
||||
## Reference
|
||||
|
||||
- adding a key to an object
|
||||
- deleting a key from an object
|
||||
- modifying an array by setting a new value at a given index
|
||||
**observe** An observer can observe multiple values with the `observe` method.
|
||||
This method takes an object or an array as its argument and will return a proxy
|
||||
(which is mapped to the initial object/array). With this proxy, the observer
|
||||
can detect whenever any internal value is changed.
|
||||
|
||||
In those situations, we need a way to tell the observer that something happened.
|
||||
This can be done by using the `set` and `delete` (only for objects) static
|
||||
methods of the `Observer`.
|
||||
**Registering a callback** Whenever an observer sees a state change, it will
|
||||
call its `notifyCB` method. No additional information is given to the callback.
|
||||
|
||||
```javascript
|
||||
**deepRevNumber** Each observed value has an internal revision number, which
|
||||
is incremented every time the value is observed. Sometimes, it can be useful
|
||||
to obtain that number:
|
||||
|
||||
```js
|
||||
const observer = new owl.Observer();
|
||||
const obj = { a: 1 };
|
||||
observer.observe(obj);
|
||||
obj.b = 2; // won't notify the change
|
||||
owl.Observer.set(obj, "b", 2); // will notify the change
|
||||
const obj = observer.observe({ a: { b: 1 } });
|
||||
|
||||
delete obj.b; // won't notify the change
|
||||
owl.Observer.delete(obj, "b"); // will notify the change
|
||||
observer.deepRevNumber(obj.a); // 1
|
||||
obj.a.b = 2;
|
||||
|
||||
observer.deepRevNumber(obj.a); // 2
|
||||
```
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const arr = ["a"];
|
||||
observer.observe(arr);
|
||||
arr[0] = "b"; // won't notify the change
|
||||
owl.Observer.set(arr, 0, "b"); // will notify the change
|
||||
```
|
||||
The `deepRevNumber` can also return 0, which indicates that the value is not
|
||||
observed.
|
||||
|
||||
+6
-7
@@ -55,7 +55,7 @@ To build an application (or a sub-part of an application), we need two things:
|
||||
|
||||
- an environment: it is the global context in which we are working. It needs to
|
||||
contain a QWeb instance (preloaded with templates), and anything else that we
|
||||
need. In practice, it could context some user session information, some
|
||||
need. In practice, it could be used to contain some user session information, some
|
||||
configuration keys (for example, isMobile = true/false if we are in mobile mode).
|
||||
|
||||
- a description of the user interface: there should be a root component, which can
|
||||
@@ -72,12 +72,11 @@ Here are a few steps that we may take to get started:
|
||||
Let us now add the javascript to make it work, in `app.js`:
|
||||
|
||||
```javascript
|
||||
const useState = owl.hooks.useState;
|
||||
|
||||
class ClickCounter extends owl.Component {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.template = "clickcounter";
|
||||
this.state = { value: 0 };
|
||||
}
|
||||
static template = "clickcounter";
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
@@ -88,7 +87,7 @@ class ClickCounter extends owl.Component {
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const templates = await owl.utils.loadFile("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
|
||||
+52
-27
@@ -20,7 +20,7 @@
|
||||
|
||||
## Overview
|
||||
|
||||
[QWeb](https://www.odoo.com/documentation/12.0/reference/qweb.html) is the primary templating engine used by Odoo. It is based on the XML format, and used
|
||||
[QWeb](https://www.odoo.com/documentation/13.0/reference/qweb.html) is the primary templating engine used by Odoo. It is based on the XML format, and used
|
||||
mostly to generate HTML. In OWL, QWeb templates are compiled into functions that
|
||||
generate a virtual dom representation of the HTML.
|
||||
|
||||
@@ -33,7 +33,7 @@ To avoid element rendering, a placeholder element `<t>` is also available, which
|
||||
<span t-if="somecondition">Some string</span>
|
||||
<ul t-else="1">
|
||||
<li t-foreach="messages" t-as="message">
|
||||
<t t-esc="message">
|
||||
<t t-esc="message"/>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -65,16 +65,15 @@ We present here a list of all standard QWeb directives:
|
||||
The component system in Owl requires additional directives, to express various
|
||||
needs. Here is a list of all Owl specific directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------------------------- | ----------------------------------------------------------------------------------- |
|
||||
| `t-component`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-mounted` | [Callback when a node or component is mounted](component.md#t-mounted-directive) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
| Name | Description |
|
||||
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `t-component`, `t-props`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
|
||||
## QWeb Engine
|
||||
|
||||
@@ -86,7 +85,7 @@ instantiated:
|
||||
const qweb = new owl.QWeb();
|
||||
```
|
||||
|
||||
It's API is quite simple:
|
||||
Its API is quite simple:
|
||||
|
||||
- **`constructor(data)`**: constructor. Takes an optional string to add initial
|
||||
templates (see `addTemplates` for more information on format of the string).
|
||||
@@ -101,7 +100,8 @@ It's API is quite simple:
|
||||
qweb.addTemplate("mytemplate", "<div>hello</div>");
|
||||
```
|
||||
|
||||
If the optional `allowDuplicate` is set to `true`, then `QWeb` will simply return whenever a template is added for a second time. Otherwise, `QWeb` will crash.
|
||||
If the optional `allowDuplicate` is set to `true`, then `QWeb` will simply
|
||||
ignore templates added for a second time. Otherwise, `QWeb` will crash.
|
||||
|
||||
- **`addTemplates(xmlStr)`**: add a list of templates (identified by `t-name`
|
||||
attribute).
|
||||
@@ -129,14 +129,23 @@ It's API is quite simple:
|
||||
const str = qweb.renderToString("someTemplate", somecontext);
|
||||
```
|
||||
|
||||
- **`register(name, Component)`**: static function to register an OWL Component
|
||||
- **`registerTemplate(name, template)`**: static function to register a global
|
||||
QWeb template. This is useful for commonly used components accross the
|
||||
application, and for making a template available to an application without
|
||||
having a reference to the actual QWeb instance.
|
||||
|
||||
```js
|
||||
QWeb.registerTemplate("mytemplate", `<div>some template</div>`);
|
||||
```
|
||||
|
||||
- **`registerComponent(name, Component)`**: static function to register an OWL Component
|
||||
to QWeb's global registry. Globally registered Components can be used in
|
||||
templates (see the `t-component` directive). This is useful for commonly used
|
||||
components accross the application.
|
||||
|
||||
```js
|
||||
class Dialog extends owl.Component { ... }
|
||||
QWeb.register("Dialog", Dialog);
|
||||
QWeb.registerComponent("Dialog", Dialog);
|
||||
|
||||
...
|
||||
|
||||
@@ -146,7 +155,7 @@ It's API is quite simple:
|
||||
|
||||
In some way, a `QWeb` instance is the core of an Owl application. It is the only
|
||||
mandatory element of an [environment](component.md#environment). As such, it
|
||||
has an extra responsability: it can act as an event bus for internal communication
|
||||
has an extra responsibility: it can act as an event bus for internal communication
|
||||
between Owl classes. This is the reason why `QWeb` actually extends [EventBus](event_bus.md).
|
||||
|
||||
## Reference
|
||||
@@ -157,7 +166,7 @@ specific extensions are documented in various other parts of the documentation.
|
||||
|
||||
### White Spaces
|
||||
|
||||
White spaces in a templates are handled in a special way:
|
||||
White spaces in a template are handled in a special way:
|
||||
|
||||
- consecutive whitespaces are always condensed to a single whitespace
|
||||
- if a whitespace-only text node contains a linebreak, it is ignored
|
||||
@@ -199,7 +208,7 @@ component). For example, `a + b.c(d)` will be converted into:
|
||||
context["a"] + context["b"].c(context["d"]);
|
||||
```
|
||||
|
||||
It is useful to explain the various rules that applies on these expressions:
|
||||
It is useful to explain the various rules that apply on these expressions:
|
||||
|
||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||
|
||||
@@ -277,6 +286,11 @@ rendered with the value `value` set to `<span>foo</span>` in the rendering conte
|
||||
<p><span>foo</span></p>
|
||||
```
|
||||
|
||||
Note that since the content of the expression is not known beforehand, the `t-raw`
|
||||
directive has to parse the html (and convert it to a virtual dom structure) for
|
||||
each rendering. So, it will be much slower than a regular template. It is
|
||||
therefore advised to limit the use of `t-raw` whenever possible.
|
||||
|
||||
### Setting Variables
|
||||
|
||||
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
|
||||
@@ -376,14 +390,25 @@ If an expression evaluates to a falsy value, it will not be set at all:
|
||||
<div t-att-foo="false"/> <!-- result: <div></div> -->
|
||||
```
|
||||
|
||||
There is another way to format a string attribute: the `t-attf-` directive. With
|
||||
it, you get string interpolation:
|
||||
It is sometimes convenient to format an attribute with string interpolation. In
|
||||
that case, the `t-attf-` directive can be used. It is useful when we need to mix
|
||||
literal and dynamic elements, such as css classes.
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
```
|
||||
|
||||
If we need completely dynamic attribute names, then there is an additional
|
||||
directive: `t-att`, which takes either an object (with keys mapping to their
|
||||
values) or a pair `[key, value]`. For example:
|
||||
|
||||
```xml
|
||||
<div t-att="{'a': 1, 'b': 2}"/> <!-- result: <div a="1" b="2"></div> -->
|
||||
|
||||
<div t-att="['a', 'b']"/> <!-- <div a="b"></div> -->
|
||||
```
|
||||
|
||||
### Loops
|
||||
|
||||
QWeb has an iteration directive `t-foreach` which take an expression returning the
|
||||
@@ -436,16 +461,16 @@ the context of the `t-foreach`, the value is copied at the end of the foreach
|
||||
into the global context.
|
||||
|
||||
```xml
|
||||
<t t-set="existing_variable" t-value="False"/>
|
||||
<t t-set="existing_variable" t-value="false"/>
|
||||
<!-- existing_variable now False -->
|
||||
|
||||
<p t-foreach="Array(3)" t-as="i">
|
||||
<t t-set="existing_variable" t-value="True"/>
|
||||
<t t-set="new_variable" t-value="True"/>
|
||||
<!-- existing_variable and new_variable now True -->
|
||||
<t t-set="existing_variable" t-value="true"/>
|
||||
<t t-set="new_variable" t-value="true"/>
|
||||
<!-- existing_variable and new_variable now true -->
|
||||
</p>
|
||||
|
||||
<!-- existing_variable always True -->
|
||||
<!-- existing_variable always true -->
|
||||
<!-- new_variable undefined -->
|
||||
```
|
||||
|
||||
@@ -518,4 +543,4 @@ will stop execution if the browser dev tools are open.
|
||||
<t t-log="foo"/>
|
||||
```
|
||||
|
||||
will print 42 to the console
|
||||
will print 42 to the console.
|
||||
|
||||
+32
-6
@@ -3,38 +3,64 @@
|
||||
## Owl Content
|
||||
|
||||
Owl is a javascript library that contains some core classes and function to help
|
||||
build applications. Here is a complete representation of its content:
|
||||
build applications. Here is a complete representation of its content:
|
||||
|
||||
```
|
||||
owl
|
||||
Component
|
||||
Context
|
||||
QWeb
|
||||
Store
|
||||
useState
|
||||
core
|
||||
EventBus
|
||||
Observer
|
||||
hooks
|
||||
onWillStart
|
||||
onMounted
|
||||
onWillUpdateProps
|
||||
onWillPatch
|
||||
onPatched
|
||||
onWillUnmount
|
||||
useContext
|
||||
useState
|
||||
useRef
|
||||
useSubEnv
|
||||
useStore
|
||||
useDispatch
|
||||
useGetters
|
||||
misc
|
||||
AsyncRoot
|
||||
router
|
||||
Link
|
||||
RouteComponent
|
||||
Router
|
||||
store
|
||||
Store
|
||||
ConnectedComponent
|
||||
tags
|
||||
xml
|
||||
utils
|
||||
debounce
|
||||
escape
|
||||
loadJS
|
||||
loadTemplates
|
||||
loadFile
|
||||
shallowEqual
|
||||
whenReady
|
||||
```
|
||||
|
||||
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
||||
|
||||
## Reference
|
||||
|
||||
- [Animations](animations.md)
|
||||
- [Component](component.md)
|
||||
- [Context](context.md)
|
||||
- [Event Bus](event_bus.md)
|
||||
- [Hooks](hooks.md)
|
||||
- [Misc](misc.md)
|
||||
- [Observer](observer.md)
|
||||
- [QWeb](qweb.md)
|
||||
- [Router](router.md)
|
||||
- [Store](store.md)
|
||||
- [Tags](tags.md)
|
||||
- [Utils](utils.md)
|
||||
- [Virtual DOM](vdom.md)
|
||||
|
||||
@@ -46,4 +72,4 @@ owl
|
||||
|
||||
- [Comparison with React/Vue](comparison.md)
|
||||
- [Tooling](tooling.md)
|
||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
||||
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
|
||||
|
||||
+14
-8
@@ -8,7 +8,7 @@
|
||||
- [Route Definition](#route-definition)
|
||||
- [Router](#router)
|
||||
- [Navigation Guards](#navigation-guards)
|
||||
- [`t-routecomponent`](#t-routecomponent)
|
||||
- [RouteComponent](#routecomponent)
|
||||
- [Link](#link)
|
||||
|
||||
## Overview
|
||||
@@ -26,8 +26,8 @@ The Owl router support the following features:
|
||||
- route redirection
|
||||
- navigation guards
|
||||
- parameterized routes
|
||||
- a `<Link>` component
|
||||
- a `t-routecomponent` directive
|
||||
- a `<Link/>` component
|
||||
- a `<RouteComponent/>` component
|
||||
|
||||
Note that it is still in early stage of developments, and there are probably
|
||||
still some issues.
|
||||
@@ -97,6 +97,13 @@ The `Router` constructor takes three arguments:
|
||||
- an optional object (with the only key `mode` which can be `history` (default
|
||||
value) or `hash`).
|
||||
|
||||
`history` will use the browser [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) as the mechanism to manage URL.\
|
||||
Example: `https://yourdomain.tld/my_custom_route`.\
|
||||
For this mechanism to work, you need a way to configure your web server accordingly.
|
||||
|
||||
`hash` will manipulate the hash of the URL.\
|
||||
Example: `https://yourdomain.tld/index.html#/my_custom_route`.
|
||||
|
||||
```js
|
||||
const ROUTES = [...];
|
||||
const router = new owl.router.Router(env, ROUTES, {mode: 'history'});
|
||||
@@ -125,7 +132,7 @@ The router also has a `navigate` method, useful to programmatically change the
|
||||
application to another state (and the url):
|
||||
|
||||
```js
|
||||
router.navigate({to: 'USER', params: {id: 51}});
|
||||
router.navigate({ to: "USER", params: { id: 51 } });
|
||||
```
|
||||
|
||||
### Navigation Guards
|
||||
@@ -148,19 +155,18 @@ async function protectRoute({ env, to }) {
|
||||
A navigation guard is a function that returns a promise, which either resolves
|
||||
to `true` (the navigation is accepted), or to another destination object.
|
||||
|
||||
### `t-routecomponent`
|
||||
### `RouteComponent`
|
||||
|
||||
The `t-routecomponent` directive directs Owl to render the component associated
|
||||
The `RouteComponent` component directs Owl to render the component associated
|
||||
to the currently active route (if any):
|
||||
|
||||
```xml
|
||||
<div t-name="App">
|
||||
<NavBar />
|
||||
<t t-routecomponent="1"/>
|
||||
<RouteComponent />
|
||||
</div>
|
||||
```
|
||||
|
||||
|
||||
### `Link`
|
||||
|
||||
The `Link` component is a Owl component which render as a `<a>` tag with any
|
||||
|
||||
+90
-57
@@ -9,6 +9,9 @@
|
||||
- [Actions](#actions)
|
||||
- [Getters](#getters)
|
||||
- [Connecting a Component](#connecting-a-component)
|
||||
- [`useStore`](#usestore)
|
||||
- [`useDispatch`](#usedispatch)
|
||||
- [`useGetters`](#usegetters)
|
||||
- [Semantics](#semantics)
|
||||
- [Good Practices](#good-practices)
|
||||
|
||||
@@ -16,13 +19,14 @@
|
||||
|
||||
Managing the state in an application is not an easy task. In some cases, the
|
||||
state of an application can be part of the component tree, in a natural way.
|
||||
However, there are situations where some part of the state need to be displayed
|
||||
However, there are situations where some parts of the state need to be displayed
|
||||
in various parts of the user interface, and then, it is not obvious which
|
||||
component should own which part of the state.
|
||||
|
||||
Owl's solution to this issue is a centralized store. It is a class that owns
|
||||
some state, and let the developer update it in a structured way, with `actions`.
|
||||
Owl components can then connect to the store, and will be updated if necessary.
|
||||
some (or all) state, and lets the developer update it in a structured way, with
|
||||
`actions`. Owl components can then connect to the store, and will be updated if
|
||||
necessary.
|
||||
|
||||
Note: Owl store is inspired by React Redux and VueX.
|
||||
|
||||
@@ -47,7 +51,7 @@ const state = {
|
||||
};
|
||||
|
||||
const store = new owl.Store({ state, actions });
|
||||
store.on("update", () => console.log(store.state));
|
||||
store.on("update", null, () => console.log(store.state));
|
||||
|
||||
// updating the state
|
||||
store.dispatch("addTodo", "fix all bugs");
|
||||
@@ -103,13 +107,22 @@ const actions = {
|
||||
try {
|
||||
const loginInfo = await doSomeRPC("/login/", info);
|
||||
state.loginState = loginInfo;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
state.loginState = "error";
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
The first argument to an action method is an object with four keys:
|
||||
|
||||
- `state`: the current state of the store content,
|
||||
- `dispatch`: a function that can be used to dispatch other actions,
|
||||
- `getters`: an object containing all getters defined in the store,
|
||||
- `env`: the current environment. This is useful sometimes, in particular if
|
||||
an action needs to apply some side effects (such as performing an rpc), and
|
||||
the `rpc` method is located in the environment.
|
||||
|
||||
Actions are called with the `dispatch` method on the store, and can receive an
|
||||
arbitrary number of arguments.
|
||||
|
||||
@@ -122,7 +135,7 @@ call.
|
||||
|
||||
Also, it is important to be aware that we need to be careful with asynchronous
|
||||
logic. Each state change will potentially trigger a rerendering, so we need to
|
||||
make sure that we do not have a partial corrupted state. Here is an example that
|
||||
make sure that we do not have a partially corrupted state. Here is an example that
|
||||
is likely not a good idea:
|
||||
|
||||
```javascript
|
||||
@@ -175,7 +188,7 @@ transform the data contained in the store.
|
||||
const getters = {
|
||||
getPost({ state }, 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 {
|
||||
id,
|
||||
author,
|
||||
@@ -190,100 +203,120 @@ const post = store.getters.getPost(id);
|
||||
|
||||
Getters take _at most_ one argument.
|
||||
|
||||
Note that getters are cached if they don't take any argument, or their argument
|
||||
is a string or a number.
|
||||
Note that getters are not cached.
|
||||
|
||||
### Connecting a Component
|
||||
|
||||
At some point, we need a way to access the state in the store from a component.
|
||||
By default, an Owl `Component` is not connected to any store. To do that, we
|
||||
need to create a component inheriting from `OwlComponent`:
|
||||
At some point, we need a way to interact with the store from a component. This
|
||||
can be done with the help of the three store hooks:
|
||||
|
||||
- [`useStore`](#usestore) to subscribe a component to some part of the store state,
|
||||
- [`useDispatch`](#usedispatch) to get a reference to a dispatch function,
|
||||
- [`useGetters`](#usegetters) to get a reference to the getters defined in the store.
|
||||
|
||||
Assume we have this store:
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({ state }, val) {
|
||||
state.counter += val;
|
||||
state.counter.value += val;
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
counter: 0
|
||||
counter: { value: 0 }
|
||||
};
|
||||
const store = new owl.Store({ state, actions });
|
||||
```
|
||||
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
increment() {
|
||||
this.env.store.dispatch("increment");
|
||||
}
|
||||
A counter component can then select this value and dispatch an action like this:
|
||||
|
||||
```js
|
||||
class Counter extends Component {
|
||||
counter = useStore(state => state.counter);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="props.value"/>]
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="counter.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
The `ConnectedComponent` class can be configured with the following fields:
|
||||
### `useStore`
|
||||
|
||||
- `mapStoreToProps`: a function that extracts the `props` of the Component
|
||||
from the `state` of the `Store` and returns them as a dict.
|
||||
- `getStore`: a function that takes the `env` in arguments and returns an
|
||||
instance of `Store` to connect to (if not given, connects to `env.store`)
|
||||
- `hashFunction`: the function to use to detect changes in the state (if not
|
||||
given, generates a function that uses revision numbers, incremented at
|
||||
each state change)
|
||||
- `deep` (boolean): [only useful if no hashFunction is given] if `false`, only watch
|
||||
for top level state changes (`true` by default)
|
||||
The `useStore` hook is used to select some part of the store state. It accepts
|
||||
two arguments:
|
||||
|
||||
Note that the class `ConnectedComponent` has a `dispatch` method. This means
|
||||
that the previous example could be simplified like this:
|
||||
- a selector function, which takes the store state as first argument (and the
|
||||
component props as second argument) and returns
|
||||
an object or an array (which will be then observed),
|
||||
- optionally, an object with a `store` key (if we want to override the default
|
||||
store) and an equality function (if we want to specialize the comparison).
|
||||
|
||||
```javascript
|
||||
class Counter extends owl.ConnectedComponent {
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
If the `useStore` callback selects a sub part of the store state, the component
|
||||
will only be rerendered whenever this part of the state changes. Otherwise, it
|
||||
will perform a strict equality check and will update the component every time this
|
||||
check fails.
|
||||
|
||||
### `useDispatch`
|
||||
|
||||
The `useDispatch` hook is useful when a component needs to be able to dispatch
|
||||
actions. It takes an optional argument, which is a store. If not given, it will
|
||||
use the store in the environment.
|
||||
|
||||
Note that a component does not need to be connected in any other way to the store.
|
||||
For example:
|
||||
|
||||
```js
|
||||
class DoSomethingButton extends Component {
|
||||
static template = xml`<button t-on-click="dispatch('something')">Click</button>`;
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
```
|
||||
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="dispatch('increment')">
|
||||
Click Me! [<t t-esc="props.value"/>]
|
||||
</button>
|
||||
### `useGetters`
|
||||
|
||||
The `useGetters` hook is useful when a component needs to be able to use the
|
||||
getters defined in a store. It takes an optional argument, which is a store. If
|
||||
not given, it will use the store in the environment.
|
||||
|
||||
Note that a component does not need to be connected in any other way to the store.
|
||||
For example:
|
||||
|
||||
```js
|
||||
class InfoButton extends Component {
|
||||
static template = xml`<span><t t-esc="getters.somevalue()"></span>`;
|
||||
getters = useGetters();
|
||||
}
|
||||
```
|
||||
|
||||
### Semantics
|
||||
|
||||
The `Store` and the `ConnectedComponent` try to be smart and to optimize as much
|
||||
The `Store` class and the `useStore` hook try to be smart and to optimize as much
|
||||
as possible the rendering and update process. What is important to know is:
|
||||
|
||||
- components are always updated in the order of their creation (so, parent
|
||||
before children)
|
||||
- they are updated only if they are in the DOM
|
||||
before children),
|
||||
- they are updated only if they are in the DOM,
|
||||
- if a parent is asynchronous, the system will wait for it to complete its
|
||||
update before updating other components.
|
||||
update before updating other components,
|
||||
- in general, updates are not coordinated. This is not a problem for synchronous
|
||||
components, but if there are many asynchronous components, this could lead to
|
||||
a situation where some part of the UI is updated and other parts of the UI is
|
||||
a situation where some part of the UI is updated and some other part of the UI is
|
||||
not updated.
|
||||
|
||||
### Good Practices
|
||||
|
||||
- avoid asynchronous components as much as possible. Asynchronous components
|
||||
lead to situations where parts of the UI is not updated immediately.
|
||||
lead to situations where parts of the UI is not updated immediately,
|
||||
- do not be afraid to connect many components, parent or children if needed. For
|
||||
example, a `MessageList` component could get a list of ids in its `mapStoreToProps` and a `Message` component could get the data of its own
|
||||
message
|
||||
- since the `mapStoreToProps` function is called for each connected component,
|
||||
example, a `MessageList` component could get a list of ids in its `useStore`
|
||||
call and a `Message` component could get the data of its own
|
||||
message,
|
||||
- since the `useStore` function is called for each connected component,
|
||||
for each state update, it is important to make sure that these functions are
|
||||
as fast as possible.
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# 🦉 Tags 🦉
|
||||
|
||||
Tags are very small helpers to make it easy to write inline templates. There is
|
||||
only one currently available tag: `xml`, but we plan to add other tags later,
|
||||
such as a `css` tag, which will be used to write single file components.
|
||||
|
||||
## XML tag
|
||||
|
||||
Without tags, creating a standalone component would look like this:
|
||||
|
||||
```js
|
||||
import { Component } from 'owl'
|
||||
|
||||
const name = 'some-unique-name';
|
||||
const template = `
|
||||
<div>
|
||||
<span t-if="somecondition">text</span>
|
||||
<button t-on-click="someMethod">Click</button>
|
||||
</div>
|
||||
`;
|
||||
QWeb.registerTemplate(name, template);
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = name;
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
With tags, this process is slightly simplified. The name is uniquely generated,
|
||||
and the template is automatically registered:
|
||||
|
||||
```js
|
||||
import { Component } from 'owl'
|
||||
import { xml } from 'owl/tags'
|
||||
|
||||
class MyComponent extends Component {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-if="somecondition">text</span>
|
||||
<button t-on-click="someMethod">Click</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
+30
-1
@@ -6,6 +6,7 @@
|
||||
- [Development Mode](#development-mode)
|
||||
- [Playground](#playground)
|
||||
- [Benchmarks](#benchmarks)
|
||||
- [Single File Component](#single-file-component)
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -38,7 +39,7 @@ Note that templates compiled with the `prod` settings will not be recompiled.
|
||||
So, changing this setting is best done at startup.
|
||||
|
||||
An important job done by the `dev` mode is to validate props for each component
|
||||
creation and update. Also, extra props will cause an error.
|
||||
creation and update. Also, extra props will cause an error.
|
||||
|
||||
## Playground
|
||||
|
||||
@@ -56,3 +57,31 @@ Note: This is more an internal tool, useful for people working on Owl.
|
||||
The benchmarks application is a very small application, implemented in different
|
||||
frameworks, and in different versions of Owl. This is a simple internal tool,
|
||||
useful to compare various performance metrics on some tasks.
|
||||
|
||||
## Single File Component
|
||||
|
||||
If you want to have `xml` syntax highlighting while using the `xml` helper which
|
||||
helps you define inline templates, there is a VS Code addon `Comment tagged template`
|
||||
which, if installed, does exactly that. To enable it, you need to add a comment,
|
||||
like this:
|
||||
|
||||
```js
|
||||
// -----------------------------------------------------------------------------
|
||||
// TEMPLATE
|
||||
// -----------------------------------------------------------------------------
|
||||
const TEMPLATE = xml/* xml */ `
|
||||
<div class="main two-columns">
|
||||
<Sidebar/>
|
||||
<Content />
|
||||
</div>`;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// CODE
|
||||
// -----------------------------------------------------------------------------
|
||||
class MyComponent extends Component {
|
||||
static template = TEMPLATE;
|
||||
static components = { Sidebar, Content };
|
||||
|
||||
// rest of component...
|
||||
}
|
||||
```
|
||||
|
||||
+93
-10
@@ -7,9 +7,10 @@ functions are all available in the `owl.utils` namespace.
|
||||
|
||||
- [`whenReady`](#whenready): executing code when DOM is ready
|
||||
- [`loadJS`](#loadjs): loading script files
|
||||
- [`loadTemplates`](#loadtemplates): loading xml files
|
||||
- [`loadFile`](#loadfile): loading a file (useful for templates)
|
||||
- [`escape`](#escape): sanitizing strings
|
||||
- [`debounce`](#debounce): limiting rate of function calls
|
||||
- [`shallowEqual`](#shallowequal): shallow object comparison
|
||||
|
||||
## `whenReady`
|
||||
|
||||
@@ -18,15 +19,15 @@ not ready yet, resolved directly otherwise). If called with a callback as
|
||||
argument, it executes it as soon as the DOM ready (or directly).
|
||||
|
||||
```js
|
||||
Promise.all([loadTemplates(), owl.utils.whenReady()]).then(function([
|
||||
templates
|
||||
]) {
|
||||
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
|
||||
const qweb = new owl.QWeb(templates);
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
or alternatively:
|
||||
|
||||
```js
|
||||
owl.utils.whenReady(function() {
|
||||
const qweb = new owl.QWeb();
|
||||
@@ -37,10 +38,12 @@ owl.utils.whenReady(function() {
|
||||
|
||||
## `loadJS`
|
||||
|
||||
`loadJS` takes a url (string) for a javascript resource, and loads it. It returns
|
||||
a promise, so the caller can properly react when it is ready. Also, it is smart:
|
||||
it maintains a list of urls previously loaded (or currently being loaded), and
|
||||
prevent doing twice the work.
|
||||
`loadJS` takes a url (string) for a javascript resource, and loads it (by adding
|
||||
a script tag in the document head). It returns a promise, so the caller can
|
||||
properly reacts when it is ready. Also, it is smart: it maintains a list of urls
|
||||
previously loaded (or currently being loaded), and prevent doing twice the work.
|
||||
|
||||
For example, it is useful for lazy loading external libraries:
|
||||
|
||||
```js
|
||||
class MyComponent extends owl.Component {
|
||||
@@ -50,16 +53,96 @@ class MyComponent extends owl.Component {
|
||||
}
|
||||
```
|
||||
|
||||
## `loadTemplates`
|
||||
## `loadFile`
|
||||
|
||||
`loadFile` is a helper function to fetch a file. It simply
|
||||
performs a `GET` request and returns the resulting string in a promise. The
|
||||
initial usecase for this function is to load a template file. For example:
|
||||
|
||||
```js
|
||||
async function makeEnv() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const templates = await owl.utils.loadFile("templates.xml");
|
||||
const qweb = new owl.QWeb(templates);
|
||||
return { qweb };
|
||||
}
|
||||
```
|
||||
|
||||
Note that unlike `loadJS`, this function returns the content of the file as a
|
||||
string. It does not add a `script` tag or any other side effect.
|
||||
|
||||
## `escape`
|
||||
|
||||
Sometimes, we need to display dynamic data (for example user-generated data) in
|
||||
the user interface. If this is done by a `QWeb` template, it is not an issue:
|
||||
|
||||
```xml
|
||||
<div><t t-esc="user.data"/></div>
|
||||
```
|
||||
|
||||
The `QWeb` engine will create a `div` node and add the content of the `user.data`
|
||||
string as a text node, so the web browser will not parse it as html. However,
|
||||
it may be a problem if this is done with some javascript code like this:
|
||||
|
||||
```js
|
||||
class BadComponent extends Component {
|
||||
// some template with a ref to a div
|
||||
// some code ...
|
||||
|
||||
mounted() {
|
||||
this.divRef.el.innerHTML = this.state.value;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this case, the content of the `div` will be parsed as html, which may inject
|
||||
unwanted behaviour. To fix this, the `escape` function will simply transform a
|
||||
string into an escaped version of the same string, which will be properly displayed
|
||||
by the browser, but which will not be parsed as html (for example, `"<ok>"` is
|
||||
escaped to the string: `"<ok>"`). So, the bad example above can be fixed
|
||||
with the following change:
|
||||
|
||||
```js
|
||||
this.divRef.el.innerHTML = owl.utils.escape(this.state.value);
|
||||
```
|
||||
|
||||
## `debounce`
|
||||
|
||||
The `debounce` function is useful when we want to limit the number of times some
|
||||
function/action is perfomed. For example, this may be useful to prevent issue
|
||||
with people double clicking on a button.
|
||||
|
||||
It takes three arguments:
|
||||
|
||||
- `func` (function): this is the function that will be rate limited
|
||||
- `wait` (number): this is the number of milliseconds that we want to use to
|
||||
rate limit the function `func`
|
||||
- `immediate` (optional, boolean, default=false): if `immediate` is true, the
|
||||
function will be triggered immediately (leading edge of the interval). If false,
|
||||
the function will be triggered at the end (trailing edge).
|
||||
|
||||
It returns a function. For example:
|
||||
|
||||
```js
|
||||
const debounce = owl.utils.debounce;
|
||||
window.addEventListener("mousemove", debounce(doSomething, 100));
|
||||
```
|
||||
|
||||
As this example shows, it is usualy useful for event handlers which are triggered
|
||||
very quickly, such as `scroll` or `mousemove` events.
|
||||
|
||||
## `shallowEqual`
|
||||
|
||||
This function checks if two objects have the same values assigned to each keys:
|
||||
|
||||
```js
|
||||
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
|
||||
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false
|
||||
```
|
||||
|
||||
However, for performance reasons, it assumes that the two objects have the same
|
||||
keys. If we are in a situation where this is not guaranteed, the following code
|
||||
will work:
|
||||
|
||||
```js
|
||||
const completeShallowEqual = (a, b) => shallowEqual(a, b) && shallowEqual(b, a);
|
||||
```
|
||||
|
||||
+6
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "owl",
|
||||
"version": "0.19.0",
|
||||
"name": "owl-framework",
|
||||
"version": "0.24.0",
|
||||
"description": "Odoo Web Library (OWL)",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
@@ -14,18 +14,20 @@
|
||||
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
||||
"tools": "npm run build && npm run tools:serve",
|
||||
"pretools:watch": "npm run build",
|
||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\""
|
||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
||||
"prettier": "prettier {src/**/*.ts,tests/**/*.ts,doc/**/*.md} --write"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/odoo/owl.git"
|
||||
},
|
||||
"author": "Odoo",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"license": "LGPL",
|
||||
"bugs": {
|
||||
"url": "https://github.com/odoo/owl/issues"
|
||||
},
|
||||
"homepage": "https://github.com/odoo/owl#readme",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^23.3.12",
|
||||
"cpx": "^1.5.0",
|
||||
@@ -42,7 +44,6 @@
|
||||
"typescript": "^3.2.2",
|
||||
"uglify-es": "^3.3.9"
|
||||
},
|
||||
"dependencies": {},
|
||||
"jest": {
|
||||
"roots": [
|
||||
"<rootDir>/src",
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# 🦉 OWL Roadmap 🦉
|
||||
|
||||
- Current version: 0.24.0
|
||||
- Status: mostly stable
|
||||
|
||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||
change!
|
||||
|
||||
### October 2019
|
||||
|
||||
We plan to complete the following tasks:
|
||||
|
||||
- improve API for root widgets (issue #306),
|
||||
- replace `t-keepalive`, and maybe `t-transition` by components (issue #295).
|
||||
|
||||
### November 2019
|
||||
|
||||
Once the previous tasks are done, release version 1.0alpha. This means that the
|
||||
API should be stable. But it could change a little bit if we need it for our
|
||||
work on Odoo.
|
||||
|
||||
### End of 2019
|
||||
|
||||
Release v1.0
|
||||
|
||||
- API should be stable,
|
||||
- we will use semantic versioning,
|
||||
- we will maintain a changelog and an upgrade guide.
|
||||
|
||||
### 1.x
|
||||
|
||||
- add chrome and firefox devtools,
|
||||
- add support for single file components,
|
||||
- fix every bugs,
|
||||
- improve documentation,
|
||||
- small backward compatible improvements.
|
||||
|
||||
### 2.x (2021? 2022?)
|
||||
|
||||
Maybe:
|
||||
|
||||
- reimplement vdom to use *block* system, like Vue 3,
|
||||
- refactor `QWeb` to use an intermediate representation (some kind of AST) to
|
||||
allow additional optimisations.
|
||||
|
||||
|
||||
+173
-210
@@ -2,7 +2,9 @@ import { Observer } from "../core/observer";
|
||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
||||
import { h, patch, VNode } from "../vdom/index";
|
||||
import "./directive";
|
||||
import { Fiber } from "./fiber";
|
||||
import "./props_validation";
|
||||
import { Scheduler } from "./scheduler";
|
||||
|
||||
/**
|
||||
* Owl Component System
|
||||
@@ -11,13 +13,15 @@ import "./props_validation";
|
||||
* contains:
|
||||
*
|
||||
* - the Env interface (generic type for the environment)
|
||||
* - the Meta interface (the owl specific metadata attached to a component)
|
||||
* - the Internal interface (the owl specific metadata attached to a component)
|
||||
* - the Component class
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
const raf = window.requestAnimationFrame.bind(window);
|
||||
export const scheduler = new Scheduler(raf);
|
||||
|
||||
/**
|
||||
* An Env (environment) is an object that will be (mostly) shared between all
|
||||
@@ -43,47 +47,47 @@ interface Internal<T extends Env, Props> {
|
||||
// relationships
|
||||
readonly id: number;
|
||||
vnode: VNode | null;
|
||||
pvnode: VNode | null;
|
||||
isMounted: boolean;
|
||||
isDestroyed: boolean;
|
||||
|
||||
// parent and children keys are obviously useful to setup the parent-children
|
||||
// relationship.
|
||||
parent: Component<T, any, any> | null;
|
||||
children: { [key: number]: Component<T, any, any> };
|
||||
parent: Component<T, any> | null;
|
||||
children: { [key: number]: Component<T, any> };
|
||||
// children mapping: from templateID to componentID. templateID identifies a
|
||||
// place in a template. The t-component directive needs it to be able to get
|
||||
// the component instance back whenever the template is rerendered.
|
||||
cmap: { [key: number]: number };
|
||||
|
||||
renderId: number;
|
||||
|
||||
// the renderProps and renderPromise keys are only useful for the "prepare"
|
||||
// step of the lifecycle of a component. Once a component has been rendered
|
||||
// and patched, it is no longer useful.
|
||||
renderProps: Props | null;
|
||||
renderPromise: Promise<VNode> | null;
|
||||
currentFiber: Fiber | null;
|
||||
|
||||
boundHandlers: { [key: number]: any };
|
||||
observer: Observer | null;
|
||||
render: CompiledTemplate | null;
|
||||
mountedHandlers: { [key: number]: Function };
|
||||
renderFn: CompiledTemplate;
|
||||
mountedCB: Function | null;
|
||||
willUnmountCB: Function | null;
|
||||
willPatchCB: Function | null;
|
||||
patchedCB: Function | null;
|
||||
willStartCB: Function | null;
|
||||
willUpdatePropsCB: Function | null;
|
||||
classObj: { [key: string]: boolean } | null;
|
||||
refs: { [key: string]: Component<T, any> | HTMLElement | undefined } | null;
|
||||
}
|
||||
|
||||
// If a component does not define explicitely a template
|
||||
// key, it needs to find a template with its name (or a parent's). This is
|
||||
// qweb dependant, so we need a place to store this information indexed by
|
||||
// qweb instances.
|
||||
const TEMPLATE_MAP: { [key: number]: { [name: string]: string } } = {};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Component
|
||||
//------------------------------------------------------------------------------
|
||||
let nextId = 1;
|
||||
|
||||
export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
export class Component<T extends Env, Props extends {}> {
|
||||
readonly __owl__: Internal<Env, Props>;
|
||||
template?: string;
|
||||
static template?: string | null = null;
|
||||
static _template?: string | null = null;
|
||||
static current: Component<any, any> | null = null;
|
||||
static components = {};
|
||||
static props?: any;
|
||||
static defaultProps?: any;
|
||||
|
||||
/**
|
||||
* The `el` is the root element of the component. Note that it could be null:
|
||||
@@ -94,17 +98,8 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
|
||||
env: T;
|
||||
state?: State;
|
||||
props: Props;
|
||||
|
||||
// type of props is not easily representable in typescript...
|
||||
static props?: any;
|
||||
static defaultProps?: any;
|
||||
|
||||
refs: {
|
||||
[key: string]: Component<T, any, any> | HTMLElement | undefined;
|
||||
} = {};
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
//--------------------------------------------------------------------------
|
||||
@@ -128,8 +123,9 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
* hand. Other components should be created automatically by the framework (with
|
||||
* the t-component directive in a template)
|
||||
*/
|
||||
constructor(parent: Component<T, any, any> | T, props?: Props) {
|
||||
constructor(parent: Component<T, any> | T, props?: Props) {
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
Component.current = this;
|
||||
if (defaultProps) {
|
||||
props = this.__applyDefaultProps(props, defaultProps);
|
||||
}
|
||||
@@ -139,7 +135,7 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
// Pro: but creating component (by a template) is always unsafe anyway
|
||||
this.props = <Props>props || <Props>{};
|
||||
let id: number = nextId++;
|
||||
let p: Component<T, any, any> | null = null;
|
||||
let p: Component<T, any> | null = null;
|
||||
if (parent instanceof Component) {
|
||||
p = parent;
|
||||
this.env = parent.env;
|
||||
@@ -165,22 +161,29 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
});
|
||||
}
|
||||
const qweb = this.env.qweb;
|
||||
|
||||
this.__owl__ = {
|
||||
id: id,
|
||||
vnode: null,
|
||||
pvnode: null,
|
||||
isMounted: false,
|
||||
isDestroyed: false,
|
||||
parent: p,
|
||||
children: {},
|
||||
cmap: {},
|
||||
renderId: 1,
|
||||
renderPromise: null,
|
||||
renderProps: props || null,
|
||||
currentFiber: null,
|
||||
boundHandlers: {},
|
||||
mountedHandlers: {},
|
||||
mountedCB: null,
|
||||
willUnmountCB: null,
|
||||
willPatchCB: null,
|
||||
patchedCB: null,
|
||||
willStartCB: null,
|
||||
willUpdatePropsCB: null,
|
||||
observer: null,
|
||||
render: null,
|
||||
classObj: null
|
||||
renderFn: qweb.render.bind(qweb, this.__getTemplate(qweb)),
|
||||
classObj: null,
|
||||
refs: null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -227,8 +230,6 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
* It is not called on the initial render. This is useful to get some
|
||||
* information which are in the DOM. For example, the current position of the
|
||||
* scrollbar
|
||||
*
|
||||
* The return value of willPatch will be given to the patched function.
|
||||
*/
|
||||
willPatch(): any {}
|
||||
|
||||
@@ -244,10 +245,8 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
* One need to be careful, because updates here will cause rerender, which in
|
||||
* turn will cause other calls to updated. So, we need to be particularly
|
||||
* careful at avoiding endless cycles.
|
||||
*
|
||||
* The snapshot parameter is the result of the call to willPatch.
|
||||
*/
|
||||
patched(snapshot: any) {}
|
||||
patched() {}
|
||||
|
||||
/**
|
||||
* willUnmount is a hook that is called each time just before a component is
|
||||
@@ -281,25 +280,33 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
async mount(target: HTMLElement, renderBeforeRemount: boolean = false): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.isMounted) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (__owl__.vnode && !renderBeforeRemount) {
|
||||
target.appendChild(this.el!);
|
||||
if (document.body.contains(target)) {
|
||||
this.__callMounted();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, false);
|
||||
if (!__owl__.vnode) {
|
||||
const vnode = await this.__prepare();
|
||||
if (__owl__.isDestroyed) {
|
||||
// component was destroyed before we get here...
|
||||
return;
|
||||
}
|
||||
this.__patch(vnode);
|
||||
} else if (renderBeforeRemount) {
|
||||
const patchQueue = [];
|
||||
await this.__render(false, patchQueue, undefined, undefined);
|
||||
this.__applyPatchQueue(<any[]>patchQueue);
|
||||
}
|
||||
target.appendChild(this.el!);
|
||||
|
||||
if (document.body.contains(target)) {
|
||||
this.__callMounted();
|
||||
this.__prepareAndRender(fiber);
|
||||
} else {
|
||||
this.__render(fiber);
|
||||
}
|
||||
return new Promise(resolve => {
|
||||
scheduler.addFiber(fiber, () => {
|
||||
if (!__owl__.isDestroyed) {
|
||||
this.__patch(fiber.vnode);
|
||||
target.appendChild(this.el!);
|
||||
if (document.body.contains(target)) {
|
||||
this.__callMounted();
|
||||
}
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -324,19 +331,22 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
*/
|
||||
async render(force: boolean = false): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (!__owl__.isMounted) {
|
||||
if (
|
||||
(!__owl__.isMounted && !__owl__.currentFiber) ||
|
||||
(__owl__.currentFiber && !__owl__.currentFiber.isRendered)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const patchQueue = [];
|
||||
|
||||
const renderId = ++__owl__.renderId;
|
||||
await this.__render(force, patchQueue, undefined, undefined);
|
||||
|
||||
if (__owl__.isMounted && renderId === __owl__.renderId) {
|
||||
// we only update the vnode and the actual DOM if no other rendering
|
||||
// occurred between now and when the render method was initially called.
|
||||
this.__applyPatchQueue(<any[]>patchQueue);
|
||||
}
|
||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, force);
|
||||
this.__render(fiber);
|
||||
return new Promise(resolve => {
|
||||
scheduler.addFiber(fiber.root, () => {
|
||||
if (__owl__.isMounted && fiber === fiber.root) {
|
||||
fiber.patchComponents();
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -368,26 +378,6 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is the correct way to update the environment of a component. Doing
|
||||
* this will cause a full rerender of the component and its children, so this is
|
||||
* an operation that should not be done frequently.
|
||||
*
|
||||
* A good usecase for updating the environment would be to update some mostly
|
||||
* static config keys, such as a boolean to determine if we are in mobile
|
||||
* mode or not.
|
||||
*/
|
||||
async updateEnv(nextEnv: Partial<T>): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.parent && __owl__.parent.env === this.env) {
|
||||
this.env = Object.create(this.env);
|
||||
}
|
||||
Object.assign(this.env, nextEnv);
|
||||
if (__owl__.isMounted) {
|
||||
await this.render(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a custom event of type 'eventType' with the given 'payload' on the
|
||||
* component's el, if it exists. However, note that the event will only bubble
|
||||
@@ -420,10 +410,13 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
* Note that it does not call the __callWillUnmount method to avoid visiting
|
||||
* all children many times.
|
||||
*/
|
||||
__destroy(parent: Component<any, any, any> | null) {
|
||||
__destroy(parent: Component<any, any> | null) {
|
||||
const __owl__ = this.__owl__;
|
||||
const isMounted = __owl__.isMounted;
|
||||
if (isMounted) {
|
||||
if (__owl__.willUnmountCB) {
|
||||
__owl__.willUnmountCB();
|
||||
}
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
}
|
||||
@@ -450,20 +443,22 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
}
|
||||
__owl__.isMounted = true;
|
||||
const handlers = __owl__.mountedHandlers;
|
||||
for (let key in handlers) {
|
||||
handlers[key]();
|
||||
}
|
||||
try {
|
||||
this.mounted();
|
||||
if (__owl__.mountedCB) {
|
||||
__owl__.mountedCB();
|
||||
}
|
||||
} catch (e) {
|
||||
errorHandler(e, this);
|
||||
console.error(e); // TODO : add a test
|
||||
}
|
||||
}
|
||||
|
||||
__callWillUnmount() {
|
||||
this.willUnmount();
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.willUnmountCB) {
|
||||
__owl__.willUnmountCB();
|
||||
}
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
@@ -480,20 +475,35 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
*/
|
||||
async __updateProps(
|
||||
nextProps: Props,
|
||||
forceUpdate: boolean = false,
|
||||
patchQueue?: any[],
|
||||
scope?: any,
|
||||
vars?: any
|
||||
parentFiber: Fiber,
|
||||
scope: any,
|
||||
vars: any,
|
||||
previousSibling?: Fiber | null
|
||||
): Promise<void> {
|
||||
const shouldUpdate = forceUpdate || this.shouldUpdate(nextProps);
|
||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||
if (shouldUpdate) {
|
||||
const __owl__ = this.__owl__;
|
||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
} else {
|
||||
previousSibling!.sibling = fiber;
|
||||
}
|
||||
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
if (defaultProps) {
|
||||
nextProps = this.__applyDefaultProps(nextProps, defaultProps);
|
||||
}
|
||||
await this.willUpdateProps(nextProps);
|
||||
await Promise.all([
|
||||
this.willUpdateProps(nextProps),
|
||||
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps)
|
||||
]);
|
||||
if (fiber.isCancelled) {
|
||||
return;
|
||||
}
|
||||
this.props = nextProps;
|
||||
await this.__render(forceUpdate, patchQueue, scope, vars);
|
||||
|
||||
this.__render(fiber);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -505,115 +515,108 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
const __owl__ = this.__owl__;
|
||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
||||
__owl__.vnode = patch(target, vnode);
|
||||
__owl__.currentFiber = null;
|
||||
}
|
||||
|
||||
__prepare(scope?: Object, vars?: any): Promise<VNode> {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.renderProps = this.props;
|
||||
__owl__.renderPromise = this.__prepareAndRender(scope, vars);
|
||||
return __owl__.renderPromise;
|
||||
/**
|
||||
* The __prepare method is only called by the t-component directive, when a
|
||||
* subcomponent is created. It gets its scope and vars, if any, from the
|
||||
* parent template.
|
||||
*/
|
||||
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
||||
fiber.shouldPatch = false;
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
} else {
|
||||
previousSibling!.sibling = fiber;
|
||||
}
|
||||
return this.__prepareAndRender(fiber);
|
||||
}
|
||||
|
||||
async __prepareAndRender(scope?: Object, vars?: any): Promise<VNode> {
|
||||
try {
|
||||
await this.willStart();
|
||||
} catch (e) {
|
||||
errorHandler(e, this);
|
||||
return Promise.resolve(h("div"));
|
||||
}
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.isDestroyed) {
|
||||
return Promise.resolve(h("div"));
|
||||
}
|
||||
const qweb = this.env.qweb;
|
||||
if (!this.template) {
|
||||
let tmap = TEMPLATE_MAP[qweb.id];
|
||||
if (!tmap) {
|
||||
tmap = {};
|
||||
TEMPLATE_MAP[qweb.id] = tmap;
|
||||
}
|
||||
let p = (<any>this).constructor;
|
||||
let name: string = p.name;
|
||||
let template = tmap[name];
|
||||
if (template) {
|
||||
this.template = template;
|
||||
__getTemplate(qweb: QWeb): string {
|
||||
let p = (<any>this).constructor;
|
||||
if (!p.hasOwnProperty("_template")) {
|
||||
if (p.template) {
|
||||
p._template = p.template;
|
||||
} else {
|
||||
// here, the component and none of its superclasses defines a static `template`
|
||||
// key. So we fall back on looking for a template matching its name (or
|
||||
// one of its subclass).
|
||||
|
||||
let template: string;
|
||||
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
||||
p = p.__proto__;
|
||||
}
|
||||
if (p === Component) {
|
||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
||||
} else {
|
||||
tmap[name] = template;
|
||||
this.template = template;
|
||||
p._template = template;
|
||||
}
|
||||
}
|
||||
}
|
||||
__owl__.render = qweb.render.bind(qweb, this.template);
|
||||
this.__observeState();
|
||||
|
||||
return this.__render(false, [], scope, vars);
|
||||
return p._template;
|
||||
}
|
||||
async __prepareAndRender(fiber: Fiber) {
|
||||
try {
|
||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
||||
} catch (e) {
|
||||
errorHandler(e, fiber);
|
||||
fiber.vnode = h("div"); // -> we render this div at the end
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this.__owl__.isDestroyed) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!fiber.isCancelled) {
|
||||
this.__render(fiber);
|
||||
}
|
||||
}
|
||||
|
||||
__render(
|
||||
force: boolean = false,
|
||||
patchQueue: any[] = [],
|
||||
scope?: Object,
|
||||
vars?: any
|
||||
): Promise<VNode> {
|
||||
__render(fiber: Fiber) {
|
||||
const __owl__ = this.__owl__;
|
||||
const promises: Promise<void>[] = [];
|
||||
const patch: any[] = [this];
|
||||
patchQueue.push(patch);
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = false;
|
||||
}
|
||||
let vnode;
|
||||
try {
|
||||
vnode = __owl__.render!(this, {
|
||||
promises,
|
||||
vnode = __owl__.renderFn!(this, {
|
||||
handlers: __owl__.boundHandlers,
|
||||
mountedHandlers: __owl__.mountedHandlers,
|
||||
forceUpdate: force,
|
||||
patchQueue,
|
||||
scope,
|
||||
vars
|
||||
fiber: fiber
|
||||
});
|
||||
} catch (e) {
|
||||
vnode = __owl__.vnode || h("div");
|
||||
errorHandler(e, this);
|
||||
errorHandler(e, fiber);
|
||||
}
|
||||
patch.push(vnode);
|
||||
fiber.vnode = vnode;
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = true;
|
||||
}
|
||||
|
||||
// this part is critical for the patching process to be done correctly. The
|
||||
// tricky part is that a child component can be rerendered on its own, which
|
||||
// will update its own vnode representation without the knowledge of the
|
||||
// parent component. With this, we make sure that the parent component will be
|
||||
// able to patch itself properly after
|
||||
vnode.key = __owl__.id;
|
||||
|
||||
// we applly here the class information described on the component by the
|
||||
// we apply here the class information described on the component by the
|
||||
// template (so, something like <MyComponent class="..."/>) to the actual
|
||||
// root vnode
|
||||
if (__owl__.classObj) {
|
||||
vnode.data.class = Object.assign(vnode.data.class || {}, __owl__.classObj);
|
||||
}
|
||||
|
||||
return Promise.all(promises).then(() => vnode);
|
||||
fiber.root.counter--;
|
||||
fiber.isRendered = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called by qweb t-component directive
|
||||
*/
|
||||
__mount(vnode: VNode, elm: HTMLElement): VNode {
|
||||
__mount(fiber: Fiber, elm: HTMLElement): VNode {
|
||||
if (fiber !== this.__owl__.currentFiber) {
|
||||
fiber = this.__owl__.currentFiber!; // TODO: check if we can remove fiber arg
|
||||
}
|
||||
const vnode = fiber.vnode!;
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.classObj) {
|
||||
(<any>vnode).data.class = Object.assign((<any>vnode).data.class || {}, __owl__.classObj);
|
||||
}
|
||||
__owl__.vnode = patch(elm, vnode);
|
||||
__owl__.currentFiber = null;
|
||||
if (__owl__.parent!.__owl__.isMounted && !__owl__.isMounted) {
|
||||
this.__callMounted();
|
||||
}
|
||||
@@ -631,19 +634,6 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the observe feature on the state. We only create an observer if
|
||||
* there is some state to be observed.
|
||||
*/
|
||||
__observeState() {
|
||||
if (this.state) {
|
||||
const __owl__ = this.__owl__;
|
||||
__owl__.observer = new Observer();
|
||||
this.state = __owl__.observer.observe(this.state);
|
||||
__owl__.observer.notifyCB = this.render.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply default props (only top level).
|
||||
*
|
||||
@@ -659,42 +649,15 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
return <Props>props;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the given patch queue. A patch is a pair [c, vn], where c is a
|
||||
* Component instance and vn a VNode.
|
||||
* 1) Call 'willPatch' on the component of each patch
|
||||
* 2) Call '__patch' on the component of each patch
|
||||
* 3) Call 'patched' on the component of each patch, in inverse order
|
||||
*/
|
||||
__applyPatchQueue(patchQueue: any[]) {
|
||||
let component = this;
|
||||
try {
|
||||
const patchLen = patchQueue.length;
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const patch = patchQueue[i];
|
||||
component = patch[0];
|
||||
patch.push(patch[0].willPatch());
|
||||
}
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const patch = patchQueue[i];
|
||||
patch[0].__patch(patch[1]);
|
||||
}
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
const patch = patchQueue[i];
|
||||
component = patch[0];
|
||||
patch[0].patched(patch[2]);
|
||||
}
|
||||
} catch (e) {
|
||||
errorHandler(e, component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Error handling
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
Fiber.prototype.handleError = function(error) {
|
||||
errorHandler(error, this);
|
||||
};
|
||||
/**
|
||||
* This is the global error handler for errors occurring in Owl main lifecycle
|
||||
* methods. Caught errors are triggered on the QWeb instance, and are
|
||||
@@ -703,8 +666,9 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
* If there are no such component, we destroy everything. This is better than
|
||||
* being in a corrupted state.
|
||||
*/
|
||||
function errorHandler(error: Error, component: Component<any, any, any>) {
|
||||
function errorHandler(error: Error, fiber: Fiber) {
|
||||
let canCatch = false;
|
||||
let component = fiber.component;
|
||||
let qweb = component.env.qweb;
|
||||
let root = component;
|
||||
while (component && !(canCatch = component.catchError !== Component.prototype.catchError)) {
|
||||
@@ -712,7 +676,6 @@ function errorHandler(error: Error, component: Component<any, any, any>) {
|
||||
component = component.__owl__.parent!;
|
||||
}
|
||||
console.error(error);
|
||||
// we trigger error on QWeb so it can be logged/handled
|
||||
qweb.trigger("error", error);
|
||||
|
||||
if (canCatch) {
|
||||
|
||||
+138
-128
@@ -1,4 +1,5 @@
|
||||
import { QWeb } from "../qweb/index";
|
||||
import { INTERP_REGEXP } from "../qweb/compilation_context";
|
||||
import { MODS_CODE } from "../qweb/extensions";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -185,7 +186,7 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "component",
|
||||
extraNames: ["props", "keepalive", "asyncroot"],
|
||||
extraNames: ["props", "keepalive"],
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
ctx.addLine("//COMPONENT");
|
||||
@@ -194,7 +195,7 @@ QWeb.addDirective({
|
||||
ctx.rootContext.shouldDefineParent = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
||||
let async = node.getAttribute("t-asyncroot") ? true : false;
|
||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||
|
||||
// t-on- events and t-transition
|
||||
const events: [string, string[], string, string][] = [];
|
||||
@@ -207,11 +208,11 @@ QWeb.addDirective({
|
||||
if (name.startsWith("t-on-")) {
|
||||
const [eventName, ...mods] = name.slice(5).split(".");
|
||||
let extraArgs;
|
||||
let handlerName = value.replace(/\(.*\)/, function(args) {
|
||||
let handlerValue = value.replace(/\(.*\)/, function(args) {
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
events.push([eventName, mods, handlerName, extraArgs]);
|
||||
events.push([eventName, mods, handlerValue, extraArgs]);
|
||||
} else if (name === "t-transition") {
|
||||
transition = value;
|
||||
} else if (!name.startsWith("t-")) {
|
||||
@@ -231,39 +232,36 @@ QWeb.addDirective({
|
||||
let propStr = Object.keys(props)
|
||||
.map(k => k + ":" + props[k])
|
||||
.join(",");
|
||||
let dummyID = ctx.generateID();
|
||||
let defID = ctx.generateID();
|
||||
let componentID = ctx.generateID();
|
||||
let keyID = key && ctx.generateID();
|
||||
if (key) {
|
||||
// we bind a variable to the key (could be a complex expression, so we
|
||||
// want to evaluate it only once)
|
||||
ctx.addLine(`let key${keyID} = ${key};`);
|
||||
ctx.addLine(`let key${keyID} = 'key' + ${key};`);
|
||||
}
|
||||
ctx.addLine(`let def${defID};`);
|
||||
let templateID = key
|
||||
? `key${keyID}`
|
||||
: ctx.inLoop
|
||||
? `String(-${componentID} - i)`
|
||||
: String(componentID);
|
||||
if (ctx.allowMultipleRoots) {
|
||||
// necessary to prevent collisions
|
||||
if (!key && ctx.inLoop) {
|
||||
let id = ctx.generateID();
|
||||
ctx.addLine(`let template${id} = "_slot_" + String(-${componentID} - i)`);
|
||||
templateID = `template${id}`;
|
||||
} else {
|
||||
templateID = `"_slot_${templateID}"`;
|
||||
}
|
||||
|
||||
let locationExpr = `\`__${ctx.generateID()}__`;
|
||||
for (let i = 0; i < ctx.loopNumber - 1; i++) {
|
||||
locationExpr += `\${i${i + 1}}__`;
|
||||
}
|
||||
if (key || ctx.currentKey) {
|
||||
const k = key ? `key${keyID}` : ctx.currentKey;
|
||||
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
|
||||
} else {
|
||||
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
|
||||
ctx.addLine(`let templateId${componentID} = ${locationExpr};`);
|
||||
}
|
||||
const templateId = `templateId${componentID}`;
|
||||
|
||||
let ref = node.getAttribute("t-ref");
|
||||
let refExpr = "";
|
||||
let refKey: string = "";
|
||||
if (ref) {
|
||||
ctx.rootContext.shouldDefineRefs = true;
|
||||
refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
||||
refExpr = `context.refs[${refKey}] = w${componentID};`;
|
||||
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
||||
}
|
||||
let transitionsInsertCode = "";
|
||||
if (transition) {
|
||||
@@ -271,7 +269,7 @@ QWeb.addDirective({
|
||||
}
|
||||
let finalizeComponentCode = `w${componentID}.${keepAlive ? "unmount" : "destroy"}();`;
|
||||
if (ref && !keepAlive) {
|
||||
finalizeComponentCode += `delete context.refs[${refKey}];`;
|
||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||
}
|
||||
if (transition) {
|
||||
finalizeComponentCode = `let finalize = () => {
|
||||
@@ -314,10 +312,10 @@ QWeb.addDirective({
|
||||
}
|
||||
}
|
||||
let eventsCode = events
|
||||
.map(function([eventName, mods, handlerName, extraArgs]) {
|
||||
.map(function([eventName, mods, handlerValue, extraArgs]) {
|
||||
let params = "owner";
|
||||
if (extraArgs) {
|
||||
if (ctx.inLoop) {
|
||||
if (ctx.loopNumber) {
|
||||
let argId = ctx.generateID();
|
||||
// we need to evaluate the arguments now, because the handler will
|
||||
// be set asynchronously later when the widget is ready, and the
|
||||
@@ -328,18 +326,17 @@ QWeb.addDirective({
|
||||
params = `owner, ${ctx.formatExpression(extraArgs)}`;
|
||||
}
|
||||
}
|
||||
let handler;
|
||||
if (mods.length > 0) {
|
||||
handler = `function (e) {`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return T_COMPONENT_MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
handler += `owner['${handlerName}'].call(${params}, e);}`;
|
||||
} else {
|
||||
handler = `owner['${handlerName}'].bind(${params})`;
|
||||
let handler = `function (e) {`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return T_COMPONENT_MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
if (handlerValue) {
|
||||
handler += `const fn = owner['${handlerValue}'];`;
|
||||
handler += `if (fn) { fn.call(${params}, e); } else { owner.${handlerValue}; }`;
|
||||
}
|
||||
handler += `}`;
|
||||
return `vn.elm.addEventListener('${eventName}', ${handler});`;
|
||||
})
|
||||
.join("");
|
||||
@@ -349,56 +346,39 @@ QWeb.addDirective({
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let w${componentID} = ${templateID} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateID}]] : false;`
|
||||
`let w${componentID} = ${templateId} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateId}]] : false;`
|
||||
);
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
|
||||
}
|
||||
let shouldProxy = false;
|
||||
if (async) {
|
||||
ctx.addLine(`const patchQueue${componentID} = [];`);
|
||||
let shouldProxy = !ctx.parentNode;
|
||||
if (keepAlive) {
|
||||
ctx.addLine(
|
||||
`c${ctx.parentNode}.push(w${componentID} && w${componentID}.__owl__.pvnode || null);`
|
||||
`const fiber${componentID} = Object.assign(Object.create(extra.fiber), {patchQueue: []});`
|
||||
);
|
||||
} else {
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(null);`);
|
||||
} else {
|
||||
let id = ctx.generateID();
|
||||
ctx.rootContext.rootNode = id;
|
||||
shouldProxy = true;
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.addLine(`let vn${id} = {};`);
|
||||
ctx.addLine(`result = vn${id};`);
|
||||
}
|
||||
}
|
||||
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
||||
if (shouldProxy) {
|
||||
let id = ctx.generateID();
|
||||
ctx.rootContext.rootNode = id;
|
||||
shouldProxy = true;
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.addLine(`let vn${id} = {};`);
|
||||
ctx.addLine(`result = vn${id};`);
|
||||
}
|
||||
if (hasDynamicProps) {
|
||||
const dynamicProp = ctx.formatExpression(node.getAttribute("t-props")!);
|
||||
ctx.addLine(`let props${componentID} = Object.assign({${propStr}}, ${dynamicProp});`);
|
||||
} else {
|
||||
ctx.addLine(`let props${componentID} = {${propStr}};`);
|
||||
}
|
||||
ctx.addIf(
|
||||
`w${componentID} && w${componentID}.__owl__.renderPromise && !w${componentID}.__owl__.vnode`
|
||||
`w${componentID} && w${componentID}.__owl__.currentFiber && !w${componentID}.__owl__.vnode`
|
||||
);
|
||||
ctx.addIf(`utils.shallowEqual(props${componentID}, w${componentID}.__owl__.renderProps)`);
|
||||
ctx.addLine(`def${defID} = w${componentID}.__owl__.renderPromise;`);
|
||||
ctx.addElse();
|
||||
ctx.addLine(`w${componentID}.destroy();`);
|
||||
ctx.addLine(`w${componentID} = false;`);
|
||||
ctx.closeIf();
|
||||
ctx.closeIf();
|
||||
|
||||
ctx.addIf(`!w${componentID}`);
|
||||
// new component
|
||||
ctx.addLine(`let componentKey${componentID} = ${ctx.interpolate(value)};`);
|
||||
ctx.addLine(
|
||||
`let W${componentID} = context.components && context.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}];`
|
||||
);
|
||||
// maybe only do this in dev mode...
|
||||
ctx.addLine(
|
||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
||||
);
|
||||
if (QWeb.dev) {
|
||||
ctx.addLine(`utils.validateProps(W${componentID}, props${componentID})`);
|
||||
let registerCode = "";
|
||||
if (shouldProxy) {
|
||||
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
||||
}
|
||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
||||
ctx.addLine(`parent.__owl__.cmap[${templateID}] = w${componentID}.__owl__.id;`);
|
||||
|
||||
// SLOTS
|
||||
const varDefs: string[] = [];
|
||||
@@ -410,10 +390,76 @@ QWeb.addDirective({
|
||||
varDefs.push(v["id"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let scopeVars;
|
||||
if (hasSlots) {
|
||||
let scope = ctx.scopeVars.length ? `Object.assign({}, scope)` : `{}`;
|
||||
let vars = varDefs.length ? `{${varDefs.join(",")}}` : "undefined";
|
||||
scopeVars = `${scope}, ${vars}`;
|
||||
} else {
|
||||
scopeVars = "undefined, undefined";
|
||||
}
|
||||
|
||||
ctx.addIf(`w${componentID}`);
|
||||
|
||||
// need to update component
|
||||
let patchQueueCode = keepAlive ? `fiber${componentID}` : "extra.fiber";
|
||||
if (keepAlive) {
|
||||
// if we have t-keepalive="1", the component could be unmounted, but then
|
||||
// we __updateProps is called. This is ok, but we do not want to call
|
||||
// the willPatch/patched hooks of the component in this case, so we
|
||||
// disable the patch queue
|
||||
patchQueueCode = `w${componentID}.__owl__.isMounted ? extra.fiber : fiber${componentID}`;
|
||||
}
|
||||
if (QWeb.dev) {
|
||||
ctx.addLine(`utils.validateProps(w${componentID}.constructor, props${componentID})`);
|
||||
}
|
||||
let styleCode = "";
|
||||
if (tattStyle) {
|
||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
|
||||
", " + scopeVars}, sibling)${styleCode};`
|
||||
);
|
||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
||||
let keepAliveCode = "";
|
||||
if (keepAlive) {
|
||||
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${componentID}.el,vn.elm);vn.elm=w${componentID}.el;w${componentID}.__remount();};`;
|
||||
ctx.addLine(keepAliveCode);
|
||||
}
|
||||
if (registerCode) {
|
||||
ctx.addLine(registerCode);
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
||||
}
|
||||
|
||||
ctx.addElse();
|
||||
|
||||
// new component
|
||||
let dynamicFallback = "";
|
||||
if (!value.match(INTERP_REGEXP)) {
|
||||
dynamicFallback = `|| ${ctx.formatExpression(value)}`;
|
||||
}
|
||||
const interpValue = ctx.interpolate(value);
|
||||
ctx.addLine(`let componentKey${componentID} = ${interpValue};`);
|
||||
ctx.addLine(
|
||||
`let W${componentID} = context.constructor.components[componentKey${componentID}] || QWeb.components[componentKey${componentID}]${dynamicFallback};`
|
||||
);
|
||||
|
||||
// maybe only do this in dev mode...
|
||||
ctx.addLine(
|
||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
||||
);
|
||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
||||
ctx.addLine(`parent.__owl__.cmap[${templateId}] = w${componentID}.__owl__.id;`);
|
||||
|
||||
if (hasSlots) {
|
||||
const clone = <Element>node.cloneNode(true);
|
||||
const slotNodes = clone.querySelectorAll("[t-set]");
|
||||
const slotId = qweb.nextSlotId++;
|
||||
const slotId = QWeb.nextSlotId++;
|
||||
ctx.addLine(`w${componentID}.__owl__.slotId = ${slotId};`);
|
||||
if (slotNodes.length) {
|
||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
||||
@@ -422,7 +468,7 @@ QWeb.addDirective({
|
||||
const key = slotNode.getAttribute("t-set")!;
|
||||
slotNode.removeAttribute("t-set");
|
||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode, ctx);
|
||||
qweb.slots[`${slotId}_${key}`] = slotFn.bind(qweb);
|
||||
QWeb.slots[`${slotId}_${key}`] = slotFn;
|
||||
}
|
||||
}
|
||||
if (clone.childNodes.length) {
|
||||
@@ -431,70 +477,34 @@ QWeb.addDirective({
|
||||
t.appendChild(child);
|
||||
}
|
||||
const slotFn = qweb._compile(`slot_default_template`, t, ctx);
|
||||
qweb.slots[`${slotId}_default`] = slotFn.bind(qweb);
|
||||
QWeb.slots[`${slotId}_default`] = slotFn;
|
||||
}
|
||||
}
|
||||
|
||||
let scopeVars = "";
|
||||
if (hasSlots) {
|
||||
scopeVars += ctx.scopeVars.length ? `Object.assign({}, scope)` : varDefs.length ? `{}` : "";
|
||||
if (varDefs.length) {
|
||||
scopeVars += `, {${varDefs.join(",")}}`;
|
||||
}
|
||||
}
|
||||
ctx.addLine(`def${defID} = w${componentID}.__prepare(${scopeVars});`);
|
||||
ctx.addLine(`let def${defID} = w${componentID}.__prepare(extra.fiber, ${scopeVars}, sibling);`);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
let registerCode = `c${ctx.parentNode}[_${dummyID}_index]=pvnode;`;
|
||||
if (shouldProxy) {
|
||||
registerCode = `utils.defineProxy(vn${ctx.rootNode}, pvnode);`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`def${defID} = def${defID}.then(vnode=>{${createHook}let pvnode=h(vnode.sel, {key: ${templateID}, hook: {insert(vn) {let nvn=w${componentID}.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeComponentCode}}}});${registerCode}w${componentID}.__owl__.pvnode = pvnode;});`
|
||||
`let pvnode = h('dummy', {key: ${templateId}, hook: {insert(vn) { let nvn=w${componentID}.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeComponentCode}}}});`
|
||||
);
|
||||
ctx.addLine(`const fiber = w${componentID}.__owl__.currentFiber;`);
|
||||
ctx.addLine(
|
||||
`def${defID}.then(function () {if (w${componentID}.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
);
|
||||
if (registerCode) {
|
||||
ctx.addLine(registerCode);
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(pvnode);`);
|
||||
}
|
||||
ctx.addLine(`w${componentID}.__owl__.pvnode = pvnode;`);
|
||||
|
||||
ctx.addElse();
|
||||
// need to update component
|
||||
let patchQueueCode = async ? `patchQueue${componentID}` : "extra.patchQueue";
|
||||
if (keepAlive) {
|
||||
// if we have t-keepalive="1", the component could be unmounted, but then
|
||||
// we __updateProps is called. This is ok, but we do not want to call
|
||||
// the willPatch/patched hooks of the component in this case, so we
|
||||
// disable the patch queue
|
||||
patchQueueCode = `w${componentID}.__owl__.isMounted ? ${patchQueueCode} : []`;
|
||||
}
|
||||
if (QWeb.dev) {
|
||||
ctx.addLine(`utils.validateProps(w${componentID}.constructor, props${componentID})`);
|
||||
}
|
||||
ctx.addLine(
|
||||
`def${defID} = def${defID} || w${componentID}.__updateProps(props${componentID}, extra.forceUpdate, ${patchQueueCode}${scopeVars &&
|
||||
", " + scopeVars});`
|
||||
);
|
||||
let keepAliveCode = "";
|
||||
if (keepAlive) {
|
||||
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${componentID}.el,vn.elm);vn.elm=w${componentID}.el;w${componentID}.__remount();};`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`def${defID} = def${defID}.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};${
|
||||
tattStyle ? `w${componentID}.el.style=${tattStyle};` : ""
|
||||
}let pvnode=w${componentID}.__owl__.pvnode;${keepAliveCode}${registerCode}});`
|
||||
);
|
||||
ctx.closeIf();
|
||||
|
||||
if (classObj) {
|
||||
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
||||
}
|
||||
|
||||
if (async) {
|
||||
ctx.addLine(
|
||||
`def${defID}.then(w${componentID}.__applyPatchQueue.bind(w${componentID}, patchQueue${componentID}));`
|
||||
);
|
||||
} else {
|
||||
ctx.addLine(`extra.promises.push(def${defID});`);
|
||||
}
|
||||
|
||||
if (node.hasAttribute("t-if") || node.hasAttribute("t-else") || node.hasAttribute("t-elif")) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
ctx.addLine(`sibling = w${componentID}.__owl__.currentFiber || sibling;`);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { VNode } from "../vdom/index";
|
||||
import { Component } from "./component";
|
||||
|
||||
/**
|
||||
* Owl Fiber Class
|
||||
*
|
||||
* Fibers are small abstractions designed to contain all the internal state
|
||||
* associated with a "rendering work unit", relative to a specific component.
|
||||
*
|
||||
* A rendering will cause the creation of a fiber for each impacted components.
|
||||
*
|
||||
* Fibers capture all that necessary information, which is critical to owl
|
||||
* asynchronous rendering pipeline. Fibers can be cancelled, can be in different
|
||||
* states and in general determine the state of the rendering.
|
||||
*/
|
||||
|
||||
export class Fiber {
|
||||
// The force attribute determines if a rendering should bypass the `shouldUpdate`
|
||||
// method potentially implemented by a component. It is usually set to false.
|
||||
force: boolean;
|
||||
|
||||
// isCancelled means that the rendering corresponding to this fiber and its
|
||||
// children is cancelled. No extra work should be done.
|
||||
isCancelled: boolean = false;
|
||||
|
||||
// the fibers corresponding to component updates (updateProps) need to call
|
||||
// the willPatch and patched hooks from the corresponding component. However,
|
||||
// fibers corresponding to a new component do not need to do that. So, the
|
||||
// shouldPatch hook is the boolean that we check whenever we need to apply
|
||||
// a patch.
|
||||
shouldPatch: boolean = true;
|
||||
|
||||
// isRendered is the last state of a fiber. If true, this means that it has
|
||||
// been rendered and is inert (so, it should not be taken into account when
|
||||
// counting the number of active fibers).
|
||||
isRendered: boolean = false;
|
||||
|
||||
// the counter number is a critical information. It is only necessary for a
|
||||
// root fiber. For that fiber, this number counts the number of active sub
|
||||
// fibers. When that number reaches 0, the fiber can be applied by the
|
||||
// scheduler.
|
||||
counter: number = 0;
|
||||
|
||||
scope: any;
|
||||
vars: any;
|
||||
props: any;
|
||||
|
||||
component: Component<any, any>;
|
||||
vnode: VNode | null = null;
|
||||
|
||||
root: Fiber;
|
||||
child: Fiber | null = null;
|
||||
sibling: Fiber | null = null;
|
||||
parent: Fiber | null = null;
|
||||
|
||||
constructor(parent: Fiber | null, component: Component<any, any>, props, scope, vars, force) {
|
||||
this.force = force;
|
||||
this.scope = scope;
|
||||
this.vars = vars;
|
||||
this.props = props;
|
||||
this.component = component;
|
||||
|
||||
this.root = parent ? parent.root : this;
|
||||
this.parent = parent;
|
||||
|
||||
let oldFiber = component.__owl__.currentFiber;
|
||||
if (oldFiber && !oldFiber.isCancelled) {
|
||||
this._remapFiber(oldFiber);
|
||||
}
|
||||
|
||||
this.root.counter++;
|
||||
|
||||
component.__owl__.currentFiber = this;
|
||||
}
|
||||
|
||||
/**
|
||||
* In some cases, a rendering initiated at some component can detect that it
|
||||
* should be part of a larger rendering initiated somewhere up the component
|
||||
* tree. In that case, it needs to cancel the previous rendering and
|
||||
* remap itself as a part of the current parent rendering.
|
||||
*/
|
||||
_remapFiber(oldFiber: Fiber) {
|
||||
oldFiber.cancel();
|
||||
if (oldFiber === oldFiber.root) {
|
||||
oldFiber.root.counter++;
|
||||
}
|
||||
if (oldFiber.parent && !this.parent) {
|
||||
// re-map links
|
||||
this.parent = oldFiber.parent;
|
||||
this.root = this.parent.root;
|
||||
this.sibling = oldFiber.sibling;
|
||||
if (this.parent.child === oldFiber) {
|
||||
this.parent.child = this;
|
||||
} else {
|
||||
let current = this.parent.child!;
|
||||
while (true) {
|
||||
if (current.sibling === oldFiber) {
|
||||
current.sibling = this;
|
||||
break;
|
||||
}
|
||||
current = current.sibling!;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function has been taken from
|
||||
* https://medium.com/react-in-depth/the-how-and-why-on-reacts-usage-of-linked-list-in-fiber-67f1014d0eb7
|
||||
*/
|
||||
_walk(doWork: (f: Fiber) => Fiber | null) {
|
||||
let root = this;
|
||||
let current: Fiber = this;
|
||||
while (true) {
|
||||
const child = doWork(current);
|
||||
if (child) {
|
||||
current = child;
|
||||
continue;
|
||||
}
|
||||
if (current === root) {
|
||||
return;
|
||||
}
|
||||
while (!current.sibling) {
|
||||
if (!current.parent || current.parent === root) {
|
||||
return;
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
current = current.sibling;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the given patch queue from a fiber.
|
||||
* 1) Call 'willPatch' on the component of each patch
|
||||
* 2) Call '__patch' on the component of each patch
|
||||
* 3) Call 'patched' on the component of each patch, in reverse order
|
||||
*/
|
||||
patchComponents() {
|
||||
const patchQueue: Fiber[] = [];
|
||||
const doWork: (Fiber) => Fiber | null = function(f) {
|
||||
if (f.shouldPatch) {
|
||||
patchQueue.push(f);
|
||||
}
|
||||
return f.child;
|
||||
};
|
||||
this._walk(doWork);
|
||||
let component: Component<any, any> = this.component;
|
||||
this.shouldPatch = false;
|
||||
const patchLen = patchQueue.length;
|
||||
try {
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
component = patchQueue[i].component;
|
||||
if (component.__owl__.willPatchCB) {
|
||||
component.__owl__.willPatchCB();
|
||||
}
|
||||
component.willPatch();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
try {
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const fiber = patchQueue[i];
|
||||
component = fiber.component;
|
||||
component.__patch(fiber.vnode);
|
||||
}
|
||||
} catch (e) {
|
||||
this.handleError(e);
|
||||
}
|
||||
try {
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
component = patchQueue[i].component;
|
||||
component.patched();
|
||||
if (component.__owl__.patchedCB) {
|
||||
component.__owl__.patchedCB();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
this.shouldPatch = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a fiber and all its children.
|
||||
*/
|
||||
cancel() {
|
||||
this._walk(f => {
|
||||
if (!f.isRendered) {
|
||||
f.root.counter--;
|
||||
}
|
||||
f.isCancelled = true;
|
||||
return f.child;
|
||||
});
|
||||
}
|
||||
|
||||
handleError(e: Error) {}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Fiber } from "./fiber";
|
||||
|
||||
/**
|
||||
* Owl Scheduler Class
|
||||
*
|
||||
* The scheduler is the part of Owl that will effectively apply a rendering
|
||||
* whenever a fiber is ready.
|
||||
*
|
||||
* Briefly, it can be used to register root fibers. Whenever there is an
|
||||
* active root fiber, it will poll continuously each animation frame (so, about
|
||||
* once every 16ms) and whenever a root fiber is ready, it will apply it.
|
||||
*/
|
||||
|
||||
interface Task {
|
||||
fiber: Fiber;
|
||||
callback: () => void;
|
||||
}
|
||||
|
||||
export class Scheduler {
|
||||
tasks: Task[] = [];
|
||||
isRunning: boolean = false;
|
||||
requestAnimationFrame: typeof window.requestAnimationFrame;
|
||||
|
||||
constructor(requestAnimationFrame) {
|
||||
this.requestAnimationFrame = requestAnimationFrame;
|
||||
}
|
||||
|
||||
addFiber(fiber, callback) {
|
||||
this.tasks.push({ fiber, callback });
|
||||
if (this.isRunning) {
|
||||
return;
|
||||
}
|
||||
this.scheduleTasks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all current tasks. This only applies to the fibers that are ready.
|
||||
* Other tasks are left unchanged.
|
||||
*/
|
||||
flush() {
|
||||
let tasks = this.tasks;
|
||||
this.tasks = [];
|
||||
tasks = tasks.filter(task => {
|
||||
if (task.fiber.isCancelled) {
|
||||
return false;
|
||||
}
|
||||
if (task.fiber.counter === 0) {
|
||||
task.callback();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.tasks = tasks.concat(this.tasks);
|
||||
}
|
||||
|
||||
scheduleTasks() {
|
||||
this.isRunning = true;
|
||||
this.requestAnimationFrame(() => {
|
||||
this.flush();
|
||||
if (this.tasks.length > 0) {
|
||||
this.scheduleTasks();
|
||||
} else {
|
||||
this.isRunning = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { Component, scheduler } from "./component/component";
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { onWillUnmount } from "./hooks";
|
||||
/**
|
||||
* The `Context` object provides a way to share data between an arbitrary number
|
||||
* of component. Usually, data is passed from a parent to its children component,
|
||||
* but when we have to deal with some mostly global information, this can be
|
||||
* annoying, since each component will need to pass the information to each
|
||||
* children, even though some or most of them will not use the information.
|
||||
*
|
||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
||||
* hook) to its state, and will be updated whenever the context state is updated.
|
||||
*/
|
||||
export class Context extends EventBus {
|
||||
state: any;
|
||||
observer: Observer;
|
||||
rev: number = 1;
|
||||
// mapping from component id to last observed context id
|
||||
mapping: { [componentId: number]: number } = {};
|
||||
|
||||
constructor(state: Object = {}) {
|
||||
super();
|
||||
this.observer = new Observer();
|
||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
||||
this.state = this.observer.observe(state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instead of using trigger to emit an update event, we actually implement
|
||||
* our own function to do that. The reason is that we need to be smarter than
|
||||
* a simple trigger function: we need to wait for parent components to be
|
||||
* done before doing children components. The reason is that if an update
|
||||
* as an effect of destroying a children, we do not want to call the
|
||||
* mapStoreToProps function of the child, nor rendering it.
|
||||
*
|
||||
* This method is not optimal if we have a bunch of asynchronous components:
|
||||
* we wait sequentially for each component to be completed before updating the
|
||||
* next. However, the only things that matters is that children are updated
|
||||
* after their parents. So, this could be optimized by being smarter, and
|
||||
* updating all widgets concurrently, except for parents/children.
|
||||
*
|
||||
* A potential cheap way to improve this situation is to keep track of the
|
||||
* depth of a component in the component tree. A root component has a depth of
|
||||
* 1, then its children of 2 and so on... Then, we can update all components
|
||||
* with the same depth in parallel.
|
||||
*/
|
||||
async __notifyComponents() {
|
||||
const rev = ++this.rev;
|
||||
const subs = this.subscriptions.update || [];
|
||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
||||
const sub = subs[i];
|
||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
||||
if (shouldCallback) {
|
||||
const render = sub.callback.call(sub.owner, rev);
|
||||
scheduler.flush();
|
||||
await render;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The`useContext` hook is the normal way for a component to register themselve
|
||||
* to context state changes. The `useContext` method returns the context state
|
||||
*/
|
||||
export function useContext(ctx: Context): any {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
return useContextWithCB(ctx, component, component.render.bind(component));
|
||||
}
|
||||
|
||||
export function useContextWithCB(ctx: Context, component: Component<any, any>, method): any {
|
||||
const __owl__ = component.__owl__;
|
||||
const id = __owl__.id;
|
||||
const mapping = ctx.mapping;
|
||||
if (id in mapping) {
|
||||
return ctx.state;
|
||||
}
|
||||
if (!__owl__.observer) {
|
||||
__owl__.observer = new Observer();
|
||||
__owl__.observer.notifyCB = component.render.bind(component);
|
||||
}
|
||||
const currentCB = __owl__.observer.notifyCB;
|
||||
__owl__.observer.notifyCB = function () {
|
||||
if (ctx.rev > mapping[id]) {
|
||||
// in this case, the context has been updated since we were rendering
|
||||
// last, and we do not need to render here with the observer. A
|
||||
// rendering is coming anyway, with the correct props.
|
||||
return;
|
||||
}
|
||||
currentCB();
|
||||
}
|
||||
|
||||
mapping[id] = 0;
|
||||
const renderFn = __owl__.renderFn;
|
||||
__owl__.renderFn = function(comp, params) {
|
||||
mapping[id] = ctx.rev;
|
||||
return renderFn(comp, params);
|
||||
};
|
||||
ctx.on("update", component, async contextRev => {
|
||||
if (mapping[id] < contextRev) {
|
||||
mapping[id] = contextRev;
|
||||
await method();
|
||||
}
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
ctx.off("update", component);
|
||||
delete mapping[id];
|
||||
});
|
||||
return ctx.state;
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export class Observer {
|
||||
|
||||
notifyCB() {}
|
||||
async notifyChange() {
|
||||
|
||||
this.dirty = true;
|
||||
await Promise.resolve();
|
||||
if (this.dirty) {
|
||||
@@ -34,7 +33,7 @@ export class Observer {
|
||||
}
|
||||
}
|
||||
|
||||
observe(value: any, parent?: any): any {
|
||||
observe<T>(value: T, parent?: any): T {
|
||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
||||
// fun fact: typeof null === 'object'
|
||||
return value;
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { Component } from "./component/component";
|
||||
import { Observer } from "./core/observer";
|
||||
|
||||
/**
|
||||
* Owl Hook System
|
||||
*
|
||||
* This file introduces the concept of hooks, similar to React or Vue hooks.
|
||||
* We have currently an implementation of:
|
||||
* - useState (reactive state)
|
||||
* - onMounted
|
||||
* - onWillUnmount
|
||||
* - useRef
|
||||
*/
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useState
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This is the main way a component can be made reactive. The useState hook
|
||||
* will return an observed object (or array). Changes to that value will then
|
||||
* trigger a rerendering of the current component.
|
||||
*/
|
||||
export function useState<T>(state: T): T {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
const __owl__ = component.__owl__;
|
||||
if (!__owl__.observer) {
|
||||
__owl__.observer = new Observer();
|
||||
__owl__.observer.notifyCB = component.render.bind(component);
|
||||
}
|
||||
return __owl__.observer.observe(state);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Life cycle hooks
|
||||
// -----------------------------------------------------------------------------
|
||||
function makeLifecycleHook(method: string, reverse: boolean = false) {
|
||||
if (reverse) {
|
||||
return function(cb) {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function() {
|
||||
current.call(component);
|
||||
cb.call(component);
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return function(cb) {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function() {
|
||||
cb.call(component);
|
||||
current.call(component);
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function makeAsyncHook(method: string) {
|
||||
return function(cb) {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
if (component.__owl__[method]) {
|
||||
const current = component.__owl__[method];
|
||||
component.__owl__[method] = function(...args) {
|
||||
return Promise.all[(current.call(component, ...args), cb.call(component, ...args))];
|
||||
};
|
||||
} else {
|
||||
component.__owl__[method] = cb;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const onMounted = makeLifecycleHook("mountedCB", true);
|
||||
export const onWillUnmount = makeLifecycleHook("willUnmountCB");
|
||||
export const onWillPatch = makeLifecycleHook("willPatchCB");
|
||||
export const onPatched = makeLifecycleHook("patchedCB", true);
|
||||
|
||||
export const onWillStart = makeAsyncHook("willStartCB");
|
||||
export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useRef
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The purpose of this hook is to allow components to get a reference to a sub
|
||||
* html node or component.
|
||||
*/
|
||||
interface Ref {
|
||||
el: HTMLElement | null;
|
||||
comp: Component<any, any> | null;
|
||||
}
|
||||
|
||||
export function useRef(name: string): Ref {
|
||||
const __owl__ = Component.current!.__owl__;
|
||||
return {
|
||||
get el(): HTMLElement | null {
|
||||
const val = __owl__.refs && __owl__.refs[name];
|
||||
return val instanceof HTMLElement ? val : null;
|
||||
},
|
||||
get comp(): Component<any, any> | null {
|
||||
const val = __owl__.refs && __owl__.refs[name];
|
||||
return val instanceof Component ? val : null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// useSubEnv
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This hook is a simple way to let components use a sub environment. Note that
|
||||
* like for all hooks, it is important that this is only called in the
|
||||
* constructor method.
|
||||
*/
|
||||
export function useSubEnv(nextEnv) {
|
||||
const component = Component.current!;
|
||||
component.env = Object.assign(Object.create(component.env), nextEnv);
|
||||
}
|
||||
+22
-8
@@ -7,19 +7,33 @@
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { QWeb } from "./qweb/index";
|
||||
import { ConnectedComponent } from "./store/connected_component";
|
||||
import { Store } from "./store/store";
|
||||
import * as _store from "./store";
|
||||
import * as _utils from "./utils";
|
||||
import { Link } from "./router/Link";
|
||||
import { Router } from "./router/Router";
|
||||
import * as _tags from "./tags";
|
||||
import {AsyncRoot} from "./misc/async_root";
|
||||
import * as _hooks from "./hooks";
|
||||
import * as _context from "./context";
|
||||
import { Link } from "./router/link";
|
||||
import { RouteComponent } from "./router/route_component";
|
||||
import { Router } from "./router/router";
|
||||
|
||||
export { Component } from "./component/component";
|
||||
export { QWeb };
|
||||
export const core = { EventBus, Observer };
|
||||
export const router = { Router, Link };
|
||||
export const store = { Store, ConnectedComponent };
|
||||
export const utils = _utils;
|
||||
|
||||
export const Context = _context.Context;
|
||||
export const useState = _hooks.useState;
|
||||
export const core = { EventBus, Observer };
|
||||
export const router = { Router, RouteComponent, Link };
|
||||
export const Store = _store.Store;
|
||||
export const utils = _utils;
|
||||
export const tags = _tags;
|
||||
export const misc = { AsyncRoot};
|
||||
export const hooks = Object.assign({}, _hooks, {
|
||||
useContext: _context.useContext,
|
||||
useDispatch: _store.useDispatch,
|
||||
useGetters: _store.useGetters,
|
||||
useStore: _store.useStore
|
||||
});
|
||||
export const __info__ = {};
|
||||
|
||||
Object.defineProperty(__info__, "mode", {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Component } from "../component/component";
|
||||
import { xml } from "../tags";
|
||||
|
||||
/**
|
||||
* AsyncRoot
|
||||
*
|
||||
* Owl is by default asynchronous, and the user interface will wait for all its
|
||||
* subcomponents to be rendered before updating the DOM. This is most of the
|
||||
* time what we want, but in some cases, it makes sense to "detach" a component
|
||||
* from this coordination. This is the goal of the AsyncRoot component.
|
||||
*/
|
||||
|
||||
export class AsyncRoot extends Component<any, any> {
|
||||
static template = xml`<t t-slot="default"/>`;
|
||||
|
||||
async __updateProps(nextProps, parentFiber) {
|
||||
this.render(parentFiber.force);
|
||||
}
|
||||
}
|
||||
+64
-39
@@ -1,6 +1,7 @@
|
||||
import { Context } from "./context";
|
||||
import { CompilationContext } from "./compilation_context";
|
||||
import { QWebExprVar } from "./expression_parser";
|
||||
import { QWeb } from "./qweb";
|
||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||
|
||||
/**
|
||||
* Owl QWeb Directives
|
||||
@@ -25,7 +26,9 @@ QWeb.utils.getFragment = function(str: string): DocumentFragment {
|
||||
return temp.content;
|
||||
};
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
|
||||
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
||||
if (value === "0" && ctx.caller) {
|
||||
qweb._compileNode(ctx.caller, ctx);
|
||||
return;
|
||||
@@ -55,17 +58,13 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
ctx.addLine(`var vn${nodeID} = {text: ${exprID}};`);
|
||||
if (ctx.rootContext.shouldDefineResult) {
|
||||
ctx.addLine(`result = vn${nodeID}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let fragID = ctx.generateID();
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.addLine(`var frag${fragID} = utils.getFragment(${exprID})`);
|
||||
let tempNodeID = ctx.generateID();
|
||||
ctx.addLine(`var p${tempNodeID} = {hook: {`);
|
||||
ctx.addLine(` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`);
|
||||
ctx.addLine(`}};`);
|
||||
ctx.addLine(`var vn${tempNodeID} = h('div', p${tempNodeID})`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(...utils.htmlToVDOM(${exprID}));`);
|
||||
}
|
||||
if (node.childNodes.length) {
|
||||
ctx.addElse();
|
||||
@@ -79,10 +78,6 @@ QWeb.addDirective({
|
||||
name: "esc",
|
||||
priority: 70,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = qweb._compileGenericNode(node, ctx);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
}
|
||||
let value = ctx.getValue(node.getAttribute("t-esc")!);
|
||||
compileValueNode(value, node, qweb, ctx.subContext("escaping", true));
|
||||
return true;
|
||||
@@ -93,10 +88,6 @@ QWeb.addDirective({
|
||||
name: "raw",
|
||||
priority: 80,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = qweb._compileGenericNode(node, ctx);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
}
|
||||
let value = ctx.getValue(node.getAttribute("t-raw")!);
|
||||
compileValueNode(value, node, qweb, ctx);
|
||||
return true;
|
||||
@@ -142,7 +133,7 @@ QWeb.addDirective({
|
||||
priority: 20,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||
ctx.addIf(`${ctx.formatExpression(cond)}`);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : cond.id);
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
@@ -155,7 +146,7 @@ QWeb.addDirective({
|
||||
priority: 30,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
||||
ctx.addLine(`else if (${ctx.formatExpression(cond)}) {`);
|
||||
ctx.addLine(`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : cond.id}) {`);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
@@ -196,14 +187,57 @@ QWeb.addDirective({
|
||||
nodeCopy.removeAttribute("t-call");
|
||||
|
||||
// extract variables from nodecopy
|
||||
const tempCtx = new Context();
|
||||
const tempCtx = new CompilationContext();
|
||||
tempCtx.nextID = ctx.rootContext.nextID;
|
||||
tempCtx.allowMultipleRoots = true;
|
||||
qweb._compileNode(nodeCopy, tempCtx);
|
||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
||||
ctx.rootContext.nextID = tempCtx.nextID;
|
||||
|
||||
const templateMap = Object.create(ctx.templates);
|
||||
// open new scope, if necessary
|
||||
const hasNewVariables = Object.keys(tempCtx.variables).length > 0;
|
||||
|
||||
// compile sub template
|
||||
let subCtx = ctx.subContext("caller", nodeCopy).subContext("variables", Object.create(vars));
|
||||
subCtx = subCtx.subContext("templates", templateMap);
|
||||
|
||||
if (templateMap[subTemplate]) {
|
||||
// OUCH, IT IS A RECURSIVE TEMPLATE SITUATION...
|
||||
// This is a tricky situation... We obviously cannot inline the compiled
|
||||
// template. So, what we need to do is to compile it, and make sure we
|
||||
// properly transfer everything from the current scope to the sub template.
|
||||
ctx.rootContext.shouldTrackScope = true;
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
let subTemplateName;
|
||||
if (ctx.hasParentWidget) {
|
||||
subTemplateName = ctx.templateName;
|
||||
} else {
|
||||
subTemplateName = `__${ctx.generateID()}`;
|
||||
subCtx.variables = {};
|
||||
let id = 0;
|
||||
for (let v in vars) {
|
||||
subCtx.variables[v] = vars[v];
|
||||
(vars[v] as any).id = `_v${id++}`;
|
||||
}
|
||||
const subTemplateFn = qweb._compile(subTemplateName, nodeTemplate.elem, subCtx);
|
||||
qweb.recursiveFns[subTemplateName] = subTemplateFn;
|
||||
}
|
||||
let varCode = `{}`;
|
||||
if (Object.keys(vars).length) {
|
||||
let id = 0;
|
||||
const content = Object.values(vars)
|
||||
.map((v: any) => `_v${id++}: ${v.expr}`)
|
||||
.join(",");
|
||||
varCode = `{${content}}`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`this.recursiveFns['${subTemplateName}'].call(this, context, Object.assign({}, extra, {parentNode: c${ctx.parentNode}, fiber: {vars: ${varCode}, scope}}));`
|
||||
);
|
||||
return true;
|
||||
}
|
||||
templateMap[subTemplate] = true;
|
||||
|
||||
if (hasNewVariables) {
|
||||
ctx.addLine("{");
|
||||
ctx.indent();
|
||||
@@ -216,10 +250,6 @@ QWeb.addDirective({
|
||||
// todo: handle XML variables...
|
||||
}
|
||||
}
|
||||
|
||||
// compile sub template
|
||||
const subCtx = ctx.subContext("caller", nodeCopy).subContext("variables", Object.create(vars));
|
||||
|
||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
||||
|
||||
// close new scope
|
||||
@@ -228,10 +258,6 @@ QWeb.addDirective({
|
||||
ctx.addLine("}");
|
||||
}
|
||||
|
||||
if (node.hasAttribute("t-if") || node.hasAttribute("t-else") || node.hasAttribute("t-elif")) {
|
||||
ctx.closeIf();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
@@ -245,7 +271,7 @@ QWeb.addDirective({
|
||||
priority: 10,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
ctx.rootContext.shouldProtectContext = true;
|
||||
ctx = ctx.subContext("inLoop", true);
|
||||
ctx = ctx.subContext("loopNumber", ctx.loopNumber + 1);
|
||||
const elems = node.getAttribute("t-foreach")!;
|
||||
const name = node.getAttribute("t-as")!;
|
||||
let arrayID = ctx.generateID();
|
||||
@@ -259,13 +285,14 @@ QWeb.addDirective({
|
||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
||||
ctx.closeIf();
|
||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
||||
ctx.addLine(`for (let i = 0; i < _length${keysID}; i++) {`);
|
||||
const loopVar = `i${ctx.loopNumber}`;
|
||||
ctx.addLine(`for (let ${loopVar} = 0; ${loopVar} < _length${keysID}; ${loopVar}++) {`);
|
||||
ctx.indent();
|
||||
ctx.addToScope(name + "_first", "i === 0");
|
||||
ctx.addToScope(name + "_last", `i === _length${keysID} - 1`);
|
||||
ctx.addToScope(name + "_index", "i");
|
||||
ctx.addToScope(name, `_${keysID}[i]`);
|
||||
ctx.addToScope(name + "_value", `_${valuesID}[i]`);
|
||||
ctx.addToScope(name + "_first", `${loopVar} === 0`);
|
||||
ctx.addToScope(name + "_last", `${loopVar} === _length${keysID} - 1`);
|
||||
ctx.addToScope(name + "_index", loopVar);
|
||||
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
|
||||
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
|
||||
const nodeCopy = <Element>node.cloneNode(true);
|
||||
let shouldWarn = nodeCopy.tagName !== "t" && !nodeCopy.hasAttribute("t-key");
|
||||
if (!shouldWarn && node.tagName === "t") {
|
||||
@@ -283,9 +310,7 @@ QWeb.addDirective({
|
||||
}
|
||||
if (shouldWarn) {
|
||||
console.warn(
|
||||
`Directive t-foreach should always be used with a t-key! (in template: '${
|
||||
ctx.templateName
|
||||
}')`
|
||||
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
||||
);
|
||||
}
|
||||
nodeCopy.removeAttribute("t-foreach");
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { compileExpr, QWebVar } from "./expression_parser";
|
||||
import { compileExpr, QWebVar, QWebExprVar } from "./expression_parser";
|
||||
|
||||
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||
//------------------------------------------------------------------------------
|
||||
// Compilation Context
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export class Context {
|
||||
export class CompilationContext {
|
||||
nextID: number = 1;
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: QWebVar } = {};
|
||||
@@ -13,25 +14,31 @@ export class Context {
|
||||
parentTextNode: number | null = null;
|
||||
rootNode: number | null = null;
|
||||
indentLevel: number = 0;
|
||||
rootContext: Context;
|
||||
rootContext: CompilationContext;
|
||||
caller: Element | undefined;
|
||||
shouldDefineOwner: boolean = false;
|
||||
shouldDefineParent: boolean = false;
|
||||
shouldDefineQWeb: boolean = false;
|
||||
shouldDefineUtils: boolean = false;
|
||||
shouldDefineResult: boolean = false;
|
||||
shouldDefineRefs: boolean = false;
|
||||
shouldDefineResult: boolean = true;
|
||||
shouldDefineSibling: boolean = true;
|
||||
shouldProtectContext: boolean = false;
|
||||
shouldTrackScope: boolean = false;
|
||||
inLoop: boolean = false;
|
||||
loopNumber: number = 0;
|
||||
inPreTag: boolean = false;
|
||||
templateName: string;
|
||||
allowMultipleRoots: boolean = false;
|
||||
hasParentWidget: boolean = false;
|
||||
scopeVars: any[] = [];
|
||||
currentKey: string = "";
|
||||
lastNodeKey: string = ""; // temp variable to communicate to previous caller
|
||||
templates: { [key: string]: boolean } = {};
|
||||
|
||||
constructor(name?: string) {
|
||||
this.rootContext = this;
|
||||
this.templateName = name || "noname";
|
||||
this.templates[this.templateName] = true;
|
||||
this.addLine("var h = this.h;");
|
||||
}
|
||||
|
||||
@@ -57,6 +64,12 @@ export class Context {
|
||||
if (this.shouldDefineResult) {
|
||||
this.code.unshift(" let result;");
|
||||
}
|
||||
if (this.shouldDefineSibling) {
|
||||
this.code.unshift(" let sibling = null;");
|
||||
}
|
||||
if (this.shouldDefineRefs) {
|
||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
||||
}
|
||||
if (this.shouldDefineOwner) {
|
||||
// this is necessary to prevent some directives (t-forach for ex) to
|
||||
// pollute the rendering context by adding some keys in it.
|
||||
@@ -78,7 +91,7 @@ export class Context {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
withParent(node: number): Context {
|
||||
withParent(node: number): CompilationContext {
|
||||
if (
|
||||
!this.allowMultipleRoots &&
|
||||
this === this.rootContext &&
|
||||
@@ -89,10 +102,13 @@ export class Context {
|
||||
if (!this.rootContext.rootNode) {
|
||||
this.rootContext.rootNode = node;
|
||||
}
|
||||
if (!this.parentNode && this.rootContext.shouldDefineResult) {
|
||||
this.addLine(`result = vn${node};`);
|
||||
}
|
||||
return this.subContext("parentNode", node);
|
||||
}
|
||||
|
||||
subContext(key: keyof Context, value: any): Context {
|
||||
subContext(key: keyof CompilationContext, value: any): CompilationContext {
|
||||
const newContext = Object.create(this);
|
||||
newContext[key] = value;
|
||||
return newContext;
|
||||
@@ -133,7 +149,7 @@ export class Context {
|
||||
this.addLine("}");
|
||||
}
|
||||
|
||||
getValue(val: any): any {
|
||||
getValue(val: any): QWebExprVar | string {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
}
|
||||
|
||||
@@ -156,7 +172,7 @@ export class Context {
|
||||
* '{{x ? 'a': 'b'}}' -> (x ? 'a' : 'b')
|
||||
*/
|
||||
interpolate(s: string): string {
|
||||
let matches = s.match(/\{\{.*?\}\}/g);
|
||||
let matches = s.match(INTERP_REGEXP);
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
||||
}
|
||||
+53
-76
@@ -40,34 +40,32 @@ QWeb.addDirective({
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
ctx.addIf(`!context['${handlerName}']`);
|
||||
ctx.addLine(
|
||||
`throw new Error('Missing handler \\'' + '${handlerName}' + \`\\' when evaluating template '${ctx.templateName.replace(
|
||||
/`/g,
|
||||
"'"
|
||||
)}'\`)`
|
||||
);
|
||||
ctx.closeIf();
|
||||
let params = extraArgs ? `owner, ${ctx.formatExpression(extraArgs)}` : "owner";
|
||||
let handler;
|
||||
if (mods.length > 0) {
|
||||
handler = `function (e) {`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
handler += `context['${handlerName}'].call(${params}, e);}`;
|
||||
let handler = `function (e) {`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
if (handlerName) {
|
||||
if (!extraArgs) {
|
||||
handler += `const fn = context['${handlerName}'];`;
|
||||
handler += `if (fn) { fn.call(${params}, e); } else { context.${handlerName}; }`;
|
||||
handler += `}`;
|
||||
ctx.addLine(
|
||||
`extra.handlers['${eventName}' + ${nodeID}] = extra.handlers['${eventName}' + ${nodeID}] || ${handler};`
|
||||
);
|
||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
||||
} else {
|
||||
const handlerKey = `handler${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`);
|
||||
handler += `if (${handlerKey}) { ${handlerKey}(e); } else { context.${value}; }`;
|
||||
handler += `}`;
|
||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
||||
}
|
||||
} else {
|
||||
handler = `context['${handlerName}'].bind(${params})`;
|
||||
}
|
||||
if (extraArgs) {
|
||||
handler += "}";
|
||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
||||
} else {
|
||||
ctx.addLine(
|
||||
`extra.handlers['${eventName}' + ${nodeID}] = extra.handlers['${eventName}' + ${nodeID}] || ${handler};`
|
||||
);
|
||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -79,9 +77,11 @@ QWeb.addDirective({
|
||||
name: "ref",
|
||||
priority: 95,
|
||||
atNodeCreation({ ctx, value, addNodeHook }) {
|
||||
ctx.rootContext.shouldDefineRefs = true;
|
||||
const refKey = `ref${ctx.generateID()}`;
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(value)};`);
|
||||
addNodeHook("create", `context.refs[${refKey}] = n.elm;`);
|
||||
addNodeHook("create", `context.__owl__.refs[${refKey}] = n.elm;`);
|
||||
addNodeHook("destroy", `delete context.__owl__.refs[${refKey}];`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -182,42 +182,6 @@ QWeb.addDirective({
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-mounted
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "mounted",
|
||||
priority: 97,
|
||||
atNodeCreation({ ctx, fullName, value, nodeID, addNodeHook }) {
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
const eventName = fullName.slice(5);
|
||||
if (!eventName) {
|
||||
throw new Error("Missing event name with t-on directive");
|
||||
}
|
||||
let extraArgs;
|
||||
let handler = value.replace(/\(.*\)/, function(args) {
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
let error = `(function () {throw new Error('Missing handler \\'' + '${handler}' + \`\\' when evaluating template '${ctx.templateName.replace(
|
||||
/`/g,
|
||||
"'"
|
||||
)}'\`)})()`;
|
||||
if (extraArgs) {
|
||||
ctx.addLine(
|
||||
`extra.mountedHandlers[${nodeID}] = (context['${handler}'] || ${error}).bind(owner, ${ctx.formatExpression(
|
||||
extraArgs
|
||||
)});`
|
||||
);
|
||||
} else {
|
||||
ctx.addLine(
|
||||
`extra.mountedHandlers[${nodeID}] = extra.mountedHandlers[${nodeID}] || (context['${handler}'] || ${error}).bind(owner);`
|
||||
);
|
||||
}
|
||||
addNodeHook("insert", `if (context.__owl__.isMounted) { extra.mountedHandlers[${nodeID}](); }`);
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-slot
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -227,13 +191,24 @@ QWeb.addDirective({
|
||||
atNodeEncounter({ ctx, value }): boolean {
|
||||
const slotKey = ctx.generateID();
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
ctx.addLine(`const slot${slotKey} = this.slots[context.__owl__.slotId + '_' + '${value}'];`);
|
||||
ctx.addIf(`slot${slotKey}`);
|
||||
ctx.addLine(
|
||||
`slot${slotKey}(context.__owl__.parent, Object.assign({}, extra, {parentNode: c${
|
||||
ctx.parentNode
|
||||
}, vars: extra.vars, parent: owner}));`
|
||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
||||
);
|
||||
ctx.addIf(`slot${slotKey}`);
|
||||
let parentNode = `c${ctx.parentNode}`;
|
||||
if (!ctx.parentNode) {
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
parentNode = `children${ctx.nextID++}`;
|
||||
ctx.addLine(`let ${parentNode}= []`);
|
||||
ctx.addLine(`result = {}`);
|
||||
}
|
||||
ctx.addLine(
|
||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, vars: extra.vars, parent: owner}));`
|
||||
);
|
||||
if (!ctx.parentNode) {
|
||||
ctx.addLine(`utils.defineProxy(result, ${parentNode}[0]);`);
|
||||
}
|
||||
ctx.closeIf();
|
||||
return true;
|
||||
}
|
||||
@@ -250,31 +225,33 @@ QWeb.utils.toNumber = function(val: string): number | string {
|
||||
QWeb.addDirective({
|
||||
name: "model",
|
||||
priority: 42,
|
||||
atNodeCreation({ ctx, nodeID, value, node, fullName }) {
|
||||
atNodeCreation({ ctx, nodeID, value, node, fullName, addNodeHook }) {
|
||||
const type = node.getAttribute("type");
|
||||
let handler;
|
||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
||||
const expr = ctx.formatExpression(value);
|
||||
if (node.tagName === "select") {
|
||||
ctx.addLine(`p${nodeID}.props = {value: context.state['${value}']};`);
|
||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||
addNodeHook("create", `n.elm.value=${expr};`);
|
||||
event = "change";
|
||||
handler = `(ev) => {context.state['${value}'] = ev.target.value}`;
|
||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
||||
} else if (type === "checkbox") {
|
||||
ctx.addLine(`p${nodeID}.props = {checked: context.state['${value}']};`);
|
||||
handler = `(ev) => {context.state['${value}'] = ev.target.checked}`;
|
||||
ctx.addLine(`p${nodeID}.props = {checked: ${expr}};`);
|
||||
handler = `(ev) => {${expr} = ev.target.checked}`;
|
||||
} else if (type === "radio") {
|
||||
const nodeValue = node.getAttribute("value")!;
|
||||
ctx.addLine(`p${nodeID}.props = {checked:context.state['${value}'] === '${nodeValue}'};`);
|
||||
handler = `(ev) => {context.state['${value}'] = ev.target.value}`;
|
||||
ctx.addLine(`p${nodeID}.props = {checked:${expr} === '${nodeValue}'};`);
|
||||
handler = `(ev) => {${expr} = ev.target.value}`;
|
||||
event = "click";
|
||||
} else {
|
||||
ctx.addLine(`p${nodeID}.props = {value: context.state['${value}']};`);
|
||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||
const trimCode = fullName.includes(".trim") ? ".trim()" : "";
|
||||
let valueCode = `ev.target.value${trimCode}`;
|
||||
if (fullName.includes(".number")) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
valueCode = `utils.toNumber(${valueCode})`;
|
||||
}
|
||||
handler = `(ev) => {context.state['${value}'] = ${valueCode}}`;
|
||||
handler = `(ev) => {${expr} = ${valueCode}}`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`extra.handlers['${event}' + ${nodeID}] = extra.handlers['${event}' + ${nodeID}] || (${handler});`
|
||||
|
||||
+102
-42
@@ -1,6 +1,8 @@
|
||||
import { EventBus } from "../core/event_bus";
|
||||
import { h, patch, VNode } from "../vdom/index";
|
||||
import { Context } from "./context";
|
||||
import { CompilationContext } from "./compilation_context";
|
||||
import { shallowEqual } from "../utils";
|
||||
import { addNS } from "../vdom/vdom";
|
||||
|
||||
/**
|
||||
* Owl QWeb Engine
|
||||
@@ -34,7 +36,7 @@ interface Template {
|
||||
interface CompilationInfo {
|
||||
node: Element;
|
||||
qweb: QWeb;
|
||||
ctx: Context;
|
||||
ctx: CompilationContext;
|
||||
fullName: string;
|
||||
value: string;
|
||||
}
|
||||
@@ -67,7 +69,8 @@ const whitespaceRE = /\s+/g;
|
||||
const NODE_HOOKS_PARAMS = {
|
||||
create: "(_, n)",
|
||||
insert: "vn",
|
||||
remove: "(vn, rm)"
|
||||
remove: "(vn, rm)",
|
||||
destroy: "()"
|
||||
};
|
||||
|
||||
interface Utils {
|
||||
@@ -92,18 +95,15 @@ const UTILS: Utils = {
|
||||
}
|
||||
return expr;
|
||||
},
|
||||
shallowEqual(p1, p2) {
|
||||
for (let k in p1) {
|
||||
if (p1[k] !== p2[k]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
shallowEqual,
|
||||
addNameSpace(vnode) {
|
||||
addNS(vnode.data, vnode.children, vnode.sel);
|
||||
}
|
||||
};
|
||||
|
||||
function parseXML(xml: string): Document {
|
||||
const parser = new DOMParser();
|
||||
|
||||
const doc = parser.parseFromString(xml, "text/xml");
|
||||
if (doc.getElementsByTagName("parsererror").length) {
|
||||
let msg = "Invalid XML in template.";
|
||||
@@ -131,13 +131,11 @@ function parseXML(xml: string): Document {
|
||||
return doc;
|
||||
}
|
||||
|
||||
let nextID = 1;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// QWeb rendering engine
|
||||
//------------------------------------------------------------------------------
|
||||
export class QWeb extends EventBus {
|
||||
templates: { [name: string]: Template } = {};
|
||||
templates: { [name: string]: Template };
|
||||
static utils = UTILS;
|
||||
static components = Object.create(null);
|
||||
|
||||
@@ -149,24 +147,29 @@ export class QWeb extends EventBus {
|
||||
};
|
||||
static DIRECTIVES: Directive[] = [];
|
||||
|
||||
static TEMPLATES: { [name: string]: Template } = {};
|
||||
|
||||
static nextId: number = 1;
|
||||
|
||||
h = h;
|
||||
// dev mode enables better error messages or more costly validations
|
||||
static dev: boolean = false;
|
||||
|
||||
// the id field is useful to be able to hash qweb instances. The current
|
||||
// use case is that component's templates are qweb dependant, and need to be
|
||||
// able to map a qweb instance to a template name.
|
||||
id = nextID++;
|
||||
|
||||
// slots contains sub templates defined with t-set inside t-component nodes, and
|
||||
// are meant to be used by the t-slot directive.
|
||||
slots = {};
|
||||
nextSlotId = 1;
|
||||
static slots = {};
|
||||
static nextSlotId = 1;
|
||||
|
||||
// recursiveTemplates contains sub templates called with t-call, but which
|
||||
// ends up in recursive situations. This is very similar to the slot situation,
|
||||
// as in we need to propagate the scope.
|
||||
recursiveFns = {};
|
||||
|
||||
isUpdating: boolean = false;
|
||||
|
||||
constructor(data?: string) {
|
||||
super();
|
||||
this.templates = Object.create(QWeb.TEMPLATES);
|
||||
if (data) {
|
||||
this.addTemplates(data);
|
||||
}
|
||||
@@ -184,13 +187,27 @@ export class QWeb extends EventBus {
|
||||
}
|
||||
}
|
||||
|
||||
static register(name: string, Component: any) {
|
||||
static registerComponent(name: string, Component: any) {
|
||||
if (QWeb.components[name]) {
|
||||
throw new Error(`Component '${name}' has already been registered`);
|
||||
}
|
||||
QWeb.components[name] = Component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register globally a template. All QWeb instances will obtain their
|
||||
* templates from their own template map, and then, from the global static
|
||||
* TEMPLATES property.
|
||||
*/
|
||||
static registerTemplate(name: string, template: string) {
|
||||
if (QWeb.TEMPLATES[name]) {
|
||||
throw new Error(`Template '${name}' has already been registered`);
|
||||
}
|
||||
const qweb = new QWeb();
|
||||
qweb.addTemplate(name, template);
|
||||
QWeb.TEMPLATES[name] = qweb.templates[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a template to the internal template map. Note that it is not
|
||||
* immediately compiled.
|
||||
@@ -212,7 +229,7 @@ export class QWeb extends EventBus {
|
||||
* template, with the name given by the t-name attribute.
|
||||
*/
|
||||
addTemplates(xmlstr: string | Document) {
|
||||
const doc = typeof xmlstr === 'string' ? parseXML(xmlstr) : xmlstr;
|
||||
const doc = typeof xmlstr === "string" ? parseXML(xmlstr) : xmlstr;
|
||||
const templates = doc.getElementsByTagName("templates")[0];
|
||||
if (!templates) {
|
||||
return;
|
||||
@@ -230,7 +247,7 @@ export class QWeb extends EventBus {
|
||||
this._processTemplate(elem);
|
||||
const template = {
|
||||
elem,
|
||||
fn: (context, extra) => {
|
||||
fn: function(this: QWeb, context, extra) {
|
||||
const compiledFunction = this._compile(name, elem);
|
||||
template.fn = compiledFunction;
|
||||
return compiledFunction.call(this, context, extra);
|
||||
@@ -298,8 +315,8 @@ export class QWeb extends EventBus {
|
||||
* to render a full component tree, since this is an asynchronous operation.
|
||||
* This method can only render templates without components.
|
||||
*/
|
||||
renderToString(name: string, context: EvalContext = {}): string {
|
||||
const vnode = this.render(name, context);
|
||||
renderToString(name: string, context: EvalContext = {}, extra?: any): string {
|
||||
const vnode = this.render(name, context, extra);
|
||||
if (vnode.sel === undefined) {
|
||||
return vnode.text!;
|
||||
}
|
||||
@@ -324,26 +341,31 @@ export class QWeb extends EventBus {
|
||||
});
|
||||
}
|
||||
|
||||
_compile(name: string, elem: Element, parentContext?: Context): CompiledTemplate {
|
||||
_compile(name: string, elem: Element, parentContext?: CompilationContext): CompiledTemplate {
|
||||
const isDebug = elem.attributes.hasOwnProperty("t-debug");
|
||||
const ctx = new Context(name);
|
||||
const ctx = new CompilationContext(name);
|
||||
if (elem.tagName !== "t") {
|
||||
ctx.shouldDefineResult = false;
|
||||
}
|
||||
if (parentContext) {
|
||||
ctx.templates = Object.create(parentContext.templates);
|
||||
ctx.variables = Object.create(parentContext.variables);
|
||||
ctx.nextID = parentContext.parentNode! + 1;
|
||||
ctx.parentNode = parentContext.parentNode!;
|
||||
ctx.nextID = parentContext.nextID + 1;
|
||||
ctx.parentNode = parentContext.parentNode || ctx.nextID++;
|
||||
ctx.allowMultipleRoots = true;
|
||||
ctx.hasParentWidget = true;
|
||||
ctx.shouldDefineResult = false;
|
||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
||||
|
||||
for (let v in parentContext.variables) {
|
||||
let variable = <any>parentContext.variables[v];
|
||||
if (variable.id) {
|
||||
ctx.addLine(`let ${variable.id} = extra.vars.${variable.id}`);
|
||||
ctx.addLine(`let ${variable.id} = extra.fiber.vars.${variable.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (parentContext) {
|
||||
ctx.addLine(" Object.assign(context, extra.scope);");
|
||||
ctx.addLine(" Object.assign(context, extra.fiber.scope);");
|
||||
}
|
||||
this._compileNode(elem, ctx);
|
||||
|
||||
@@ -386,7 +408,7 @@ export class QWeb extends EventBus {
|
||||
* Generate code from an xml node
|
||||
*
|
||||
*/
|
||||
_compileNode(node: ChildNode, ctx: Context) {
|
||||
_compileNode(node: ChildNode, ctx: CompilationContext) {
|
||||
if (!(node instanceof Element)) {
|
||||
// this is a text node, there are no directive to apply
|
||||
let text = node.textContent!;
|
||||
@@ -397,7 +419,11 @@ export class QWeb extends EventBus {
|
||||
text = text.replace(whitespaceRE, " ");
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||
if (node.nodeType === 3) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||
} else if (node.nodeType === 8) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push(h('!', \`${text}\`));`);
|
||||
}
|
||||
} else if (ctx.parentTextNode) {
|
||||
ctx.addLine(`vn${ctx.parentTextNode}.text += \`${text}\`;`);
|
||||
} else {
|
||||
@@ -405,6 +431,7 @@ export class QWeb extends EventBus {
|
||||
// template rendering.
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.addLine(`var vn${nodeID} = {text: \`${text}\`};`);
|
||||
ctx.addLine(`result = vn${nodeID};`);
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
}
|
||||
@@ -425,7 +452,7 @@ export class QWeb extends EventBus {
|
||||
fullName: string;
|
||||
}[] = [];
|
||||
|
||||
let withHandlers = false;
|
||||
const finalizers: typeof validDirectives = [];
|
||||
|
||||
// maybe this is not optimal: we iterate on all attributes here, and again
|
||||
// just after for each directive.
|
||||
@@ -436,11 +463,21 @@ export class QWeb extends EventBus {
|
||||
if (!(dName in QWeb.DIRECTIVE_NAMES)) {
|
||||
throw new Error(`Unknown QWeb directive: '${attrName}'`);
|
||||
}
|
||||
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
|
||||
const tNode = document.createElement("t");
|
||||
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
|
||||
for (let child of Array.from(node.childNodes)) {
|
||||
tNode.appendChild(child);
|
||||
}
|
||||
node.appendChild(tNode);
|
||||
node.removeAttribute(attrName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DIR_N = QWeb.DIRECTIVES.length;
|
||||
const ATTR_N = attributes.length;
|
||||
let withHandlers = false;
|
||||
for (let i = 0; i < DIR_N; i++) {
|
||||
let directive = QWeb.DIRECTIVES[i];
|
||||
let fullName;
|
||||
@@ -461,7 +498,11 @@ export class QWeb extends EventBus {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.finalize) {
|
||||
finalizers.push({ directive, value, fullName });
|
||||
}
|
||||
if (directive.atNodeEncounter) {
|
||||
const isDone = directive.atNodeEncounter({
|
||||
node,
|
||||
@@ -471,6 +512,9 @@ export class QWeb extends EventBus {
|
||||
value
|
||||
});
|
||||
if (isDone) {
|
||||
for (let { directive, value, fullName } of finalizers) {
|
||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -479,6 +523,7 @@ export class QWeb extends EventBus {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
ctx = ctx.subContext("currentKey", ctx.lastNodeKey);
|
||||
let nodeHooks = {};
|
||||
let addNodeHook = function(hook, handler) {
|
||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||
@@ -516,15 +561,28 @@ export class QWeb extends EventBus {
|
||||
}
|
||||
|
||||
this._compileChildren(node, ctx);
|
||||
// svg support
|
||||
// we hadd svg namespace if it is a svg or if it is a g, but only if it is
|
||||
// the root node. This is the easiest way to support svg sub components:
|
||||
// they need to have a g tag as root. Otherwise, we would need a complete
|
||||
// list of allowed svg tags.
|
||||
const shouldAddNS =
|
||||
node.nodeName === "svg" || (node.nodeName === "g" && ctx.rootNode === ctx.parentNode);
|
||||
if (shouldAddNS) {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.addLine(`utils.addNameSpace(vn${ctx.parentNode});`);
|
||||
}
|
||||
|
||||
for (let { directive, value, fullName } of validDirectives) {
|
||||
if (directive.finalize) {
|
||||
directive.finalize({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
for (let { directive, value, fullName } of finalizers) {
|
||||
directive.finalize!({ node, qweb: this, ctx, fullName, value });
|
||||
}
|
||||
}
|
||||
|
||||
_compileGenericNode(node: ChildNode, ctx: Context, withHandlers: boolean = true): number {
|
||||
_compileGenericNode(
|
||||
node: ChildNode,
|
||||
ctx: CompilationContext,
|
||||
withHandlers: boolean = true
|
||||
): number {
|
||||
// nodeType 1 is generic tag
|
||||
if (node.nodeType !== 1) {
|
||||
throw new Error("unsupported node type");
|
||||
@@ -587,7 +645,7 @@ export class QWeb extends EventBus {
|
||||
if (name.startsWith("t-att-")) {
|
||||
let attName = name.slice(6);
|
||||
const v = ctx.getValue(value);
|
||||
let formattedValue = v.id || ctx.formatExpression(v);
|
||||
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : v.id;
|
||||
|
||||
if (attName === "class") {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
@@ -647,7 +705,9 @@ export class QWeb extends EventBus {
|
||||
let nodeID = ctx.generateID();
|
||||
let nodeKey: any = (<Element>node).getAttribute("t-key");
|
||||
if (nodeKey) {
|
||||
nodeKey = ctx.formatExpression(nodeKey);
|
||||
ctx.addLine(`const nodeKey${nodeID} = ${ctx.formatExpression(nodeKey)}`);
|
||||
nodeKey = `nodeKey${nodeID}`;
|
||||
ctx.lastNodeKey = nodeKey;
|
||||
} else {
|
||||
nodeKey = nodeID;
|
||||
}
|
||||
@@ -685,7 +745,7 @@ export class QWeb extends EventBus {
|
||||
return nodeID;
|
||||
}
|
||||
|
||||
_compileChildren(node: ChildNode, ctx: Context) {
|
||||
_compileChildren(node: ChildNode, ctx: CompilationContext) {
|
||||
if (node.childNodes.length > 0) {
|
||||
for (let child of Array.from(node.childNodes)) {
|
||||
this._compileNode(child, ctx);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { RouterEnv } from "./Router";
|
||||
|
||||
export function makeDirective(env: RouterEnv) {
|
||||
return {
|
||||
name: "routecomponent",
|
||||
priority: 13,
|
||||
atNodeEncounter({ node }): boolean {
|
||||
let first = true;
|
||||
const router = env.router;
|
||||
for (let name of router.routeIds) {
|
||||
const route = router.routes[name];
|
||||
if (route.component) {
|
||||
// make new t t-component element
|
||||
const comp = node.ownerDocument.createElement("t");
|
||||
comp.setAttribute("t-component", "__component__" + route.name);
|
||||
comp.setAttribute(first ? "t-if" : "t-elif", `env.router.currentRouteName === '${route.name}'`);
|
||||
first = false;
|
||||
for (let param of route.params) {
|
||||
comp.setAttribute(param, `env.router.currentParams.${param}`);
|
||||
}
|
||||
node.appendChild(comp);
|
||||
}
|
||||
}
|
||||
node.removeAttribute("t-routecomponent");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
import { Component } from "../component/component";
|
||||
import { Destination, RouterEnv } from "./Router";
|
||||
import { xml } from "../tags";
|
||||
import { Destination, RouterEnv } from "./router";
|
||||
|
||||
export const LINK_TEMPLATE_NAME = "__owl__-router-link";
|
||||
export const LINK_TEMPLATE = `
|
||||
type Props = Destination;
|
||||
|
||||
export class Link<Env extends RouterEnv> extends Component<Env, Props> {
|
||||
static template = xml`
|
||||
<a t-att-class="{'router-link-active': isActive }"
|
||||
t-att-href="href"
|
||||
t-on-click="navigate">
|
||||
<t t-slot="default"/>
|
||||
</a>`;
|
||||
</a>
|
||||
`;
|
||||
|
||||
type Props = Destination;
|
||||
|
||||
export class Link<Env extends RouterEnv> extends Component<Env, Props, {}> {
|
||||
template = LINK_TEMPLATE_NAME;
|
||||
href: string = this.env.router.destToPath(this.props);
|
||||
|
||||
async willUpdateProps(nextProps) {
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Component } from "../component/component";
|
||||
import { xml } from "../tags";
|
||||
|
||||
export class RouteComponent extends Component<any, {}> {
|
||||
static template = xml`
|
||||
<t>
|
||||
<t
|
||||
t-if="routeComponent"
|
||||
t-component="routeComponent"
|
||||
t-key="env.router.currentRouteName"
|
||||
t-props="env.router.currentParams" />
|
||||
</t>
|
||||
`;
|
||||
|
||||
get routeComponent(): any {
|
||||
return this.env.router.currentRoute && this.env.router.currentRoute.component;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Env } from "../component/component";
|
||||
import { QWeb } from "../qweb/index";
|
||||
import { makeDirective } from "./directive";
|
||||
import { LINK_TEMPLATE, LINK_TEMPLATE_NAME } from "./Link";
|
||||
import { shallowEqual } from "../utils";
|
||||
|
||||
type NavigationGuard = (info: {
|
||||
env: Env;
|
||||
@@ -74,7 +73,7 @@ export class Router {
|
||||
partialRoute.name = "__route__" + nextId++;
|
||||
}
|
||||
if (partialRoute.component) {
|
||||
QWeb.register("__component__" + partialRoute.name, partialRoute.component);
|
||||
QWeb.registerComponent("__component__" + partialRoute.name, partialRoute.component);
|
||||
}
|
||||
if (partialRoute.redirect) {
|
||||
this.validateDestination(partialRoute.redirect);
|
||||
@@ -83,13 +82,6 @@ export class Router {
|
||||
this.routes[partialRoute.name] = partialRoute as Route;
|
||||
this.routeIds.push(partialRoute.name);
|
||||
}
|
||||
|
||||
(this as any)._listener = () => this.matchAndApplyRules(this.currentPath());
|
||||
window.addEventListener("popstate", (this as any)._listener);
|
||||
|
||||
// setup link and directive
|
||||
env.qweb.addTemplate(LINK_TEMPLATE_NAME, LINK_TEMPLATE);
|
||||
QWeb.addDirective(makeDirective(<RouterEnv>env));
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
@@ -97,6 +89,11 @@ export class Router {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
async start() {
|
||||
(this as any)._listener = ev => this._navigate(this.currentPath(), ev);
|
||||
window.addEventListener("popstate", (this as any)._listener);
|
||||
if (this.mode === "hash") {
|
||||
window.addEventListener("hashchange", (this as any)._listener);
|
||||
}
|
||||
const result = await this.matchAndApplyRules(this.currentPath());
|
||||
if (result.type === "match") {
|
||||
this.currentRoute = result.route;
|
||||
@@ -110,18 +107,27 @@ export class Router {
|
||||
|
||||
async navigate(to: Destination): Promise<boolean> {
|
||||
const path = this.destToPath(to);
|
||||
return this._navigate(path);
|
||||
}
|
||||
async _navigate(path: string, ev?: any): Promise<boolean> {
|
||||
const initialName = this.currentRouteName;
|
||||
const initialParams = this.currentParams;
|
||||
const result = await this.matchAndApplyRules(path);
|
||||
if (result.type === "match") {
|
||||
const finalPath = this.routeToPath(result.route, result.params);
|
||||
this.setUrlFromPath(finalPath);
|
||||
const isPopStateEvent = ev && ev instanceof PopStateEvent;
|
||||
if (!isPopStateEvent) {
|
||||
this.setUrlFromPath(finalPath);
|
||||
}
|
||||
this.currentRoute = result.route;
|
||||
this.currentParams = result.params;
|
||||
} else if (result.type === "nomatch") {
|
||||
this.currentRoute = null;
|
||||
this.currentParams = null;
|
||||
}
|
||||
if (this.currentRouteName !== initialName) {
|
||||
const didChange =
|
||||
this.currentRouteName !== initialName || !shallowEqual(this.currentParams, initialParams);
|
||||
if (didChange) {
|
||||
this.env.qweb.forceUpdate();
|
||||
return true;
|
||||
}
|
||||
@@ -142,8 +148,11 @@ export class Router {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
private setUrlFromPath(path: string) {
|
||||
const url = location.origin + path;
|
||||
window.history.pushState({}, path, url);
|
||||
const separator = this.mode === "hash" ? "/" : "";
|
||||
const url = location.origin + separator + path;
|
||||
if (url !== window.location.href) {
|
||||
window.history.pushState({}, path, url);
|
||||
}
|
||||
}
|
||||
|
||||
private validateDestination(dest: Destination) {
|
||||
@@ -164,7 +173,8 @@ export class Router {
|
||||
parts[i] = <string>params[key];
|
||||
}
|
||||
}
|
||||
return parts.join("/");
|
||||
const prefix = this.mode === "hash" ? "#" : "";
|
||||
return prefix + parts.join("/");
|
||||
}
|
||||
|
||||
private currentPath(): string {
|
||||
@@ -223,6 +233,9 @@ export class Router {
|
||||
if (route.path === "*") {
|
||||
return {};
|
||||
}
|
||||
if (path.startsWith("#")) {
|
||||
path = path.slice(1);
|
||||
}
|
||||
const descrParts = route.path.split("/");
|
||||
const targetParts = path.split("/");
|
||||
const l = descrParts.length;
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { Component } from "./component/component";
|
||||
import { Env } from "./component/component";
|
||||
import { Context, useContextWithCB } from "./context";
|
||||
import { onWillUpdateProps } from "./hooks";
|
||||
|
||||
/**
|
||||
* Owl Store
|
||||
*
|
||||
* We have here:
|
||||
* - a Store class
|
||||
* - useStore hook
|
||||
* - useDispatch hook
|
||||
* - useGetters hook
|
||||
*
|
||||
* The Owl store is our answer to the problem of managing complex state across
|
||||
* components. The main idea is that the store owns some state, allow external
|
||||
* code to modify it through actions, and for each state changes,
|
||||
* connected component will be notified, and updated if necessary.
|
||||
*
|
||||
* Note that this code is partly inspired by VueX and React/Redux
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Store Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
||||
export type Getter = ({ state: any, getters }, payload?) => any;
|
||||
|
||||
interface StoreConfig {
|
||||
env?: Env;
|
||||
state?: any;
|
||||
actions?: { [name: string]: Action };
|
||||
getters?: { [name: string]: Getter };
|
||||
}
|
||||
|
||||
export class Store extends Context {
|
||||
actions: any;
|
||||
env: any;
|
||||
getters: { [name: string]: (payload?) => any };
|
||||
updateFunctions: { [key: number]: (() => boolean)[] };
|
||||
|
||||
constructor(config: StoreConfig) {
|
||||
super(config.state);
|
||||
this.actions = config.actions;
|
||||
this.env = config.env;
|
||||
this.getters = {};
|
||||
this.updateFunctions = [];
|
||||
if (config.getters) {
|
||||
const firstArg = {
|
||||
state: this.state,
|
||||
getters: this.getters
|
||||
};
|
||||
for (let g in config.getters) {
|
||||
this.getters[g] = config.getters[g].bind(this, firstArg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(action: string, ...payload: any): Promise<void> | void {
|
||||
if (!this.actions[action]) {
|
||||
throw new Error(`[Error] action ${action} is undefined`);
|
||||
}
|
||||
const result = this.actions[action](
|
||||
{
|
||||
dispatch: this.dispatch.bind(this),
|
||||
env: this.env,
|
||||
state: this.state,
|
||||
getters: this.getters
|
||||
},
|
||||
...payload
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
interface SelectorOptions {
|
||||
store?: Store;
|
||||
isEqual?: (a: any, b: any) => boolean;
|
||||
}
|
||||
|
||||
const isStrictEqual = (a, b) => a === b;
|
||||
|
||||
export function useStore(selector, options: SelectorOptions = {}): any {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
const store = options.store || (component.env.store as Store);
|
||||
let result = selector(store.state, component.props);
|
||||
const hashFn = store.observer.deepRevNumber.bind(store.observer);
|
||||
let revNumber = hashFn(result) || result;
|
||||
const isEqual = options.isEqual || isStrictEqual;
|
||||
if (!store.updateFunctions[component.__owl__.id]) {
|
||||
store.updateFunctions[component.__owl__.id] = [];
|
||||
}
|
||||
const updateFunctions = store.updateFunctions[component.__owl__.id];
|
||||
updateFunctions.push(function(): boolean {
|
||||
const oldResult = result;
|
||||
result = selector(store!.state, component.props);
|
||||
const newRevNumber = hashFn(result);
|
||||
if (
|
||||
(newRevNumber > 0 && revNumber !== newRevNumber) ||
|
||||
(newRevNumber === 0 && !isEqual(oldResult, result))
|
||||
) {
|
||||
revNumber = newRevNumber;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
useContextWithCB(store, component, function(): Promise<void> | void {
|
||||
let shouldRender = false;
|
||||
updateFunctions.forEach(function(updateFn) {
|
||||
shouldRender = updateFn() || shouldRender;
|
||||
});
|
||||
if (shouldRender) {
|
||||
return component.render();
|
||||
}
|
||||
});
|
||||
onWillUpdateProps(props => {
|
||||
// FIXME: only do that if not keepalive + do it in destroy in that case
|
||||
delete store.updateFunctions[component.__owl__.id];
|
||||
result = selector(store.state, props);
|
||||
});
|
||||
return new Proxy(result, {
|
||||
get(target, k) {
|
||||
return result[k];
|
||||
},
|
||||
set(target, k, v) {
|
||||
result[k] = v;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function useDispatch(store?: Store): Store["dispatch"] {
|
||||
store = store || (Component.current!.env.store as Store);
|
||||
return store.dispatch.bind(store);
|
||||
}
|
||||
|
||||
export function useGetters(store?: Store): Store["getters"] {
|
||||
store = store || (Component.current!.env.store as Store);
|
||||
return store.getters;
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { Component, Env } from "../component/component";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Connect function
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
type HashFunction = (a: any, b: any) => number;
|
||||
|
||||
export class ConnectedComponent<T extends Env, P, S> extends Component<T, P, S> {
|
||||
deep: boolean = true;
|
||||
getStore(env) {
|
||||
return env.store;
|
||||
}
|
||||
|
||||
storeProps: any;
|
||||
|
||||
hashFunction: HashFunction = (storeProps, options) => {
|
||||
const revFn = (this.__owl__ as any).revFn;
|
||||
const rev = revFn(storeProps);
|
||||
if (rev > 0) {
|
||||
return rev;
|
||||
}
|
||||
let hash = 0;
|
||||
for (let key in storeProps) {
|
||||
const val = storeProps[key];
|
||||
const hashVal = revFn(val);
|
||||
if (hashVal === 0) {
|
||||
if (val !== options.prevStoreProps[key]) {
|
||||
options.didChange = true;
|
||||
}
|
||||
} else {
|
||||
hash += hashVal;
|
||||
}
|
||||
}
|
||||
return hash;
|
||||
};
|
||||
|
||||
static mapStoreToProps(storeState, ownProps, getters) {
|
||||
return {};
|
||||
}
|
||||
|
||||
dispatch(name, ...payload) {
|
||||
return (this.__owl__ as any).store.dispatch(name, ...payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Need to do this here so 'deep' can be overrided by subcomponent easily
|
||||
*/
|
||||
async __prepareAndRender(
|
||||
scope?: Object,
|
||||
vars?: any
|
||||
): ReturnType<Component<any, any, any>["__prepareAndRender"]> {
|
||||
const store = this.getStore(this.env);
|
||||
const ownProps = this.props || {};
|
||||
this.storeProps = (<any>this.constructor).mapStoreToProps(store.state, ownProps, store.getters);
|
||||
const observer = store.observer;
|
||||
const revFn = this.deep ? observer.deepRevNumber : observer.revNumber;
|
||||
(this.__owl__ as any).store = store;
|
||||
(this.__owl__ as any).revFn = revFn.bind(observer);
|
||||
(this.__owl__ as any).storeHash = this.hashFunction(this.storeProps, {
|
||||
prevStoreProps: this.storeProps
|
||||
});
|
||||
(this.__owl__ as any).rev = observer.rev;
|
||||
return super.__prepareAndRender(scope, vars);
|
||||
}
|
||||
/**
|
||||
* We do not use the mounted hook here for a subtle reason: we want the
|
||||
* updates to be called for the parents before the children. However,
|
||||
* if we use the mounted hook, this will be done in the reverse order.
|
||||
*/
|
||||
__callMounted() {
|
||||
(this.__owl__ as any).store.on("update", this, this.__checkUpdate);
|
||||
super.__callMounted();
|
||||
}
|
||||
__callWillUnmount() {
|
||||
(this.__owl__ as any).store.off("update", this);
|
||||
super.__callWillUnmount();
|
||||
}
|
||||
__destroy(parent: any) {
|
||||
(this.__owl__ as any).store.off("update", this);
|
||||
super.__destroy(parent);
|
||||
}
|
||||
|
||||
async __updateProps(nextProps: P, f, p, s, v) {
|
||||
this.__updateStoreProps(nextProps);
|
||||
return super.__updateProps(nextProps, f, p, s, v);
|
||||
}
|
||||
|
||||
__updateStoreProps(nextProps): boolean {
|
||||
const store = (this.__owl__ as any).store;
|
||||
const storeProps = (<any>this.constructor).mapStoreToProps(
|
||||
store.state,
|
||||
nextProps,
|
||||
store.getters
|
||||
);
|
||||
const options = { prevStoreProps: this.storeProps, didChange: false };
|
||||
const storeHash = this.hashFunction(storeProps, options);
|
||||
this.storeProps = storeProps;
|
||||
let didChange = options.didChange;
|
||||
if (storeHash !== (this.__owl__ as any).storeHash) {
|
||||
(this.__owl__ as any).storeHash = storeHash;
|
||||
didChange = true;
|
||||
}
|
||||
(this.__owl__ as any).rev = store.observer.rev;
|
||||
return didChange;
|
||||
}
|
||||
|
||||
async __checkUpdate() {
|
||||
const observer = (this.__owl__ as any).store.observer;
|
||||
if (observer.rev === (this.__owl__ as any).rev) {
|
||||
// update was already done by updateProps, from parent
|
||||
return;
|
||||
}
|
||||
const didChange = this.__updateStoreProps(this.props);
|
||||
if (didChange) {
|
||||
return this.render();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { Env } from "../component/component";
|
||||
import { EventBus } from "../core/event_bus";
|
||||
import { Observer } from "../core/observer";
|
||||
|
||||
/**
|
||||
* Owl Store
|
||||
*
|
||||
* We have here:
|
||||
* - a Store class
|
||||
* - the ConnectedComponent class
|
||||
*
|
||||
* The Owl store is our answer to the problem of managing complex state across
|
||||
* components. The main idea is that the store owns some state, allow external
|
||||
* code to modify it through actions, and for each state changes,
|
||||
* connected component will be notified, and updated if necessary.
|
||||
*
|
||||
* Note that this code is partly inspired by VueX and React/Redux
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Store Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export type Action = ({ state, dispatch, env, getters }, ...payload: any) => any;
|
||||
export type Getter = ({ state: any, getters }, payload?) => any;
|
||||
|
||||
interface StoreConfig {
|
||||
env?: Env;
|
||||
state?: any;
|
||||
actions?: { [name: string]: Action };
|
||||
getters?: { [name: string]: Getter };
|
||||
}
|
||||
|
||||
interface StoreOption {
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
export class Store extends EventBus {
|
||||
state: any;
|
||||
actions: any;
|
||||
mutations: any;
|
||||
debug: boolean;
|
||||
env: any;
|
||||
observer: Observer;
|
||||
getters: { [name: string]: (payload?) => any };
|
||||
|
||||
constructor(config: StoreConfig, options: StoreOption = {}) {
|
||||
super();
|
||||
this.debug = options.debug || false;
|
||||
this.actions = config.actions;
|
||||
this.env = config.env;
|
||||
this.observer = new Observer();
|
||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
||||
this.state = this.observer.observe(config.state || {});
|
||||
this.getters = {};
|
||||
if (config.getters) {
|
||||
const firstArg = {
|
||||
state: this.state,
|
||||
getters: this.getters,
|
||||
};
|
||||
for (let g in config.getters) {
|
||||
this.getters[g] = config.getters[g].bind(this, firstArg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(action: string, ...payload: any): Promise<void> | void {
|
||||
if (!this.actions[action]) {
|
||||
throw new Error(`[Error] action ${action} is undefined`);
|
||||
}
|
||||
const result = this.actions[action](
|
||||
{
|
||||
dispatch: this.dispatch.bind(this),
|
||||
env: this.env,
|
||||
state: this.state,
|
||||
getters: this.getters
|
||||
},
|
||||
...payload
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instead of using trigger to emit an update event, we actually implement
|
||||
* our own function to do that. The reason is that we need to be smarter than
|
||||
* a simple trigger function: we need to wait for parent components to be
|
||||
* done before doing children components. The reason is that if an update
|
||||
* as an effect of destroying a children, we do not want to call the
|
||||
* mapStoreToProps function of the child, nor rendering it.
|
||||
*
|
||||
* This method is not optimal if we have a bunch of asynchronous components:
|
||||
* we wait sequentially for each component to be completed before updating the
|
||||
* next. However, the only things that matters is that children are updated
|
||||
* after their parents. So, this could be optimized by being smarter, and
|
||||
* updating all widgets concurrently, except for parents/children.
|
||||
*/
|
||||
async __notifyComponents() {
|
||||
const subs = this.subscriptions.update || [];
|
||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
||||
const sub = subs[i];
|
||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
||||
if (shouldCallback) {
|
||||
await sub.callback.call(sub.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { QWeb } from "./qweb/index";
|
||||
|
||||
/**
|
||||
* Owl Tags
|
||||
*
|
||||
* We have here a (very) small collection of tag functions:
|
||||
*
|
||||
* - xml
|
||||
*
|
||||
* The plan is to add a few other tags such as css, globalcss.
|
||||
*/
|
||||
|
||||
/**
|
||||
* XML tag helper for defining templates. With this, one can simply define
|
||||
* an inline template with just the template xml:
|
||||
* ```js
|
||||
* class A extends Component {
|
||||
* static template = xml`<div>some template</div>`;
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function xml(strings, ...args) {
|
||||
const name = `__template__${QWeb.nextId++}`;
|
||||
const value = String.raw(strings, ...args);
|
||||
QWeb.registerTemplate(name, value);
|
||||
return name;
|
||||
}
|
||||
+12
-5
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* - whenReady
|
||||
* - loadJS
|
||||
* - loadTemplates
|
||||
* - loadFile
|
||||
* - escape
|
||||
* - debounce
|
||||
*/
|
||||
@@ -43,14 +43,12 @@ export function loadJS(url: string): Promise<void> {
|
||||
return promise;
|
||||
}
|
||||
|
||||
export async function loadTemplates(url: string): Promise<string> {
|
||||
export async function loadFile(url: string): Promise<string> {
|
||||
const result = await fetch(url);
|
||||
if (!result.ok) {
|
||||
throw new Error("Error while fetching xml templates");
|
||||
}
|
||||
let templates = await result.text();
|
||||
templates = templates.replace(/<!--[\s\S]*?-->/g, "");
|
||||
return templates;
|
||||
return await result.text();
|
||||
}
|
||||
|
||||
export function escape(str: string | number | undefined): string {
|
||||
@@ -95,3 +93,12 @@ export function debounce(func: Function, wait: number, immediate?: boolean): Fun
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function shallowEqual(p1, p2): boolean {
|
||||
for (let k in p1) {
|
||||
if (p1[k] !== p2[k]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { VNode, h } from "./vdom";
|
||||
|
||||
const parser = new DOMParser();
|
||||
|
||||
export function htmlToVDOM(html: string): VNode[] {
|
||||
const doc = parser.parseFromString(html, "text/html");
|
||||
const result: VNode[] = [];
|
||||
for (let child of doc.body.childNodes) {
|
||||
result.push(htmlToVNode(child));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function htmlToVNode(node: ChildNode): VNode {
|
||||
if (!(node instanceof Element)) {
|
||||
return { text: node.textContent! } as VNode;
|
||||
}
|
||||
const attrs = {};
|
||||
for (let attr of node.attributes) {
|
||||
attrs[attr.name] = attr.textContent;
|
||||
}
|
||||
const children: VNode[] = [];
|
||||
if (node.hasChildNodes) {
|
||||
for (let c of node.childNodes) {
|
||||
children.push(htmlToVNode(c));
|
||||
}
|
||||
}
|
||||
return h((node as Element).tagName, { attrs }, children);
|
||||
}
|
||||
+12
-22
@@ -176,18 +176,10 @@ export function init(modules: Array<Partial<Module>>, domApi?: DOMAPI) {
|
||||
}
|
||||
vnode.elm = api.createComment(vnode.text as string);
|
||||
} else if (sel !== undefined) {
|
||||
// Parse selector
|
||||
const hashIdx = sel.indexOf("#");
|
||||
const dotIdx = sel.indexOf(".", hashIdx);
|
||||
const hash = hashIdx > 0 ? hashIdx : sel.length;
|
||||
const dot = dotIdx > 0 ? dotIdx : sel.length;
|
||||
const tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
|
||||
const elm = (vnode.elm =
|
||||
isDef(data) && isDef((i = (data as VNodeData).ns))
|
||||
? api.createElementNS(i, tag)
|
||||
: api.createElement(tag));
|
||||
if (hash < dot) elm.setAttribute("id", sel.slice(hash + 1, dot));
|
||||
if (dotIdx > 0) elm.setAttribute("class", sel.slice(dot + 1).replace(/\./g, " "));
|
||||
? api.createElementNS(i, sel)
|
||||
: api.createElement(sel));
|
||||
for (i = 0, iLen = cbs.create.length; i < iLen; ++i) cbs.create[i](emptyNode, vnode);
|
||||
if (array(children)) {
|
||||
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
||||
@@ -526,7 +518,7 @@ const htmlDomApi = {
|
||||
parentNode,
|
||||
nextSibling,
|
||||
tagName,
|
||||
setTextContent,
|
||||
setTextContent
|
||||
} as DOMAPI;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -564,13 +556,19 @@ type VNodeChildElement = VNode | string | number | undefined | null;
|
||||
type ArrayOrElement<T> = T | T[];
|
||||
type VNodeChildren = ArrayOrElement<VNodeChildElement>;
|
||||
|
||||
function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
|
||||
export function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
|
||||
if (sel === "dummy") {
|
||||
// we do not need to add the namespace on dummy elements, they come from a
|
||||
// subcomponent, which will handle the namespace itself
|
||||
return;
|
||||
}
|
||||
data.ns = "http://www.w3.org/2000/svg";
|
||||
if (sel !== "foreignObject" && children !== undefined) {
|
||||
for (let i = 0, iLen = children.length; i < iLen; ++i) {
|
||||
let childData = children[i].data;
|
||||
const child = children[i];
|
||||
let childData = child.data;
|
||||
if (childData !== undefined) {
|
||||
addNS(childData, (children[i] as VNode).children as VNodes, children[i].sel);
|
||||
addNS(childData, (child as VNode).children as VNodes, child.sel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -612,13 +610,5 @@ export function h(sel: any, b?: any, c?: any): VNode {
|
||||
children[i] = vnode(undefined, undefined, undefined, children[i], undefined);
|
||||
}
|
||||
}
|
||||
if (
|
||||
sel[0] === "s" &&
|
||||
sel[1] === "v" &&
|
||||
sel[2] === "g" &&
|
||||
(sel.length === 3 || sel[3] === "." || sel[3] === "#")
|
||||
) {
|
||||
addNS(data, children, sel);
|
||||
}
|
||||
return vnode(sel, data, children, text, undefined);
|
||||
}
|
||||
|
||||
@@ -7,39 +7,39 @@ exports[`animations t-transition combined with component 1`] = `
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`Child\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w4.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
let componentKey3 = \`Child\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w3.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
@@ -51,40 +51,40 @@ exports[`animations t-transition combined with t-component and t-if 1`] = `
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['state'].display) {
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`Child\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w4.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
let componentKey3 = \`Child\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w3.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
@@ -94,6 +94,7 @@ exports[`animations t-transition with no delay/duration 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('span', p1, c1);
|
||||
@@ -114,6 +115,7 @@ exports[`animations t-transition, on a simple node (insert) 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('span', p1, c1);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`various scenarios scenarios with async store updates and some components events 1`] = `"<div><button>Do stuff</button><div><span>Attachment 100</span><span>Name: text.txt</span></div></div>"`;
|
||||
|
||||
exports[`various scenarios scenarios with async store updates and some components events 2`] = `"<div><button>Do stuff</button></div>"`;
|
||||
+20
-45
@@ -1,10 +1,10 @@
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { QWeb } from "../src/qweb/index";
|
||||
import { useState, useRef } from "../src/hooks";
|
||||
import {
|
||||
makeDeferred,
|
||||
makeTestFixture,
|
||||
makeTestEnv,
|
||||
nextTick,
|
||||
patchNextFrame,
|
||||
renderToDOM,
|
||||
unpatchNextFrame
|
||||
@@ -36,7 +36,7 @@ afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
class Widget extends Component<any, any, any> {}
|
||||
class Widget extends Component<any, any> {}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tests
|
||||
@@ -106,7 +106,7 @@ describe("animations", () => {
|
||||
`<div><span t-if="!state.hide" t-transition="chimay">blue</span></div>`
|
||||
);
|
||||
class TestWidget extends Widget {
|
||||
state = { hide: false };
|
||||
state = useState({ hide: false });
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
|
||||
@@ -148,7 +148,8 @@ describe("animations", () => {
|
||||
`<div><span t-ref="span" t-transition="chimay">blue</span></div>`
|
||||
);
|
||||
class TestWidget extends Widget {
|
||||
state = { hide: false };
|
||||
state = useState({ hide: false });
|
||||
span = useRef("span");
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
|
||||
@@ -163,7 +164,7 @@ describe("animations", () => {
|
||||
});
|
||||
await widget.mount(fixture);
|
||||
spanNode = widget.el!.children[0];
|
||||
expect(widget.refs.span).toBe(spanNode);
|
||||
expect(widget.span.el).toBe(spanNode);
|
||||
expect(spanNode.className).toBe("chimay-enter chimay-enter-active");
|
||||
await def; // wait for the mocked repaint to be done
|
||||
spanNode.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
@@ -175,10 +176,10 @@ describe("animations", () => {
|
||||
|
||||
env.qweb.addTemplate("Parent", `<div><Child t-transition="chimay"/></div>`);
|
||||
env.qweb.addTemplate("Child", `<span>blue</span>`);
|
||||
class Parent extends Widget {
|
||||
components = { Child: Child };
|
||||
}
|
||||
class Child extends Widget {}
|
||||
class Parent extends Widget {
|
||||
static components = { Child: Child };
|
||||
}
|
||||
const widget = new Parent(env);
|
||||
|
||||
let def = makeDeferred();
|
||||
@@ -214,11 +215,11 @@ describe("animations", () => {
|
||||
`<div><t t-if="state.display" t-component="Child" t-transition="chimay"/></div>`
|
||||
);
|
||||
env.qweb.addTemplate("Child", `<span>blue</span>`);
|
||||
class Parent extends Widget {
|
||||
components = { Child: Child };
|
||||
state = { display: true };
|
||||
}
|
||||
class Child extends Widget {}
|
||||
class Parent extends Widget {
|
||||
static components = { Child: Child };
|
||||
state = useState({ display: true });
|
||||
}
|
||||
const widget = new Parent(env);
|
||||
|
||||
let def = makeDeferred();
|
||||
@@ -250,11 +251,11 @@ describe("animations", () => {
|
||||
widget.state.display = false;
|
||||
patchNextFrame(cb => {
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="4">blue</span></div>'
|
||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__4__">blue</span></div>'
|
||||
);
|
||||
cb();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="4">blue</span></div>'
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__4__">blue</span></div>'
|
||||
);
|
||||
def.resolve();
|
||||
});
|
||||
@@ -263,28 +264,6 @@ describe("animations", () => {
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
});
|
||||
|
||||
test("t-transition combined with t-mounted", async () => {
|
||||
env.qweb.addTemplate(
|
||||
"TestWidget",
|
||||
`<div><span t-if="state.flag" t-mounted="f" t-transition="chimay">blue</span></div>`
|
||||
);
|
||||
class TestWidget extends Widget {
|
||||
state = { flag: false };
|
||||
f() {}
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
widget.f = jest.fn();
|
||||
await widget.mount(fixture);
|
||||
|
||||
patchNextFrame(cb => cb());
|
||||
expect(widget.f).toHaveBeenCalledTimes(0);
|
||||
|
||||
widget.state.flag = true;
|
||||
await nextTick();
|
||||
expect(widget.f).toHaveBeenCalledTimes(1);
|
||||
unpatchNextFrame();
|
||||
});
|
||||
|
||||
test("t-transition, remove and re-add before transitionend", async () => {
|
||||
expect.assertions(11);
|
||||
|
||||
@@ -297,10 +276,8 @@ describe("animations", () => {
|
||||
</templates>`
|
||||
);
|
||||
class Parent extends Widget {
|
||||
constructor(parent) {
|
||||
super(parent);
|
||||
this.state = { flag: false };
|
||||
}
|
||||
state = useState({ flag: false });
|
||||
|
||||
toggle() {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
@@ -356,11 +333,9 @@ describe("animations", () => {
|
||||
);
|
||||
class Child extends Widget {}
|
||||
class Parent extends Widget {
|
||||
components = { Child };
|
||||
constructor(parent) {
|
||||
super(parent);
|
||||
this.state = { flag: false };
|
||||
}
|
||||
static components = { Child };
|
||||
state = useState({ flag: false });
|
||||
|
||||
toggle() {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,5 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`default props default values are also set whenever component is updated 1`] = `"<div>1</div>"`;
|
||||
|
||||
exports[`default props default values are also set whenever component is updated 2`] = `"<div>4</div>"`;
|
||||
|
||||
exports[`props validation props are validated in dev mode (code snapshot) 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
@@ -11,38 +7,37 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {message:1};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let props3 = {message:1};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`Child\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
utils.validateProps(W4, props4)
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
if (w3) {
|
||||
utils.validateProps(w3.constructor, props3)
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
utils.validateProps(w4.constructor, props4)
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
let componentKey3 = \`Child\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
+1963
-1040
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,8 @@
|
||||
import { Component, Env } from "../../src/component/component";
|
||||
import { makeTestFixture, makeTestEnv } from "../helpers";
|
||||
import { makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||
import { useState } from "../../src/hooks";
|
||||
import { QWeb } from "../../src/qweb";
|
||||
import { xml } from "../../src/tags";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup and helpers
|
||||
@@ -22,7 +24,7 @@ afterEach(() => {
|
||||
QWeb.dev = dev;
|
||||
});
|
||||
|
||||
class Widget extends Component<any, any, any> {}
|
||||
class Widget extends Component<any, any> {}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tests
|
||||
@@ -31,6 +33,7 @@ describe("props validation", () => {
|
||||
test("validation is only done in dev mode", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = ["message"];
|
||||
static template = xml`<div>hey</div>`;
|
||||
}
|
||||
|
||||
QWeb.dev = true;
|
||||
@@ -48,6 +51,7 @@ describe("props validation", () => {
|
||||
test("props: list of strings", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = ["message"];
|
||||
static template = xml`<div>hey</div>`;
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
@@ -67,6 +71,7 @@ describe("props validation", () => {
|
||||
|
||||
for (let test of Tests) {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: test.type };
|
||||
};
|
||||
|
||||
@@ -96,6 +101,7 @@ describe("props validation", () => {
|
||||
|
||||
for (let test of Tests) {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: test.type } };
|
||||
};
|
||||
|
||||
@@ -115,6 +121,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate a prop with multiple types", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: [String, Boolean] };
|
||||
};
|
||||
|
||||
@@ -130,6 +137,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate an optional props", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: String, optional: true } };
|
||||
};
|
||||
|
||||
@@ -145,6 +153,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate an array with given primitive type", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: Array, element: String } };
|
||||
};
|
||||
|
||||
@@ -164,6 +173,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate an array with multiple sub element types", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: Array, element: [String, Boolean] } };
|
||||
};
|
||||
|
||||
@@ -180,6 +190,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate an object with simple shape", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = {
|
||||
p: { type: Object, shape: { id: Number, url: String } }
|
||||
};
|
||||
@@ -201,6 +212,7 @@ describe("props validation", () => {
|
||||
|
||||
test("can validate recursively complicated prop def", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = {
|
||||
p: {
|
||||
type: Object,
|
||||
@@ -235,7 +247,7 @@ describe("props validation", () => {
|
||||
static props = ["message"];
|
||||
}
|
||||
class App extends Widget {
|
||||
components = { Child };
|
||||
static components = { Child };
|
||||
}
|
||||
const app = new App(env);
|
||||
await app.mount(fixture);
|
||||
@@ -280,7 +292,7 @@ describe("props validation", () => {
|
||||
|
||||
test("props: extra props cause an error, part 2", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = {message: true};
|
||||
static props = { message: true };
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
@@ -294,29 +306,29 @@ describe("props validation", () => {
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { message: 1});
|
||||
QWeb.utils.validateProps(TestWidget, { message: 1 });
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
test("optional prop do not cause an error if value is undefined", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = {message: {type: String, optional: true}};
|
||||
static props = { message: { type: String, optional: true } };
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { message: undefined});
|
||||
QWeb.utils.validateProps(TestWidget, { message: undefined });
|
||||
}).not.toThrow();
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { message: null});
|
||||
QWeb.utils.validateProps(TestWidget, { message: null });
|
||||
}).toThrow();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("default props", () => {
|
||||
test("can set default values", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static defaultProps = { p: 4 };
|
||||
static template = xml`<div>hey</div>`;
|
||||
}
|
||||
|
||||
const w = new TestWidget(env, {});
|
||||
@@ -325,19 +337,38 @@ describe("default props", () => {
|
||||
|
||||
test("default values are also set whenever component is updated", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||
static defaultProps = { p: 4 };
|
||||
}
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="TestWidget"><t t-esc="props.p"/></div>
|
||||
</templates>`);
|
||||
class Parent extends Widget {
|
||||
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
state: any = useState({ p: 1 });
|
||||
}
|
||||
|
||||
const w = new TestWidget(env, { p: 1 });
|
||||
const w = new Parent(env);
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
await w.__updateProps({});
|
||||
await w.render();
|
||||
expect(w.props.p).toBe(4);
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
|
||||
w.state.p = undefined;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||
});
|
||||
|
||||
test("can set default required boolean values", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = ["p", "q"];
|
||||
static defaultProps = { p: true, q: false };
|
||||
static template = xml`<span><t t-if="props.p">hey</t><t t-if="!props.q">hey</t></span>`;
|
||||
}
|
||||
|
||||
class App extends Widget {
|
||||
static template = xml`<div><TestWidget/></div>`;
|
||||
static components = { TestWidget };
|
||||
}
|
||||
|
||||
const w = new App(env, {});
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>heyhey</span></div>");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { Context, useContext } from "../src/context";
|
||||
import { xml } from "../src/tags";
|
||||
import { useState } from "../src/hooks";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// We create before each test:
|
||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||
// manipulations. Note that it is removed after each test.
|
||||
// - env: a WEnv, necessary to create new components
|
||||
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tests
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
describe("Context", () => {
|
||||
test("very simple use, with initial value", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
|
||||
class Test extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||
contextObj = useContext(testContext);
|
||||
}
|
||||
const test = new Test(env);
|
||||
await test.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||
});
|
||||
|
||||
test("useContext hook is reactive, for one component", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
|
||||
class Test extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||
contextObj = useContext(testContext);
|
||||
}
|
||||
const test = new Test(env);
|
||||
await test.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||
test.contextObj.value = 321;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>321</div>");
|
||||
});
|
||||
|
||||
test("two components can subscribe to same context", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||
contextObj = useContext(testContext);
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child /><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||
testContext.state.value = 321;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||
});
|
||||
|
||||
test("one components can subscribe twice to same context", async () => {
|
||||
const testContext = new Context({ a: 1, b: 2 });
|
||||
const steps: string[] = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj1.a"/><t t-esc="contextObj2.b"/></span>`;
|
||||
contextObj1 = useContext(testContext);
|
||||
contextObj2 = useContext(testContext);
|
||||
__render(fiber) {
|
||||
steps.push("child");
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||
expect(steps).toEqual(["child"]);
|
||||
testContext.state.a = 3;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>32</span></div>");
|
||||
expect(steps).toEqual(["child", "child"]);
|
||||
});
|
||||
|
||||
test("parent and children subscribed to same context", async () => {
|
||||
const testContext = new Context({ a: 123, b: 321 });
|
||||
const steps: string[] = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||
contextObj = useContext(testContext);
|
||||
__render(fiber) {
|
||||
steps.push("child");
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child /><t t-esc="contextObj.b"/></div>`;
|
||||
static components = { Child };
|
||||
contextObj = useContext(testContext);
|
||||
__render(fiber) {
|
||||
steps.push("parent");
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
|
||||
parent.contextObj.a = 124;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>124</span>321</div>");
|
||||
|
||||
// we only want one render from the child here, not two
|
||||
expect(steps).toEqual(["parent", "child", "parent", "child"]);
|
||||
});
|
||||
|
||||
test("destroyed component is inactive", async () => {
|
||||
const testContext = new Context({ a: 123 });
|
||||
const steps: string[] = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||
contextObj = useContext(testContext);
|
||||
__render(fiber) {
|
||||
steps.push("child");
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||
static components = { Child };
|
||||
state = useState({ flag: true });
|
||||
__render(fiber) {
|
||||
steps.push("parent");
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
expect(testContext.subscriptions.update.length).toBe(1);
|
||||
|
||||
parent.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(steps).toEqual(["parent", "child", "parent"]);
|
||||
// kind of whitebox...
|
||||
// we make sure we do not have any pending subscriptions to the 'update'
|
||||
// event
|
||||
expect(testContext.subscriptions.update.length).toBe(0);
|
||||
});
|
||||
|
||||
test("concurrent renderings", async () => {
|
||||
const testContext = new Context({ x: { n: 1 }, key: "x" });
|
||||
const def = makeDeferred();
|
||||
let stateC;
|
||||
class ComponentC extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="context[props.key].n"/><t t-esc="state.x"/></span>`;
|
||||
context = useContext(testContext);
|
||||
state = useState({ x: "a" });
|
||||
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
stateC = this.state;
|
||||
}
|
||||
}
|
||||
class ComponentB extends Component<any, any> {
|
||||
static components = { ComponentC };
|
||||
static template = xml`<p><ComponentC key="props.key"/></p>`;
|
||||
|
||||
willUpdateProps() {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
class ComponentA extends Component<any, any> {
|
||||
static components = { ComponentB };
|
||||
static template = xml`<div><ComponentB key="context.key"/></div>`;
|
||||
context = useContext(testContext);
|
||||
}
|
||||
|
||||
const component = new ComponentA(env);
|
||||
await component.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||
testContext.state.key = "y";
|
||||
testContext.state.y = {n: 2};
|
||||
delete testContext.state.x;
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||
stateC.x = "b";
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><p><span>2b</span></p></div>");
|
||||
});
|
||||
});
|
||||
@@ -65,7 +65,7 @@ describe("observer", () => {
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(typeof obj.date.getFullYear()).toBe('number');
|
||||
expect(typeof obj.date.getFullYear()).toBe("number");
|
||||
expect(obj.date).toBe(date);
|
||||
|
||||
obj.date = new Date();
|
||||
|
||||
@@ -13,7 +13,8 @@ const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
|
||||
function getFiles(): string[] {
|
||||
const DOCFILES = fs.readdirSync("doc").map(f => `doc/${f}`);
|
||||
const MAINREADME = "README.md";
|
||||
return DOCFILES.concat(MAINREADME);
|
||||
DOCFILES.push("roadmap.md", MAINREADME);
|
||||
return DOCFILES;
|
||||
}
|
||||
|
||||
test("All markdown links work", () => {
|
||||
@@ -53,6 +54,10 @@ interface FileData {
|
||||
}
|
||||
|
||||
function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
|
||||
if (link.link.startsWith("http")) {
|
||||
// no check on external links
|
||||
return true;
|
||||
}
|
||||
const parts = link.link.split("#");
|
||||
const currentParts = current.name.split("/");
|
||||
const path = currentParts.length > 1 ? currentParts[0] + "/" : "";
|
||||
|
||||
+41
-7
@@ -1,16 +1,45 @@
|
||||
import { Env } from "../src/component/component";
|
||||
import { Env, scheduler } from "../src/component/component";
|
||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||
import { patch } from "../src/vdom";
|
||||
import "../src/qweb/base_directives";
|
||||
import "../src/qweb/extensions";
|
||||
import "../src/component/directive";
|
||||
|
||||
// modifies scheduler to make it faster to test components
|
||||
scheduler.requestAnimationFrame = function(callback: FrameRequestCallback) {
|
||||
setTimeout(callback, 1);
|
||||
return 1;
|
||||
};
|
||||
|
||||
// Some static cleanup
|
||||
let nextSlotId;
|
||||
let slots;
|
||||
let nextId;
|
||||
let TEMPLATES;
|
||||
|
||||
beforeEach(() => {
|
||||
nextSlotId = QWeb.nextSlotId;
|
||||
slots = Object.assign({}, QWeb.slots);
|
||||
nextId = QWeb.nextId;
|
||||
TEMPLATES = Object.assign({}, QWeb.TEMPLATES);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
QWeb.nextSlotId = nextSlotId;
|
||||
QWeb.slots = slots;
|
||||
QWeb.nextId = nextId;
|
||||
QWeb.TEMPLATES = TEMPLATES;
|
||||
});
|
||||
|
||||
// helpers
|
||||
export function nextMicroTick(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function nextTick(): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve));
|
||||
export async function nextTick(): Promise<void> {
|
||||
return new Promise(function(resolve) {
|
||||
setTimeout(() => scheduler.requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
export function makeTestFixture() {
|
||||
@@ -78,11 +107,16 @@ export function renderToDOM(
|
||||
* Note that the result of renderToString is guaranteed to be the same as the
|
||||
* one from QWeb.
|
||||
*/
|
||||
export function renderToString(qweb: QWeb, t: string, context: EvalContext = {}): string {
|
||||
const node = renderToDOM(qweb, t, context);
|
||||
export function renderToString(
|
||||
qweb: QWeb,
|
||||
t: string,
|
||||
context: EvalContext = {},
|
||||
extra?: any
|
||||
): string {
|
||||
const node = renderToDOM(qweb, t, context, extra);
|
||||
const result = node instanceof Text ? node.textContent! : node.outerHTML;
|
||||
if (result !== qweb.renderToString(t, context)) {
|
||||
throw new Error("HTML string returned by renderToString helper does not match QWeb render");
|
||||
if (result !== qweb.renderToString(t, context, extra)) {
|
||||
throw new Error("HTML string returned by renderToString helper does not match QWeb render");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import {
|
||||
useState,
|
||||
onMounted,
|
||||
onWillUnmount,
|
||||
useRef,
|
||||
onPatched,
|
||||
onWillPatch,
|
||||
onWillStart,
|
||||
onWillUpdateProps,
|
||||
useSubEnv
|
||||
} from "../src/hooks";
|
||||
import { xml } from "../src/tags";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// We create before each test:
|
||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||
// manipulations. Note that it is removed after each test.
|
||||
// - env: a WEnv, necessary to create new components
|
||||
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tests
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
describe("hooks", () => {
|
||||
test("can use a state hook", async () => {
|
||||
class Counter extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
||||
counter = useState({ value: 42 });
|
||||
}
|
||||
const counter = new Counter(env);
|
||||
await counter.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>42</div>");
|
||||
counter.counter.value = 3;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||
});
|
||||
|
||||
test("can use onMounted, onWillUnmount", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onMounted(() => {
|
||||
steps.push("mounted");
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
steps.push("willunmount");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(component).not.toHaveProperty("mounted");
|
||||
expect(component).not.toHaveProperty("willUnmount");
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
expect(steps).toEqual(["mounted"]);
|
||||
component.unmount();
|
||||
expect(fixture.innerHTML).toBe("");
|
||||
expect(steps).toEqual(["mounted", "willunmount"]);
|
||||
});
|
||||
|
||||
test("can use onMounted, onWillUnmount, part 2", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onMounted(() => {
|
||||
steps.push("mounted");
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
steps.push("willunmount");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||
static components = { MyComponent };
|
||||
state = useState({ flag: true });
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||
expect(steps).toEqual(["mounted"]);
|
||||
|
||||
parent.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(steps).toEqual(["mounted", "willunmount"]);
|
||||
});
|
||||
|
||||
test("mounted, willUnmount, onMounted, onWillUnmount order", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onMounted(() => {
|
||||
steps.push("hook:mounted");
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
steps.push("hook:willunmount");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
mounted() {
|
||||
steps.push("comp:mounted");
|
||||
}
|
||||
willUnmount() {
|
||||
steps.push("comp:willunmount");
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.unmount();
|
||||
expect(fixture.innerHTML).toBe("");
|
||||
expect(steps).toEqual(["comp:mounted", "hook:mounted", "hook:willunmount", "comp:willunmount"]);
|
||||
});
|
||||
|
||||
test("mounted, willUnmount, onMounted, onWillUnmount order, part 2", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onMounted(() => {
|
||||
steps.push("hook:mounted");
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
steps.push("hook:willunmount");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
mounted() {
|
||||
steps.push("comp:mounted");
|
||||
}
|
||||
willUnmount() {
|
||||
steps.push("comp:willunmount");
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><MyComponent t-if="state.flag"/></div>`;
|
||||
static components = { MyComponent };
|
||||
state = useState({ flag: true });
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||
parent.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
|
||||
expect(steps).toEqual(["comp:mounted", "hook:mounted", "hook:willunmount", "comp:willunmount"]);
|
||||
});
|
||||
|
||||
test("two different call to mounted/willunmount should work", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook(i) {
|
||||
onMounted(() => {
|
||||
steps.push("hook:mounted" + i);
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
steps.push("hook:willunmount" + i);
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook(1);
|
||||
useMyHook(2);
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.unmount();
|
||||
expect(fixture.innerHTML).toBe("");
|
||||
expect(steps).toEqual([
|
||||
"hook:mounted1",
|
||||
"hook:mounted2",
|
||||
"hook:willunmount2",
|
||||
"hook:willunmount1"
|
||||
]);
|
||||
});
|
||||
|
||||
test("useRef hook", async () => {
|
||||
class Counter extends Component<any, any> {
|
||||
static template = xml`<div><button t-ref="button"><t t-esc="value"/></button></div>`;
|
||||
button = useRef("button");
|
||||
value = 0;
|
||||
increment() {
|
||||
this.value++;
|
||||
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
||||
}
|
||||
}
|
||||
const counter = new Counter(env);
|
||||
await counter.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
||||
counter.increment();
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><button>1</button></div>");
|
||||
});
|
||||
|
||||
test("useRef hook is null if ref is removed ", async () => {
|
||||
expect.assertions(4);
|
||||
class TestRef extends Component<any, any> {
|
||||
static template = xml`<div><span t-if="state.flag" t-ref="span">owl</span></div>`;
|
||||
spanRef = useRef("span");
|
||||
state = useState({ flag: true });
|
||||
willPatch() {
|
||||
expect(this.spanRef.el).not.toBeNull();
|
||||
}
|
||||
patched() {
|
||||
expect(this.spanRef.el).toBeNull();
|
||||
}
|
||||
}
|
||||
const component = new TestRef(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
||||
component.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
});
|
||||
|
||||
test("can use onPatched, onWillPatch", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onWillPatch(() => {
|
||||
steps.push("willPatch");
|
||||
});
|
||||
onPatched(() => {
|
||||
steps.push("patched");
|
||||
});
|
||||
}
|
||||
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||
state = useState({ flag: true });
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(component).not.toHaveProperty("patched");
|
||||
expect(component).not.toHaveProperty("willPatch");
|
||||
expect(steps).toEqual([]);
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
|
||||
expect(steps).toEqual(["willPatch", "patched"]);
|
||||
});
|
||||
|
||||
test("patched, willPatch, onPatched, onWillPatch order", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onPatched(() => {
|
||||
steps.push("hook:patched");
|
||||
});
|
||||
onWillPatch(() => {
|
||||
steps.push("hook:willPatch");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||
state = useState({ flag: true });
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook();
|
||||
}
|
||||
willPatch() {
|
||||
steps.push("comp:willPatch");
|
||||
}
|
||||
patched() {
|
||||
steps.push("comp:patched");
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.state.flag = false;
|
||||
await nextTick();
|
||||
|
||||
expect(steps).toEqual(["hook:willPatch", "comp:willPatch", "comp:patched", "hook:patched"]);
|
||||
});
|
||||
|
||||
test("two different call to willPatch/patched should work", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook(i) {
|
||||
onPatched(() => {
|
||||
steps.push("hook:patched" + i);
|
||||
});
|
||||
onWillPatch(() => {
|
||||
steps.push("hook:willPatch" + i);
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
||||
state = useState({ value: 1 });
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useMyHook(1);
|
||||
useMyHook(2);
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
||||
component.state.value++;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>hey2</div>");
|
||||
|
||||
expect(steps).toEqual(["hook:willPatch2", "hook:willPatch1", "hook:patched1", "hook:patched2"]);
|
||||
});
|
||||
|
||||
describe("autofocus hook", () => {
|
||||
function useAutofocus(name) {
|
||||
let ref = useRef(name);
|
||||
let isInDom = false;
|
||||
function updateFocus() {
|
||||
if (!isInDom && ref.el) {
|
||||
isInDom = true;
|
||||
ref.el.focus();
|
||||
} else if (isInDom && !ref.el) {
|
||||
isInDom = false;
|
||||
}
|
||||
}
|
||||
onPatched(updateFocus);
|
||||
onMounted(updateFocus);
|
||||
}
|
||||
|
||||
test("simple input", async () => {
|
||||
class SomeComponent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<input t-ref="input1"/>
|
||||
<input t-ref="input2"/>
|
||||
</div>`;
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useAutofocus("input2");
|
||||
}
|
||||
}
|
||||
|
||||
const component = new SomeComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
||||
const input2 = fixture.querySelectorAll("input")[1];
|
||||
expect(input2).toBe(document.activeElement);
|
||||
});
|
||||
|
||||
test("input in a t-if", async () => {
|
||||
class SomeComponent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<input t-ref="input1"/>
|
||||
<t t-if="state.flag"><input t-ref="input2"/></t>
|
||||
</div>`;
|
||||
|
||||
state = useState({ flag: false });
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useAutofocus("input2");
|
||||
}
|
||||
}
|
||||
|
||||
const component = new SomeComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><input></div>");
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
|
||||
component.state.flag = true;
|
||||
await nextTick();
|
||||
const input2 = fixture.querySelectorAll("input")[1];
|
||||
expect(input2).toBe(document.activeElement);
|
||||
});
|
||||
});
|
||||
|
||||
test("can use sub env", async () => {
|
||||
class TestComponent extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useSubEnv({ val: 3 });
|
||||
}
|
||||
}
|
||||
const component = new TestComponent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||
expect(env).not.toHaveProperty("val");
|
||||
expect(component.env).toHaveProperty("val");
|
||||
});
|
||||
|
||||
test("parent and child env", async () => {
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useSubEnv({ val: 5 });
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
||||
static components = { Child };
|
||||
constructor(env) {
|
||||
super(env);
|
||||
useSubEnv({ val: 3 });
|
||||
}
|
||||
}
|
||||
const component = new Parent(env);
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
||||
});
|
||||
|
||||
test("can use onWillStart, onWillUpdateProps", async () => {
|
||||
const steps: string[] = [];
|
||||
function useMyHook() {
|
||||
onWillStart(() => {
|
||||
steps.push("onWillStart");
|
||||
});
|
||||
onWillUpdateProps(nextProps => {
|
||||
expect(nextProps).toEqual({ value: 2 });
|
||||
steps.push("onWillUpdateProps");
|
||||
});
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="props.value"/></span>`;
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><MyComponent value="state.value"/></div>`;
|
||||
static components = { MyComponent };
|
||||
state = useState({ value: 1 });
|
||||
}
|
||||
|
||||
const app = new App(env);
|
||||
await app.mount(fixture);
|
||||
expect(app).not.toHaveProperty("willStart");
|
||||
expect(app).not.toHaveProperty("willUpdateProps");
|
||||
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
|
||||
expect(steps).toEqual(["onWillStart"]);
|
||||
|
||||
app.state.value = 2;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
|
||||
expect(steps).toEqual(["onWillStart", "onWillUpdateProps"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import { AsyncRoot } from "../../src/misc/async_root";
|
||||
import { useState } from "../../src/hooks";
|
||||
import { xml } from "../../src/tags";
|
||||
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||
import { Env, Component } from "../../src/component/component";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// We create before each test:
|
||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||
// manipulations. Note that it is removed after each test.
|
||||
// - env: a WEnv, necessary to create new components
|
||||
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
describe("Asyncroot", () => {
|
||||
test("delayed component with AsyncRoot component", async () => {
|
||||
let def;
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||
}
|
||||
class AsyncChild extends Child {
|
||||
willUpdateProps() {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<button t-on-click="updateApp">Update App State</button>
|
||||
<div class="children">
|
||||
<Child val="state.val"/>
|
||||
<AsyncRoot>
|
||||
<AsyncChild val="state.val"/>
|
||||
</AsyncRoot>
|
||||
</div>
|
||||
</div>`;
|
||||
static components = { Child, AsyncChild, AsyncRoot };
|
||||
state = useState({ val: 0 });
|
||||
|
||||
updateApp() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||
|
||||
// click on button to increment Parent counter
|
||||
def = makeDeferred();
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>0</span>");
|
||||
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>1</span>");
|
||||
});
|
||||
|
||||
test("fast component with AsyncRoot", async () => {
|
||||
let def;
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="props.val"/></span>`;
|
||||
}
|
||||
class AsyncChild extends Child {
|
||||
willUpdateProps() {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<button t-on-click="updateApp">Update App State</button>
|
||||
<div class="children">
|
||||
<AsyncRoot>
|
||||
<Child val="state.val"/>
|
||||
</AsyncRoot>
|
||||
<AsyncChild val="state.val"/>
|
||||
</div>
|
||||
</div>`;
|
||||
static components = { Child, AsyncChild, AsyncRoot };
|
||||
state = useState({ val: 0 });
|
||||
|
||||
updateApp() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||
|
||||
// click on button to increment Parent counter
|
||||
def = makeDeferred();
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>0</span>");
|
||||
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1</span><span>1</span>");
|
||||
});
|
||||
|
||||
test("asyncroot component: mixed re-renderings", async () => {
|
||||
let def;
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`
|
||||
<span t-on-click="increment">
|
||||
<t t-esc="state.val"/>/<t t-esc="props.val"/>
|
||||
</span>`;
|
||||
state = useState({ val: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
class AsyncChild extends Child {
|
||||
willUpdateProps() {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<button t-on-click="updateApp">Update App State</button>
|
||||
<div class="children">
|
||||
<Child val="state.val"/>
|
||||
<AsyncRoot>
|
||||
<AsyncChild val="state.val"/>
|
||||
</AsyncRoot>
|
||||
</div>
|
||||
</div>`;
|
||||
static components = { Child, AsyncChild, AsyncRoot };
|
||||
state = useState({ val: 0 });
|
||||
|
||||
updateApp() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/0</span><span>0/0</span>");
|
||||
|
||||
// click on button to increment Parent counter
|
||||
def = makeDeferred();
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/1</span><span>0/0</span>");
|
||||
|
||||
// click on each Child to increment their local counter
|
||||
const children = parent.el!.querySelectorAll("span");
|
||||
children[0]!.click();
|
||||
await nextTick();
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>0/0</span>");
|
||||
|
||||
children[1]!.click();
|
||||
await nextTick();
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>0/0</span>");
|
||||
|
||||
// finalize first re-rendering (coming from the props update)
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>1/1</span><span>1/1</span>");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
+339
-12
@@ -11,6 +11,7 @@ import { normalize, renderToDOM, renderToString, trim, nextTick } from "../helpe
|
||||
let qweb: QWeb;
|
||||
|
||||
beforeEach(() => {
|
||||
QWeb.TEMPLATES = {};
|
||||
qweb = new QWeb();
|
||||
});
|
||||
|
||||
@@ -48,6 +49,11 @@ describe("static templates", () => {
|
||||
qweb.addTemplate("test", "<div><span>word</span></div>");
|
||||
expect(renderToString(qweb, "test")).toBe("<div><span>word</span></div>");
|
||||
});
|
||||
|
||||
test("properly handle comments", () => {
|
||||
qweb.addTemplate("test", "<div>hello <!-- comment-->owl</div>");
|
||||
expect(renderToString(qweb, "test")).toBe("<div>hello <!-- comment-->owl</div>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
@@ -73,19 +79,12 @@ describe("error handling", () => {
|
||||
expect(() => qweb.addTemplate("test", "<div/>")).toThrow("already defined");
|
||||
});
|
||||
|
||||
test("loadTemplates throw if parser error", () => {
|
||||
test("addTemplates throw if parser error", () => {
|
||||
expect(() => {
|
||||
qweb.addTemplates("<templates><abc>></templates>");
|
||||
}).toThrow("Invalid XML in template");
|
||||
});
|
||||
|
||||
test("nice error when t-on-directive is evaluated with a missing handler", () => {
|
||||
qweb.addTemplate("templatename", `<div t-on-click="somemethod"></div>`);
|
||||
expect(() => qweb.render("templatename", {}, { handlers: [] })).toThrow(
|
||||
"Missing handler 'somemethod' when evaluating template 'templatename'"
|
||||
);
|
||||
});
|
||||
|
||||
test("nice error when t-on is evaluated with a missing event", () => {
|
||||
qweb.addTemplate("templatename", `<div t-on="somemethod"></div>`);
|
||||
expect(() => qweb.render("templatename", { someMethod() {} }, { handlers: [] })).toThrow(
|
||||
@@ -322,6 +321,61 @@ describe("t-if", () => {
|
||||
};
|
||||
expect(normalize(renderToString(qweb, "test", context))).toBe("<div>andormgtnlt</div>");
|
||||
});
|
||||
|
||||
test("t-esc with t-if", () => {
|
||||
qweb.addTemplate("test", `<div><t t-if="true" t-esc="'x'"/></div>`);
|
||||
expect(renderToString(qweb, "test")).toBe("<div>x</div>");
|
||||
});
|
||||
|
||||
test("t-esc with t-elif", () => {
|
||||
qweb.addTemplate("test", `<div><t t-if="false">abc</t><t t-else="1" t-esc="'x'"/></div>`);
|
||||
expect(renderToString(qweb, "test")).toBe("<div>x</div>");
|
||||
});
|
||||
|
||||
test("t-set, then t-if", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`
|
||||
<div>
|
||||
<t t-set="title" t-value="'test'"/>
|
||||
<t t-if="title"><t t-esc="title"/></t>
|
||||
</div>`
|
||||
);
|
||||
const result = renderToString(qweb, "test");
|
||||
const expected = `<div>test</div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
test("t-set, then t-if, part 2", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`
|
||||
<div>
|
||||
<t t-set="y" t-value="true"/>
|
||||
<t t-set="x" t-value="y"/>
|
||||
<span t-if="x">COUCOU</span>
|
||||
</div>`
|
||||
);
|
||||
const result = renderToString(qweb, "test");
|
||||
const expected = `<div><span>COUCOU</span></div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
test("t-set, then t-elif, part 3", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`
|
||||
<div>
|
||||
<t t-set="y" t-value="false"/>
|
||||
<t t-set="x" t-value="y"/>
|
||||
<span t-if="x">AAA</span>
|
||||
<span t-elif="!x">BBB</span>
|
||||
</div>`
|
||||
);
|
||||
const result = renderToString(qweb, "test");
|
||||
const expected = `<div><span>BBB</span></div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attributes", () => {
|
||||
@@ -573,6 +627,103 @@ describe("t-call (template calling", () => {
|
||||
const expected = "<div>ok</div>";
|
||||
expect(trim(renderToString(qweb, "caller"))).toBe(expected);
|
||||
});
|
||||
|
||||
test("call with several sub nodes on same line", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="SubTemplate">
|
||||
<t t-raw="0"/>
|
||||
</div>
|
||||
|
||||
<div t-name="main">
|
||||
<t t-call="SubTemplate">
|
||||
<span>hey</span> <span>yay</span>
|
||||
</t>
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
const expected = "<div><div><span>hey</span> <span>yay</span></div></div>";
|
||||
expect(renderToString(qweb, "main")).toBe(expected);
|
||||
});
|
||||
|
||||
test("recursive template, part 1", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="recursive">
|
||||
<span>hey</span>
|
||||
<t t-if="false">
|
||||
<t t-call="recursive"/>
|
||||
</t>
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
const expected = "<div><span>hey</span></div>";
|
||||
expect(renderToString(qweb, "recursive")).toBe(expected);
|
||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("recursive template, part 2", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="Parent">
|
||||
<t t-call="nodeTemplate">
|
||||
<t t-set="node" t-value="root"/>
|
||||
</t>
|
||||
</div>
|
||||
<div t-name="nodeTemplate">
|
||||
<p><t t-esc="node.val"/></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" }, { val: "c" }] };
|
||||
const expected = "<div><div><p>a</p><div><p>b</p></div><div><p>c</p></div></div></div>";
|
||||
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
|
||||
expected
|
||||
);
|
||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("recursive template, part 3", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="Parent">
|
||||
<t t-call="nodeTemplate">
|
||||
<t t-set="node" t-value="root"/>
|
||||
</t>
|
||||
</div>
|
||||
<div t-name="nodeTemplate">
|
||||
<p><t t-esc="node.val"/></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: "d" }] }, { val: "c" }] };
|
||||
const expected =
|
||||
"<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);
|
||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("t-call, global templates", () => {
|
||||
QWeb.registerTemplate("abcd", '<div><t t-call="john"/></div>');
|
||||
qweb.addTemplate("john", `<span>desk</span>`);
|
||||
const expected = "<div><span>desk</span></div>";
|
||||
expect(trim(renderToString(qweb, "abcd"))).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreach", () => {
|
||||
@@ -646,6 +797,23 @@ describe("foreach", () => {
|
||||
expect(Object.keys(context).length).toBe(0);
|
||||
});
|
||||
|
||||
test("t-foreach in t-forach", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div>
|
||||
<t t-foreach="numbers" t-as="number">
|
||||
<t t-foreach="letters" t-as="letter">
|
||||
[<t t-esc="number"/><t t-esc="letter"/>]
|
||||
</t>
|
||||
</t>
|
||||
</div>`
|
||||
);
|
||||
const context = { numbers: [1, 2, 3], letters: ["a", "b"] };
|
||||
expect(renderToString(qweb, "test", context)).toBe(
|
||||
"<div> [1a] [1b] [2a] [2b] [3a] [3b] </div>"
|
||||
);
|
||||
});
|
||||
|
||||
test("throws error if invalid loop expression", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
@@ -675,7 +843,7 @@ describe("foreach", () => {
|
||||
|
||||
describe("misc", () => {
|
||||
test("global", () => {
|
||||
qweb.addTemplate("_callee-asc", `<Año t-att-falló="'agüero'" t-raw="0"/>`);
|
||||
qweb.addTemplate("_callee-asc", `<año t-att-falló="'agüero'" t-raw="0"/>`);
|
||||
qweb.addTemplate("_callee-uses-foo", `<span t-esc="foo">foo default</span>`);
|
||||
qweb.addTemplate("_callee-asc-toto", `<div t-raw="toto">toto default</div>`);
|
||||
qweb.addTemplate(
|
||||
@@ -872,6 +1040,33 @@ describe("t-on", () => {
|
||||
(<HTMLElement>node).click();
|
||||
});
|
||||
|
||||
test("t-on with inline statement", () => {
|
||||
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
|
||||
let owner = {
|
||||
state: {
|
||||
counter: 0,
|
||||
},
|
||||
};
|
||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||
expect(owner.state.counter).toBe(0);
|
||||
(<HTMLElement>node).click();
|
||||
expect(owner.state.counter).toBe(1);
|
||||
});
|
||||
|
||||
test("t-on with inline statement (function call)", () => {
|
||||
qweb.addTemplate("test", `<button t-on-click="state.incrementCounter(2)">Click</button>`);
|
||||
let owner = {
|
||||
state: {
|
||||
counter: 0,
|
||||
incrementCounter: (inc) => { owner.state.counter += inc; },
|
||||
},
|
||||
};
|
||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||
expect(owner.state.counter).toBe(0);
|
||||
(<HTMLElement>node).click();
|
||||
expect(owner.state.counter).toBe(2);
|
||||
});
|
||||
|
||||
test("t-on with prevent and/or stop modifiers", async () => {
|
||||
expect.assertions(7);
|
||||
qweb.addTemplate(
|
||||
@@ -983,20 +1178,110 @@ describe("t-on", () => {
|
||||
|
||||
expect(steps).toEqual([true, true]);
|
||||
});
|
||||
|
||||
test("t-on with prevent modifier in t-foreach", async () => {
|
||||
expect.assertions(5);
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div>
|
||||
<t t-foreach="projects" t-as="project">
|
||||
<a href="#" t-key="project" t-on-click.prevent="onEdit(project.id)">
|
||||
Edit <t t-esc="project.name"/>
|
||||
</a>
|
||||
</t>
|
||||
</div>`
|
||||
);
|
||||
const steps: string[] = [];
|
||||
const owner = {
|
||||
projects: [{ id: 1, name: "Project 1" }, { id: 2, name: "Project 2" }],
|
||||
|
||||
onEdit(projectId, ev) {
|
||||
expect(ev.defaultPrevented).toBe(true);
|
||||
steps.push(projectId);
|
||||
}
|
||||
};
|
||||
|
||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||
expect(node.outerHTML).toBe(
|
||||
`<div><a href="#"> Edit Project 1</a><a href="#"> Edit Project 2</a></div>`
|
||||
);
|
||||
|
||||
const links = node.querySelectorAll("a")!;
|
||||
links[0].click();
|
||||
links[1].click();
|
||||
|
||||
expect(steps).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("t-on with empty handler (only modifiers)", () => {
|
||||
expect.assertions(2);
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div>
|
||||
<button t-on-click.prevent="">Button</button>
|
||||
</div>`
|
||||
);
|
||||
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
|
||||
|
||||
node.addEventListener('click', (e) => {
|
||||
expect(e.defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
const button = (<HTMLElement>node).getElementsByTagName("button")[0];
|
||||
button.click();
|
||||
});
|
||||
|
||||
test("t-on combined with t-esc", async () => {
|
||||
expect.assertions(3);
|
||||
qweb.addTemplate("test", `<div><button t-on-click="onClick" t-esc="text"/></div>`);
|
||||
const steps: string[] = [];
|
||||
const owner = {
|
||||
text: "Click here",
|
||||
onClick() {
|
||||
steps.push("onClick");
|
||||
}
|
||||
};
|
||||
|
||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||
expect(node.outerHTML).toBe(`<div><button>Click here</button></div>`);
|
||||
|
||||
node.querySelector("button")!.click();
|
||||
|
||||
expect(steps).toEqual(["onClick"]);
|
||||
});
|
||||
|
||||
test("t-on combined with t-raw", async () => {
|
||||
expect.assertions(3);
|
||||
qweb.addTemplate("test", `<div><button t-on-click="onClick" t-raw="html"/></div>`);
|
||||
const steps: string[] = [];
|
||||
const owner = {
|
||||
html: "Click <b>here</b>",
|
||||
onClick() {
|
||||
steps.push("onClick");
|
||||
}
|
||||
};
|
||||
|
||||
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||
expect(node.outerHTML).toBe(`<div><button>Click <b>here</b></button></div>`);
|
||||
|
||||
node.querySelector("button")!.click();
|
||||
|
||||
expect(steps).toEqual(["onClick"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("t-ref", () => {
|
||||
test("can get a ref on a node", () => {
|
||||
qweb.addTemplate("test", `<div><span t-ref="myspan"/></div>`);
|
||||
let refs: any = {};
|
||||
renderToDOM(qweb, "test", { refs });
|
||||
renderToDOM(qweb, "test", { __owl__: { refs } });
|
||||
expect(refs.myspan.tagName).toBe("SPAN");
|
||||
});
|
||||
|
||||
test("can get a dynamic ref on a node", () => {
|
||||
qweb.addTemplate("test", `<div><span t-ref="myspan{{id}}"/></div>`);
|
||||
let refs: any = {};
|
||||
renderToDOM(qweb, "test", { refs, id: 3 });
|
||||
renderToDOM(qweb, "test", { id: 3, __owl__: { refs } });
|
||||
expect(refs.myspan3.tagName).toBe("SPAN");
|
||||
});
|
||||
|
||||
@@ -1011,7 +1296,7 @@ describe("t-ref", () => {
|
||||
</div>`
|
||||
);
|
||||
let refs: any = {};
|
||||
renderToDOM(qweb, "test", { refs, items: [1, 2, 3] });
|
||||
renderToDOM(qweb, "test", { items: [1, 2, 3], __owl__: { refs } });
|
||||
expect(Object.keys(refs)).toEqual(["1", "2", "3"]);
|
||||
});
|
||||
});
|
||||
@@ -1190,3 +1475,45 @@ describe("update on event bus", () => {
|
||||
expect(fn).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("global template registration", () => {
|
||||
test("can register template globally", () => {
|
||||
expect.assertions(5);
|
||||
let qweb = new QWeb();
|
||||
try {
|
||||
qweb.render("mytemplate");
|
||||
} catch (e) {
|
||||
expect(e.message).toMatch("Template mytemplate does not exist");
|
||||
}
|
||||
expect(qweb.templates.mytemplate).toBeUndefined();
|
||||
|
||||
QWeb.registerTemplate("mytemplate", "<div>global</div>");
|
||||
expect(qweb.templates.mytemplate).toBeDefined();
|
||||
const vnode = qweb.render("mytemplate");
|
||||
expect(vnode.sel).toBe("div");
|
||||
expect((vnode as any).children[0].text).toBe("global");
|
||||
});
|
||||
});
|
||||
|
||||
describe("properly support svg", () => {
|
||||
test("add proper namespace to svg", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<svg width="100px" height="90px"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </svg>`
|
||||
);
|
||||
expect(renderToString(qweb, "test")).toBe(
|
||||
`<svg width=\"100px\" height=\"90px\"><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </svg>`
|
||||
);
|
||||
});
|
||||
|
||||
test("add proper namespace to g tags", () => {
|
||||
// this is necessary if one wants to use components in a svg
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </g>`
|
||||
);
|
||||
expect(renderToString(qweb, "test")).toBe(
|
||||
`<g><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </g>`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`router directive t-routecomponent can render parameterized route 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['env'].router.currentRouteName==='book') {
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {title:context['env'].router.currentParams.title};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`__component__book\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`router directive t-routecomponent can render parameterized route with suffixes 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['env'].router.currentRouteName==='book') {
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {title:context['env'].router.currentParams.title,val:context['env'].router.currentParams.val};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`__component__book\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`router directive t-routecomponent can render simple cases 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['env'].router.currentRouteName==='about') {
|
||||
//COMPONENT
|
||||
let def3;
|
||||
let w4 = 4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[4]] : false;
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let props4 = {};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
}
|
||||
if (!w4) {
|
||||
let componentKey4 = \`__component__about\`;
|
||||
let W4 = context.components && context.components[componentKey4] || QWeb.components[componentKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||
w4 = new W4(parent, props4);
|
||||
parent.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4.__prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4.__updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
}
|
||||
else if (context['env'].router.currentRouteName==='users') {
|
||||
//COMPONENT
|
||||
let def6;
|
||||
let w7 = 7 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[7]] : false;
|
||||
let _5_index = c1.length;
|
||||
c1.push(null);
|
||||
let props7 = {};
|
||||
if (w7 && w7.__owl__.renderPromise && !w7.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props7, w7.__owl__.renderProps)) {
|
||||
def6 = w7.__owl__.renderPromise;
|
||||
} else {
|
||||
w7.destroy();
|
||||
w7 = false;
|
||||
}
|
||||
}
|
||||
if (!w7) {
|
||||
let componentKey7 = \`__component__users\`;
|
||||
let W7 = context.components && context.components[componentKey7] || QWeb.components[componentKey7];
|
||||
if (!W7) {throw new Error('Cannot find the definition of component \\"' + componentKey7 + '\\"')}
|
||||
w7 = new W7(parent, props7);
|
||||
parent.__owl__.cmap[7] = w7.__owl__.id;
|
||||
def6 = w7.__prepare();
|
||||
def6 = def6.then(vnode=>{let pvnode=h(vnode.sel, {key: 7, hook: {insert(vn) {let nvn=w7.__mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w7.destroy();}}});c1[_5_index]=pvnode;w7.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def6 = def6 || w7.__updateProps(props7, extra.forceUpdate, extra.patchQueue);
|
||||
def6 = def6.then(()=>{if (w7.__owl__.isDestroyed) {return};let pvnode=w7.__owl__.pvnode;c1[_5_index]=pvnode;});
|
||||
}
|
||||
extra.promises.push(def6);
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
+4
-6
@@ -5,19 +5,17 @@ exports[`Link component can render simple cases 1`] = `
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let _1 = utils.toObj({'router-link-active':context['isActive']});
|
||||
var _2 = context['href'];
|
||||
let c3 = [], p3 = {key:3,attrs:{href: _2},class:_1,on:{}};
|
||||
var vn3 = h('a', p3, c3);
|
||||
if (!context['navigate']) {
|
||||
throw new Error('Missing handler \\\\'' + 'navigate' + \`\\\\' when evaluating template '__owl__-router-link'\`)
|
||||
}
|
||||
extra.handlers['click' + 3] = extra.handlers['click' + 3] || context['navigate'].bind(owner);
|
||||
extra.handlers['click' + 3] = extra.handlers['click' + 3] || function (e) {const fn = context['navigate'];if (fn) { fn.call(owner, e); } else { context.navigate; }};
|
||||
p3.on['click'] = extra.handlers['click' + 3];
|
||||
const slot4 = this.slots[context.__owl__.slotId + '_' + 'default'];
|
||||
const slot4 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||
if (slot4) {
|
||||
slot4(context.__owl__.parent, Object.assign({}, extra, {parentNode: c3, vars: extra.vars, parent: owner}));
|
||||
slot4.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c3, vars: extra.vars, parent: owner}));
|
||||
}
|
||||
return vn3;
|
||||
}"
|
||||
@@ -0,0 +1,46 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`RouteComponent can render simple cases 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
let result;
|
||||
var h = this.h;
|
||||
if (context['routeComponent']) {
|
||||
//COMPONENT
|
||||
let key3 = 'key' + context['env'].router.currentRouteName;
|
||||
let templateId2 = \`__4__\` + key3;
|
||||
let w2 = templateId2 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId2]] : false;
|
||||
let vn5 = {};
|
||||
result = vn5;
|
||||
let props2 = Object.assign({}, context['env'].router.currentParams);
|
||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
||||
w2.destroy();
|
||||
w2 = false;
|
||||
}
|
||||
if (w2) {
|
||||
w2.__updateProps(props2, extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = w2.__owl__.pvnode;
|
||||
utils.defineProxy(vn5, pvnode);
|
||||
} else {
|
||||
let componentKey2 = \`routeComponent\`;
|
||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| context['routeComponent'];
|
||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
||||
w2 = new W2(parent, props2);
|
||||
parent.__owl__.cmap[templateId2] = w2.__owl__.id;
|
||||
let def1 = w2.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId2, hook: {insert(vn) { let nvn=w2.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w2.destroy();}}});
|
||||
const fiber = w2.__owl__.currentFiber;
|
||||
def1.then(function () {if (w2.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
utils.defineProxy(vn5, pvnode);
|
||||
w2.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w2.__owl__.currentFiber || sibling;
|
||||
}
|
||||
return result;
|
||||
}"
|
||||
`;
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Component } from "../../src/component/component";
|
||||
import { Link, LINK_TEMPLATE_NAME } from "../../src/router/Link";
|
||||
import { RouterEnv } from "../../src/router/Router";
|
||||
import { Link } from "../../src/router/link";
|
||||
import { RouterEnv } from "../../src/router/router";
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
||||
import { TestRouter } from "./TestRouter";
|
||||
import { TestRouter } from "./test_router";
|
||||
|
||||
describe("Link component", () => {
|
||||
let fixture: HTMLElement;
|
||||
@@ -30,8 +30,8 @@ describe("Link component", () => {
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
class App extends Component<any, any, any> {
|
||||
components = { Link: Link };
|
||||
class App extends Component<any, any> {
|
||||
static components = { Link: Link };
|
||||
}
|
||||
|
||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
||||
@@ -50,7 +50,7 @@ describe("Link component", () => {
|
||||
'<div><a href="/about" class="router-link-active">About</a></div>'
|
||||
);
|
||||
|
||||
expect(env.qweb.templates[LINK_TEMPLATE_NAME].fn.toString()).toMatchSnapshot();
|
||||
expect(env.qweb.templates[Link.template].fn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("do not redirect if right clicking", async () => {
|
||||
@@ -61,8 +61,8 @@ describe("Link component", () => {
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
class App extends Component<any, any, any> {
|
||||
components = { Link: Link };
|
||||
class App extends Component<any, any> {
|
||||
static components = { Link: Link };
|
||||
}
|
||||
|
||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Component } from "../../src/component/component";
|
||||
import { RouterEnv } from "../../src/router/Router";
|
||||
import { RouterEnv } from "../../src/router/router";
|
||||
import { RouteComponent } from "../../src/router/route_component";
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
||||
import { TestRouter } from "./TestRouter";
|
||||
import { TestRouter } from "./test_router";
|
||||
|
||||
describe("router directive t-routecomponent", () => {
|
||||
describe("RouteComponent", () => {
|
||||
let fixture: HTMLElement;
|
||||
let env: RouterEnv;
|
||||
let router: TestRouter | null = null;
|
||||
@@ -25,16 +26,16 @@ describe("router directive t-routecomponent", () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="App">
|
||||
<t t-routecomponent="1" />
|
||||
<RouteComponent />
|
||||
</div>
|
||||
<span t-name="About">About</span>
|
||||
<span t-name="Users">Users</span>
|
||||
</templates>
|
||||
`);
|
||||
class About extends Component<any, any, any> {}
|
||||
class Users extends Component<any, any, any> {}
|
||||
class App extends Component<any, any, any> {
|
||||
components = { About, Users };
|
||||
class About extends Component<any, any> {}
|
||||
class Users extends Component<any, any> {}
|
||||
class App extends Component<any, any> {
|
||||
static components = { RouteComponent };
|
||||
}
|
||||
|
||||
const routes = [
|
||||
@@ -51,21 +52,21 @@ describe("router directive t-routecomponent", () => {
|
||||
await router.navigate({ to: "users" });
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>Users</span></div>");
|
||||
expect(env.qweb.templates.App.fn.toString()).toMatchSnapshot();
|
||||
expect(env.qweb.templates[RouteComponent.template].fn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("can render parameterized route", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="App">
|
||||
<t t-routecomponent="1" />
|
||||
<RouteComponent />
|
||||
</div>
|
||||
<span t-name="Book">Book <t t-esc="props.title"/></span>
|
||||
</templates>
|
||||
`);
|
||||
class Book extends Component<any, any, any> {}
|
||||
class App extends Component<any, any, any> {
|
||||
components = { Book };
|
||||
class Book extends Component<any, any> {}
|
||||
class App extends Component<any, any> {
|
||||
static components = { RouteComponent };
|
||||
}
|
||||
|
||||
const routes = [{ name: "book", path: "/book/{{title}}", component: Book }];
|
||||
@@ -74,25 +75,24 @@ describe("router directive t-routecomponent", () => {
|
||||
const app = new App(env);
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984</span></div>");
|
||||
expect(env.qweb.templates.App.fn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("can render parameterized route with suffixes", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="App">
|
||||
<t t-routecomponent="1" />
|
||||
<RouteComponent />
|
||||
</div>
|
||||
<span t-name="Book">Book <t t-esc="props.title"/>|<t t-esc="incVal"/></span>
|
||||
</templates>
|
||||
`);
|
||||
class Book extends Component<any, any, any> {
|
||||
class Book extends Component<any, any> {
|
||||
get incVal() {
|
||||
return this.props.val + 1;
|
||||
}
|
||||
}
|
||||
class App extends Component<any, any, any> {
|
||||
components = { Book };
|
||||
class App extends Component<any, any> {
|
||||
static components = { RouteComponent };
|
||||
}
|
||||
|
||||
const routes = [{ name: "book", path: "/book/{{title}}/{{val.number}}", component: Book }];
|
||||
@@ -101,6 +101,5 @@ describe("router directive t-routecomponent", () => {
|
||||
const app = new App(env);
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984|124</span></div>");
|
||||
expect(env.qweb.templates.App.fn.toString()).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
+104
-26
@@ -1,6 +1,6 @@
|
||||
import { Destination, Router, RouterEnv, Route } from "../../src/router/Router";
|
||||
import { makeTestEnv } from "../helpers";
|
||||
import { TestRouter } from "./TestRouter";
|
||||
import { Destination, RouterEnv, Route } from "../../src/router/router";
|
||||
import { makeTestEnv, nextTick } from "../helpers";
|
||||
import { TestRouter } from "./test_router";
|
||||
|
||||
let env: RouterEnv;
|
||||
let router: TestRouter | null = null;
|
||||
@@ -25,18 +25,58 @@ describe("router miscellaneous", () => {
|
||||
]);
|
||||
}).toThrow(`Invalid destination: {"abc":"hey"}`);
|
||||
});
|
||||
|
||||
test("navigate to same route but with different params should trigger update", async () => {
|
||||
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }]);
|
||||
env.qweb.forceUpdate = jest.fn();
|
||||
await router.navigate({ to: "users", params: { id: 3 } });
|
||||
expect(window.location.pathname).toBe("/users/3");
|
||||
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(1);
|
||||
|
||||
await router.navigate({ to: "users", params: { id: 5 } });
|
||||
expect(window.location.pathname).toBe("/users/5");
|
||||
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("changing url to same route but with different params should trigger update (hash mode)", async () => {
|
||||
env.qweb.forceUpdate = jest.fn();
|
||||
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }], { mode: "hash" });
|
||||
await router.start();
|
||||
await router.navigate({ to: "users", params: { id: 3 } });
|
||||
expect(window.location.hash).toBe("#/users/3");
|
||||
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(1);
|
||||
|
||||
window.location.hash = "/users/5";
|
||||
window.dispatchEvent(new Event("hashchange"));
|
||||
await nextTick();
|
||||
expect(window.location.hash).toBe("#/users/5");
|
||||
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("routeToPath", () => {
|
||||
const routeToPath = Router.prototype["routeToPath"];
|
||||
test("simple non parameterized path", () => {
|
||||
expect(routeToPath({path: "/abc"} as Route, {})).toBe("/abc");
|
||||
expect(routeToPath({path: "/abc/def"} as Route, {})).toBe("/abc/def");
|
||||
expect(routeToPath({path: "/abc"} as Route, { val: 12 })).toBe("/abc");
|
||||
router = new TestRouter(env, []);
|
||||
expect(router["routeToPath"]({ path: "/abc" } as Route, {})).toBe("/abc");
|
||||
expect(router["routeToPath"]({ path: "/abc/def" } as Route, {})).toBe("/abc/def");
|
||||
expect(router["routeToPath"]({ path: "/abc" } as Route, { val: 12 })).toBe("/abc");
|
||||
});
|
||||
|
||||
test("simple parameterized path", () => {
|
||||
expect(routeToPath({path: "/abc/{{def}}"} as Route, { def: 34 })).toBe("/abc/34");
|
||||
router = new TestRouter(env, []);
|
||||
expect(router["routeToPath"]({ path: "/abc/{{def}}" } as Route, { def: 34 })).toBe("/abc/34");
|
||||
});
|
||||
|
||||
test("simple non parameterized path, mode = hash", () => {
|
||||
router = new TestRouter(env, [], { mode: "hash" });
|
||||
expect(router["routeToPath"]({ path: "/abc" } as Route, {})).toBe("#/abc");
|
||||
expect(router["routeToPath"]({ path: "/abc/def" } as Route, {})).toBe("#/abc/def");
|
||||
expect(router["routeToPath"]({ path: "/abc" } as Route, { val: 12 })).toBe("#/abc");
|
||||
});
|
||||
|
||||
test("simple parameterized path, mode=hash", () => {
|
||||
router = new TestRouter(env, [], { mode: "hash" });
|
||||
expect(router["routeToPath"]({ path: "/abc/{{def}}" } as Route, { def: 34 })).toBe("#/abc/34");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -58,26 +98,60 @@ describe("destToPath", () => {
|
||||
});
|
||||
|
||||
describe("getRouteParams", () => {
|
||||
const getRouteParams = Router.prototype["getRouteParams"];
|
||||
test("properly match simple routes", () => {
|
||||
router = new TestRouter(env, []);
|
||||
// simple route
|
||||
expect(getRouteParams({path: "/home"} as Route, "/home")).toEqual({});
|
||||
expect(router["getRouteParams"]({ path: "/home" } as Route, "/home")).toEqual({});
|
||||
|
||||
// no match
|
||||
expect(getRouteParams({path: "/home"} as Route, "/otherpath")).toEqual(false);
|
||||
expect(router["getRouteParams"]({ path: "/home" } as Route, "/otherpath")).toEqual(false);
|
||||
|
||||
// fallback route
|
||||
expect(getRouteParams({path: "*"} as Route, "somepath")).toEqual({});
|
||||
expect(router["getRouteParams"]({ path: "*" } as Route, "somepath")).toEqual({});
|
||||
});
|
||||
|
||||
test("properly match simple routes, mode hash", () => {
|
||||
router = new TestRouter(env, [], { mode: "hash" });
|
||||
// simple route
|
||||
expect(router["getRouteParams"]({ path: "/home" } as Route, "#/home")).toEqual({});
|
||||
|
||||
// no match
|
||||
expect(router["getRouteParams"]({ path: "/home" } as Route, "#/otherpath")).toEqual(false);
|
||||
|
||||
// fallback route
|
||||
expect(router["getRouteParams"]({ path: "*" } as Route, "#/somepath")).toEqual({});
|
||||
});
|
||||
|
||||
test("match some parameterized routes", () => {
|
||||
expect(getRouteParams({path: "/invoices/{{id}}"} as Route, "/invoices/3")).toEqual({
|
||||
router = new TestRouter(env, []);
|
||||
expect(router["getRouteParams"]({ path: "/invoices/{{id}}" } as Route, "/invoices/3")).toEqual({
|
||||
id: "3"
|
||||
});
|
||||
});
|
||||
|
||||
test("match some parameterized routes, mode hash", () => {
|
||||
router = new TestRouter(env, [], { mode: "hash" });
|
||||
expect(router["getRouteParams"]({ path: "/invoices/{{id}}" } as Route, "#/invoices/3")).toEqual(
|
||||
{
|
||||
id: "3"
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("can convert to number if needed", () => {
|
||||
expect(getRouteParams({path: "/invoices/{{id.number}}"} as Route, "/invoices/3")).toEqual({
|
||||
router = new TestRouter(env, []);
|
||||
expect(
|
||||
router["getRouteParams"]({ path: "/invoices/{{id.number}}" } as Route, "/invoices/3")
|
||||
).toEqual({
|
||||
id: 3
|
||||
});
|
||||
});
|
||||
|
||||
test("can convert to number if needed, mode: hash", () => {
|
||||
router = new TestRouter(env, [], { mode: "hash" });
|
||||
expect(
|
||||
router["getRouteParams"]({ path: "/invoices/{{id.number}}" } as Route, "#/invoices/3")
|
||||
).toEqual({
|
||||
id: 3
|
||||
});
|
||||
});
|
||||
@@ -131,9 +205,9 @@ describe("beforeRouteEnter", () => {
|
||||
expect(window.location.pathname).toBe("/");
|
||||
const guard = jest.fn(() => false);
|
||||
router = new TestRouter(env, [
|
||||
{ name: "routea", path: "/some/patha"},
|
||||
{ name: "routeb", path: "/some/pathb", beforeRouteEnter: guard }
|
||||
]);
|
||||
{ name: "routea", path: "/some/patha" },
|
||||
{ name: "routeb", path: "/some/pathb", beforeRouteEnter: guard }
|
||||
]);
|
||||
|
||||
await router.start();
|
||||
await router.navigate({ to: "routea" });
|
||||
@@ -147,12 +221,14 @@ describe("beforeRouteEnter", () => {
|
||||
|
||||
test("navigation is redirected if guard decides so", async () => {
|
||||
expect(window.location.pathname).toBe("/");
|
||||
const guard = jest.fn(() => {return {to: "routec"}});
|
||||
const guard = jest.fn(() => {
|
||||
return { to: "routec" };
|
||||
});
|
||||
router = new TestRouter(env, [
|
||||
{ name: "routea", path: "/some/patha"},
|
||||
{ name: "routeb", path: "/some/pathb", beforeRouteEnter: guard },
|
||||
{ name: "routec", path: "/some/pathc"},
|
||||
]);
|
||||
{ name: "routea", path: "/some/patha" },
|
||||
{ name: "routeb", path: "/some/pathb", beforeRouteEnter: guard },
|
||||
{ name: "routec", path: "/some/pathc" }
|
||||
]);
|
||||
|
||||
await router.start();
|
||||
const result = await router.navigate({ to: "routea" });
|
||||
@@ -166,11 +242,13 @@ describe("beforeRouteEnter", () => {
|
||||
|
||||
test("navigation is initially redirected if guard decides so", async () => {
|
||||
expect(window.location.pathname).toBe("/");
|
||||
const guard = jest.fn(() => {return {to: "otherroute"}});
|
||||
const guard = jest.fn(() => {
|
||||
return { to: "otherroute" };
|
||||
});
|
||||
router = new TestRouter(env, [
|
||||
{ name: "landing", path: "/", beforeRouteEnter: guard},
|
||||
{ name: "otherroute", path: "/some/other/route"}
|
||||
]);
|
||||
{ name: "landing", path: "/", beforeRouteEnter: guard },
|
||||
{ name: "otherroute", path: "/some/other/route" }
|
||||
]);
|
||||
|
||||
expect(window.location.pathname).toBe("/");
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { Router } from "../../src/router/Router";
|
||||
import { Router } from "../../src/router/router";
|
||||
import { QWeb } from "../../src/qweb/index";
|
||||
|
||||
export class TestRouter extends Router {
|
||||
destroy() {
|
||||
window.removeEventListener("popstate", (this as any)._listener);
|
||||
delete QWeb.DIRECTIVE_NAMES.routecomponent;
|
||||
QWeb.DIRECTIVES = QWeb.DIRECTIVES.filter(d => d.name !== "routecomponent");
|
||||
|
||||
// remove component defined inroutes
|
||||
for (let key in QWeb.components) {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Env } from "../../src/component/component";
|
||||
import { Store, Getter } from "../../src/store/store";
|
||||
import { nextTick, nextMicroTick } from "../helpers";
|
||||
import { Env } from "../src/component/component";
|
||||
import { Store, Getter } from "../src/store";
|
||||
import { nextTick, nextMicroTick } from "./helpers";
|
||||
|
||||
describe("basic use", () => {
|
||||
test("dispatch an action", () => {
|
||||
@@ -249,32 +249,32 @@ describe("advanced state properties", () => {
|
||||
expect(store.state.a).toEqual([1, 2, 3, 53]);
|
||||
});
|
||||
|
||||
test("can use object assign in store", async () => {
|
||||
const actions = {
|
||||
dosomething({ state }) {
|
||||
Object.assign(state.westmalle, { a: 3, b: 4 });
|
||||
}
|
||||
};
|
||||
const store = new Store({
|
||||
state: { westmalle: { a: 1, b: 2 } },
|
||||
actions
|
||||
});
|
||||
store.dispatch("dosomething");
|
||||
expect(store.state.westmalle).toEqual({ a: 3, b: 4 });
|
||||
test("can use object assign in store", async () => {
|
||||
const actions = {
|
||||
dosomething({ state }) {
|
||||
Object.assign(state.westmalle, { a: 3, b: 4 });
|
||||
}
|
||||
};
|
||||
const store = new Store({
|
||||
state: { westmalle: { a: 1, b: 2 } },
|
||||
actions
|
||||
});
|
||||
store.dispatch("dosomething");
|
||||
expect(store.state.westmalle).toEqual({ a: 3, b: 4 });
|
||||
});
|
||||
|
||||
test("aku reactive store state 1", async () => {
|
||||
const actions = {
|
||||
inc({ state }) {
|
||||
state.counter++;
|
||||
}
|
||||
};
|
||||
const state = { counter: 0 };
|
||||
const store = new Store({ state, actions });
|
||||
expect(store.state.counter).toBe(0);
|
||||
store.dispatch("inc", {});
|
||||
expect(store.state.counter).toBe(1);
|
||||
});
|
||||
test("aku reactive store state 1", async () => {
|
||||
const actions = {
|
||||
inc({ state }) {
|
||||
state.counter++;
|
||||
}
|
||||
};
|
||||
const state = { counter: 0 };
|
||||
const store = new Store({ state, actions });
|
||||
expect(store.state.counter).toBe(0);
|
||||
store.dispatch("inc", {});
|
||||
expect(store.state.counter).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updates triggered by the store", () => {
|
||||
@@ -1,17 +0,0 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`connecting a component to store connecting a component to a local store 1`] = `"<div></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component to a local store 2`] = `"<div><span>hello</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component works 1`] = `"<div></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component works 2`] = `"<div><span>hello</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store deep and shallow connecting a component 1`] = `"<div><span>Kasteel</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store deep and shallow connecting a component 2`] = `"<div><span>Kasteel</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store deep and shallow connecting a component 3`] = `"<div><span>Bertinchamps</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store deep and shallow connecting a component 4`] = `"<div><span>Kasteel</span></div>"`;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,990 @@
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { Store, useStore, useDispatch, useGetters } from "../src/store";
|
||||
import { useState } from "../src/hooks";
|
||||
import { xml } from "../src/tags";
|
||||
import { shallowEqual } from "../src/utils";
|
||||
import { makeTestEnv, makeTestFixture, nextTick, makeDeferred } from "./helpers";
|
||||
|
||||
describe("connecting a component to store", () => {
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
test("connecting a component works, with useStore", async () => {
|
||||
let nextId = 1;
|
||||
const state = { todos: [] };
|
||||
const actions = {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg, id: nextId++ });
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-foreach="todos" t-key="todo.id" t-as="todo"><t t-esc="todo.msg"/></span>
|
||||
</div>`;
|
||||
todos = useStore(state => state.todos);
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
|
||||
await store.dispatch("addTodo", "hello");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>hello</span></div>");
|
||||
});
|
||||
|
||||
test("can use useStore twice in a component", async () => {
|
||||
const state = { a: 1, b: 2 };
|
||||
const actions = {
|
||||
doSomething({ state }) {
|
||||
state.a = 2;
|
||||
state.b = 3;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-esc="a.value"/>
|
||||
<span t-esc="b.value"/>
|
||||
</div>`;
|
||||
a = useStore(state => ({ value: state.a }));
|
||||
b = useStore(state => ({ value: state.b }));
|
||||
}
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>1</span><span>2</span></div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(1);
|
||||
|
||||
await store.dispatch("doSomething");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>2</span><span>3</span></div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(2);
|
||||
});
|
||||
|
||||
test("useStore: do not re-render if not changed", async () => {
|
||||
let nextId = 1;
|
||||
const state = { todos: [], a: 1 };
|
||||
const actions = {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg, id: nextId++ });
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-foreach="todos" t-key="todo.id" t-as="todo"><t t-esc="todo.msg"/></span>
|
||||
</div>`;
|
||||
todos = useStore(state => state.todos);
|
||||
}
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(1);
|
||||
|
||||
store.state.todos.push({ id: 3, msg: "hello" });
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>hello</span></div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(2);
|
||||
|
||||
store.state.a = 2;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>hello</span></div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(2);
|
||||
});
|
||||
|
||||
test("connecting a component with useStore returning number", async () => {
|
||||
let nextId = 1;
|
||||
const state = { todos: [] };
|
||||
const actions = {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg, id: nextId++ });
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="nbrTodos.value"/></div>`;
|
||||
nbrTodos = useStore(state => ({ value: state.todos.length }));
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
|
||||
await store.dispatch("addTodo", "hello");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||
});
|
||||
|
||||
test("connecting a component with useStore returning number", async () => {
|
||||
let nextId = 1;
|
||||
const state = { todos: [], a: 1 };
|
||||
const actions = {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg, id: nextId++ });
|
||||
},
|
||||
incrementA({ state }) {
|
||||
state.a++;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="nbrTodos.value"/></div>`;
|
||||
nbrTodos = useStore(state => ({ value: state.todos.length }), { isEqual: shallowEqual });
|
||||
}
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(1);
|
||||
|
||||
await store.dispatch("addTodo", "hello");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(2);
|
||||
|
||||
await store.dispatch("incrementA");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||
expect(App.prototype.__render).toBeCalledTimes(2);
|
||||
});
|
||||
|
||||
test("connecting a component to a local store", async () => {
|
||||
let nextId = 1;
|
||||
const state = { todos: [] };
|
||||
const actions = {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg, id: nextId++ });
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-foreach="todos" t-key="todo.id" t-as="todo"><t t-esc="todo.msg"/></span>
|
||||
</div>`;
|
||||
todos = useStore(state => state.todos, { store });
|
||||
}
|
||||
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
|
||||
await store.dispatch("addTodo", "hello");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>hello</span></div>");
|
||||
});
|
||||
|
||||
test("can dispatch actions from a connected component", async () => {
|
||||
const store = new Store({
|
||||
state: { value: 1 },
|
||||
actions: {
|
||||
inc({ state }) {
|
||||
state.value++;
|
||||
}
|
||||
}
|
||||
});
|
||||
(<any>env).store = store;
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<button t-on-click="dispatch('inc')">Inc</button>
|
||||
<span><t t-esc="storeState.value"/></span>
|
||||
</div>`;
|
||||
storeState = useStore(state => state);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><button>Inc</button><span>1</span></div>");
|
||||
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><button>Inc</button><span>2</span></div>");
|
||||
});
|
||||
|
||||
test("useStore can use props", async () => {
|
||||
const state = { todos: [{ id: 1, text: "jupiler" }, { id: 2, text: "chimay" }] };
|
||||
const store = new Store({ state, actions: {} });
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="todo.text"/></span>`;
|
||||
todo = useStore((state, props) => {
|
||||
return state.todos.find(t => t.id === props.todoId);
|
||||
});
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><TodoItem todoId="state.currentId"/></div>`;
|
||||
static components = { TodoItem };
|
||||
state = useState({ currentId: 1 });
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
|
||||
app.state.currentId = 2;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>chimay</span></div>");
|
||||
});
|
||||
|
||||
test("useStore receives props as second argument", async () => {
|
||||
const state = { todos: [{ id: 1, text: "jupiler" }] };
|
||||
let nextId = 2;
|
||||
const actions = {
|
||||
addTodo({ state }, text) {
|
||||
state.todos.push({ text, id: nextId++ });
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="todo.text"/></span>`;
|
||||
todo = useStore((state, props) => {
|
||||
return state.todos.find(t => t.id === props.id);
|
||||
});
|
||||
}
|
||||
|
||||
class TodoList extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<TodoItem t-foreach="todos" t-as="todo" id="todo.id" t-key="todo.id"/>
|
||||
</div>`;
|
||||
static components = { TodoItem };
|
||||
todos = useStore(state => state.todos);
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoList(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
|
||||
store.dispatch("addTodo", "hoegaarden");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span><span>hoegaarden</span></div>");
|
||||
});
|
||||
|
||||
test("can call useGetters to receive store getters", async () => {
|
||||
const state = {
|
||||
importantID: 1,
|
||||
todos: [{ id: 1, text: "jupiler" }, { id: 2, text: "bertinchamps" }]
|
||||
};
|
||||
const getters = {
|
||||
importantTodoText({ state }) {
|
||||
return state.todos.find(todo => todo.id === state.importantID).text;
|
||||
},
|
||||
text({ state }, id) {
|
||||
return state.todos.find(todo => todo.id === id).text;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, getters });
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span><t t-esc="storeProps.activeTodoText"/></span>
|
||||
<span><t t-esc="storeProps.importantTodoText"/></span>
|
||||
</div>`;
|
||||
getters = useGetters();
|
||||
storeProps = useStore((state, props) => {
|
||||
const todo = state.todos.find(t => t.id === props.id);
|
||||
return {
|
||||
activeTodoText: this.getters.text(todo.id),
|
||||
importantTodoText: this.getters.importantTodoText()
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
class TodoList extends Component<any, any> {
|
||||
static components = { TodoItem };
|
||||
static template = xml`
|
||||
<div>
|
||||
<t t-foreach="todos" t-as="todo">
|
||||
<TodoItem id="todo.id" t-key="todo.id"/>
|
||||
</t>
|
||||
</div>`;
|
||||
todos = useStore(state => state.todos);
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoList(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>jupiler</span><span>jupiler</span></div><div><span>bertinchamps</span><span>jupiler</span></div></div>"
|
||||
);
|
||||
});
|
||||
|
||||
test("connected component is updated when props are updated", async () => {
|
||||
class Beer extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="beer.name"/></span>`;
|
||||
beer = useStore((state, props) => state.beers[props.id]);
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><Beer id="state.beerId"/></div>`;
|
||||
static components = { Beer };
|
||||
state = useState({ beerId: 1 });
|
||||
}
|
||||
|
||||
const state = { beers: { 1: { name: "jupiler" }, 2: { name: "kwak" } } };
|
||||
const store = new Store({ state });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
|
||||
app.state.beerId = 2;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>kwak</span></div>");
|
||||
});
|
||||
|
||||
test("connected component is updated when store is changed", async () => {
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-foreach="data.beers" t-as="beer" t-key="beer.name"><t t-esc="beer.name"/></span>
|
||||
</div>`;
|
||||
|
||||
// we have here a new object
|
||||
data = useStore(state => ({ beers: state.beers, otherKey: 1 }));
|
||||
}
|
||||
|
||||
const actions = {
|
||||
addBeer({ state }, name) {
|
||||
state.beers.push({ name });
|
||||
}
|
||||
};
|
||||
|
||||
const state = { beers: [{ name: "jupiler" }] };
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
|
||||
store.dispatch("addBeer", "kwak");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span><span>kwak</span></div>");
|
||||
});
|
||||
|
||||
test("connected component with undefined, null and string props", async () => {
|
||||
class Beer extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div t-name="Beer">
|
||||
<span>taster:<t t-esc="data.taster"/></span>
|
||||
<span t-if="data.selected">selected:<t t-esc="data.selected.name"/></span>
|
||||
<span t-if="data.consumed">consumed:<t t-esc="data.consumed.name"/></span>
|
||||
</div>`;
|
||||
data = useStore((state, props) => ({
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
}));
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><Beer id="state.beerId"/></div>`;
|
||||
static components = { Beer };
|
||||
state = useState({ beerId: 0 });
|
||||
}
|
||||
|
||||
const actions = {
|
||||
consume({ state }, beerId) {
|
||||
state.consumedID = beerId;
|
||||
}
|
||||
};
|
||||
const state = {
|
||||
beers: {
|
||||
1: { name: "jupiler" }
|
||||
},
|
||||
consumedID: null,
|
||||
taster: "aaron"
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||
|
||||
app.state.beerId = 1;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>selected:jupiler</span></div></div>"
|
||||
);
|
||||
|
||||
store.dispatch("consume", 1);
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>selected:jupiler</span><span>consumed:jupiler</span></div></div>"
|
||||
);
|
||||
|
||||
app.state.beerId = 0;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>consumed:jupiler</span></div></div>"
|
||||
);
|
||||
});
|
||||
|
||||
test("connected component deeply reactive with undefined, null and string props", async () => {
|
||||
class Beer extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span>taster:<t t-esc="info.taster"/></span>
|
||||
<span t-if="info.selected">selected:<t t-esc="info.selected.name"/></span>
|
||||
<span t-if="info.consumed">consumed:<t t-esc="info.consumed.name"/></span>
|
||||
</div>`;
|
||||
info = useStore(function(state, props) {
|
||||
return {
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><Beer id="state.beerId"/></div>`;
|
||||
static components = { Beer };
|
||||
state = useState({ beerId: 0 });
|
||||
}
|
||||
|
||||
const actions = {
|
||||
changeTaster({ state }, newTaster) {
|
||||
state.taster = newTaster;
|
||||
},
|
||||
consume({ state }, beerId) {
|
||||
state.consumedID = beerId;
|
||||
},
|
||||
renameBeer({ state }, { beerId, name }) {
|
||||
state.beers[beerId].name = name;
|
||||
}
|
||||
};
|
||||
const state = {
|
||||
beers: {
|
||||
1: { name: "jupiler" }
|
||||
},
|
||||
consumedID: null,
|
||||
taster: "aaron"
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||
|
||||
app.state.beerId = 1;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>selected:jupiler</span></div></div>"
|
||||
);
|
||||
|
||||
store.dispatch("renameBeer", { beerId: 1, name: "kwak" });
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>selected:kwak</span></div></div>"
|
||||
);
|
||||
|
||||
store.dispatch("consume", 1);
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>selected:kwak</span><span>consumed:kwak</span></div></div>"
|
||||
);
|
||||
|
||||
app.state.beerId = 0;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>consumed:kwak</span></div></div>"
|
||||
);
|
||||
|
||||
store.dispatch("renameBeer", { beerId: 1, name: "jupiler" });
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:aaron</span><span>consumed:jupiler</span></div></div>"
|
||||
);
|
||||
|
||||
store.dispatch("changeTaster", "matthieu");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><span>taster:matthieu</span><span>consumed:jupiler</span></div></div>"
|
||||
);
|
||||
});
|
||||
|
||||
test("correct update order when parent/children are connected", async () => {
|
||||
const steps: string[] = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="state.msg"/></span>`;
|
||||
|
||||
state = useStore((state, props) => {
|
||||
steps.push("child");
|
||||
return { msg: state.msg[props.key] };
|
||||
});
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child key="state.current"/></div>`;
|
||||
static components = { Child };
|
||||
|
||||
state = useStore(state => {
|
||||
steps.push("parent");
|
||||
return {
|
||||
current: state.current,
|
||||
isvisible: state.isvisible
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const state = { current: "a", msg: { a: "a", b: "b" } };
|
||||
const actions = {
|
||||
setCurrent({ state }, c) {
|
||||
state.current = c;
|
||||
}
|
||||
};
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new Parent(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>a</span></div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
|
||||
store.dispatch("setCurrent", "b");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>b</span></div>");
|
||||
expect(steps).toEqual(["parent", "child", "parent", "child"]);
|
||||
});
|
||||
|
||||
test("correct update order when parent/children are connected, part 2", async () => {
|
||||
const steps: string[] = [];
|
||||
let def = makeDeferred();
|
||||
def.resolve();
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="state.msg"/></span>`;
|
||||
state = useStore((s, props) => {
|
||||
steps.push("child");
|
||||
return { msg: s.messages[props.someId] };
|
||||
});
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<Child t-if="state.flag" someId="state.someId"/>
|
||||
</div>`;
|
||||
static components = { Child };
|
||||
state = useStore(s => {
|
||||
steps.push("parent");
|
||||
return { flag: s.flag, someId: s.someId };
|
||||
});
|
||||
|
||||
async render(force) {
|
||||
await def;
|
||||
return super.render(force);
|
||||
}
|
||||
}
|
||||
|
||||
const state = { someId: 1, flag: true, messages: { 1: "abc" } };
|
||||
const actions = {
|
||||
setFlagToFalse({ state }) {
|
||||
state.flag = false;
|
||||
}
|
||||
};
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new Parent(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>abc</span></div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
|
||||
def = makeDeferred();
|
||||
store.dispatch("setFlagToFalse");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>abc</span></div>");
|
||||
expect(steps).toEqual(["parent", "child", "parent"]);
|
||||
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["parent", "child", "parent"]);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
});
|
||||
|
||||
test("connected parent/children: no double rendering", async () => {
|
||||
let steps: string[] = [];
|
||||
const actions = {
|
||||
editTodo({ state }) {
|
||||
state.todos[1].title = "abc";
|
||||
}
|
||||
};
|
||||
const todos = { 1: { id: 1, title: "kikoou" } };
|
||||
const state = {
|
||||
todos
|
||||
};
|
||||
const store = new Store({
|
||||
state,
|
||||
actions
|
||||
});
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div class="todo">
|
||||
<t t-esc="state.todo.title"/>
|
||||
<button class="destroy" t-on-click="editTodo">x</button>
|
||||
</div>`;
|
||||
state = useStore((state, props) => {
|
||||
steps.push("item:usestore");
|
||||
return {
|
||||
todo: state.todos[props.id]
|
||||
};
|
||||
});
|
||||
|
||||
editTodo() {
|
||||
this.env.store.dispatch("editTodo");
|
||||
}
|
||||
__render(f) {
|
||||
steps.push("item:render");
|
||||
return super.__render(f);
|
||||
}
|
||||
}
|
||||
class TodoApp extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div class="todoapp">
|
||||
<t t-foreach="Object.values(state.todos)" t-as="todo">
|
||||
<TodoItem t-key="todo.id" id="todo.id"/>
|
||||
</t>
|
||||
</div>`;
|
||||
static components = { TodoItem };
|
||||
state = useStore(state => {
|
||||
steps.push("app:usestore");
|
||||
return { todos: state.todos };
|
||||
});
|
||||
__render(f) {
|
||||
steps.push("app:render");
|
||||
return super.__render(f);
|
||||
}
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoApp(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div class="todoapp"><div class="todo">kikoou<button class="destroy">x</button></div></div>'
|
||||
);
|
||||
|
||||
expect(steps).toEqual(["app:usestore", "app:render", "item:usestore", "item:render"]);
|
||||
steps = [];
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["app:usestore", "app:render", "item:usestore", "item:render"]);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div class="todoapp"><div class="todo">abc<button class="destroy">x</button></div></div>'
|
||||
);
|
||||
});
|
||||
|
||||
test("connected parent/children: no rendering if child is destroyed", async () => {
|
||||
let steps: string[] = [];
|
||||
const actions = {
|
||||
removeTodo({ state }) {
|
||||
delete state.todos[1];
|
||||
}
|
||||
};
|
||||
const todos = { 1: { id: 1, title: "kikoou" } };
|
||||
const state = {
|
||||
todos
|
||||
};
|
||||
const store = new Store({
|
||||
state,
|
||||
actions
|
||||
});
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div class="todo">
|
||||
<t t-esc="state.todo.title"/>
|
||||
<button class="destroy" t-on-click="removeTodo">x</button>
|
||||
</div>`;
|
||||
state = useStore((state, props) => {
|
||||
steps.push("item:usestore");
|
||||
return {
|
||||
todo: state.todos[props.id]
|
||||
};
|
||||
});
|
||||
|
||||
removeTodo() {
|
||||
this.env.store.dispatch("removeTodo");
|
||||
}
|
||||
__render(f) {
|
||||
steps.push("item:render");
|
||||
return super.__render(f);
|
||||
}
|
||||
}
|
||||
|
||||
class TodoApp extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div class="todoapp">
|
||||
<t t-foreach="Object.values(state.todos)" t-as="todo">
|
||||
<TodoItem t-key="todo.id" id="todo.id"/>
|
||||
</t>
|
||||
</div>`;
|
||||
static components = { TodoItem };
|
||||
state = useStore(state => {
|
||||
steps.push("app:usestore");
|
||||
return { todos: state.todos };
|
||||
});
|
||||
__render(f) {
|
||||
steps.push("app:render");
|
||||
return super.__render(f);
|
||||
}
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoApp(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div class="todoapp"><div class="todo">kikoou<button class="destroy">x</button></div></div>'
|
||||
);
|
||||
|
||||
expect(steps).toEqual(["app:usestore", "app:render", "item:usestore", "item:render"]);
|
||||
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
expect(steps).toEqual([
|
||||
"app:usestore",
|
||||
"app:render",
|
||||
"item:usestore",
|
||||
"item:render",
|
||||
"app:usestore",
|
||||
"app:render"
|
||||
]);
|
||||
expect(fixture.innerHTML).toBe('<div class="todoapp"></div>');
|
||||
});
|
||||
|
||||
test("connected component willpatch/patch hooks are called on store updates", async () => {
|
||||
const steps: string[] = [];
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="store.msg"/></div>`;
|
||||
store = useStore(s => ({ msg: s.msg }));
|
||||
|
||||
willPatch() {
|
||||
steps.push("willpatch");
|
||||
}
|
||||
patched() {
|
||||
steps.push("patched");
|
||||
}
|
||||
}
|
||||
|
||||
const state = { msg: "a" };
|
||||
const actions = {
|
||||
setMsg({ state }, c) {
|
||||
state.msg = c;
|
||||
}
|
||||
};
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>a</div>");
|
||||
|
||||
store.dispatch("setMsg", "b");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>b</div>");
|
||||
expect(steps).toEqual(["willpatch", "patched"]);
|
||||
});
|
||||
|
||||
test("connected child components stop listening to store when destroyed", async () => {
|
||||
let steps: any = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="store.val"/></div>`;
|
||||
store = useStore(s => s);
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child t-if="state.child" /></div>`;
|
||||
static components = { Child };
|
||||
state = useState({ child: true });
|
||||
}
|
||||
|
||||
class TestStore extends Store {
|
||||
on(eventType, owner, callback) {
|
||||
steps.push(`on:${eventType}`);
|
||||
super.on(eventType, owner, callback);
|
||||
}
|
||||
off(eventType, owner) {
|
||||
steps.push(`off:${eventType}`);
|
||||
super.off(eventType, owner);
|
||||
}
|
||||
}
|
||||
const store = new TestStore({ state: { val: 1 } });
|
||||
(<any>env).store = store;
|
||||
const parent = new Parent(env);
|
||||
|
||||
await parent.mount(fixture);
|
||||
expect(steps).toEqual(["on:update"]);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
|
||||
parent.state.child = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(steps).toEqual(["on:update", "off:update"]);
|
||||
});
|
||||
|
||||
test("dispatch an action", async () => {
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="store.counter"/></div>`;
|
||||
store = useStore(state => state);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const state = {
|
||||
counter: 0
|
||||
};
|
||||
|
||||
const actions = {
|
||||
inc({ state }) {
|
||||
return ++state.counter;
|
||||
}
|
||||
};
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
|
||||
const res = app.dispatch("inc");
|
||||
expect(res).toBe(1);
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("various scenarios", () => {
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
test("scenarios with async store updates and some components events", async () => {
|
||||
const actions = {
|
||||
async deleteAttachment({ state }) {
|
||||
await Promise.resolve();
|
||||
delete state.attachments[100];
|
||||
state.messages[10].attachmentIds = [];
|
||||
}
|
||||
};
|
||||
const state = {
|
||||
attachments: {
|
||||
100: {
|
||||
id: 100,
|
||||
name: "text.txt"
|
||||
}
|
||||
},
|
||||
messages: {
|
||||
10: {
|
||||
attachmentIds: [100],
|
||||
id: 10
|
||||
}
|
||||
}
|
||||
};
|
||||
const store = new Store({ actions, state });
|
||||
|
||||
class Attachment extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span>Attachment <t t-esc="props.id"/></span>
|
||||
<span>Name: <t t-esc="attachment.name"/></span>
|
||||
</div>`;
|
||||
|
||||
attachment = useStore((state, props) => ({ name: state.attachments[props.id].name }));
|
||||
}
|
||||
|
||||
class Message extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<button t-on-click="doStuff">Do stuff</button>
|
||||
<Attachment t-foreach="store.attachmentIds" t-key="attachmentId" t-as="attachmentId" id="attachmentId"/>
|
||||
</div>`;
|
||||
|
||||
store = useStore(state => ({ attachmentIds: state.messages[10].attachmentIds }));
|
||||
static components = { Attachment };
|
||||
state = { isAttachmentDeleted: false };
|
||||
dispatch = useDispatch();
|
||||
doStuff() {
|
||||
this.dispatch("deleteAttachment", 100);
|
||||
this.state.isAttachmentDeleted = true;
|
||||
}
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const message = new Message(env);
|
||||
await message.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
+57
-59
@@ -1,5 +1,6 @@
|
||||
import { h, patch } from "../src/vdom";
|
||||
import { init } from "../src/vdom/vdom";
|
||||
import { htmlToVDOM } from "../src/vdom/html_to_vdom";
|
||||
import { init, addNS } from "../src/vdom/vdom";
|
||||
|
||||
function map(list, fn) {
|
||||
var ret: any[] = [];
|
||||
@@ -184,20 +185,6 @@ describe("snabbdom", function() {
|
||||
expect(elm.tagName).toBe("DIV");
|
||||
});
|
||||
|
||||
test("has different tag and id", function() {
|
||||
let elm: any = document.createElement("div");
|
||||
vnode0.appendChild(elm);
|
||||
const vnode1 = h("span#id");
|
||||
elm = patch(elm, vnode1).elm;
|
||||
expect(elm.tagName).toBe("SPAN");
|
||||
expect(elm.id).toBe("id");
|
||||
});
|
||||
|
||||
test("has id", function() {
|
||||
elm = patch(vnode0, h("div", [h("div#unique")])).elm;
|
||||
expect(elm.firstChild.id).toBe("unique");
|
||||
});
|
||||
|
||||
test("has correct namespace", function() {
|
||||
const SVGNamespace = "http://www.w3.org/2000/svg";
|
||||
const XHTMLNamespace = "http://www.w3.org/1999/xhtml";
|
||||
@@ -206,33 +193,15 @@ describe("snabbdom", function() {
|
||||
expect(elm.firstChild.namespaceURI).toBe(SVGNamespace);
|
||||
|
||||
// verify that svg tag automatically gets svg namespace
|
||||
elm = patch(vnode0, h("svg", [h("foreignObject", [h("div", ["I am HTML embedded in SVG"])])]))
|
||||
.elm;
|
||||
const vnode = h("svg", [h("foreignObject", [h("div", ["I am HTML embedded in SVG"])])]);
|
||||
// need to add namespace manually. it is usually done by the template
|
||||
// compiler
|
||||
addNS(vnode.data, (vnode as any).children, vnode.sel);
|
||||
|
||||
elm = patch(vnode0, vnode).elm;
|
||||
expect(elm.namespaceURI).toBe(SVGNamespace);
|
||||
expect(elm.firstChild.namespaceURI).toBe(SVGNamespace);
|
||||
expect(elm.firstChild.firstChild.namespaceURI).toBe(XHTMLNamespace);
|
||||
|
||||
// verify that svg tag with extra selectors gets svg namespace
|
||||
elm = patch(vnode0, h("svg#some-id")).elm;
|
||||
expect(elm.namespaceURI).toBe(SVGNamespace);
|
||||
|
||||
// verify that non-svg tag beginning with 'svg' does NOT get namespace
|
||||
elm = patch(vnode0, h("svg-custom-el")).elm;
|
||||
expect(elm.namespaceURI).not.toBe(SVGNamespace);
|
||||
});
|
||||
|
||||
test("receives classes in selector", function() {
|
||||
elm = patch(vnode0, h("div", [h("i.am.a.class")])).elm;
|
||||
expect(elm.firstChild.classList.contains("am")).toBeTruthy();
|
||||
expect(elm.firstChild.classList.contains("a")).toBeTruthy();
|
||||
expect(elm.firstChild.classList.contains("class")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("receives classes in selector when namespaced", function() {
|
||||
elm = patch(vnode0, h("svg", [h("g.am.a.class.too")])).elm;
|
||||
expect(elm.firstChild.classList.contains("am")).toBeTruthy();
|
||||
expect(elm.firstChild.classList.contains("a")).toBeTruthy();
|
||||
expect(elm.firstChild.classList.contains("class")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("can create elements with text content", function() {
|
||||
@@ -271,26 +240,6 @@ describe("snabbdom", function() {
|
||||
});
|
||||
|
||||
describe("patching an element", function() {
|
||||
test("changes the elements classes", function() {
|
||||
const vnode1 = h("i.i.am.horse");
|
||||
const vnode2 = h("i.i.am");
|
||||
patch(vnode0, vnode1);
|
||||
elm = patch(vnode1, vnode2).elm;
|
||||
expect(elm.classList.contains("i")).toBeTruthy();
|
||||
expect(elm.classList.contains("am")).toBeTruthy();
|
||||
expect(!elm.classList.contains("horse")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("removes missing classes", function() {
|
||||
const vnode1 = h("i.i.am.horse");
|
||||
const vnode2 = h("i.i.am");
|
||||
patch(vnode0, vnode1);
|
||||
elm = patch(vnode1, vnode2).elm;
|
||||
expect(elm.classList.contains("i")).toBeTruthy();
|
||||
expect(elm.classList.contains("am")).toBeTruthy();
|
||||
expect(!elm.classList.contains("horse")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("changes an elements props", function() {
|
||||
const vnode1 = h("a", { props: { src: "http://other/" } });
|
||||
const vnode2 = h("a", { props: { src: "http://localhost/" } });
|
||||
@@ -1108,3 +1057,52 @@ describe("snabbdom", function() {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Html to vdom
|
||||
//------------------------------------------------------------------------------
|
||||
describe("html to vdom", function() {
|
||||
let elm, vnode0;
|
||||
beforeEach(function() {
|
||||
elm = document.createElement("div");
|
||||
vnode0 = elm;
|
||||
});
|
||||
|
||||
test("empty strings return empty list", function() {
|
||||
expect(htmlToVDOM("")).toEqual([]);
|
||||
});
|
||||
|
||||
test("just text", function() {
|
||||
const nodeList = htmlToVDOM("simple text");
|
||||
expect(nodeList).toHaveLength(1);
|
||||
expect(nodeList[0]).toEqual({ text: "simple text" });
|
||||
});
|
||||
|
||||
test("empty tag", function() {
|
||||
const nodeList = htmlToVDOM("<span></span>");
|
||||
expect(nodeList).toHaveLength(1);
|
||||
elm = patch(vnode0, nodeList[0]).elm;
|
||||
expect(elm.outerHTML).toEqual("<span></span>");
|
||||
});
|
||||
|
||||
test("tag with text", function() {
|
||||
const nodeList = htmlToVDOM("<span>abc</span>");
|
||||
expect(nodeList).toHaveLength(1);
|
||||
elm = patch(vnode0, nodeList[0]).elm;
|
||||
expect(elm.outerHTML).toEqual("<span>abc</span>");
|
||||
});
|
||||
|
||||
test("tag with attribute", function() {
|
||||
const nodeList = htmlToVDOM(`<span a="1" b="2">abc</span>`);
|
||||
expect(nodeList).toHaveLength(1);
|
||||
elm = patch(vnode0, nodeList[0]).elm;
|
||||
expect(elm.outerHTML).toEqual(`<span a="1" b="2">abc</span>`);
|
||||
});
|
||||
|
||||
test("misc", function() {
|
||||
const nodeList = htmlToVDOM(`<span a="1" b="2">abc<div>1</div></span>`);
|
||||
expect(nodeList).toHaveLength(1);
|
||||
elm = patch(vnode0, nodeList[0]).elm;
|
||||
expect(elm.outerHTML).toEqual(`<span a="1" b="2">abc<div>1</div></span>`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { buildData, startMeasure, stopMeasure, formatNumber } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
static components = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps.message !== this.props.message;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove-message", {
|
||||
id: this.props.message.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
static components = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
|
||||
mounted() {
|
||||
this.log(`Benchmarking Owl v${owl.__info__.version} (build date: ${owl.__info__.date})`);
|
||||
}
|
||||
|
||||
benchmark(message, fn, callback) {
|
||||
if (this.state.multipleFlag) {
|
||||
const N = 20;
|
||||
let n = N;
|
||||
let total = 0;
|
||||
let cb = info => {
|
||||
let finalize = () => {
|
||||
n--;
|
||||
total += info.delta;
|
||||
if (n === 0) {
|
||||
const avg = total / N;
|
||||
this.log(`Average: ${formatNumber(avg)}ms`, true);
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
this._benchmark(message, fn, cb);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.state.clearAfterFlag) {
|
||||
this._benchmark(
|
||||
"clear",
|
||||
() => {
|
||||
this.state.messages = [];
|
||||
},
|
||||
finalize,
|
||||
false
|
||||
);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
}
|
||||
|
||||
_benchmark(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
fn();
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
});
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._benchmark("clear", () => {
|
||||
this.state.messages = [];
|
||||
});
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
messages[i] = msg;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(event) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === event.detail.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>OWL 0.21.0 Benchmark</title>
|
||||
<link href="../shared/main.css" rel="stylesheet"/>
|
||||
<script src='owl.js'></script>
|
||||
</head>
|
||||
<body>
|
||||
<script src='app.js' type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
<templates>
|
||||
<div t-name="App" class="main">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1k messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10k messages</button>
|
||||
<button t-on-click="addMessages(30000)">Add 30k messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th messages</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" id="multipleflag" t-model="multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-model="clearAfterFlag" />
|
||||
<label for="clearFlag">Clear after</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info">Number of messages: <t t-esc="state.messages.length"/></div>
|
||||
<hr/>
|
||||
<div class="title">Log <span class="clear-log" t-on-click="clearLog">(clear)</span></div>
|
||||
<div class="log">
|
||||
<div class="log-content" t-ref="log"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content" t-on-remove-message="removeMessage">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<Message t-key="message.id" message="message"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.message.author"/></span>
|
||||
<span class="msg"><t t-esc="props.message.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<Counter/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,10 +1,11 @@
|
||||
import { buildData, startMeasure, stopMeasure, formatNumber } from "../shared/utils.js";
|
||||
|
||||
const { useState, useRef } = owl.hooks;
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
state = useState({ counter: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
@@ -15,7 +16,7 @@ class Counter extends owl.Component {
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
components = { Counter };
|
||||
static components = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps.message !== this.props.message;
|
||||
@@ -31,8 +32,9 @@ class Message extends owl.Component {
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
components = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
static components = { Message };
|
||||
state = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
|
||||
logRef = useRef("log");
|
||||
|
||||
mounted() {
|
||||
this.log(`Benchmarking Owl v${owl.__info__.version} (build date: ${owl.__info__.date})`);
|
||||
@@ -129,12 +131,12 @@ class App extends owl.Component {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
this.logRef.el.appendChild(div);
|
||||
this.logRef.el.scrollTop = this.logRef.el.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
this.logRef.el.innerHTML = "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +144,7 @@ class App extends owl.Component {
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const templates = await owl.utils.loadFile("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" id="multipleflag" t-model="multipleFlag"/>
|
||||
<input type="checkbox" id="multipleflag" t-model="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-model="clearAfterFlag" />
|
||||
<input type="checkbox" id="clearFlag" t-model="state.clearAfterFlag" />
|
||||
<label for="clearFlag">Clear after</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
<li><a href="benchmarks/owl-0.16.0">OWL 0.16.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.17.0">OWL 0.17.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.18.0">OWL 0.18.0</a></li>
|
||||
<li><a href="benchmarks/owl-0.21.0">OWL 0.21.0</a></li>
|
||||
<li><a href="benchmarks/owl-master">OWL Master</a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
|
||||
+168
-106
@@ -1,5 +1,5 @@
|
||||
import { SAMPLES } from "./samples.js";
|
||||
|
||||
const { useState, useRef, onMounted, onWillUnmount } = owl.hooks;
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants, helpers, utils
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -127,7 +127,7 @@ async function makeApp(js, css, xml) {
|
||||
const JS = `
|
||||
async function loadTemplates() {
|
||||
try {
|
||||
return owl.utils.loadTemplates('app.xml');
|
||||
return owl.utils.loadFile('app.xml');
|
||||
} catch(e) {
|
||||
console.error(\`This app requires a static server. If you have python installed, try 'python app.py'\`);
|
||||
}
|
||||
@@ -150,6 +150,152 @@ Promise.all([loadTemplates(), owl.utils.whenReady()]).then(start);
|
||||
return zip.generateAsync({ type: "blob" });
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// SAMPLES
|
||||
//------------------------------------------------------------------------------
|
||||
function loadSamples() {
|
||||
let result = SAMPLES.slice();
|
||||
const localSample = localStorage.getItem("owl-playground-local-sample");
|
||||
if (localSample) {
|
||||
const { js, css, xml } = JSON.parse(localSample);
|
||||
result.unshift({
|
||||
description: "Local Storage Code",
|
||||
code: js,
|
||||
xml,
|
||||
css
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function saveLocalSample(js, css, xml) {
|
||||
const str = JSON.stringify({ js, css, xml });
|
||||
localStorage.setItem("owl-playground-local-sample", str);
|
||||
}
|
||||
|
||||
function deleteLocalSample() {
|
||||
localStorage.removeItem("owl-playground-local-sample");
|
||||
}
|
||||
|
||||
function useSamples() {
|
||||
const samples = loadSamples();
|
||||
const component = owl.Component.current;
|
||||
let interval;
|
||||
|
||||
onMounted(() => {
|
||||
const state = component.state;
|
||||
interval = setInterval(() => {
|
||||
if (component.isDirty) {
|
||||
saveLocalSample(state.js, state.css, state.xml);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
clearInterval(interval);
|
||||
});
|
||||
return samples;
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
// Tabbed editor
|
||||
//------------------------------------------------------------------------------
|
||||
class TabbedEditor extends owl.Component {
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = useState({
|
||||
currentTab: props.js !== false ? "js" : props.xml ? "xml" : "css"
|
||||
});
|
||||
this.setTab = owl.utils.debounce(this.setTab, 250, true);
|
||||
|
||||
this.sessions = {};
|
||||
this._setupSessions(props);
|
||||
this.editorNode = useRef("editor");
|
||||
this._updateCode = this._updateCode.bind(this);
|
||||
}
|
||||
|
||||
mounted() {
|
||||
this.editor = this.editor || ace.edit(this.editorNode.el);
|
||||
|
||||
this.editor.setValue(this.props[this.state.currentTab], -1);
|
||||
this.editor.setFontSize("12px");
|
||||
this.editor.setTheme("ace/theme/monokai");
|
||||
this.editor.setSession(this.sessions[this.state.currentTab]);
|
||||
const tabSize = this.state.currentTab === "xml" ? 2 : 4;
|
||||
this.editor.session.setOption("tabSize", tabSize);
|
||||
this.editor.on("blur", this._updateCode);
|
||||
this.interval = setInterval(this._updateCode, 3000);
|
||||
}
|
||||
|
||||
willUnmount() {
|
||||
clearInterval(this.interval);
|
||||
this.editor.off("blur", this._updateCode);
|
||||
}
|
||||
willUpdateProps(nextProps) {
|
||||
this._setupSessions(nextProps);
|
||||
}
|
||||
|
||||
patched() {
|
||||
const session = this.sessions[this.state.currentTab];
|
||||
let content = this.props[this.state.currentTab];
|
||||
if (content === false) {
|
||||
const tab = this.props.js !== false ? "js" : this.props.xml ? "xml" : "css";
|
||||
content = this.props[tab];
|
||||
this.state.currentTab = tab;
|
||||
}
|
||||
if (this.editor.getValue() !== content) {
|
||||
session.setValue(content, -1);
|
||||
this.editor.setSession(session);
|
||||
this.editor.resize();
|
||||
}
|
||||
}
|
||||
|
||||
setTab(tab) {
|
||||
if (this.state.currentTab !== tab) {
|
||||
this.state.currentTab = tab;
|
||||
const session = this.sessions[this.state.currentTab];
|
||||
session.doc.setValue(this.props[tab], -1);
|
||||
this.editor.setSession(session);
|
||||
}
|
||||
}
|
||||
|
||||
onMouseDown(ev) {
|
||||
if (ev.target.tagName === "DIV") {
|
||||
let y = ev.clientY;
|
||||
const resizer = ev => {
|
||||
const delta = ev.clientY - y;
|
||||
y = ev.clientY;
|
||||
this.trigger("updatePanelHeight", { delta });
|
||||
};
|
||||
document.body.addEventListener("mousemove", resizer);
|
||||
document.body.addEventListener("mouseup", () => {
|
||||
document.body.removeEventListener("mousemove", resizer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
_setupSessions(props) {
|
||||
for (let tab of ["js", "xml", "css"]) {
|
||||
if (props[tab] !== false && !this.sessions[tab]) {
|
||||
this.sessions[tab] = new ace.EditSession(props[tab], MODES[tab]);
|
||||
this.sessions[tab].setOption("useWorker", false);
|
||||
const tabSize = tab === "xml" ? 2 : 4;
|
||||
this.sessions[tab].setOption("tabSize", tabSize);
|
||||
this.sessions[tab].setUndoManager(new ace.UndoManager());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_updateCode() {
|
||||
const editorValue = this.editor.getValue();
|
||||
const propsValue = this.props[this.state.currentTab];
|
||||
if (editorValue !== propsValue) {
|
||||
this.trigger("updateCode", {
|
||||
type: this.state.currentTab,
|
||||
value: editorValue
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// MAIN APP
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -157,30 +303,31 @@ class App extends owl.Component {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.version = owl.__info__.version;
|
||||
this.SAMPLES = SAMPLES;
|
||||
this.components = { TabbedEditor };
|
||||
this.SAMPLES = useSamples();
|
||||
this.isDirty = false;
|
||||
|
||||
this.state = {
|
||||
js: SAMPLES[0].code,
|
||||
css: SAMPLES[0].css || "",
|
||||
xml: SAMPLES[0].xml || DEFAULT_XML,
|
||||
this.state = useState({
|
||||
js: this.SAMPLES[0].code,
|
||||
css: this.SAMPLES[0].css || "",
|
||||
xml: this.SAMPLES[0].xml || DEFAULT_XML,
|
||||
error: false,
|
||||
displayWelcome: true,
|
||||
splitLayout: true,
|
||||
leftPaneWidth: Math.ceil(window.innerWidth / 2),
|
||||
topPanelHeight: null
|
||||
};
|
||||
});
|
||||
|
||||
this.toggleLayout = owl.utils.debounce(this.toggleLayout, 250, true);
|
||||
this.runCode = owl.utils.debounce(this.runCode, 250, true);
|
||||
this.downloadCode = owl.utils.debounce(this.downloadCode, 250, true);
|
||||
this.content = useRef("content");
|
||||
}
|
||||
|
||||
displayError(error) {
|
||||
this.state.error = error;
|
||||
if (error) {
|
||||
setTimeout(() => {
|
||||
this.refs.content.innerHTML = "";
|
||||
this.content.el.innerHTML = "";
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -206,15 +353,17 @@ class App extends owl.Component {
|
||||
} else {
|
||||
this.state.error = false;
|
||||
}
|
||||
this.refs.content.innerHTML = "";
|
||||
this.refs.content.appendChild(subiframe);
|
||||
this.content.el.innerHTML = "";
|
||||
this.content.el.appendChild(subiframe);
|
||||
}
|
||||
|
||||
setSample(ev) {
|
||||
const sample = SAMPLES.find(s => s.description === ev.target.value);
|
||||
const sample = this.SAMPLES.find(s => s.description === ev.target.value);
|
||||
this.state.js = sample.code;
|
||||
this.state.css = sample.css || "";
|
||||
this.state.xml = sample.xml || DEFAULT_XML;
|
||||
deleteLocalSample();
|
||||
this.isDirty = false;
|
||||
}
|
||||
|
||||
get leftPaneStyle() {
|
||||
@@ -247,7 +396,10 @@ class App extends owl.Component {
|
||||
});
|
||||
}
|
||||
updateCode(ev) {
|
||||
this.state[ev.detail.type] = ev.detail.value;
|
||||
if (this.state[ev.detail.type] !== ev.detail.value) {
|
||||
this.state[ev.detail.type] = ev.detail.value;
|
||||
this.isDirty = true;
|
||||
}
|
||||
}
|
||||
toggleLayout() {
|
||||
this.state.splitLayout = !this.state.splitLayout;
|
||||
@@ -270,97 +422,7 @@ class App extends owl.Component {
|
||||
saveAs(content, "app.zip");
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tabbed editor
|
||||
//------------------------------------------------------------------------------
|
||||
class TabbedEditor extends owl.Component {
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
this.state = {
|
||||
currentTab: props.js ? "js" : props.xml ? "xml" : "css"
|
||||
};
|
||||
this.setTab = owl.utils.debounce(this.setTab, 250, true);
|
||||
|
||||
this.sessions = {};
|
||||
this._setupSessions(props);
|
||||
this.editor = null;
|
||||
}
|
||||
|
||||
mounted() {
|
||||
this.editor = this.editor || ace.edit(this.refs.editor);
|
||||
|
||||
this.editor.setValue(this.props[this.state.currentTab], -1);
|
||||
this.editor.setFontSize("12px");
|
||||
this.editor.setTheme("ace/theme/monokai");
|
||||
this.editor.setSession(this.sessions[this.state.currentTab]);
|
||||
const tabSize = this.state.currentTab === "xml" ? 2 : 4;
|
||||
this.editor.session.setOption("tabSize", tabSize);
|
||||
this.editor.on("blur", () => {
|
||||
const editorValue = this.editor.getValue();
|
||||
const propsValue = this.props[this.state.currentTab];
|
||||
if (editorValue !== propsValue) {
|
||||
this.trigger("updateCode", {
|
||||
type: this.state.currentTab,
|
||||
value: editorValue
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
willUpdateProps(nextProps) {
|
||||
this._setupSessions(nextProps);
|
||||
}
|
||||
|
||||
patched() {
|
||||
const session = this.sessions[this.state.currentTab];
|
||||
let content = this.props[this.state.currentTab];
|
||||
if (content === false) {
|
||||
const tab = this.props.js ? "js" : this.props.xml ? "xml" : "css";
|
||||
content = this.props[tab];
|
||||
this.state.currentTab = tab;
|
||||
}
|
||||
session.setValue(content, -1);
|
||||
this.editor.setSession(session);
|
||||
this.editor.resize();
|
||||
}
|
||||
|
||||
setTab(tab) {
|
||||
if (this.state.currentTab !== tab) {
|
||||
this.state.currentTab = tab;
|
||||
const session = this.sessions[this.state.currentTab];
|
||||
session.doc.setValue(this.props[tab], -1);
|
||||
this.editor.setSession(session);
|
||||
}
|
||||
}
|
||||
|
||||
onMouseDown(ev) {
|
||||
if (ev.target.tagName === "DIV") {
|
||||
let y = ev.clientY;
|
||||
const resizer = ev => {
|
||||
const delta = ev.clientY - y;
|
||||
y = ev.clientY;
|
||||
this.trigger("updatePanelHeight", { delta });
|
||||
};
|
||||
document.body.addEventListener("mousemove", resizer);
|
||||
document.body.addEventListener("mouseup", () => {
|
||||
document.body.removeEventListener("mousemove", resizer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
_setupSessions(props) {
|
||||
for (let tab of ["js", "xml", "css"]) {
|
||||
if (props[tab] && !this.sessions[tab]) {
|
||||
this.sessions[tab] = new ace.EditSession(props[tab], MODES[tab]);
|
||||
this.sessions[tab].setOption("useWorker", false);
|
||||
const tabSize = tab === "xml" ? 2 : 4;
|
||||
this.sessions[tab].setOption("tabSize", tabSize);
|
||||
this.sessions[tab].setUndoManager(new ace.UndoManager());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
App.components = { TabbedEditor };
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
@@ -368,7 +430,7 @@ class TabbedEditor extends owl.Component {
|
||||
async function start() {
|
||||
document.title = `${document.title} (v${owl.__info__.version})`;
|
||||
const [templates] = await Promise.all([
|
||||
owl.utils.loadTemplates("templates.xml"),
|
||||
owl.utils.loadFile("templates.xml"),
|
||||
owl.utils.whenReady()
|
||||
]);
|
||||
const qweb = new owl.QWeb(templates);
|
||||
|
||||
@@ -173,8 +173,10 @@ body {
|
||||
}
|
||||
|
||||
.right-pane .note {
|
||||
font-size: 20px;
|
||||
font-size: 18px;
|
||||
text-align: left;
|
||||
margin-top: 20px;
|
||||
padding: 5%;
|
||||
}
|
||||
|
||||
.right-pane .error {
|
||||
|
||||
+312
-177
@@ -1,18 +1,19 @@
|
||||
const COMPONENTS = `// In this example, we show how components can be defined and created.
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Greeter extends owl.Component {
|
||||
state = { word: 'Hello' };
|
||||
class Greeter extends Component {
|
||||
state = useState({ word: 'Hello' });
|
||||
|
||||
toggle() {
|
||||
this.state.word = this.state.word === 'Hi' ? 'Hello' : 'Hi'
|
||||
this.state.word = this.state.word === 'Hi' ? 'Hello' : 'Hi';
|
||||
}
|
||||
}
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
components = { Greeter };
|
||||
state = { name: 'World'};
|
||||
class App extends Component {
|
||||
state = useState({ name: 'World'});
|
||||
}
|
||||
App.components = { Greeter };
|
||||
|
||||
// Application setup
|
||||
// Note that the xml templates are injected into the global TEMPLATES variable.
|
||||
@@ -45,18 +46,18 @@ const COMPONENTS_CSS = `.greeter {
|
||||
|
||||
const ANIMATION = `// The goal of this component is to see how the t-transition directive can be
|
||||
// used to generate simple transition effects.
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Counter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
class Counter extends Component {
|
||||
state = useState({ value: 0 });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
|
||||
class App extends owl.Component {
|
||||
state = { flag: false, componentFlag: false, numbers: [] };
|
||||
components = { Counter };
|
||||
class App extends Component {
|
||||
state = useState({ flag: false, componentFlag: false, numbers: [] });
|
||||
|
||||
toggle(key) {
|
||||
this.state[key] = !this.state[key];
|
||||
@@ -66,8 +67,8 @@ class App extends owl.Component {
|
||||
const n = this.state.numbers.length + 1;
|
||||
this.state.numbers.push(n);
|
||||
}
|
||||
|
||||
}
|
||||
App.components = { Counter };
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const app = new App({qweb});
|
||||
@@ -183,11 +184,12 @@ const LIFECYCLE_DEMO = `// This example shows all the possible lifecycle hooks
|
||||
// methods in the console. Try modifying its state by clicking on it, or by
|
||||
// clicking on the two main buttons, and look into the console to see what
|
||||
// happens.
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class DemoComponent extends owl.Component {
|
||||
class DemoComponent extends Component {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = { n: 0 };
|
||||
this.state = useState({ n: 0 });
|
||||
console.log("constructor");
|
||||
}
|
||||
async willStart() {
|
||||
@@ -213,9 +215,8 @@ class DemoComponent extends owl.Component {
|
||||
}
|
||||
}
|
||||
|
||||
class App extends owl.Component {
|
||||
components = { DemoComponent };
|
||||
state = { n: 0, flag: true };
|
||||
class App extends Component {
|
||||
state = useState({ n: 0, flag: true });
|
||||
|
||||
increment() {
|
||||
this.state.n++;
|
||||
@@ -225,6 +226,7 @@ class App extends owl.Component {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
}
|
||||
App.components = { DemoComponent };
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const app = new App({ qweb });
|
||||
@@ -259,101 +261,209 @@ const LIFECYCLE_CSS = `button {
|
||||
width: 250px;
|
||||
}`;
|
||||
|
||||
const HOOKS_DEMO = `// In this example, we show how hooks can be used or defined.
|
||||
const {useState, onMounted, onWillUnmount} = owl.hooks;
|
||||
|
||||
// We define here a custom behaviour: this hook tracks the state of the mouse
|
||||
// position
|
||||
function useMouse() {
|
||||
const position = useState({x:0, y: 0});
|
||||
|
||||
function update(e) {
|
||||
position.x = e.clientX;
|
||||
position.y = e.clientY;
|
||||
}
|
||||
onMounted(() => {
|
||||
window.addEventListener('mousemove', update);
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
window.removeEventListener('mousemove', update);
|
||||
});
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
// simple state hook (reactive object)
|
||||
counter = useState({ value: 0 });
|
||||
|
||||
// this hooks is bound to the 'mouse' property.
|
||||
mouse = useMouse();
|
||||
|
||||
increment() {
|
||||
this.counter.value++;
|
||||
}
|
||||
}
|
||||
|
||||
// Application setup
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
const HOOKS_DEMO_XML = `<templates>
|
||||
<div t-name="App">
|
||||
<button t-on-click="increment">Click! <t t-esc="counter.value"/></button>
|
||||
<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>
|
||||
</div>
|
||||
</templates>
|
||||
`;
|
||||
|
||||
const HOOKS_CSS = `button {
|
||||
width: 120px;
|
||||
height: 35px;
|
||||
font-size: 16px;
|
||||
}`;
|
||||
|
||||
const CONTEXT_JS = `// In this example, we show how components can use the Context and 'useContext'
|
||||
// hook to share information between them.
|
||||
const { Component, Context } = owl;
|
||||
const { useContext } = owl.hooks;
|
||||
|
||||
class ToolbarButton extends Component {
|
||||
theme = useContext(this.env.themeContext);
|
||||
|
||||
get style () {
|
||||
const theme = this.theme;
|
||||
return \`background-color: \${theme.background}; color: \${theme.foreground}\`;
|
||||
}
|
||||
}
|
||||
|
||||
class Toolbar extends Component {}
|
||||
Toolbar.components = { ToolbarButton };
|
||||
|
||||
// Main root component
|
||||
class App extends Component {
|
||||
toggleTheme() {
|
||||
const { background, foreground } = this.env.themeContext.state;
|
||||
this.env.themeContext.state.background = foreground;
|
||||
this.env.themeContext.state.foreground = background;
|
||||
}
|
||||
}
|
||||
App.components = { Toolbar };
|
||||
|
||||
// Application setup
|
||||
const themeContext = new Context({
|
||||
background: '#000',
|
||||
foreground: '#fff',
|
||||
});
|
||||
const env = {
|
||||
qweb: new owl.QWeb(TEMPLATES),
|
||||
themeContext: themeContext,
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
const CONTEXT_XML = `<templates>
|
||||
<button t-name="ToolbarButton" t-att-style="style">
|
||||
<t t-esc="props.name"/>
|
||||
</button>
|
||||
|
||||
<div t-name="Toolbar">
|
||||
<ToolbarButton name="'A'"/>
|
||||
<ToolbarButton name="'B'"/>
|
||||
<ToolbarButton name="'C'"/>
|
||||
</div>
|
||||
|
||||
<div t-name="App">
|
||||
<button t-on-click="toggleTheme">Toggle Mode</button>
|
||||
<Toolbar/>
|
||||
</div>
|
||||
</templates>
|
||||
`;
|
||||
|
||||
const TODO_APP_STORE = `// This example is an implementation of the TodoList application, from the
|
||||
// www.todomvc.com project. This is a non trivial application with some
|
||||
// interesting user interactions. It uses the local storage for persistence.
|
||||
//
|
||||
// In this implementation, we use the owl Store class to manage the state. It
|
||||
// is very similar to the VueX store.
|
||||
const { Component, useState } = owl;
|
||||
const { useRef, useStore, useDispatch, onPatched, onMounted } = owl.hooks;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants, helpers
|
||||
//------------------------------------------------------------------------------
|
||||
const ENTER_KEY = 13;
|
||||
const ESC_KEY = 27;
|
||||
const LOCALSTORAGE_KEY = "todomvc";
|
||||
|
||||
function useAutofocus(name) {
|
||||
let ref = useRef(name);
|
||||
let isInDom = false;
|
||||
function updateFocus() {
|
||||
if (!isInDom && ref.el) {
|
||||
isInDom = true;
|
||||
const current = ref.el.value;
|
||||
ref.el.value = "";
|
||||
ref.el.focus();
|
||||
ref.el.value = current;
|
||||
} else if (isInDom && !ref.el) {
|
||||
isInDom = false;
|
||||
}
|
||||
}
|
||||
onPatched(updateFocus);
|
||||
onMounted(updateFocus);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Store Definition
|
||||
// Store
|
||||
//------------------------------------------------------------------------------
|
||||
const initialState = { todos: [], nextId: 1};
|
||||
|
||||
const actions = {
|
||||
addTodo({ state }, title) {
|
||||
state.todos.push({
|
||||
const todo = {
|
||||
id: state.nextId++,
|
||||
title,
|
||||
completed: false
|
||||
});
|
||||
}
|
||||
state.todos.push(todo);
|
||||
},
|
||||
removeTodo({ state }, id) {
|
||||
const index = state.todos.findIndex(t => t.id === id);
|
||||
state.todos.splice(index, 1);
|
||||
},
|
||||
toggleTodo({ state, dispatch }, id) {
|
||||
updateTodo({state, dispatch}, {id, title}) {
|
||||
const value = title.trim();
|
||||
if (!value) {
|
||||
dispatch('removeTodo', id);
|
||||
} else {
|
||||
const todo = state.todos.find(t => t.id === id);
|
||||
todo.title = value;
|
||||
}
|
||||
},
|
||||
toggleTodo({ state }, id) {
|
||||
const todo = state.todos.find(t => t.id === id);
|
||||
dispatch("editTodo", { id, completed: !todo.completed });
|
||||
todo.completed = !todo.completed;
|
||||
},
|
||||
clearCompleted({ state, dispatch }) {
|
||||
state.todos
|
||||
.filter(todo => todo.completed)
|
||||
.forEach(todo => {
|
||||
for (let todo of state.todos) {
|
||||
if (todo.completed) {
|
||||
dispatch("removeTodo", todo.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
toggleAll({ state, dispatch }, completed) {
|
||||
state.todos.forEach(todo => {
|
||||
dispatch("editTodo", {
|
||||
id: todo.id,
|
||||
completed
|
||||
});
|
||||
});
|
||||
},
|
||||
editTodo({ state }, { id, title, completed }) {
|
||||
const todo = state.todos.find(t => t.id === id);
|
||||
if (title !== undefined) {
|
||||
todo.title = title;
|
||||
}
|
||||
if (completed !== undefined) {
|
||||
for (let todo of state.todos) {
|
||||
todo.completed = completed;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
function saveState(state) {
|
||||
const str = JSON.stringify(state);
|
||||
window.localStorage.setItem(LOCALSTORAGE_KEY, str);
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
const localState = window.localStorage.getItem(LOCALSTORAGE_KEY);
|
||||
return localState ? JSON.parse(localState) : { todos: [], nextId: 1};
|
||||
}
|
||||
|
||||
function makeStore() {
|
||||
const state = loadState();
|
||||
const store = new owl.store.Store({ state, actions });
|
||||
store.on("update", null, () => saveState(store.state));
|
||||
return store;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// TodoItem
|
||||
//------------------------------------------------------------------------------
|
||||
class TodoItem extends owl.Component {
|
||||
state = { isEditing: false };
|
||||
class TodoItem extends Component {
|
||||
state = useState({ isEditing: false });
|
||||
dispatch = useDispatch();
|
||||
|
||||
removeTodo() {
|
||||
this.env.store.dispatch("removeTodo", this.props.id);
|
||||
}
|
||||
|
||||
toggleTodo() {
|
||||
this.env.store.dispatch("toggleTodo", this.props.id);
|
||||
}
|
||||
|
||||
async editTodo() {
|
||||
this.state.isEditing = true;
|
||||
}
|
||||
|
||||
focusInput() {
|
||||
this.refs.input.value = "";
|
||||
this.refs.input.focus();
|
||||
this.refs.input.value = this.props.title;
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
useAutofocus("input");
|
||||
}
|
||||
|
||||
handleKeyup(ev) {
|
||||
@@ -371,48 +481,33 @@ class TodoItem extends owl.Component {
|
||||
}
|
||||
|
||||
updateTitle(title) {
|
||||
const value = title.trim();
|
||||
if (!value) {
|
||||
this.removeTodo(this.props.id);
|
||||
} else {
|
||||
this.env.store.dispatch("editTodo", {
|
||||
id: this.props.id,
|
||||
title: value
|
||||
});
|
||||
this.state.isEditing = false;
|
||||
}
|
||||
this.dispatch("updateTodo", {title, id: this.props.id});
|
||||
this.state.isEditing = false;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// TodoApp
|
||||
//------------------------------------------------------------------------------
|
||||
class TodoApp extends owl.store.ConnectedComponent {
|
||||
components = { TodoItem };
|
||||
state = { filter: "all" };
|
||||
class TodoApp extends Component {
|
||||
state = useState({ filter: "all" });
|
||||
todos = useStore(state => state.todos);
|
||||
dispatch = useDispatch();
|
||||
|
||||
static mapStoreToProps(state) {
|
||||
return {
|
||||
todos: state.todos
|
||||
};
|
||||
}
|
||||
get visibleTodos() {
|
||||
let todos = this.storeProps.todos;
|
||||
if (this.state.filter === "active") {
|
||||
todos = todos.filter(t => !t.completed);
|
||||
switch (this.state.filter) {
|
||||
case "active": return this.todos.filter(t => !t.completed);
|
||||
case "completed": return this.todos.filter(t => t.completed);
|
||||
case "all": return this.todos;
|
||||
}
|
||||
if (this.state.filter === "completed") {
|
||||
todos = todos.filter(t => t.completed);
|
||||
}
|
||||
return todos;
|
||||
}
|
||||
|
||||
get allChecked() {
|
||||
return this.storeProps.todos.every(todo => todo.completed);
|
||||
return this.todos.every(todo => todo.completed);
|
||||
}
|
||||
|
||||
get remaining() {
|
||||
return this.storeProps.todos.filter(todo => !todo.completed).length;
|
||||
return this.todos.filter(todo => !todo.completed).length;
|
||||
}
|
||||
|
||||
get remainingText() {
|
||||
@@ -434,16 +529,30 @@ class TodoApp extends owl.store.ConnectedComponent {
|
||||
this.state.filter = filter;
|
||||
}
|
||||
}
|
||||
TodoApp.components = { TodoItem };
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// App Initialization
|
||||
//------------------------------------------------------------------------------
|
||||
const store = makeStore();
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const env = {
|
||||
qweb,
|
||||
store,
|
||||
};
|
||||
function saveState(state) {
|
||||
const str = JSON.stringify(state);
|
||||
window.localStorage.setItem(LOCALSTORAGE_KEY, str);
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
const localState = window.localStorage.getItem(LOCALSTORAGE_KEY);
|
||||
return localState ? JSON.parse(localState) : initialState;
|
||||
}
|
||||
|
||||
function makeEnv() {
|
||||
const state = loadState();
|
||||
const store = new owl.Store({ state, actions });
|
||||
store.on("update", null, () => saveState(store.state));
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
return { qweb, store };
|
||||
}
|
||||
|
||||
const env = makeEnv();
|
||||
const app = new TodoApp(env);
|
||||
app.mount(document.body);
|
||||
`;
|
||||
@@ -454,7 +563,7 @@ const TODO_APP_STORE_XML = `<templates>
|
||||
<h1>todos</h1>
|
||||
<input class="new-todo" autofocus="true" autocomplete="off" placeholder="What needs to be done?" t-on-keyup="addTodo"/>
|
||||
</header>
|
||||
<section class="main" t-if="storeProps.todos.length">
|
||||
<section class="main" t-if="todos.length">
|
||||
<input class="toggle-all" id="toggle-all" type="checkbox" t-att-checked="allChecked" t-on-click="dispatch('toggleAll', !allChecked)"/>
|
||||
<label for="toggle-all"></label>
|
||||
<ul class="todo-list">
|
||||
@@ -463,7 +572,7 @@ const TODO_APP_STORE_XML = `<templates>
|
||||
</t>
|
||||
</ul>
|
||||
</section>
|
||||
<footer class="footer" t-if="storeProps.todos.length">
|
||||
<footer class="footer" t-if="todos.length">
|
||||
<span class="todo-count">
|
||||
<strong>
|
||||
<t t-esc="remaining"/>
|
||||
@@ -481,7 +590,7 @@ const TODO_APP_STORE_XML = `<templates>
|
||||
<a t-on-click="setFilter('completed')" t-att-class="{selected: state.filter === 'completed'}">Completed</a>
|
||||
</li>
|
||||
</ul>
|
||||
<button class="clear-completed" t-if="storeProps.todos.length gt remaining" t-on-click="dispatch('clearCompleted')">
|
||||
<button class="clear-completed" t-if="todos.length gt remaining" t-on-click="dispatch('clearCompleted')">
|
||||
Clear completed
|
||||
</button>
|
||||
</footer>
|
||||
@@ -489,13 +598,13 @@ const TODO_APP_STORE_XML = `<templates>
|
||||
|
||||
<li t-name="TodoItem" class="todo" t-att-class="{completed: props.completed, editing: state.isEditing}">
|
||||
<div class="view">
|
||||
<input class="toggle" type="checkbox" t-on-change="toggleTodo" t-att-checked="props.completed"/>
|
||||
<label t-on-dblclick="editTodo">
|
||||
<input class="toggle" type="checkbox" t-on-change="dispatch('toggleTodo', props.id)" t-att-checked="props.completed"/>
|
||||
<label t-on-dblclick="state.isEditing = true">
|
||||
<t t-esc="props.title"/>
|
||||
</label>
|
||||
<button class="destroy" t-on-click="removeTodo"></button>
|
||||
<button class="destroy" t-on-click="dispatch('removeTodo', props.id)"></button>
|
||||
</div>
|
||||
<input class="edit" t-ref="input" t-if="state.isEditing" t-att-value="props.title" t-on-keyup="handleKeyup" t-mounted="focusInput" t-on-blur="handleBlur"/>
|
||||
<input class="edit" t-ref="input" t-if="state.isEditing" t-att-value="props.title" t-on-keyup="handleKeyup" t-on-blur="handleBlur"/>
|
||||
</li>
|
||||
</templates>`;
|
||||
|
||||
@@ -896,26 +1005,22 @@ const RESPONSIVE = `// In this example, we show how we can modify keys in the gl
|
||||
//------------------------------------------------------------------------------
|
||||
class Navbar extends owl.Component {}
|
||||
|
||||
class ControlPanel extends owl.Component {
|
||||
components = { MobileSearchView };
|
||||
}
|
||||
class MobileSearchView extends owl.Component {}
|
||||
|
||||
class FormView extends owl.Component {
|
||||
components = { AdvancedComponent };
|
||||
}
|
||||
class ControlPanel extends owl.Component {}
|
||||
ControlPanel.components = { MobileSearchView };
|
||||
|
||||
class AdvancedComponent extends owl.Component {}
|
||||
|
||||
class FormView extends owl.Component {}
|
||||
FormView.components = { AdvancedComponent };
|
||||
|
||||
class Chatter extends owl.Component {
|
||||
messages = Array.from(Array(100).keys());
|
||||
}
|
||||
|
||||
class MobileSearchView extends owl.Component {}
|
||||
|
||||
|
||||
class App extends owl.Component {
|
||||
components = { Navbar, ControlPanel, FormView, Chatter };
|
||||
}
|
||||
class App extends owl.Component {}
|
||||
App.components = { Navbar, ControlPanel, FormView, Chatter };
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Responsive plugin
|
||||
@@ -1053,17 +1158,18 @@ const SLOTS = `// We show here how slots can be used to create generic component
|
||||
//
|
||||
// Note that the t-on-click event, defined in the App template, is executed in
|
||||
// the context of the App component, even though it is inside the Card component
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Card extends owl.Component {
|
||||
state = { showContent: true };
|
||||
class Card extends Component {
|
||||
state = useState({ showContent: true });
|
||||
|
||||
toggleDisplay() {
|
||||
this.state.showContent = !this.state.showContent;
|
||||
}
|
||||
}
|
||||
|
||||
class Counter extends owl.Component {
|
||||
state = {val: 1};
|
||||
class Counter extends Component {
|
||||
state = useState({val: 1});
|
||||
|
||||
inc() {
|
||||
this.state.val++;
|
||||
@@ -1071,14 +1177,14 @@ class Counter extends owl.Component {
|
||||
}
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
components = {Card, Counter};
|
||||
state = {a: 1, b: 3};
|
||||
class App extends Component {
|
||||
state = useState({a: 1, b: 3});
|
||||
|
||||
inc(key, delta) {
|
||||
this.state[key] += delta;
|
||||
}
|
||||
}
|
||||
App.components = {Card, Counter};
|
||||
|
||||
// Application setup
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
@@ -1167,12 +1273,23 @@ const ASYNC_COMPONENTS = `// This example will not work if your browser does not
|
||||
|
||||
// In this example, we have 2 sub components, one of them being async (slow).
|
||||
// However, we don't want renderings of the other sub component to be delayed
|
||||
// because of the slow component. We use the 't-asyncroot' directive for this
|
||||
// because of the slow component. We use the AsyncRoot component for this
|
||||
// purpose. Try removing it to see the difference.
|
||||
const { Component, useState } = owl;
|
||||
const { AsyncRoot } = owl.misc;
|
||||
|
||||
class App extends owl.Component {
|
||||
components = {SlowComponent, NotificationList};
|
||||
state = { value: 0, notifs: [] };
|
||||
class SlowComponent extends Component {
|
||||
willUpdateProps() {
|
||||
// simulate a component that needs to perform async stuff (e.g. an RPC)
|
||||
// with the updated props before re-rendering itself
|
||||
return new Promise(resolve => setTimeout(resolve, 1500));
|
||||
}
|
||||
}
|
||||
|
||||
class NotificationList extends Component {}
|
||||
|
||||
class App extends Component {
|
||||
state = useState({ value: 0, notifs: [] });
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
@@ -1184,16 +1301,7 @@ class App extends owl.Component {
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
class SlowComponent extends owl.Component {
|
||||
willUpdateProps() {
|
||||
// simulate a component that needs to perform async stuff (e.g. an RPC)
|
||||
// with the updated props before re-rendering itself
|
||||
return new Promise(resolve => setTimeout(resolve, 1500));
|
||||
}
|
||||
}
|
||||
|
||||
class NotificationList extends owl.Component {}
|
||||
App.components = {SlowComponent, NotificationList};
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const app = new App({ qweb });
|
||||
@@ -1204,9 +1312,10 @@ const ASYNC_COMPONENTS_XML = `<templates>
|
||||
<div t-name="App" class="app">
|
||||
<button t-on-click="increment">Increment</button>
|
||||
<SlowComponent value="state.value"/>
|
||||
<NotificationList t-asyncroot="1" notifications="state.notifs"/>
|
||||
<AsyncRoot>
|
||||
<NotificationList notifications="state.notifs"/>
|
||||
</AsyncRoot>
|
||||
</div>
|
||||
|
||||
<div t-name="SlowComponent" class="value" >
|
||||
Current value: <t t-esc="props.value"/>
|
||||
</div>
|
||||
@@ -1251,15 +1360,16 @@ const FORM = `// This example illustrate how the t-model directive can be used t
|
||||
// data between html inputs (and select/textareas) and the state of a component.
|
||||
// Note that there are two controls with t-model="color": they are totally
|
||||
// synchronized.
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Form extends owl.Component {
|
||||
state = {
|
||||
class Form extends Component {
|
||||
state = useState({
|
||||
text: "",
|
||||
othertext: "",
|
||||
number: 11,
|
||||
color: "",
|
||||
bool: false
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// Application setup
|
||||
@@ -1272,20 +1382,20 @@ const FORM_XML = `<templates>
|
||||
<div t-name="Form">
|
||||
<h1>Form</h1>
|
||||
<div>
|
||||
Text (immediate): <input t-model="text"/>
|
||||
Text (immediate): <input t-model="state.text"/>
|
||||
</div>
|
||||
<div>
|
||||
Other text (lazy): <input t-model.lazy="othertext"/>
|
||||
Other text (lazy): <input t-model.lazy="state.othertext"/>
|
||||
</div>
|
||||
<div>
|
||||
Number: <input t-model.number="number"/>
|
||||
Number: <input t-model.number="state.number"/>
|
||||
</div>
|
||||
<div>
|
||||
Boolean: <input type="checkbox" t-model="bool"/>
|
||||
Boolean: <input type="checkbox" t-model="state.bool"/>
|
||||
</div>
|
||||
<div>
|
||||
Color, with a select:
|
||||
<select t-model="color">
|
||||
<select t-model="state.color">
|
||||
<option value="">Select a color</option>
|
||||
<option value="red">Red</option>
|
||||
<option value="blue">Blue</option>
|
||||
@@ -1293,8 +1403,8 @@ const FORM_XML = `<templates>
|
||||
</div>
|
||||
<div>
|
||||
Color, with radio buttons:
|
||||
<span><input type="radio" name="color" id="red" value="red" t-model="color"/><label for="red">Red</label></span>
|
||||
<span><input type="radio" name="color" id="blue" value="blue" t-model="color"/><label for="blue">Blue</label></span>
|
||||
<span><input type="radio" name="color" id="red" value="red" t-model="state.color"/><label for="red">Red</label></span>
|
||||
<span><input type="radio" name="color" id="blue" value="blue" t-model="state.color"/><label for="blue">Blue</label></span>
|
||||
</div>
|
||||
<hr/>
|
||||
<h1>State</h1>
|
||||
@@ -1317,26 +1427,31 @@ const WMS = `// This example is slightly more complex than usual. We demonstrate
|
||||
// - minimal width/height
|
||||
// - better heuristic for initial window position
|
||||
// - ...
|
||||
const { Component, useState } = owl;
|
||||
const { useRef } = owl.hooks;
|
||||
|
||||
class HelloWorld extends owl.Component {}
|
||||
class HelloWorld extends Component {}
|
||||
|
||||
class Counter extends owl.Component {
|
||||
state = { value: 0 };
|
||||
class Counter extends Component {
|
||||
state = useState({ value: 0 });
|
||||
|
||||
inc() {
|
||||
this.state.value++;
|
||||
}
|
||||
}
|
||||
|
||||
class Window extends owl.Component {
|
||||
class Window extends Component {
|
||||
|
||||
get style() {
|
||||
let { width, height, top, left, zindex } = this.props.info;
|
||||
|
||||
return \`width: \${width}px;height: \${height}px;top:\${top}px;left:\${left}px;z-index:\${zindex}\`;
|
||||
}
|
||||
|
||||
close() {
|
||||
this.trigger("close-window", { id: this.props.info.id });
|
||||
}
|
||||
|
||||
startDragAndDrop(ev) {
|
||||
this.updateZIndex();
|
||||
this.el.classList.add('dragging');
|
||||
@@ -1362,44 +1477,51 @@ class Window extends owl.Component {
|
||||
self.trigger("set-window-position", options);
|
||||
}
|
||||
}
|
||||
|
||||
updateZIndex() {
|
||||
this.trigger("update-z-index", { id: this.props.info.id });
|
||||
}
|
||||
}
|
||||
|
||||
class WindowManager extends owl.Component {
|
||||
components = { Window };
|
||||
class WindowManager extends Component {
|
||||
windows = [];
|
||||
nextId = 1;
|
||||
currentZindex = 1;
|
||||
nextLeft = 0;
|
||||
nextTop = 0;
|
||||
|
||||
addWindow(name) {
|
||||
const info = this.env.windows.find(w => w.name === name);
|
||||
const id = \`w\${this.nextId++}\`;
|
||||
this.nextLeft = this.nextLeft + 30;
|
||||
this.nextTop = this.nextTop + 30;
|
||||
this.windows.push({
|
||||
id: id,
|
||||
id: this.nextId++,
|
||||
title: info.title,
|
||||
width: info.defaultWidth,
|
||||
height: info.defaultHeight,
|
||||
top: 0,
|
||||
left: 0,
|
||||
zindex: this.currentZindex++
|
||||
top: this.nextTop,
|
||||
left: this.nextLeft,
|
||||
zindex: this.currentZindex++,
|
||||
component: info.component
|
||||
});
|
||||
this.components[id] = info.component;
|
||||
this.render();
|
||||
}
|
||||
|
||||
closeWindow(ev) {
|
||||
const id = ev.detail.id;
|
||||
delete this.components[id];
|
||||
delete this.constructor.components[id];
|
||||
const index = this.windows.findIndex(w => w.id === id);
|
||||
this.windows.splice(index, 1);
|
||||
this.render();
|
||||
}
|
||||
|
||||
setWindowPosition(ev) {
|
||||
const id = ev.detail.id;
|
||||
const w = this.windows.find(w => w.id === id);
|
||||
w.top = ev.detail.top;
|
||||
w.left = ev.detail.left;
|
||||
}
|
||||
|
||||
updateZIndex(ev) {
|
||||
const id = ev.detail.id;
|
||||
const w = this.windows.find(w => w.id === id);
|
||||
@@ -1407,14 +1529,16 @@ class WindowManager extends owl.Component {
|
||||
ev.target.style["z-index"] = w.zindex;
|
||||
}
|
||||
}
|
||||
WindowManager.components = { Window };
|
||||
|
||||
class App extends owl.Component {
|
||||
components = { WindowManager };
|
||||
class App extends Component {
|
||||
wmRef = useRef("wm");
|
||||
|
||||
addWindow(name) {
|
||||
this.refs.wm.addWindow(name);
|
||||
this.wmRef.comp.addWindow(name);
|
||||
}
|
||||
}
|
||||
App.components = { WindowManager };
|
||||
|
||||
const qweb = new owl.QWeb(TEMPLATES);
|
||||
const windows = [
|
||||
@@ -1453,7 +1577,7 @@ const WMS_XML = `<templates>
|
||||
t-on-update-z-index="updateZIndex"
|
||||
t-on-set-window-position="setWindowPosition">
|
||||
<Window t-foreach="windows" t-as="w" t-key="w.id" info="w">
|
||||
<t t-component="{{w.id}}"/>
|
||||
<t t-component="w.component"/>
|
||||
</Window>
|
||||
</div>
|
||||
|
||||
@@ -1571,6 +1695,17 @@ export const SAMPLES = [
|
||||
xml: LIFECYCLE_DEMO_XML,
|
||||
css: LIFECYCLE_CSS
|
||||
},
|
||||
{
|
||||
description: "Hooks",
|
||||
code: HOOKS_DEMO,
|
||||
xml: HOOKS_DEMO_XML,
|
||||
css: HOOKS_CSS
|
||||
},
|
||||
{
|
||||
description: "Context",
|
||||
code: CONTEXT_JS,
|
||||
xml: CONTEXT_XML,
|
||||
},
|
||||
{
|
||||
description: "Todo List App (with store)",
|
||||
code: TODO_APP_STORE,
|
||||
|
||||
@@ -45,7 +45,11 @@
|
||||
<div>🦉 Odoo Web Library 🦉</div>
|
||||
<div>v<t t-esc="version"/></div>
|
||||
<div class="url"><a href="https://github.com/odoo/owl">https://github.com/odoo/owl</a></div>
|
||||
<div class="note">Note: these examples require a recent browser to work without a transpilation step. </div>
|
||||
<div class="note">
|
||||
<p>Note: these examples are using recent features of Javascript, and require a recent browser to work without a transpilation step!
|
||||
For example, it makes use of class fields and class static fields. These examples should work in a recent Chrome version.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div t-if="state.error" class="error">
|
||||
<h3>Error</h3>
|
||||
|
||||
Reference in New Issue
Block a user