mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bd3c1265d3 | |||
| 2413c98f50 | |||
| d74b5a03db | |||
| 83532db48f | |||
| 534152eff7 | |||
| 05a678c039 | |||
| 8fbf2172c5 | |||
| ea1376d0ca | |||
| ba483b6e2c | |||
| 2fc71cfb62 | |||
| 08cb83149e | |||
| 7d249d6f09 | |||
| 0addca63a0 | |||
| 5ba73cc09d | |||
| 9106c19066 | |||
| 9f93da4765 | |||
| 9e37b968e8 | |||
| fa6801b523 | |||
| 9edf29a3a1 | |||
| 6a434310ee | |||
| e7967d0779 | |||
| b0e2ef82f7 | |||
| c9c2b3fa6d | |||
| 62608cbb0d | |||
| 3035a9f009 | |||
| c2adb429bd | |||
| da9dda5eca | |||
| 5614c85b04 | |||
| 5d57a7bf13 | |||
| 4ebe419c56 | |||
| 9779cd196c | |||
| 9cee12d7b4 | |||
| 2c563ee380 | |||
| 2aa705f5c8 | |||
| 5911c8e3f6 | |||
| 2279dafbec | |||
| f07ec21a07 | |||
| b5b6b7342e | |||
| 97b914b9cd | |||
| 9dfcfda365 | |||
| e026f537ae |
@@ -28,20 +28,16 @@ Owl is currently mostly stable. Possible future changes are explained in the
|
|||||||
Here is a short example to illustrate interactive components:
|
Here is a short example to illustrate interactive components:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
import { Component, QWeb, useState } from "owl";
|
const { Component, useState } = owl;
|
||||||
import { xml } from "owl/tags";
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
class Counter extends Component {
|
class Counter extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<button t-on-click="increment">
|
<button t-on-click="state.value++">
|
||||||
Click Me! [<t t-esc="state.value"/>]
|
Click Me! [<t t-esc="state.value"/>]
|
||||||
</button>`;
|
</button>`;
|
||||||
|
|
||||||
state = useState({ value: 0 });
|
state = useState({ value: 0 });
|
||||||
|
|
||||||
increment() {
|
|
||||||
this.state.value++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class App extends Component {
|
class App extends Component {
|
||||||
@@ -54,12 +50,12 @@ class App extends Component {
|
|||||||
static components = { Counter };
|
static components = { Counter };
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App({ qweb: new QWeb() });
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the counter component is made reactive with the [`useState`](doc/hooks.md#usestate)
|
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
|
||||||
hook. Also, all examples here uses the `xml` helper to define inline templates.
|
Also, all examples here uses the [`xml` helper](doc/reference/tags.md#xml-tag) to define inline templates.
|
||||||
But this is not mandatory, many applications will load templates separately.
|
But this is not mandatory, many applications will load templates separately.
|
||||||
|
|
||||||
More interesting examples can be found on the
|
More interesting examples can be found on the
|
||||||
@@ -96,9 +92,9 @@ A complete documentation for Owl can be found here:
|
|||||||
|
|
||||||
The most important sections are:
|
The most important sections are:
|
||||||
|
|
||||||
- [Quick Start](doc/quick_start.md)
|
- [Quick Start](doc/learning/quick_start.md)
|
||||||
- [Component](doc/component.md)
|
- [Component](doc/reference/component.md)
|
||||||
- [Hooks](doc/hooks.md)
|
- [Hooks](doc/reference/hooks.md)
|
||||||
|
|
||||||
Found an issue in the documentation? A broken link? Some outdated information?
|
Found an issue in the documentation? A broken link? Some outdated information?
|
||||||
Submit a PR!
|
Submit a PR!
|
||||||
@@ -107,8 +103,8 @@ Submit a PR!
|
|||||||
|
|
||||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||||
|
|
||||||
- [owl-0.24.0.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.js)
|
- [owl-1.0.0-alpha2.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha2/owl.js)
|
||||||
- [owl-0.24.0.min.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.min.js)
|
- [owl-1.0.0-alpha2.min.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha2/owl.min.js)
|
||||||
|
|
||||||
Some npm scripts are available:
|
Some npm scripts are available:
|
||||||
|
|
||||||
@@ -131,23 +127,6 @@ Owl components in an application are used to define a (dynamic) tree of componen
|
|||||||
C D
|
C D
|
||||||
```
|
```
|
||||||
|
|
||||||
**Environment:** the root component is special: it is created with an environment,
|
|
||||||
which should contain a `QWeb` instance. The environment is then automatically
|
|
||||||
propagated to each sub components (and accessible in the `this.env` property).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const env = { qweb: new QWeb() };
|
|
||||||
const app = new App(env);
|
|
||||||
app.mount(document.body);
|
|
||||||
```
|
|
||||||
|
|
||||||
The environment is mostly static. Each application is free to add anything to
|
|
||||||
the environment, which is very useful, since this can be accessed by each sub
|
|
||||||
component. Some good use case for that is some configuration keys, session
|
|
||||||
information or generic services (such as doing rpcs, or accessing local storage).
|
|
||||||
Doing it this way means that components are easily testable: we can simply
|
|
||||||
create a test environment with mock services.
|
|
||||||
|
|
||||||
**State:** each component can manage its own local state. It is a simple ES6
|
**State:** each component can manage its own local state. It is a simple ES6
|
||||||
class, there are no special rules:
|
class, there are no special rules:
|
||||||
|
|
||||||
@@ -259,7 +238,7 @@ class Parent extends Component {
|
|||||||
In this example, the `OrderLine` component trigger a `add-to-order` event. This
|
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
|
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
|
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)
|
`detail` key) and then increment its quantity. See the section on [event handling](doc/reference/component.md#event-handling)
|
||||||
for more details on how events work.
|
for more details on how events work.
|
||||||
|
|
||||||
Note that this example would have also worked if the `OrderLine` component
|
Note that this example would have also worked if the `OrderLine` component
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 🦉 Rendering Pipeline 🦉
|
||||||
|
|
||||||
|
We explain here how Owl is designed, from the perspective of its rendering
|
||||||
|
pipeline.
|
||||||
|
|
||||||
|
Warning: these notes are technical by nature, and intended for people working
|
||||||
|
on Owl (or interested in understanding its design).
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
A rendering occurs in two phases:
|
||||||
|
|
||||||
|
- virtual rendering: this generates the virtual dom in memory, asynchronously
|
||||||
|
- patch: applies a virtual tree to the screen (synchronously)
|
||||||
|
|
||||||
|
There are several classes involved in a rendering:
|
||||||
|
|
||||||
|
- components
|
||||||
|
- a scheduler
|
||||||
|
- fibers: small objects containing some metadata, associated with a rendering of
|
||||||
|
a specific component
|
||||||
|
|
||||||
|
Components are organized in a dynamic component tree, visible in the user
|
||||||
|
interface. Whenever a rendering is initiated in a component `C`:
|
||||||
|
|
||||||
|
- a fiber is created on `C` with the rendering props information
|
||||||
|
- the virtual rendering phase starts on C (will asynchronously render all the
|
||||||
|
child components)
|
||||||
|
- the fiber is added to the scheduler, which will poll continuously, every
|
||||||
|
animation frame, if the fiber is done
|
||||||
|
- once it is done, the scheduler will call the task callback, which will apply
|
||||||
|
the patch (if it was not cancelled in the meantime).
|
||||||
+6
-5
@@ -79,7 +79,7 @@ additional tools, we made a lot of effort to make the most of the web platform.
|
|||||||
|
|
||||||
For example, Owl uses the standard `xml` parser that comes with every browser.
|
For example, Owl uses the standard `xml` parser that comes with every browser.
|
||||||
Because of that, Owl did not have to write its own template parser. Another
|
Because of that, Owl did not have to write its own template parser. Another
|
||||||
example is the [`xml`](tags.md#xml-tag) tag helper function, which makes use of
|
example is the [`xml`](reference/tags.md#xml-tag) tag helper function, which makes use of
|
||||||
native template literals to allow in a natural way to write `xml` templates
|
native template literals to allow in a natural way to write `xml` templates
|
||||||
directly in the javascript code. This can be easily integrated with editor
|
directly in the javascript code. This can be easily integrated with editor
|
||||||
plugins to have autocompletion inside the template.
|
plugins to have autocompletion inside the template.
|
||||||
@@ -127,7 +127,7 @@ structured than a template language. Note that the tooling is quite impressive:
|
|||||||
there is a syntax highlighter for jsx here on github!
|
there is a syntax highlighter for jsx here on github!
|
||||||
|
|
||||||
By comparison, here is the equivalent Owl component, written with the
|
By comparison, here is the equivalent Owl component, written with the
|
||||||
[`xml`](tags.md#xml-tag) tag helper:
|
[`xml`](reference/tags.md#xml-tag) tag helper:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
class Clock extends Component {
|
class Clock extends Component {
|
||||||
@@ -251,7 +251,7 @@ keeps track of who get data, and retrigger a render when it was changed.
|
|||||||
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
|
||||||
mutations), and like VueX, it keeps track of the state changes. However, it does
|
mutations), and like VueX, it keeps track of the state changes. However, it does
|
||||||
not notify a component when the state changes. Instead, components need to connect
|
not notify a component when the state changes. Instead, components need to connect
|
||||||
to the store like in redux, with the `useStore` hook (see the [store documentation](store.md#connecting-a-component)).
|
to the store like in redux, with the `useStore` hook (see the [store documentation](reference/store.md#connecting-a-component)).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const actions = {
|
const actions = {
|
||||||
@@ -274,7 +274,8 @@ class Counter extends Component {
|
|||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
const counter = new Counter({ store, qweb });
|
Counter.env.store = store;
|
||||||
|
const counter = new Counter();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Hooks
|
## Hooks
|
||||||
@@ -314,7 +315,7 @@ This work is based on the new ideas introduced by React hooks.
|
|||||||
|
|
||||||
From the way React and Vue introduce their hooks, it may look like hooks are not
|
From the way React and Vue introduce their hooks, it may look like hooks are not
|
||||||
compatible with class components. However, this is not the case, as shown by
|
compatible with class components. However, this is not the case, as shown by
|
||||||
Owl [hooks](hooks.md). They are inspired by both React and Vue. For example,
|
Owl [hooks](reference/hooks.md). They are inspired by both React and Vue. For example,
|
||||||
the `useState` hook is named after React, but its API is closer to the `reactive`
|
the `useState` hook is named after React, but its API is closer to the `reactive`
|
||||||
Vue hook.
|
Vue hook.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# 🦉 Environment 🦉
|
||||||
|
|
||||||
|
An environment is an object which contains a [`QWeb` instance](../reference/qweb.md).
|
||||||
|
Whenever a root component is created, it is assigned an environment (see the
|
||||||
|
reference section on [environment](../reference/environment.md). This environment
|
||||||
|
is then automatically given to each sub components (and accessible in the `this.env` property).
|
||||||
|
|
||||||
|
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 cases for the environment is:
|
||||||
|
|
||||||
|
- some configuration keys,
|
||||||
|
- session information,
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
async function myEnv() {
|
||||||
|
const templates = await loadTemplates();
|
||||||
|
const qweb = new QWeb({ templates });
|
||||||
|
const session = getSession();
|
||||||
|
|
||||||
|
return {
|
||||||
|
_t: myTranslateFunction,
|
||||||
|
session: session,
|
||||||
|
qweb: qweb,
|
||||||
|
services: {
|
||||||
|
localStorage: localStorage,
|
||||||
|
rpc: rpc
|
||||||
|
},
|
||||||
|
debug: false,
|
||||||
|
inMobileMode: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
App.env = await myEnv();
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(document.body);
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -2,8 +2,17 @@
|
|||||||
|
|
||||||
## Static Server
|
## Static Server
|
||||||
|
|
||||||
Let us assume that we have a static server running somewhere. We could then
|
Let us assume that we have a static server running somewhere. Let us start by
|
||||||
simply add an html page with a few extra files.
|
adding an html page with a few extra files:
|
||||||
|
|
||||||
|
```
|
||||||
|
my-app/
|
||||||
|
index.html
|
||||||
|
app.css
|
||||||
|
app.js
|
||||||
|
owl-X.Y.Z.js
|
||||||
|
templates.xml
|
||||||
|
```
|
||||||
|
|
||||||
### HTML and CSS
|
### HTML and CSS
|
||||||
|
|
||||||
@@ -88,10 +97,8 @@ class ClickCounter extends owl.Component {
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
async function start() {
|
async function start() {
|
||||||
const templates = await owl.utils.loadFile("templates.xml");
|
const templates = await owl.utils.loadFile("templates.xml");
|
||||||
const env = {
|
ClickCounter.env = { qweb: new owl.QWeb({ templates }) };
|
||||||
qweb: new owl.QWeb(templates)
|
const counter = new ClickCounter();
|
||||||
};
|
|
||||||
const counter = new ClickCounter(env);
|
|
||||||
const target = document.getElementById("main");
|
const target = document.getElementById("main");
|
||||||
await counter.mount(target);
|
await counter.mount(target);
|
||||||
}
|
}
|
||||||
+59
-62
@@ -1,75 +1,72 @@
|
|||||||
# 🦉 OWL Documentation 🦉
|
# 🦉 OWL Documentation 🦉
|
||||||
|
|
||||||
## 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:
|
|
||||||
|
|
||||||
```
|
|
||||||
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
|
|
||||||
tags
|
|
||||||
xml
|
|
||||||
utils
|
|
||||||
debounce
|
|
||||||
escape
|
|
||||||
loadJS
|
|
||||||
loadFile
|
|
||||||
shallowEqual
|
|
||||||
whenReady
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
- [Animations](animations.md)
|
- [Animations](reference/animations.md)
|
||||||
- [Component](component.md)
|
- [Component](reference/component.md)
|
||||||
- [Context](context.md)
|
- [Configuration](reference/config.md)
|
||||||
- [Event Bus](event_bus.md)
|
- [Context](reference/context.md)
|
||||||
- [Hooks](hooks.md)
|
- [Environment](reference/environment.md)
|
||||||
- [Misc](misc.md)
|
- [Event Bus](reference/event_bus.md)
|
||||||
- [Observer](observer.md)
|
- [Hooks](reference/hooks.md)
|
||||||
- [QWeb](qweb.md)
|
- [Misc](reference/misc.md)
|
||||||
- [Router](router.md)
|
- [Observer](reference/observer.md)
|
||||||
- [Store](store.md)
|
- [QWeb](reference/qweb.md)
|
||||||
- [Tags](tags.md)
|
- [Router](reference/router.md)
|
||||||
- [Utils](utils.md)
|
- [Store](reference/store.md)
|
||||||
- [Virtual DOM](vdom.md)
|
- [Tags](reference/tags.md)
|
||||||
|
- [Utils](reference/utils.md)
|
||||||
|
|
||||||
## Learning Resources
|
## Learning Resources
|
||||||
|
|
||||||
- [Quick Start](quick_start.md)
|
- [Quick Start: create an (almost) empty Owl application](learning/quick_start.md)
|
||||||
|
- [Environment: what it is and what it should contain](learning/environment.md)
|
||||||
|
|
||||||
## Miscellaneous
|
## Miscellaneous
|
||||||
|
|
||||||
- [Comparison with React/Vue](comparison.md)
|
- [Comparison with React/Vue](comparison.md)
|
||||||
- [Tooling](tooling.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)
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
This section explains in more detail the inner workings of Owl. It is targeted
|
||||||
|
for developers working on Owl itself.
|
||||||
|
|
||||||
|
- [Virtual DOM](architecture/vdom.md)
|
||||||
|
- [Rendering](architecture/rendering.md)
|
||||||
|
|
||||||
|
## Owl Content
|
||||||
|
|
||||||
|
Here is a complete visual representation of everything exported by the `owl`
|
||||||
|
global object (so, for example, `Component` is available at `owl.Component`,
|
||||||
|
and `EventBus` is exported as `owl.core.EventBus`):
|
||||||
|
|
||||||
|
```
|
||||||
|
Component misc
|
||||||
|
Context AsyncRoot
|
||||||
|
QWeb router
|
||||||
|
Store Link
|
||||||
|
useState RouteComponent
|
||||||
|
config Router
|
||||||
|
mode tags
|
||||||
|
core xml
|
||||||
|
EventBus utils
|
||||||
|
Observer debounce
|
||||||
|
hooks escape
|
||||||
|
onWillStart loadJS
|
||||||
|
onMounted loadFile
|
||||||
|
onWillUpdateProps shallowEqual
|
||||||
|
onWillPatch whenReady
|
||||||
|
onPatched
|
||||||
|
onWillUnmount
|
||||||
|
useContext
|
||||||
|
useState
|
||||||
|
useRef
|
||||||
|
useSubEnv
|
||||||
|
useStore
|
||||||
|
useDispatch
|
||||||
|
useGetters
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
- [Methods](#methods)
|
- [Methods](#methods)
|
||||||
- [Lifecycle](#lifecycle)
|
- [Lifecycle](#lifecycle)
|
||||||
- [Root Component](#root-component)
|
- [Root Component](#root-component)
|
||||||
- [Environment](#environment)
|
|
||||||
- [Composition](#composition)
|
- [Composition](#composition)
|
||||||
- [Event Handling](#event-handling)
|
- [Event Handling](#event-handling)
|
||||||
- [Form Input Bindings](#form-input-bindings)
|
- [Form Input Bindings](#form-input-bindings)
|
||||||
@@ -81,8 +80,8 @@ a state object is defined, by using the `useState` hook. It is not mandatory to
|
|||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
An Owl component is a small class which represents a component or some UI element.
|
An Owl component is a small class which represents a component or some UI element.
|
||||||
It exists in the context of an environment (`env`), which is propagated from a
|
It exists in the context of an [environment](environment.md) (`env`), which is propagated from a
|
||||||
parent to its children. The environment needs to have a QWeb instance, which
|
parent to its children. The environment needs to have a [QWeb](qweb.md) instance, which
|
||||||
will be used to render the component template.
|
will be used to render the component template.
|
||||||
|
|
||||||
Be aware that the name of the component may be significant: if a component does
|
Be aware that the name of the component may be significant: if a component does
|
||||||
@@ -370,8 +369,8 @@ will slightly slow down the component.
|
|||||||
#### `willUpdateProps(nextProps)`
|
#### `willUpdateProps(nextProps)`
|
||||||
|
|
||||||
The willUpdateProps is an asynchronous hook, called just before new props
|
The willUpdateProps is an asynchronous hook, called just before new props
|
||||||
are set. This is useful if the component needs some asynchronous task
|
are set. This is useful if the component needs to perform an asynchronous task,
|
||||||
performed, depending on the props (for example, assuming that the props are
|
depending on the props (for example, assuming that the props are
|
||||||
some record Id, fetching the record data).
|
some record Id, fetching the record data).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
@@ -386,14 +385,13 @@ and performs a similar job).
|
|||||||
#### `willPatch()`
|
#### `willPatch()`
|
||||||
|
|
||||||
The willPatch hook is called just before the DOM patching process starts.
|
The willPatch hook is called just before the DOM patching process starts.
|
||||||
It is not called on the initial render. This is useful to read some
|
It is not called on the initial render. This is useful to read
|
||||||
information from the DOM. For example, the current position of the
|
information from the DOM. For example, the current position of the
|
||||||
scrollbar.
|
scrollbar.
|
||||||
|
|
||||||
Note that modifying the state is not allowed here. This method is called just
|
Note that modifying the state is not allowed here. This method is called just
|
||||||
before an actual DOM patch, and is only intended to be used to save some local
|
before an actual DOM patch, and is only intended to be used to save some local
|
||||||
DOM state. Also, it will not be called if the component is not in the DOM (this can
|
DOM state. Also, it will not be called if the component is not in the DOM.
|
||||||
happen with components with `t-keepalive`).
|
|
||||||
|
|
||||||
#### `patched(snapshot)`
|
#### `patched(snapshot)`
|
||||||
|
|
||||||
@@ -403,7 +401,7 @@ likely via a change in its state/props or environment).
|
|||||||
This method is not called on the initial render. It is useful to interact
|
This method is not called on the initial render. It is useful to interact
|
||||||
with the DOM (for example, through an external library) whenever the
|
with the DOM (for example, through an external library) whenever the
|
||||||
component was patched. Note that this hook will not be called if the compoent is
|
component was patched. Note that this hook will not be called if the compoent is
|
||||||
not in the DOM (this can happen with components with `t-keepalive`).
|
not in the DOM.
|
||||||
|
|
||||||
Updating the component state in this hook is possible, but not encouraged.
|
Updating the component state in this hook is possible, but not encouraged.
|
||||||
One needs to be careful, because updates here will create an additional rendering, which in
|
One needs to be careful, because updates here will create an additional rendering, which in
|
||||||
@@ -413,7 +411,7 @@ careful at avoiding endless cycles.
|
|||||||
#### `willUnmount()`
|
#### `willUnmount()`
|
||||||
|
|
||||||
willUnmount is a hook that is called each time just before a component is unmounted from
|
willUnmount is a hook that is called each time just before a component is unmounted from
|
||||||
the DOM. This is a good place to remove some listeners, for example.
|
the DOM. This is a good place to remove listeners, for example.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -441,49 +439,17 @@ of an Owl application has to be created manually:
|
|||||||
```js
|
```js
|
||||||
class App extends owl.Component { ... }
|
class App extends owl.Component { ... }
|
||||||
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const env = { qweb: qweb };
|
|
||||||
const app = new App(env);
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
```
|
```
|
||||||
|
|
||||||
The root component needs an environment.
|
The root component does not have a parent nor `props` (see note below). It will be setup with an
|
||||||
|
[environment](environment.md) (either the `env` defined on its class, or a
|
||||||
|
default empty environment).
|
||||||
|
|
||||||
### Environment
|
Note: a root component can however be given a `props` object in its constructor,
|
||||||
|
like this: `new App(null, {some: 'object'});`. It will not be a true `props`
|
||||||
In Owl, an environment is an object with a `qweb` key, which has to be a
|
object, managed by Owl (so, for example, it will never be updated).
|
||||||
[QWeb](qweb.md) instance. This qweb instance will be used to render everything.
|
|
||||||
|
|
||||||
The environment is meant to contain (mostly) static global information and
|
|
||||||
methods for the whole application. For example, settings keys (`mode` to determine
|
|
||||||
if we are in desktop or mobile mode, or `theme`: dark or light), `rpc` methods,
|
|
||||||
session information, ...
|
|
||||||
|
|
||||||
The environment will be given to each child, unchanged, in the `env` property.
|
|
||||||
This can be very useful to share common information/methods. For example, all
|
|
||||||
rpcs can be made through a `rpc` method in the environment. This makes it very
|
|
||||||
easy to test a component.
|
|
||||||
|
|
||||||
Updating the environment is not as simple as changing a component's state: its
|
|
||||||
content is not observed, so updates will not be reflected immediately in the
|
|
||||||
user interface. There is however a mechanism to force root widgets to rerender
|
|
||||||
themselves whenever the environment is modified: one only needs to call the
|
|
||||||
`forceUpdate` method on the QWeb instance. For example, a responsive environment
|
|
||||||
could be done like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
function setupResponsivePlugin(env) {
|
|
||||||
const isMobile = () => window.innerWidth <= 768;
|
|
||||||
env.isMobile = isMobile();
|
|
||||||
const updateEnv = owl.utils.debounce(() => {
|
|
||||||
if (env.isMobile !== isMobile()) {
|
|
||||||
env.isMobile = !env.isMobile;
|
|
||||||
env.qweb.forceUpdate();
|
|
||||||
}
|
|
||||||
}, 15);
|
|
||||||
window.addEventListener("resize", updateEnv);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Composition
|
### Composition
|
||||||
|
|
||||||
@@ -539,7 +505,7 @@ constructor. This will be assigned to the `props` variable, which can be accesse
|
|||||||
on the component (and also, in the template). Whenever the state is updated, then
|
on the component (and also, in the template). Whenever the state is updated, then
|
||||||
the sub component will also be updated automatically.
|
the sub component will also be updated automatically.
|
||||||
|
|
||||||
Note that there are some restrictions on prop names: `class`, `style` and any
|
Note that there are restrictions on valid prop names: `class`, `style` and any
|
||||||
string which starts with `t-` are not allowed.
|
string which starts with `t-` are not allowed.
|
||||||
|
|
||||||
It is not common, but sometimes we need a dynamic component name and/or dynamic props. In this case,
|
It is not common, but sometimes we need a dynamic component name and/or dynamic props. In this case,
|
||||||
@@ -598,7 +564,7 @@ class App extends Component<any, any, any> {
|
|||||||
In this example, the component `App` selects dynamically the concrete sub
|
In this example, the component `App` selects dynamically the concrete sub
|
||||||
component class.
|
component class.
|
||||||
|
|
||||||
**CSS and style:** there is some specific support to allow the parent to declare
|
**CSS and style:** Owl allows the parent to declare
|
||||||
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||||
root component element.
|
root component element.
|
||||||
|
|
||||||
@@ -611,7 +577,7 @@ root component element.
|
|||||||
Warning: there is a small caveat with dynamic class attributes: since Owl needs
|
Warning: there is a small caveat with dynamic class attributes: since Owl needs
|
||||||
to be able to add/remove proper classes whenever necessary, it needs to be aware
|
to be able to add/remove proper classes whenever necessary, it needs to be aware
|
||||||
of the possible classes. Otherwise, it will not be able to make the difference
|
of the possible classes. Otherwise, it will not be able to make the difference
|
||||||
between a valid css class added by the component, or some custom code, and a
|
between a valid css class added by the component, or other custom code, and a
|
||||||
class that need to be removed. This is why we only support the explicit syntax
|
class that need to be removed. This is why we only support the explicit syntax
|
||||||
with a class object:
|
with a class object:
|
||||||
|
|
||||||
@@ -621,7 +587,7 @@ with a class object:
|
|||||||
|
|
||||||
### Event Handling
|
### Event Handling
|
||||||
|
|
||||||
In a component's template, it is useful to be able to register handlers on some
|
In a component's template, it is useful to be able to register handlers on DOM
|
||||||
elements to some specific events. This is what makes a template _alive_. There
|
elements to some specific events. This is what makes a template _alive_. There
|
||||||
are four different use cases.
|
are four different use cases.
|
||||||
|
|
||||||
@@ -677,8 +643,7 @@ to event `menu-loaded` will receive the payload in its `someMethod` handler
|
|||||||
|
|
||||||
By convention, we use KebabCase for the name of _business_ events.
|
By convention, we use KebabCase for the name of _business_ events.
|
||||||
|
|
||||||
|
The `t-on` directive allows to prebind its arguments. For example,
|
||||||
The `t-on` directive allows to prebind some arguments. For example,
|
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<button t-on-click="someMethod(expr)">Do something</button>
|
<button t-on-click="someMethod(expr)">Do something</button>
|
||||||
@@ -695,10 +660,12 @@ One can also directly specify inline statements. For example,
|
|||||||
|
|
||||||
Here, `state` must be defined in the rendering context (typically the component)
|
Here, `state` must be defined in the rendering context (typically the component)
|
||||||
as it will be translated to:
|
as it will be translated to:
|
||||||
```js
|
|
||||||
button.addEventListener("click", () => { component.state.counter++; });
|
|
||||||
```
|
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
component.state.counter++;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
In order to remove the DOM event details from the event handlers (like calls to
|
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
|
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
|
||||||
@@ -802,7 +769,7 @@ The `t-model` directive works with `<input>`, `<input type="checkbox">`,
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
Like event handling, the `t-model` directive accepts some modifiers:
|
Like event handling, the `t-model` directive accepts the following modifiers:
|
||||||
|
|
||||||
| Modifier | Description |
|
| Modifier | Description |
|
||||||
| --------- | -------------------------------------------------------------------- |
|
| --------- | -------------------------------------------------------------------- |
|
||||||
@@ -827,24 +794,63 @@ 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,
|
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
|
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
|
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
|
algorithm to keep the actual DOM node as much as possible.
|
||||||
sometimes not enough, and we need to help Owl decide if an element is actually
|
|
||||||
the same, or is different. The `t-key` directive is used to give an identity to an element.
|
|
||||||
|
|
||||||
There are three main use cases:
|
However, in some situations, this is not enough, and we need to help Owl decide
|
||||||
|
if an element is actually the same, or is a different element with the same
|
||||||
|
properties.
|
||||||
|
|
||||||
- _elements in a list_:
|
Consider the following situation: we have a list of two items `[{text: "a"}, {text: "b"}]`
|
||||||
|
and we render them in this template:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<span t-foreach="todos" t-as="todo" t-key="todo.id">
|
<p t-foreach="items" t-as="item"><t t-esc="item.text"/></p>
|
||||||
<t t-esc="todo.text" />
|
```
|
||||||
</span>
|
|
||||||
```
|
|
||||||
|
|
||||||
- _`t-if`/`t-else`_
|
The result will be two `<p>` tags with text `a` and `b`. Now, if we swap them,
|
||||||
|
and rerender the template, Owl needs to know what the intent is:
|
||||||
|
|
||||||
- _animations_: give a different identity to a component. Ex: thread id with
|
- should Owl actually swap the DOM nodes,
|
||||||
animations on add/remove message.
|
- or should it keep the DOM nodes, but with an updated text content?
|
||||||
|
|
||||||
|
This might look trivial, but it actually matters. These two possibilities lead
|
||||||
|
to different results in some cases. For example, if the user selected the text
|
||||||
|
of the first `p`, swapping them will keep the selection while updating the
|
||||||
|
text content will not.
|
||||||
|
|
||||||
|
There are many other cases where this is important: `input` tags with their
|
||||||
|
value, css classes and animations, scroll position...
|
||||||
|
|
||||||
|
So, the `t-key` directive is used to give an identity to an element. It allows
|
||||||
|
Owl to understand if different elements of a list are actually different or not.
|
||||||
|
|
||||||
|
The above example could be modified by adding an ID: `[{id: 1, text: "a"}, {id: 2, text: "b"}]`.
|
||||||
|
Then, the template could look like this:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<p t-foreach="items" t-as="item" t-key="item.id"><t t-esc="item.text"/></p>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `t-key` directive is useful for lists (`t-foreach`). A key should be
|
||||||
|
a unique number or string (objects will not work: they will be cast to the
|
||||||
|
`"[object Object]"` string, which is obviously not unique).
|
||||||
|
|
||||||
|
Also, the key can be set on a `t` tag or on its children. The following variations
|
||||||
|
are all equivalent:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<p t-foreach="items" t-as="item" t-key="item.id">
|
||||||
|
<t t-esc="item.text"/>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<t t-foreach="items" t-as="item" t-key="item.id">
|
||||||
|
<p t-esc="item.text"/>
|
||||||
|
</t>
|
||||||
|
|
||||||
|
<t t-foreach="items" t-as="item">
|
||||||
|
<p t-key="item.id" t-esc="item.text"/>
|
||||||
|
</t>
|
||||||
|
```
|
||||||
|
|
||||||
### Semantics
|
### Semantics
|
||||||
|
|
||||||
@@ -946,7 +952,7 @@ of the props. Here is how it works in Owl:
|
|||||||
- `props` key is a static key (so, different from `this.props` in a component instance)
|
- `props` key is a static key (so, different from `this.props` in a component instance)
|
||||||
- it is optional: it is ok for a component to not define a `props` key.
|
- it is optional: it is ok for a component to not define a `props` key.
|
||||||
- props are validated whenever a component is created/updated
|
- props are validated whenever a component is created/updated
|
||||||
- props are only validated in `dev` mode (see [tooling page](tooling.md#development-mode))
|
- props are only validated in `dev` mode (see [config page](config.md#mode))
|
||||||
- if a key does not match the description, an error is thrown
|
- if a key does not match the description, an error is thrown
|
||||||
- it validates keys defined in (static) `props`. Additional keys given by the
|
- it validates keys defined in (static) `props`. Additional keys given by the
|
||||||
parent will cause an error.
|
parent will cause an error.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 🦉 Config 🦉
|
||||||
|
|
||||||
|
The Owl framework is designed to work in many situations. However, it is
|
||||||
|
sometimes necessary to customize some behaviour. This is done by using the
|
||||||
|
global `config` object. It currently has one key:
|
||||||
|
|
||||||
|
- [`mode`](#mode).
|
||||||
|
|
||||||
|
## Mode
|
||||||
|
|
||||||
|
By default, Owl is in _production_ mode, this means that it will try to do its
|
||||||
|
job fast, and skip some expensive operations. However, it is sometimes necessary
|
||||||
|
to have better information on what is going on, this is the purpose
|
||||||
|
of the `dev` mode.
|
||||||
|
|
||||||
|
Owl has a mode flag, in `owl.config.mode`. Its default value is `prod`, but
|
||||||
|
it can be set to `dev`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
owl.config.mode = "dev";
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that templates compiled with the `prod` settings will not be recompiled.
|
||||||
|
So, changing this setting is best done at startup.
|
||||||
|
|
||||||
|
An important job done by the `dev` mode is to validate props for each component
|
||||||
|
creation and update. Also, extra props will cause an error.
|
||||||
@@ -28,10 +28,7 @@ context, and add it to the environment:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const deviceContext = new Context({ isMobile: true });
|
const deviceContext = new Context({ isMobile: true });
|
||||||
const env = {
|
App.env.deviceContext = deviceContext;
|
||||||
qweb: new QWeb(TEMPLATES),
|
|
||||||
deviceContext
|
|
||||||
};
|
|
||||||
```
|
```
|
||||||
|
|
||||||
If we want to make it completely responsive, we need to update its value whenever
|
If we want to make it completely responsive, we need to update its value whenever
|
||||||
@@ -56,14 +53,14 @@ fact that we are in a mobile or desktop mode.
|
|||||||
```js
|
```js
|
||||||
class SomeComponent extends Component {
|
class SomeComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
<div>
|
<div>
|
||||||
<t t-if=device.isMobile>
|
<t t-if=device.isMobile>
|
||||||
some simplified user interface
|
some simplified user interface
|
||||||
</t>
|
</t>
|
||||||
<t t-else="1">
|
<t t-else="1">
|
||||||
some more sopthisticated user interface
|
a more advanced user interface
|
||||||
</t>
|
</t>
|
||||||
`;
|
</div>`;
|
||||||
device = useContext(this.env.deviceContext);
|
device = useContext(this.env.deviceContext);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 🦉 Environment 🦉
|
||||||
|
|
||||||
|
An environment is an object which contains a [`QWeb` instance](qweb.md). Whenever
|
||||||
|
a root component is created, it is assigned an environment (see
|
||||||
|
[below](#setting-an-environment) for more info on this). This environment is
|
||||||
|
then automatically given to each sub component (and accessible in the `this.env`
|
||||||
|
property).
|
||||||
|
|
||||||
|
```
|
||||||
|
Root
|
||||||
|
/ \
|
||||||
|
A B
|
||||||
|
```
|
||||||
|
|
||||||
|
This way, all components share the same `QWeb` instance.
|
||||||
|
|
||||||
|
Note: some additional information about what should go into an environment
|
||||||
|
can be found in the [learning section](../learning/environment.md).
|
||||||
|
|
||||||
|
## Setting an environment
|
||||||
|
|
||||||
|
An Owl application needs an [environment](environment.md) to be executed. The
|
||||||
|
environment has an important key: the [QWeb](qweb.md) instance, which will render
|
||||||
|
all templates.
|
||||||
|
|
||||||
|
Whenever a root component `App` is mounted, Owl will setup a valid environment by
|
||||||
|
following the next steps:
|
||||||
|
|
||||||
|
- take the `env` object defined on `App.env` (if no `env` was explicitely setup,
|
||||||
|
this will be return the empty `env` object defined on `Component`)
|
||||||
|
- if `env.qweb` is not set, then Owl will create a `QWeb` instance.
|
||||||
|
|
||||||
|
The correct way to customize an environment is to simply set it up on the root
|
||||||
|
component class, before the first component is created:
|
||||||
|
|
||||||
|
```js
|
||||||
|
App.env = {
|
||||||
|
_t: myTranslateFunction,
|
||||||
|
user: {...},
|
||||||
|
services: {
|
||||||
|
...
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const app = new App();
|
||||||
|
app.mount(document.body);
|
||||||
|
```
|
||||||
|
|
||||||
|
It is also possible to simply share an environment between all root components,
|
||||||
|
by simply doing this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
Component.env = myEnv; // will be the default env for all components
|
||||||
|
```
|
||||||
@@ -181,6 +181,9 @@ class Counter extends owl.Component {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
It is important to remember that `useState` only works with objects or arrays. It
|
||||||
|
is necessary, since Owl needs to react to a change in state.
|
||||||
|
|
||||||
### `onMounted`
|
### `onMounted`
|
||||||
|
|
||||||
`onMounted` is not a user hook, but is a building block designed to help make useful
|
`onMounted` is not a user hook, but is a building block designed to help make useful
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
- [Dynamic Attributes](#dynamic-attributes)
|
- [Dynamic Attributes](#dynamic-attributes)
|
||||||
- [Loops](#loops)
|
- [Loops](#loops)
|
||||||
- [Rendering Sub Templates](#rendering-sub-templates)
|
- [Rendering Sub Templates](#rendering-sub-templates)
|
||||||
|
- [Translations](#translations)
|
||||||
- [Debugging](#debugging)
|
- [Debugging](#debugging)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
@@ -60,20 +61,21 @@ We present here a list of all standard QWeb directives:
|
|||||||
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
|
||||||
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
|
||||||
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
| `t-debug`, `t-log` | [Debugging](#debugging) |
|
||||||
|
| `t-translation` | [Disabling the translation of a node](#translations) |
|
||||||
| `t-name` | [Defining a template (not really a directive)](#qweb-engine) |
|
| `t-name` | [Defining a template (not really a directive)](#qweb-engine) |
|
||||||
|
|
||||||
The component system in Owl requires additional directives, to express various
|
The component system in Owl requires additional directives, to express various
|
||||||
needs. Here is a list of all Owl specific directives:
|
needs. Here is a list of all Owl specific directives:
|
||||||
|
|
||||||
| Name | Description |
|
| Name | Description |
|
||||||
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
| ------------------------ | ----------------------------------------------------------------------------------- |
|
||||||
| `t-component`, `t-props`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
| `t-component`, `t-props` | [Defining a sub component](component.md#composition) |
|
||||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||||
|
|
||||||
## QWeb Engine
|
## QWeb Engine
|
||||||
|
|
||||||
@@ -87,11 +89,14 @@ const qweb = new owl.QWeb();
|
|||||||
|
|
||||||
Its API is quite simple:
|
Its API is quite simple:
|
||||||
|
|
||||||
- **`constructor(data)`**: constructor. Takes an optional string to add initial
|
- **`constructor(config)`**: constructor. Takes an optional configuration object
|
||||||
templates (see `addTemplates` for more information on format of the string).
|
with an optional `templates` string to add initial
|
||||||
|
templates (see `addTemplates` for more information on format of the string)
|
||||||
|
and an optional `translateFn` translate function (see the section on
|
||||||
|
[translations](#translations)).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const qweb = new owl.QWeb({ templates: TEMPLATES, translateFn: _t });
|
||||||
```
|
```
|
||||||
|
|
||||||
- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template.
|
- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template.
|
||||||
@@ -116,7 +121,7 @@ Its API is quite simple:
|
|||||||
```
|
```
|
||||||
|
|
||||||
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
|
||||||
which is a virtual representation of the DOM (see [vdom doc](vdom.md)).
|
which is a virtual representation of the DOM (see [vdom doc](../architecture/vdom.md)).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const vnode = qweb.render("App", component);
|
const vnode = qweb.render("App", component);
|
||||||
@@ -154,7 +159,7 @@ Its API is quite simple:
|
|||||||
```
|
```
|
||||||
|
|
||||||
In some way, a `QWeb` instance is the core of an Owl application. It is the only
|
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
|
mandatory element of an [environment](environment.md). As such, it
|
||||||
has an extra responsibility: 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).
|
between Owl classes. This is the reason why `QWeb` actually extends [EventBus](event_bus.md).
|
||||||
|
|
||||||
@@ -201,7 +206,7 @@ root nodes.
|
|||||||
### Expression Evaluation
|
### Expression Evaluation
|
||||||
|
|
||||||
QWeb expressions are strings that will be processed at compile time. Each variable in
|
QWeb expressions are strings that will be processed at compile time. Each variable in
|
||||||
the javascript expression will be replaced by a lookup in the context (so, the
|
the javascript expression will be replaced with a lookup in the context (so, the
|
||||||
component). For example, `a + b.c(d)` will be converted into:
|
component). For example, `a + b.c(d)` will be converted into:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@@ -234,14 +239,14 @@ It is useful to explain the various rules that apply on these expressions:
|
|||||||
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
|
||||||
`&` or `|`. This is useful to make sure that we still write valid XML.
|
`&` or `|`. This is useful to make sure that we still write valid XML.
|
||||||
|
|
||||||
| Word | will be replaced by |
|
| Word | replaced with |
|
||||||
| ----- | ------------------- |
|
| ----- | ------------- |
|
||||||
| `and` | `&&` |
|
| `and` | `&&` |
|
||||||
| `or` | `\|\|` |
|
| `or` | `\|\|` |
|
||||||
| `gt` | `>` |
|
| `gt` | `>` |
|
||||||
| `gte` | `>=` |
|
| `gte` | `>=` |
|
||||||
| `lt` | `<` |
|
| `lt` | `<` |
|
||||||
| `lte` | `<=` |
|
| `lte` | `<=` |
|
||||||
|
|
||||||
So, one can write this:
|
So, one can write this:
|
||||||
|
|
||||||
@@ -443,7 +448,7 @@ is equivalent to the previous example.
|
|||||||
or an object (the current item will be the current key).
|
or an object (the current item will be the current key).
|
||||||
|
|
||||||
In addition to the name passed via t-as, `t-foreach` provides a few other
|
In addition to the name passed via t-as, `t-foreach` provides a few other
|
||||||
variables for various data points (note: `$as` will be replaced by the name
|
variables for various data points (note: `$as` will be replaced with the name
|
||||||
passed to `t-as`):
|
passed to `t-as`):
|
||||||
|
|
||||||
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
- `$as_value`: the current iteration value, identical to `$as` for lists and
|
||||||
@@ -474,6 +479,20 @@ into the global context.
|
|||||||
<!-- new_variable undefined -->
|
<!-- new_variable undefined -->
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Owl QWeb is used as the template engine for components. Components are frequently
|
||||||
|
updated, and reuse as much of the previous DOM as possible. Loops offer a specific
|
||||||
|
problem for this usecase: how does the template engine know if two rows have
|
||||||
|
been swapped, or if the content of these rows was changed? To help Owl with that,
|
||||||
|
there is an additional directive: [`t-key`](component.md#t-key-directive).
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<p t-foreach="state.things" t-as="thing" t-key="thing.id">
|
||||||
|
<t t-esc="thing.content"/>
|
||||||
|
</p>
|
||||||
|
```
|
||||||
|
|
||||||
|
If there is no `t-key` directive, Owl will use the index as a default key.
|
||||||
|
|
||||||
### Rendering Sub Templates
|
### Rendering Sub Templates
|
||||||
|
|
||||||
QWeb templates can be used for top level rendering, but they can also be used
|
QWeb templates can be used for top level rendering, but they can also be used
|
||||||
@@ -522,6 +541,53 @@ will result in :
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Translations
|
||||||
|
|
||||||
|
If properly setup, Owl QWeb engine can translate all rendered templates. To do
|
||||||
|
so, it needs a translate function, which takes a string and returns a string.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const translations = {
|
||||||
|
hello: "bonjour",
|
||||||
|
yes: "oui",
|
||||||
|
no: "non"
|
||||||
|
};
|
||||||
|
const translateFn = str => translations[str] || str;
|
||||||
|
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
```
|
||||||
|
|
||||||
|
Once setup, all rendered templates will be translated using `translateFn`:
|
||||||
|
|
||||||
|
- each text node will be replaced with its translation,
|
||||||
|
- each of the following attribute values will be translated as well: `title`,
|
||||||
|
`placeholder`, `label` and `alt`,
|
||||||
|
- translating text nodes can be disabled with the special attribute `t-translation`,
|
||||||
|
if its value is `off`.
|
||||||
|
|
||||||
|
So, with the above `translateFn`, the following templates:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div>hello</div>
|
||||||
|
<div t-translation="off">hello</div>
|
||||||
|
<div>Are you sure?</div>
|
||||||
|
<input placeholder="hello" other="yes"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
will be rendered as:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<div>bonjour</div>
|
||||||
|
<div>hello</div>
|
||||||
|
<div>Are you sure?</div>
|
||||||
|
<input placeholder="bonjour" other="yes"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that the translation is done during the compilation of the template, not
|
||||||
|
when it is rendered.
|
||||||
|
|
||||||
### Debugging
|
### Debugging
|
||||||
|
|
||||||
The javascript QWeb implementation provides two useful debugging directives:
|
The javascript QWeb implementation provides two useful debugging directives:
|
||||||
@@ -67,6 +67,9 @@ function makeEnvironment() {
|
|||||||
await env.router.start();
|
await env.router.start();
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
App.env = makeEnvironment();
|
||||||
|
// create root component here
|
||||||
```
|
```
|
||||||
|
|
||||||
Notice that the router needs to be started. This is an asynchronous operation
|
Notice that the router needs to be started. This is an asynchronous operation
|
||||||
@@ -262,6 +262,10 @@ will only be rerendered whenever this part of the state changes. Otherwise, it
|
|||||||
will perform a strict equality check and will update the component every time this
|
will perform a strict equality check and will update the component every time this
|
||||||
check fails.
|
check fails.
|
||||||
|
|
||||||
|
Also, it may not be obvious, but it is crucial to remember that the selector
|
||||||
|
function should return an object or an array. The reason is that it needs to be
|
||||||
|
observed, otherwise the component would not be able to react to changes.
|
||||||
|
|
||||||
### `useDispatch`
|
### `useDispatch`
|
||||||
|
|
||||||
The `useDispatch` hook is useful when a component needs to be able to dispatch
|
The `useDispatch` hook is useful when a component needs to be able to dispatch
|
||||||
@@ -1,8 +1,15 @@
|
|||||||
# 🦉 Tags 🦉
|
# 🦉 Tags 🦉
|
||||||
|
|
||||||
|
## Content
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [`xml` tag](#xml-tag)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
Tags are very small helpers to make it easy to write inline templates. There is
|
Tags are very small helpers to make it easy to write inline templates. There is
|
||||||
only one currently available tag: `xml`, but we plan to add other tags later,
|
only one currently available tag: `xml`, but we plan to add other tags later,
|
||||||
such as a `css` tag, which will be used to write single file components.
|
such as a `css` tag, which will be used to write [single file components](../tooling.md#single-file-component).
|
||||||
|
|
||||||
## XML tag
|
## XML tag
|
||||||
|
|
||||||
@@ -31,8 +38,8 @@ With tags, this process is slightly simplified. The name is uniquely generated,
|
|||||||
and the template is automatically registered:
|
and the template is automatically registered:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { Component } from 'owl'
|
const { Component } = owl;
|
||||||
import { xml } from 'owl/tags'
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
class MyComponent extends Component {
|
class MyComponent extends Component {
|
||||||
static template = xml`
|
static template = xml`
|
||||||
@@ -20,7 +20,7 @@ argument, it executes it as soon as the DOM ready (or directly).
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
|
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
|
||||||
const qweb = new owl.QWeb(templates);
|
const qweb = new owl.QWeb({ templates });
|
||||||
const app = new App({ qweb });
|
const app = new App({ qweb });
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
});
|
});
|
||||||
@@ -62,7 +62,7 @@ initial usecase for this function is to load a template file. For example:
|
|||||||
```js
|
```js
|
||||||
async function makeEnv() {
|
async function makeEnv() {
|
||||||
const templates = await owl.utils.loadFile("templates.xml");
|
const templates = await owl.utils.loadFile("templates.xml");
|
||||||
const qweb = new owl.QWeb(templates);
|
const qweb = new owl.QWeb({ templates });
|
||||||
return { qweb };
|
return { qweb };
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
+18
-25
@@ -3,7 +3,6 @@
|
|||||||
## Content
|
## Content
|
||||||
|
|
||||||
- [Overview](#overview)
|
- [Overview](#overview)
|
||||||
- [Development Mode](#development-mode)
|
|
||||||
- [Playground](#playground)
|
- [Playground](#playground)
|
||||||
- [Benchmarks](#benchmarks)
|
- [Benchmarks](#benchmarks)
|
||||||
- [Single File Component](#single-file-component)
|
- [Single File Component](#single-file-component)
|
||||||
@@ -21,26 +20,6 @@ by using a static http server. A simple python
|
|||||||
server is available in `server.py`. There is also a npm script to start it:
|
server is available in `server.py`. There is also a npm script to start it:
|
||||||
`npm run tools` (and its version with a watcher: `npm run tools:watch`).
|
`npm run tools` (and its version with a watcher: `npm run tools:watch`).
|
||||||
|
|
||||||
## Development Mode
|
|
||||||
|
|
||||||
By default, Owl is in _production_ mode, this means that it will try to do its
|
|
||||||
job fast, and skip some expensive operations. However, in some cases, it is
|
|
||||||
convenient to have better information on what is going on, this is the purpose
|
|
||||||
of the dev mode.
|
|
||||||
|
|
||||||
Owl has a mode flag, in `owl.__info__.mode`. Its default value is `prod`, but
|
|
||||||
it can be set to `dev`:
|
|
||||||
|
|
||||||
```js
|
|
||||||
owl.__info__.mode = "dev";
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that templates compiled with the `prod` settings will not be recompiled.
|
|
||||||
So, changing this setting is best done at startup.
|
|
||||||
|
|
||||||
An important job done by the `dev` mode is to validate props for each component
|
|
||||||
creation and update. Also, extra props will cause an error.
|
|
||||||
|
|
||||||
## Playground
|
## Playground
|
||||||
|
|
||||||
The playground is an important application designed to help learning and
|
The playground is an important application designed to help learning and
|
||||||
@@ -60,12 +39,21 @@ useful to compare various performance metrics on some tasks.
|
|||||||
|
|
||||||
## Single File Component
|
## Single File Component
|
||||||
|
|
||||||
If you want to have `xml` syntax highlighting while using the `xml` helper which
|
It is very useful to group code by feature instead of by type of file. It makes
|
||||||
helps you define inline templates, there is a VS Code addon `Comment tagged template`
|
it easier to scale application to larger size.
|
||||||
which, if installed, does exactly that. To enable it, you need to add a comment,
|
|
||||||
like this:
|
To do so, Owl currently has a small helper that makes it easy to define a
|
||||||
|
template inside a javascript (or typescript) file: the [`xml`](reference/tags.md#xml-tag)
|
||||||
|
helper. With this, a template is automatically registered to [QWeb](reference/qweb.md).
|
||||||
|
|
||||||
|
This means that the template and the javascript code can be defined in the same
|
||||||
|
file. It is not currently possible to add css to the same file, but Owl may
|
||||||
|
get a `css` tag helper later.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
const { Component } = owl;
|
||||||
|
const { xml } = owl.tags;
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// TEMPLATE
|
// TEMPLATE
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
@@ -85,3 +73,8 @@ class MyComponent extends Component {
|
|||||||
// rest of component...
|
// rest of component...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Note that the above example has an inline xml comment, just after the `xml` call.
|
||||||
|
This is useful for some editor plugins, such as the VS Code addon
|
||||||
|
`Comment tagged template`, which, if installed, add syntax highlighting to the
|
||||||
|
content of the template string.
|
||||||
|
|||||||
+6
-3
@@ -1,8 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "owl-framework",
|
"name": "owl-framework",
|
||||||
"version": "0.24.0",
|
"version": "1.0.0-alpha2",
|
||||||
"description": "Odoo Web Library (OWL)",
|
"description": "Odoo Web Library (OWL)",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.15.3"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
|
||||||
"build:bundle": "rollup -c",
|
"build:bundle": "rollup -c",
|
||||||
@@ -15,7 +18,7 @@
|
|||||||
"tools": "npm run build && npm run tools:serve",
|
"tools": "npm run build && npm run tools:serve",
|
||||||
"pretools:watch": "npm run build",
|
"pretools:watch": "npm run build",
|
||||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
||||||
"prettier": "prettier {src/**/*.ts,tests/**/*.ts,doc/**/*.md} --write"
|
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -41,7 +44,7 @@
|
|||||||
"sass": "^1.16.1",
|
"sass": "^1.16.1",
|
||||||
"source-map-support": "^0.5.10",
|
"source-map-support": "^0.5.10",
|
||||||
"ts-jest": "^23.10.5",
|
"ts-jest": "^23.10.5",
|
||||||
"typescript": "^3.2.2",
|
"typescript": "^3.6.4",
|
||||||
"uglify-es": "^3.3.9"
|
"uglify-es": "^3.3.9"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
|
|||||||
+12
-10
@@ -1,23 +1,25 @@
|
|||||||
# 🦉 OWL Roadmap 🦉
|
# 🦉 OWL Roadmap 🦉
|
||||||
|
|
||||||
- Current version: 0.24.0
|
- Current version: 1.0.0-alpha2
|
||||||
- Status: mostly stable
|
- Status: mostly stable
|
||||||
|
|
||||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||||
change!
|
change!
|
||||||
|
|
||||||
### October 2019
|
|
||||||
|
|
||||||
We plan to complete the following tasks:
|
|
||||||
|
|
||||||
- improve API for root widgets (issue #306),
|
|
||||||
- replace `t-keepalive`, and maybe `t-transition` by components (issue #295).
|
|
||||||
|
|
||||||
### November 2019
|
### November 2019
|
||||||
|
|
||||||
Once the previous tasks are done, release version 1.0alpha. This means that the
|
Owl will be used in various Odoo projects. We plan to:
|
||||||
API should be stable. But it could change a little bit if we need it for our
|
|
||||||
work on Odoo.
|
- fix any issues encountered
|
||||||
|
- maybe cleanup slightly the router API
|
||||||
|
- improve the documentation
|
||||||
|
- improve error handling, add more helpful error messages
|
||||||
|
|
||||||
|
### December 2019
|
||||||
|
|
||||||
|
If all goes well, Owl will be upgraded to beta status. From then, no API change,
|
||||||
|
even small, is expected.
|
||||||
|
|
||||||
### End of 2019
|
### End of 2019
|
||||||
|
|
||||||
|
|||||||
+75
-110
@@ -4,7 +4,7 @@ import { h, patch, VNode } from "../vdom/index";
|
|||||||
import "./directive";
|
import "./directive";
|
||||||
import { Fiber } from "./fiber";
|
import { Fiber } from "./fiber";
|
||||||
import "./props_validation";
|
import "./props_validation";
|
||||||
import { Scheduler } from "./scheduler";
|
import { scheduler } from "./scheduler";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Component System
|
* Owl Component System
|
||||||
@@ -20,8 +20,6 @@ import { Scheduler } from "./scheduler";
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Types/helpers
|
// 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
|
* An Env (environment) is an object that will be (mostly) shared between all
|
||||||
@@ -46,6 +44,7 @@ interface Internal<T extends Env, Props> {
|
|||||||
// each component has a unique id, useful mostly to handle parent/child
|
// each component has a unique id, useful mostly to handle parent/child
|
||||||
// relationships
|
// relationships
|
||||||
readonly id: number;
|
readonly id: number;
|
||||||
|
depth: number;
|
||||||
vnode: VNode | null;
|
vnode: VNode | null;
|
||||||
pvnode: VNode | null;
|
pvnode: VNode | null;
|
||||||
isMounted: boolean;
|
isMounted: boolean;
|
||||||
@@ -88,6 +87,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
static components = {};
|
static components = {};
|
||||||
static props?: any;
|
static props?: any;
|
||||||
static defaultProps?: any;
|
static defaultProps?: any;
|
||||||
|
static env: any = {};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `el` is the root element of the component. Note that it could be null:
|
* The `el` is the root element of the component. Note that it could be null:
|
||||||
@@ -107,45 +107,36 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* Creates an instance of Component.
|
* Creates an instance of Component.
|
||||||
*
|
*
|
||||||
* The root component of a component tree needs an environment:
|
|
||||||
*
|
|
||||||
* ```javascript
|
|
||||||
* const root = new RootComponent(env, props);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* Every other component simply needs a reference to its parent:
|
|
||||||
*
|
|
||||||
* ```javascript
|
|
||||||
* const child = new SomeComponent(parent, props);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* Note that most of the time, only the root component needs to be created by
|
* Note that most of the time, only the root component needs to be created by
|
||||||
* hand. Other components should be created automatically by the framework (with
|
* hand. Other components should be created automatically by the framework (with
|
||||||
* the t-component directive in a template)
|
* the t-component directive in a template)
|
||||||
*/
|
*/
|
||||||
constructor(parent: Component<T, any> | T, props?: Props) {
|
constructor(parent?: Component<T, any> | null, props?: Props) {
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
|
||||||
Component.current = this;
|
Component.current = this;
|
||||||
|
|
||||||
|
let constr = this.constructor as any;
|
||||||
|
const defaultProps = constr.defaultProps;
|
||||||
if (defaultProps) {
|
if (defaultProps) {
|
||||||
props = this.__applyDefaultProps(props, defaultProps);
|
props = props || {} as Props;
|
||||||
|
this.__applyDefaultProps(props, defaultProps);
|
||||||
}
|
}
|
||||||
// is this a good idea?
|
this.props = <Props>props;
|
||||||
// Pro: if props is empty, we can create easily a component
|
if (QWeb.dev) {
|
||||||
// Con: this is not really safe
|
QWeb.utils.validateProps(constr, this.props);
|
||||||
// Pro: but creating component (by a template) is always unsafe anyway
|
}
|
||||||
this.props = <Props>props || <Props>{};
|
|
||||||
let id: number = nextId++;
|
const id: number = nextId++;
|
||||||
let p: Component<T, any> | null = null;
|
let depth;
|
||||||
if (parent instanceof Component) {
|
if (parent) {
|
||||||
p = parent;
|
|
||||||
this.env = parent.env;
|
this.env = parent.env;
|
||||||
parent.__owl__.children[id] = this;
|
const __powl__ = parent.__owl__;
|
||||||
|
__powl__.children[id] = this;
|
||||||
|
depth = __powl__.depth + 1;
|
||||||
} else {
|
} else {
|
||||||
this.env = parent;
|
// we are the root component
|
||||||
if (QWeb.dev) {
|
this.env = (this.constructor as any).env;
|
||||||
// we only validate props for root widgets here. "Regular" widget
|
if (!this.env.qweb) {
|
||||||
// props are validated by the t-component directive
|
this.env.qweb = new QWeb();
|
||||||
QWeb.utils.validateProps(this.constructor, this.props);
|
|
||||||
}
|
}
|
||||||
this.env.qweb.on("update", this, () => {
|
this.env.qweb.on("update", this, () => {
|
||||||
if (this.__owl__.isMounted) {
|
if (this.__owl__.isMounted) {
|
||||||
@@ -160,16 +151,19 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
this.env.qweb.off("update", this);
|
this.env.qweb.off("update", this);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
depth = 0;
|
||||||
}
|
}
|
||||||
const qweb = this.env.qweb;
|
|
||||||
|
|
||||||
|
const qweb = this.env.qweb;
|
||||||
|
const template = constr.template || this.__getTemplate(qweb);
|
||||||
this.__owl__ = {
|
this.__owl__ = {
|
||||||
id: id,
|
id: id,
|
||||||
|
depth: depth,
|
||||||
vnode: null,
|
vnode: null,
|
||||||
pvnode: null,
|
pvnode: null,
|
||||||
isMounted: false,
|
isMounted: false,
|
||||||
isDestroyed: false,
|
isDestroyed: false,
|
||||||
parent: p,
|
parent: parent || null,
|
||||||
children: {},
|
children: {},
|
||||||
cmap: {},
|
cmap: {},
|
||||||
currentFiber: null,
|
currentFiber: null,
|
||||||
@@ -181,7 +175,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
willStartCB: null,
|
willStartCB: null,
|
||||||
willUpdatePropsCB: null,
|
willUpdatePropsCB: null,
|
||||||
observer: null,
|
observer: null,
|
||||||
renderFn: qweb.render.bind(qweb, this.__getTemplate(qweb)),
|
renderFn: qweb.render.bind(qweb, template),
|
||||||
classObj: null,
|
classObj: null,
|
||||||
refs: null
|
refs: null
|
||||||
};
|
};
|
||||||
@@ -262,8 +256,11 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* catchError is a method called whenever some error happens in the rendering or
|
* catchError is a method called whenever some error happens in the rendering or
|
||||||
* lifecycle hooks of a child.
|
* lifecycle hooks of a child.
|
||||||
|
*
|
||||||
|
* It needs to be implemented by a component that is designed to handle the
|
||||||
|
* error properly.
|
||||||
*/
|
*/
|
||||||
catchError(error: Error): void {}
|
catchError?(error?: Error): void;
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
// Public
|
// Public
|
||||||
@@ -289,14 +286,13 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, false);
|
return new Promise((resolve, reject) => {
|
||||||
if (!__owl__.vnode) {
|
const fiber = new Fiber(null, this, undefined, undefined, false);
|
||||||
this.__prepareAndRender(fiber);
|
scheduler.addFiber(fiber, err => {
|
||||||
} else {
|
if (err) {
|
||||||
this.__render(fiber);
|
reject(err);
|
||||||
}
|
return;
|
||||||
return new Promise(resolve => {
|
}
|
||||||
scheduler.addFiber(fiber, () => {
|
|
||||||
if (!__owl__.isDestroyed) {
|
if (!__owl__.isDestroyed) {
|
||||||
this.__patch(fiber.vnode);
|
this.__patch(fiber.vnode);
|
||||||
target.appendChild(this.el!);
|
target.appendChild(this.el!);
|
||||||
@@ -306,6 +302,11 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
}
|
}
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
|
if (!__owl__.vnode) {
|
||||||
|
this.__prepareAndRender(fiber);
|
||||||
|
} else {
|
||||||
|
this.__render(fiber);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,15 +338,19 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, force);
|
return new Promise((resolve, reject) => {
|
||||||
this.__render(fiber);
|
const fiber = new Fiber(null, this, undefined, undefined, force);
|
||||||
return new Promise(resolve => {
|
scheduler.addFiber(fiber.root, err => {
|
||||||
scheduler.addFiber(fiber.root, () => {
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (__owl__.isMounted && fiber === fiber.root) {
|
if (__owl__.isMounted && fiber === fiber.root) {
|
||||||
fiber.patchComponents();
|
fiber.patchComponents();
|
||||||
}
|
}
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
|
this.__render(fiber);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -483,7 +488,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||||
if (shouldUpdate) {
|
if (shouldUpdate) {
|
||||||
const __owl__ = this.__owl__;
|
const __owl__ = this.__owl__;
|
||||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||||
if (!parentFiber.child) {
|
if (!parentFiber.child) {
|
||||||
parentFiber.child = fiber;
|
parentFiber.child = fiber;
|
||||||
} else {
|
} else {
|
||||||
@@ -492,7 +497,10 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
|
|
||||||
const defaultProps = (<any>this.constructor).defaultProps;
|
const defaultProps = (<any>this.constructor).defaultProps;
|
||||||
if (defaultProps) {
|
if (defaultProps) {
|
||||||
nextProps = this.__applyDefaultProps(nextProps, defaultProps);
|
this.__applyDefaultProps(nextProps, defaultProps);
|
||||||
|
}
|
||||||
|
if (QWeb.dev) {
|
||||||
|
QWeb.utils.validateProps(this.constructor, nextProps);
|
||||||
}
|
}
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.willUpdateProps(nextProps),
|
this.willUpdateProps(nextProps),
|
||||||
@@ -524,7 +532,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
* parent template.
|
* parent template.
|
||||||
*/
|
*/
|
||||||
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
||||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||||
fiber.shouldPatch = false;
|
fiber.shouldPatch = false;
|
||||||
if (!parentFiber.child) {
|
if (!parentFiber.child) {
|
||||||
parentFiber.child = fiber;
|
parentFiber.child = fiber;
|
||||||
@@ -537,22 +545,18 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
__getTemplate(qweb: QWeb): string {
|
__getTemplate(qweb: QWeb): string {
|
||||||
let p = (<any>this).constructor;
|
let p = (<any>this).constructor;
|
||||||
if (!p.hasOwnProperty("_template")) {
|
if (!p.hasOwnProperty("_template")) {
|
||||||
if (p.template) {
|
// here, the component and none of its superclasses defines a static `template`
|
||||||
p._template = p.template;
|
// key. So we fall back on looking for a template matching its name (or
|
||||||
} else {
|
// one of its subclass).
|
||||||
// here, the component and none of its superclasses defines a static `template`
|
|
||||||
// key. So we fall back on looking for a template matching its name (or
|
|
||||||
// one of its subclass).
|
|
||||||
|
|
||||||
let template: string;
|
let template: string;
|
||||||
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
|
||||||
p = p.__proto__;
|
p = p.__proto__;
|
||||||
}
|
}
|
||||||
if (p === Component) {
|
if (p === Component) {
|
||||||
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
throw new Error(`Could not find template for component "${this.constructor.name}"`);
|
||||||
} else {
|
} else {
|
||||||
p._template = template;
|
p._template = template;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return p._template;
|
return p._template;
|
||||||
@@ -561,7 +565,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
try {
|
try {
|
||||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
errorHandler(e, fiber);
|
fiber.handleError(e);
|
||||||
fiber.vnode = h("div"); // -> we render this div at the end
|
fiber.vnode = h("div"); // -> we render this div at the end
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
@@ -586,7 +590,7 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
vnode = __owl__.vnode || h("div");
|
vnode = __owl__.vnode || h("div");
|
||||||
errorHandler(e, fiber);
|
fiber.handleError(e);
|
||||||
}
|
}
|
||||||
fiber.vnode = vnode;
|
fiber.vnode = vnode;
|
||||||
if (__owl__.observer) {
|
if (__owl__.observer) {
|
||||||
@@ -637,52 +641,13 @@ export class Component<T extends Env, Props extends {}> {
|
|||||||
/**
|
/**
|
||||||
* Apply default props (only top level).
|
* Apply default props (only top level).
|
||||||
*
|
*
|
||||||
* Note that this method does not modify in place the props, it returns a new
|
* Note that this method does modify in place the props
|
||||||
* prop object
|
|
||||||
*/
|
*/
|
||||||
__applyDefaultProps(props: Object | undefined, defaultProps: Object): Props {
|
__applyDefaultProps(props: Object, defaultProps: Object) {
|
||||||
props = props ? Object.assign({}, props) : {};
|
|
||||||
for (let propName in defaultProps) {
|
for (let propName in defaultProps) {
|
||||||
if (props![propName] === undefined) {
|
if (props![propName] === undefined) {
|
||||||
props![propName] = defaultProps[propName];
|
props![propName] = defaultProps[propName];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return <Props>props;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
// 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
|
|
||||||
* potentially given to some parent component which implements `catchError`.
|
|
||||||
*
|
|
||||||
* If there are no such component, we destroy everything. This is better than
|
|
||||||
* being in a corrupted state.
|
|
||||||
*/
|
|
||||||
function errorHandler(error: Error, 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)) {
|
|
||||||
root = component;
|
|
||||||
component = component.__owl__.parent!;
|
|
||||||
}
|
|
||||||
console.error(error);
|
|
||||||
qweb.trigger("error", error);
|
|
||||||
|
|
||||||
if (canCatch) {
|
|
||||||
setTimeout(() => {
|
|
||||||
component.catchError(error);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
root.destroy();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -186,7 +186,7 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
|||||||
|
|
||||||
QWeb.addDirective({
|
QWeb.addDirective({
|
||||||
name: "component",
|
name: "component",
|
||||||
extraNames: ["props", "keepalive"],
|
extraNames: ["props"],
|
||||||
priority: 100,
|
priority: 100,
|
||||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||||
ctx.addLine("//COMPONENT");
|
ctx.addLine("//COMPONENT");
|
||||||
@@ -194,7 +194,6 @@ QWeb.addDirective({
|
|||||||
ctx.rootContext.shouldDefineQWeb = true;
|
ctx.rootContext.shouldDefineQWeb = true;
|
||||||
ctx.rootContext.shouldDefineParent = true;
|
ctx.rootContext.shouldDefineParent = true;
|
||||||
ctx.rootContext.shouldDefineUtils = true;
|
ctx.rootContext.shouldDefineUtils = true;
|
||||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
|
||||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||||
|
|
||||||
// t-on- events and t-transition
|
// t-on- events and t-transition
|
||||||
@@ -223,30 +222,19 @@ QWeb.addDirective({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let key = node.getAttribute("t-key");
|
|
||||||
if (key) {
|
|
||||||
key = ctx.formatExpression(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
// computing the props string representing the props object
|
// computing the props string representing the props object
|
||||||
let propStr = Object.keys(props)
|
let propStr = Object.keys(props)
|
||||||
.map(k => k + ":" + props[k])
|
.map(k => k + ":" + props[k])
|
||||||
.join(",");
|
.join(",");
|
||||||
let defID = ctx.generateID();
|
let defID = ctx.generateID();
|
||||||
let componentID = ctx.generateID();
|
let componentID = ctx.generateID();
|
||||||
let keyID = key && ctx.generateID();
|
|
||||||
if (key) {
|
|
||||||
// we bind a variable to the key (could be a complex expression, so we
|
|
||||||
// want to evaluate it only once)
|
|
||||||
ctx.addLine(`let key${keyID} = 'key' + ${key};`);
|
|
||||||
}
|
|
||||||
|
|
||||||
let locationExpr = `\`__${ctx.generateID()}__`;
|
let locationExpr = `\`__${ctx.generateID()}__`;
|
||||||
for (let i = 0; i < ctx.loopNumber - 1; i++) {
|
for (let i = 0; i < ctx.loopNumber - 1; i++) {
|
||||||
locationExpr += `\${i${i + 1}}__`;
|
locationExpr += `\${i${i + 1}}__`;
|
||||||
}
|
}
|
||||||
if (key || ctx.currentKey) {
|
if (ctx.lastNodeKey || ctx.currentKey) {
|
||||||
const k = key ? `key${keyID}` : ctx.currentKey;
|
const k = ctx.lastNodeKey || ctx.currentKey;
|
||||||
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
|
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
|
||||||
} else {
|
} else {
|
||||||
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
|
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
|
||||||
@@ -267,8 +255,8 @@ QWeb.addDirective({
|
|||||||
if (transition) {
|
if (transition) {
|
||||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
||||||
}
|
}
|
||||||
let finalizeComponentCode = `w${componentID}.${keepAlive ? "unmount" : "destroy"}();`;
|
let finalizeComponentCode = `w${componentID}.destroy();`;
|
||||||
if (ref && !keepAlive) {
|
if (ref) {
|
||||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||||
}
|
}
|
||||||
if (transition) {
|
if (transition) {
|
||||||
@@ -349,11 +337,6 @@ QWeb.addDirective({
|
|||||||
`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;`
|
||||||
);
|
);
|
||||||
let shouldProxy = !ctx.parentNode;
|
let shouldProxy = !ctx.parentNode;
|
||||||
if (keepAlive) {
|
|
||||||
ctx.addLine(
|
|
||||||
`const fiber${componentID} = Object.assign(Object.create(extra.fiber), {patchQueue: []});`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (shouldProxy) {
|
if (shouldProxy) {
|
||||||
let id = ctx.generateID();
|
let id = ctx.generateID();
|
||||||
ctx.rootContext.rootNode = id;
|
ctx.rootContext.rootNode = id;
|
||||||
@@ -404,31 +387,15 @@ QWeb.addDirective({
|
|||||||
ctx.addIf(`w${componentID}`);
|
ctx.addIf(`w${componentID}`);
|
||||||
|
|
||||||
// need to update component
|
// 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 = "";
|
let styleCode = "";
|
||||||
if (tattStyle) {
|
if (tattStyle) {
|
||||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||||
}
|
}
|
||||||
ctx.addLine(
|
ctx.addLine(
|
||||||
`w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
|
`w${componentID}.__updateProps(props${componentID}, extra.fiber${scopeVars &&
|
||||||
", " + scopeVars}, sibling)${styleCode};`
|
", " + scopeVars}, sibling)${styleCode};`
|
||||||
);
|
);
|
||||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
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) {
|
if (registerCode) {
|
||||||
ctx.addLine(registerCode);
|
ctx.addLine(registerCode);
|
||||||
}
|
}
|
||||||
|
|||||||
+41
-14
@@ -1,5 +1,6 @@
|
|||||||
import { VNode } from "../vdom/index";
|
import { VNode } from "../vdom/index";
|
||||||
import { Component } from "./component";
|
import { Component } from "./component";
|
||||||
|
import { scheduler } from "./scheduler";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owl Fiber Class
|
* Owl Fiber Class
|
||||||
@@ -43,7 +44,6 @@ export class Fiber {
|
|||||||
|
|
||||||
scope: any;
|
scope: any;
|
||||||
vars: any;
|
vars: any;
|
||||||
props: any;
|
|
||||||
|
|
||||||
component: Component<any, any>;
|
component: Component<any, any>;
|
||||||
vnode: VNode | null = null;
|
vnode: VNode | null = null;
|
||||||
@@ -53,11 +53,12 @@ export class Fiber {
|
|||||||
sibling: Fiber | null = null;
|
sibling: Fiber | null = null;
|
||||||
parent: Fiber | null = null;
|
parent: Fiber | null = null;
|
||||||
|
|
||||||
constructor(parent: Fiber | null, component: Component<any, any>, props, scope, vars, force) {
|
error?: Error;
|
||||||
|
|
||||||
|
constructor(parent: Fiber | null, component: Component<any, any>, scope, vars, force) {
|
||||||
this.force = force;
|
this.force = force;
|
||||||
this.scope = scope;
|
this.scope = scope;
|
||||||
this.vars = vars;
|
this.vars = vars;
|
||||||
this.props = props;
|
|
||||||
this.component = component;
|
this.component = component;
|
||||||
|
|
||||||
this.root = parent ? parent.root : this;
|
this.root = parent ? parent.root : this;
|
||||||
@@ -146,7 +147,6 @@ export class Fiber {
|
|||||||
};
|
};
|
||||||
this._walk(doWork);
|
this._walk(doWork);
|
||||||
let component: Component<any, any> = this.component;
|
let component: Component<any, any> = this.component;
|
||||||
this.shouldPatch = false;
|
|
||||||
const patchLen = patchQueue.length;
|
const patchLen = patchQueue.length;
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < patchLen; i++) {
|
for (let i = 0; i < patchLen; i++) {
|
||||||
@@ -159,14 +159,10 @@ export class Fiber {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
}
|
}
|
||||||
try {
|
for (let i = 0; i < patchLen; i++) {
|
||||||
for (let i = 0; i < patchLen; i++) {
|
const fiber = patchQueue[i];
|
||||||
const fiber = patchQueue[i];
|
component = fiber.component;
|
||||||
component = fiber.component;
|
component.__patch(fiber.vnode);
|
||||||
component.__patch(fiber.vnode);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
this.handleError(e);
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
for (let i = patchLen - 1; i >= 0; i--) {
|
for (let i = patchLen - 1; i >= 0; i--) {
|
||||||
@@ -179,7 +175,6 @@ export class Fiber {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
}
|
}
|
||||||
this.shouldPatch = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -195,5 +190,37 @@ export class Fiber {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
handleError(e: Error) {}
|
/**
|
||||||
|
* This is the global error handler for errors occurring in Owl main lifecycle
|
||||||
|
* methods. Caught errors are triggered on the QWeb instance, and are
|
||||||
|
* potentially given to some parent component which implements `catchError`.
|
||||||
|
*
|
||||||
|
* If there are no such component, we destroy everything. This is better than
|
||||||
|
* being in a corrupted state.
|
||||||
|
*/
|
||||||
|
handleError(error: Error) {
|
||||||
|
let canCatch = false;
|
||||||
|
let component = this.component;
|
||||||
|
let qweb = component.env.qweb;
|
||||||
|
let root = component;
|
||||||
|
while (component && !(canCatch = !!component.catchError)) {
|
||||||
|
root = component;
|
||||||
|
component = component.__owl__.parent!;
|
||||||
|
}
|
||||||
|
qweb.trigger("error", error);
|
||||||
|
|
||||||
|
if (canCatch) {
|
||||||
|
setTimeout(() => {
|
||||||
|
console.error(error);
|
||||||
|
component.catchError!(error);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// the 3 next lines aim to mark the root fiber as being in error, and
|
||||||
|
// to force it to end, without waiting for its children
|
||||||
|
this.root.counter = 0;
|
||||||
|
this.root.error = error;
|
||||||
|
scheduler.flush();
|
||||||
|
root.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
|
|||||||
// optional prop
|
// optional prop
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!props[propName]) {
|
if (!(propName in props)) {
|
||||||
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { Fiber } from "./fiber";
|
|||||||
|
|
||||||
interface Task {
|
interface Task {
|
||||||
fiber: Fiber;
|
fiber: Fiber;
|
||||||
callback: () => void;
|
callback: (err?: Error) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Scheduler {
|
export class Scheduler {
|
||||||
@@ -45,7 +45,7 @@ export class Scheduler {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (task.fiber.counter === 0) {
|
if (task.fiber.counter === 0) {
|
||||||
task.callback();
|
task.callback(task.fiber.error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -65,3 +65,6 @@ export class Scheduler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const raf = window.requestAnimationFrame.bind(window);
|
||||||
|
export const scheduler = new Scheduler(raf);
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { QWeb } from "./qweb/index";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This file creates and exports the OWL 'config' object, with keys:
|
||||||
|
* - 'mode': 'prod' or 'dev',
|
||||||
|
* - 'env': the environment to use in root components.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Config {
|
||||||
|
mode: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {} as Config;
|
||||||
|
|
||||||
|
Object.defineProperty(config, "mode", {
|
||||||
|
get() {
|
||||||
|
return QWeb.dev ? "dev" : "prod";
|
||||||
|
},
|
||||||
|
set(mode: string) {
|
||||||
|
QWeb.dev = mode === "dev";
|
||||||
|
if (QWeb.dev) {
|
||||||
|
const url = `https://github.com/odoo/owl/blob/master/doc/reference/config.md#mode`;
|
||||||
|
console.warn(
|
||||||
|
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.log(`Owl is now running in 'prod' mode.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
+63
-31
@@ -1,4 +1,5 @@
|
|||||||
import { Component, scheduler } from "./component/component";
|
import { Component } from "./component/component";
|
||||||
|
import { scheduler } from "./component/scheduler";
|
||||||
import { EventBus } from "./core/event_bus";
|
import { EventBus } from "./core/event_bus";
|
||||||
import { Observer } from "./core/observer";
|
import { Observer } from "./core/observer";
|
||||||
import { onWillUnmount } from "./hooks";
|
import { onWillUnmount } from "./hooks";
|
||||||
@@ -12,6 +13,28 @@ import { onWillUnmount } from "./hooks";
|
|||||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
* With a `Context` object, each component can subscribe (with the `useContext`
|
||||||
* hook) to its state, and will be updated whenever the context state is updated.
|
* hook) to its state, and will be updated whenever the context state is updated.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
function partitionBy<T>(arr: T[], fn: (t: T) => boolean) {
|
||||||
|
let lastGroup: T[] | false = false;
|
||||||
|
let lastValue;
|
||||||
|
return arr.reduce((acc: T[][], cur) => {
|
||||||
|
let curVal = fn(cur);
|
||||||
|
if (lastGroup) {
|
||||||
|
if (curVal === lastValue) {
|
||||||
|
lastGroup.push(cur);
|
||||||
|
} else {
|
||||||
|
lastGroup = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lastGroup) {
|
||||||
|
lastGroup = [cur];
|
||||||
|
acc.push(lastGroup);
|
||||||
|
}
|
||||||
|
lastValue = curVal;
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
|
||||||
export class Context extends EventBus {
|
export class Context extends EventBus {
|
||||||
state: any;
|
state: any;
|
||||||
observer: Observer;
|
observer: Observer;
|
||||||
@@ -24,38 +47,47 @@ export class Context extends EventBus {
|
|||||||
this.observer = new Observer();
|
this.observer = new Observer();
|
||||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
||||||
this.state = this.observer.observe(state);
|
this.state = this.observer.observe(state);
|
||||||
|
this.subscriptions.update = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instead of using trigger to emit an update event, we actually implement
|
* Instead of using trigger to emit an update event, we actually implement
|
||||||
* our own function to do that. The reason is that we need to be smarter than
|
* our own function to do that. The reason is that we need to be smarter than
|
||||||
* a simple trigger function: we need to wait for parent components to be
|
* a simple trigger function: we need to wait for parent components to be
|
||||||
* done before doing children components. The reason is that if an update
|
* done before doing children components. More precisely, if an update
|
||||||
* as an effect of destroying a children, we do not want to call the
|
* as an effect of destroying a children, we do not want to call any code
|
||||||
* mapStoreToProps function of the child, nor rendering it.
|
* from the child, and certainly not render it.
|
||||||
*
|
*
|
||||||
* This method is not optimal if we have a bunch of asynchronous components:
|
* This method implements a simple grouping algorithm by depth. If we have
|
||||||
* we wait sequentially for each component to be completed before updating the
|
* connected components of depths [2, 4,4,4,4, 3,8,8], the Context will notify
|
||||||
* next. However, the only things that matters is that children are updated
|
* them in the following groups: [2], [4,4,4,4], [3], [8,8]. Each group will
|
||||||
* after their parents. So, this could be optimized by being smarter, and
|
* be updated sequentially, but each components in a given group will be done in
|
||||||
* updating all widgets concurrently, except for parents/children.
|
* parallel.
|
||||||
*
|
*
|
||||||
* A potential cheap way to improve this situation is to keep track of the
|
* This is a very simple algorithm, but it avoids checking if a given
|
||||||
* depth of a component in the component tree. A root component has a depth of
|
* component is a child of another.
|
||||||
* 1, then its children of 2 and so on... Then, we can update all components
|
|
||||||
* with the same depth in parallel.
|
|
||||||
*/
|
*/
|
||||||
async __notifyComponents() {
|
async __notifyComponents() {
|
||||||
const rev = ++this.rev;
|
const rev = ++this.rev;
|
||||||
const subs = this.subscriptions.update || [];
|
const subscriptions = this.subscriptions.update;
|
||||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
const groups = partitionBy(subscriptions, s => (s.owner ? s.owner.__owl__.depth : -1));
|
||||||
const sub = subs[i];
|
for (let group of groups) {
|
||||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
const proms = Promise.all(
|
||||||
if (shouldCallback) {
|
group.map(sub => {
|
||||||
const render = sub.callback.call(sub.owner, rev);
|
if (sub.owner ? sub.owner.__owl__.isMounted : true) {
|
||||||
scheduler.flush();
|
return sub.callback.call(sub.owner, rev);
|
||||||
await render;
|
}
|
||||||
}
|
})
|
||||||
|
);
|
||||||
|
// at this point, each component in the current group has registered a
|
||||||
|
// top level fiber in the scheduler. It could happen that rendering these
|
||||||
|
// components is done (if they have no children). This is why we manually
|
||||||
|
// flush the scheduler. This will force the scheduler to check
|
||||||
|
// immediately if they are done, which will cause their rendering
|
||||||
|
// promise to resolve earlier, which means that there is a chance of
|
||||||
|
// processing the next group in the same frame.
|
||||||
|
scheduler.flush();
|
||||||
|
await proms;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,15 +113,15 @@ export function useContextWithCB(ctx: Context, component: Component<any, any>, m
|
|||||||
__owl__.observer.notifyCB = component.render.bind(component);
|
__owl__.observer.notifyCB = component.render.bind(component);
|
||||||
}
|
}
|
||||||
const currentCB = __owl__.observer.notifyCB;
|
const currentCB = __owl__.observer.notifyCB;
|
||||||
__owl__.observer.notifyCB = function () {
|
__owl__.observer.notifyCB = function() {
|
||||||
if (ctx.rev > mapping[id]) {
|
if (ctx.rev > mapping[id]) {
|
||||||
// in this case, the context has been updated since we were rendering
|
// 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
|
// last, and we do not need to render here with the observer. A
|
||||||
// rendering is coming anyway, with the correct props.
|
// rendering is coming anyway, with the correct props.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
currentCB();
|
currentCB();
|
||||||
}
|
};
|
||||||
|
|
||||||
mapping[id] = 0;
|
mapping[id] = 0;
|
||||||
const renderFn = __owl__.renderFn;
|
const renderFn = __owl__.renderFn;
|
||||||
|
|||||||
@@ -46,10 +46,6 @@ export class Observer {
|
|||||||
const metadata = this.weakMap.get(value);
|
const metadata = this.weakMap.get(value);
|
||||||
return metadata ? metadata.rev : 0;
|
return metadata ? metadata.rev : 0;
|
||||||
}
|
}
|
||||||
deepRevNumber(value): number {
|
|
||||||
const metadata = this.weakMap.get(value);
|
|
||||||
return metadata ? metadata.deepRev : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
_observe(value, parent) {
|
_observe(value, parent) {
|
||||||
var self = this;
|
var self = this;
|
||||||
@@ -87,7 +83,6 @@ export class Observer {
|
|||||||
value,
|
value,
|
||||||
proxy,
|
proxy,
|
||||||
rev: this.rev,
|
rev: this.rev,
|
||||||
deepRev: this.rev,
|
|
||||||
parent
|
parent
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -99,11 +94,10 @@ export class Observer {
|
|||||||
_updateRevNumber(target: any) {
|
_updateRevNumber(target: any) {
|
||||||
this.rev++;
|
this.rev++;
|
||||||
let metadata = this.weakMap.get(target);
|
let metadata = this.weakMap.get(target);
|
||||||
metadata.rev!++;
|
|
||||||
let parent = target;
|
let parent = target;
|
||||||
do {
|
do {
|
||||||
metadata = this.weakMap.get(parent);
|
metadata = this.weakMap.get(parent);
|
||||||
metadata.deepRev++;
|
metadata.rev++;
|
||||||
} while ((parent = metadata.parent) && parent !== target);
|
} while ((parent = metadata.parent) && parent !== target);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-19
@@ -7,10 +7,11 @@
|
|||||||
import { EventBus } from "./core/event_bus";
|
import { EventBus } from "./core/event_bus";
|
||||||
import { Observer } from "./core/observer";
|
import { Observer } from "./core/observer";
|
||||||
import { QWeb } from "./qweb/index";
|
import { QWeb } from "./qweb/index";
|
||||||
|
import { config } from "./config";
|
||||||
import * as _store from "./store";
|
import * as _store from "./store";
|
||||||
import * as _utils from "./utils";
|
import * as _utils from "./utils";
|
||||||
import * as _tags from "./tags";
|
import * as _tags from "./tags";
|
||||||
import {AsyncRoot} from "./misc/async_root";
|
import { AsyncRoot } from "./misc/async_root";
|
||||||
import * as _hooks from "./hooks";
|
import * as _hooks from "./hooks";
|
||||||
import * as _context from "./context";
|
import * as _context from "./context";
|
||||||
import { Link } from "./router/link";
|
import { Link } from "./router/link";
|
||||||
@@ -19,6 +20,7 @@ import { Router } from "./router/router";
|
|||||||
|
|
||||||
export { Component } from "./component/component";
|
export { Component } from "./component/component";
|
||||||
export { QWeb };
|
export { QWeb };
|
||||||
|
export { config };
|
||||||
|
|
||||||
export const Context = _context.Context;
|
export const Context = _context.Context;
|
||||||
export const useState = _hooks.useState;
|
export const useState = _hooks.useState;
|
||||||
@@ -27,7 +29,7 @@ export const router = { Router, RouteComponent, Link };
|
|||||||
export const Store = _store.Store;
|
export const Store = _store.Store;
|
||||||
export const utils = _utils;
|
export const utils = _utils;
|
||||||
export const tags = _tags;
|
export const tags = _tags;
|
||||||
export const misc = { AsyncRoot};
|
export const misc = { AsyncRoot };
|
||||||
export const hooks = Object.assign({}, _hooks, {
|
export const hooks = Object.assign({}, _hooks, {
|
||||||
useContext: _context.useContext,
|
useContext: _context.useContext,
|
||||||
useDispatch: _store.useDispatch,
|
useDispatch: _store.useDispatch,
|
||||||
@@ -35,20 +37,3 @@ export const hooks = Object.assign({}, _hooks, {
|
|||||||
useStore: _store.useStore
|
useStore: _store.useStore
|
||||||
});
|
});
|
||||||
export const __info__ = {};
|
export const __info__ = {};
|
||||||
|
|
||||||
Object.defineProperty(__info__, "mode", {
|
|
||||||
get() {
|
|
||||||
return QWeb.dev ? "dev" : "prod";
|
|
||||||
},
|
|
||||||
set(mode: string) {
|
|
||||||
QWeb.dev = mode === "dev";
|
|
||||||
if (QWeb.dev) {
|
|
||||||
const url = `https://github.com/odoo/owl/blob/master/doc/tooling.md#development-mode`;
|
|
||||||
console.warn(
|
|
||||||
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
console.log(`Owl is now running in 'prod' mode.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -294,25 +294,17 @@ QWeb.addDirective({
|
|||||||
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
|
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
|
||||||
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
|
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
|
||||||
const nodeCopy = <Element>node.cloneNode(true);
|
const nodeCopy = <Element>node.cloneNode(true);
|
||||||
let shouldWarn = nodeCopy.tagName !== "t" && !nodeCopy.hasAttribute("t-key");
|
let shouldWarn =
|
||||||
if (!shouldWarn && node.tagName === "t") {
|
!nodeCopy.hasAttribute("t-key") &&
|
||||||
if (node.hasAttribute("t-component") && !node.hasAttribute("t-key")) {
|
node.children.length === 1 &&
|
||||||
shouldWarn = true;
|
node.children[0].tagName !== "t" &&
|
||||||
}
|
!node.children[0].hasAttribute("t-key");
|
||||||
if (
|
|
||||||
!shouldWarn &&
|
|
||||||
node.children.length === 1 &&
|
|
||||||
node.children[0].tagName !== "t" &&
|
|
||||||
!node.children[0].hasAttribute("t-key")
|
|
||||||
) {
|
|
||||||
shouldWarn = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (shouldWarn) {
|
if (shouldWarn) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
nodeCopy.removeAttribute("t-foreach");
|
nodeCopy.removeAttribute("t-foreach");
|
||||||
qweb._compileNode(nodeCopy, ctx);
|
qweb._compileNode(nodeCopy, ctx);
|
||||||
ctx.dedent();
|
ctx.dedent();
|
||||||
|
|||||||
+16
-1
@@ -58,7 +58,9 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
|
||||||
} else {
|
} else {
|
||||||
const handlerKey = `handler${ctx.generateID()}`;
|
const handlerKey = `handler${ctx.generateID()}`;
|
||||||
ctx.addLine(`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`);
|
ctx.addLine(
|
||||||
|
`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`
|
||||||
|
);
|
||||||
handler += `if (${handlerKey}) { ${handlerKey}(e); } else { context.${value}; }`;
|
handler += `if (${handlerKey}) { ${handlerKey}(e); } else { context.${value}; }`;
|
||||||
handler += `}`;
|
handler += `}`;
|
||||||
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
|
||||||
@@ -259,3 +261,16 @@ QWeb.addDirective({
|
|||||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
|
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// t-key
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
QWeb.addDirective({
|
||||||
|
name: "key",
|
||||||
|
priority: 45,
|
||||||
|
atNodeEncounter({ ctx, value }) {
|
||||||
|
let id = ctx.generateID();
|
||||||
|
ctx.addLine(`const nodeKey${id} = ${ctx.formatExpression(value)};`);
|
||||||
|
ctx.lastNodeKey = `nodeKey${id}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
+27
-13
@@ -57,12 +57,19 @@ export interface Directive {
|
|||||||
finalize?(info: CompilationInfo): void;
|
finalize?(info: CompilationInfo): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface QWebConfig {
|
||||||
|
templates?: string;
|
||||||
|
translateFn?(text: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Const/global stuff/helpers
|
// Const/global stuff/helpers
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
|
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
|
||||||
|
|
||||||
|
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
|
||||||
|
|
||||||
const lineBreakRE = /[\r\n]/;
|
const lineBreakRE = /[\r\n]/;
|
||||||
const whitespaceRE = /\s+/g;
|
const whitespaceRE = /\s+/g;
|
||||||
|
|
||||||
@@ -134,6 +141,7 @@ function parseXML(xml: string): Document {
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// QWeb rendering engine
|
// QWeb rendering engine
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
|
|
||||||
export class QWeb extends EventBus {
|
export class QWeb extends EventBus {
|
||||||
templates: { [name: string]: Template };
|
templates: { [name: string]: Template };
|
||||||
static utils = UTILS;
|
static utils = UTILS;
|
||||||
@@ -143,7 +151,7 @@ export class QWeb extends EventBus {
|
|||||||
name: 1,
|
name: 1,
|
||||||
att: 1,
|
att: 1,
|
||||||
attf: 1,
|
attf: 1,
|
||||||
key: 1
|
translation: 1
|
||||||
};
|
};
|
||||||
static DIRECTIVES: Directive[] = [];
|
static DIRECTIVES: Directive[] = [];
|
||||||
|
|
||||||
@@ -166,12 +174,16 @@ export class QWeb extends EventBus {
|
|||||||
recursiveFns = {};
|
recursiveFns = {};
|
||||||
|
|
||||||
isUpdating: boolean = false;
|
isUpdating: boolean = false;
|
||||||
|
translateFn?: QWebConfig["translateFn"];
|
||||||
|
|
||||||
constructor(data?: string) {
|
constructor(config: QWebConfig = {}) {
|
||||||
super();
|
super();
|
||||||
this.templates = Object.create(QWeb.TEMPLATES);
|
this.templates = Object.create(QWeb.TEMPLATES);
|
||||||
if (data) {
|
if (config.templates) {
|
||||||
this.addTemplates(data);
|
this.addTemplates(config.templates);
|
||||||
|
}
|
||||||
|
if (config.translateFn) {
|
||||||
|
this.translateFn = config.translateFn;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,6 +430,11 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
text = text.replace(whitespaceRE, " ");
|
text = text.replace(whitespaceRE, " ");
|
||||||
}
|
}
|
||||||
|
if (this.translateFn) {
|
||||||
|
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
|
||||||
|
text = this.translateFn(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (ctx.parentNode) {
|
if (ctx.parentNode) {
|
||||||
if (node.nodeType === 3) {
|
if (node.nodeType === 3) {
|
||||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||||
@@ -617,7 +634,11 @@ export class QWeb extends EventBus {
|
|||||||
|
|
||||||
for (let i = 0; i < attributes.length; i++) {
|
for (let i = 0; i < attributes.length; i++) {
|
||||||
let name = attributes[i].name;
|
let name = attributes[i].name;
|
||||||
const value = attributes[i].textContent!;
|
let value = attributes[i].textContent!;
|
||||||
|
|
||||||
|
if (this.translateFn && TRANSLATABLE_ATTRS.includes(name)) {
|
||||||
|
value = this.translateFn(value);
|
||||||
|
}
|
||||||
|
|
||||||
// regular attributes
|
// regular attributes
|
||||||
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
|
||||||
@@ -703,14 +724,7 @@ export class QWeb extends EventBus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let nodeID = ctx.generateID();
|
let nodeID = ctx.generateID();
|
||||||
let nodeKey: any = (<Element>node).getAttribute("t-key");
|
let nodeKey = ctx.lastNodeKey || nodeID;
|
||||||
if (nodeKey) {
|
|
||||||
ctx.addLine(`const nodeKey${nodeID} = ${ctx.formatExpression(nodeKey)}`);
|
|
||||||
nodeKey = `nodeKey${nodeID}`;
|
|
||||||
ctx.lastNodeKey = nodeKey;
|
|
||||||
} else {
|
|
||||||
nodeKey = nodeID;
|
|
||||||
}
|
|
||||||
const parts = [`key:${nodeKey}`];
|
const parts = [`key:${nodeKey}`];
|
||||||
if (attrs.length + tattrs.length > 0) {
|
if (attrs.length + tattrs.length > 0) {
|
||||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
parts.push(`attrs:{${attrs.join(",")}}`);
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ export class Router {
|
|||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
private setUrlFromPath(path: string) {
|
private setUrlFromPath(path: string) {
|
||||||
const separator = this.mode === "hash" ? "/" : "";
|
const separator = this.mode === "hash" ? location.pathname : "";
|
||||||
const url = location.origin + separator + path;
|
const url = location.origin + separator + path;
|
||||||
if (url !== window.location.href) {
|
if (url !== window.location.href) {
|
||||||
window.history.pushState({}, path, url);
|
window.history.pushState({}, path, url);
|
||||||
|
|||||||
+1
-2
@@ -85,7 +85,7 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
|||||||
const component: Component<any, any> = Component.current!;
|
const component: Component<any, any> = Component.current!;
|
||||||
const store = options.store || (component.env.store as Store);
|
const store = options.store || (component.env.store as Store);
|
||||||
let result = selector(store.state, component.props);
|
let result = selector(store.state, component.props);
|
||||||
const hashFn = store.observer.deepRevNumber.bind(store.observer);
|
const hashFn = store.observer.revNumber.bind(store.observer);
|
||||||
let revNumber = hashFn(result) || result;
|
let revNumber = hashFn(result) || result;
|
||||||
const isEqual = options.isEqual || isStrictEqual;
|
const isEqual = options.isEqual || isStrictEqual;
|
||||||
if (!store.updateFunctions[component.__owl__.id]) {
|
if (!store.updateFunctions[component.__owl__.id]) {
|
||||||
@@ -116,7 +116,6 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
onWillUpdateProps(props => {
|
onWillUpdateProps(props => {
|
||||||
// FIXME: only do that if not keepalive + do it in destroy in that case
|
|
||||||
delete store.updateFunctions[component.__owl__.id];
|
delete store.updateFunctions[component.__owl__.id];
|
||||||
result = selector(store.state, props);
|
result = selector(store.state, props);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ let cssEl: HTMLElement;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
qweb = new QWeb();
|
qweb = new QWeb();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -108,7 +109,7 @@ describe("animations", () => {
|
|||||||
class TestWidget extends Widget {
|
class TestWidget extends Widget {
|
||||||
state = useState({ hide: false });
|
state = useState({ hide: false });
|
||||||
}
|
}
|
||||||
const widget = new TestWidget(env);
|
const widget = new TestWidget();
|
||||||
|
|
||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
@@ -151,7 +152,7 @@ describe("animations", () => {
|
|||||||
state = useState({ hide: false });
|
state = useState({ hide: false });
|
||||||
span = useRef("span");
|
span = useRef("span");
|
||||||
}
|
}
|
||||||
const widget = new TestWidget(env);
|
const widget = new TestWidget();
|
||||||
|
|
||||||
// insert widget into the DOM
|
// insert widget into the DOM
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
@@ -180,7 +181,7 @@ describe("animations", () => {
|
|||||||
class Parent extends Widget {
|
class Parent extends Widget {
|
||||||
static components = { Child: Child };
|
static components = { Child: Child };
|
||||||
}
|
}
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
@@ -220,7 +221,7 @@ describe("animations", () => {
|
|||||||
static components = { Child: Child };
|
static components = { Child: Child };
|
||||||
state = useState({ display: true });
|
state = useState({ display: true });
|
||||||
}
|
}
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
|
|
||||||
let def = makeDeferred();
|
let def = makeDeferred();
|
||||||
var spanNode;
|
var spanNode;
|
||||||
@@ -283,7 +284,7 @@ describe("animations", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
await widget.mount(fixture);
|
await widget.mount(fixture);
|
||||||
let button = widget.el!.querySelector("button");
|
let button = widget.el!.querySelector("button");
|
||||||
|
|
||||||
@@ -341,7 +342,7 @@ describe("animations", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const widget = new Parent(env);
|
const widget = new Parent();
|
||||||
await widget.mount(fixture);
|
await widget.mount(fixture);
|
||||||
let button = widget.el!.querySelector("button");
|
let button = widget.el!.querySelector("button");
|
||||||
|
|
||||||
|
|||||||
@@ -234,51 +234,6 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`composition sub components dom state with t-keepalive is preserved 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let QWeb = this.constructor;
|
|
||||||
let parent = context;
|
|
||||||
let owner = context;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('div', p1, c1);
|
|
||||||
if (context['state'].ok) {
|
|
||||||
//COMPONENT
|
|
||||||
let templateId3 = \`__4__\`;
|
|
||||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
|
||||||
const fiber3 = Object.assign(Object.create(extra.fiber), {patchQueue: []});
|
|
||||||
let props3 = {};
|
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
|
||||||
w3.destroy();
|
|
||||||
w3 = false;
|
|
||||||
}
|
|
||||||
if (w3) {
|
|
||||||
w3.__updateProps(props3, w3.__owl__.isMounted ? extra.fiber : fiber3, undefined, undefined, sibling);
|
|
||||||
let pvnode = w3.__owl__.pvnode;
|
|
||||||
pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w3.el,vn.elm);vn.elm=w3.el;w3.__remount();};
|
|
||||||
c1.push(pvnode);
|
|
||||||
} else {
|
|
||||||
let componentKey3 = \`InputWidget\`;
|
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['InputWidget'];
|
|
||||||
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.unmount();}}});
|
|
||||||
const fiber = w3.__owl__.currentFiber;
|
|
||||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
|
||||||
c1.push(pvnode);
|
|
||||||
w3.__owl__.pvnode = pvnode;
|
|
||||||
}
|
|
||||||
sibling = w3.__owl__.currentFiber || sibling;
|
|
||||||
}
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
exports[`composition sub components with some state rendered in a loop 1`] = `
|
exports[`composition sub components with some state rendered in a loop 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context,extra
|
||||||
) {
|
) {
|
||||||
@@ -305,33 +260,33 @@ exports[`composition sub components with some state rendered in a loop 1`] = `
|
|||||||
context.number_index = i1;
|
context.number_index = i1;
|
||||||
context.number = _3[i1];
|
context.number = _3[i1];
|
||||||
context.number_value = _4[i1];
|
context.number_value = _4[i1];
|
||||||
|
const nodeKey5 = context['number'];
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let key7 = 'key' + context['number'];
|
let templateId7 = \`__8__\` + nodeKey5;
|
||||||
let templateId6 = \`__8__\` + key7;
|
let w7 = templateId7 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId7]] : false;
|
||||||
let w6 = templateId6 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId6]] : false;
|
let props7 = {};
|
||||||
let props6 = {};
|
if (w7 && w7.__owl__.currentFiber && !w7.__owl__.vnode) {
|
||||||
if (w6 && w6.__owl__.currentFiber && !w6.__owl__.vnode) {
|
w7.destroy();
|
||||||
w6.destroy();
|
w7 = false;
|
||||||
w6 = false;
|
|
||||||
}
|
}
|
||||||
if (w6) {
|
if (w7) {
|
||||||
w6.__updateProps(props6, extra.fiber, undefined, undefined, sibling);
|
w7.__updateProps(props7, extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = w6.__owl__.pvnode;
|
let pvnode = w7.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey6 = \`ChildWidget\`;
|
let componentKey7 = \`ChildWidget\`;
|
||||||
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| context['ChildWidget'];
|
let W7 = context.constructor.components[componentKey7] || QWeb.components[componentKey7]|| context['ChildWidget'];
|
||||||
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
if (!W7) {throw new Error('Cannot find the definition of component \\"' + componentKey7 + '\\"')}
|
||||||
w6 = new W6(parent, props6);
|
w7 = new W7(parent, props7);
|
||||||
parent.__owl__.cmap[templateId6] = w6.__owl__.id;
|
parent.__owl__.cmap[templateId7] = w7.__owl__.id;
|
||||||
let def5 = w6.__prepare(extra.fiber, undefined, undefined, sibling);
|
let def6 = w7.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = h('dummy', {key: templateId6, hook: {insert(vn) { let nvn=w6.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w6.destroy();}}});
|
let pvnode = h('dummy', {key: templateId7, hook: {insert(vn) { let nvn=w7.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w7.destroy();}}});
|
||||||
const fiber = w6.__owl__.currentFiber;
|
const fiber = w7.__owl__.currentFiber;
|
||||||
def5.then(function () {if (w6.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
def6.then(function () {if (w7.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w6.__owl__.pvnode = pvnode;
|
w7.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w6.__owl__.currentFiber || sibling;
|
sibling = w7.__owl__.currentFiber || sibling;
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -460,51 +415,6 @@ exports[`dynamic t-props basic use 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`lifecycle hooks willPatch/patched hook with t-keepalive 1`] = `
|
|
||||||
"function anonymous(context,extra
|
|
||||||
) {
|
|
||||||
let utils = this.constructor.utils;
|
|
||||||
let QWeb = this.constructor;
|
|
||||||
let parent = context;
|
|
||||||
let owner = context;
|
|
||||||
let sibling = null;
|
|
||||||
var h = this.h;
|
|
||||||
let c1 = [], p1 = {key:1};
|
|
||||||
var vn1 = h('div', p1, c1);
|
|
||||||
if (context['state'].flag) {
|
|
||||||
//COMPONENT
|
|
||||||
let templateId3 = \`__4__\`;
|
|
||||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
|
||||||
const fiber3 = Object.assign(Object.create(extra.fiber), {patchQueue: []});
|
|
||||||
let props3 = {v:context['state'].n};
|
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
|
||||||
w3.destroy();
|
|
||||||
w3 = false;
|
|
||||||
}
|
|
||||||
if (w3) {
|
|
||||||
w3.__updateProps(props3, w3.__owl__.isMounted ? extra.fiber : fiber3, undefined, undefined, sibling);
|
|
||||||
let pvnode = w3.__owl__.pvnode;
|
|
||||||
pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w3.el,vn.elm);vn.elm=w3.el;w3.__remount();};
|
|
||||||
c1.push(pvnode);
|
|
||||||
} else {
|
|
||||||
let componentKey3 = \`ChildWidget\`;
|
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['ChildWidget'];
|
|
||||||
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.unmount();}}});
|
|
||||||
const fiber = w3.__owl__.currentFiber;
|
|
||||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
|
||||||
c1.push(pvnode);
|
|
||||||
w3.__owl__.pvnode = pvnode;
|
|
||||||
}
|
|
||||||
sibling = w3.__owl__.currentFiber || sibling;
|
|
||||||
}
|
|
||||||
return vn1;
|
|
||||||
}"
|
|
||||||
`;
|
|
||||||
|
|
||||||
exports[`other directives with t-component t-on with getter as handler 1`] = `
|
exports[`other directives with t-component t-on with getter as handler 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context,extra
|
||||||
) {
|
) {
|
||||||
@@ -993,33 +903,33 @@ exports[`random stuff/miscellaneous snapshotting compiled code 1`] = `
|
|||||||
var h = this.h;
|
var h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('div', p1, c1);
|
var vn1 = h('div', p1, c1);
|
||||||
|
const nodeKey2 = 'somestring';
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let key4 = 'key' + 'somestring';
|
let templateId4 = \`__5__\` + nodeKey2;
|
||||||
let templateId3 = \`__5__\` + key4;
|
let w4 = templateId4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId4]] : false;
|
||||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
let props4 = {flag:context['state'].flag};
|
||||||
let props3 = {flag:context['state'].flag};
|
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
|
||||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
w4.destroy();
|
||||||
w3.destroy();
|
w4 = false;
|
||||||
w3 = false;
|
|
||||||
}
|
}
|
||||||
if (w3) {
|
if (w4) {
|
||||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
w4.__updateProps(props4, extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = w3.__owl__.pvnode;
|
let pvnode = w4.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey3 = \`child\`;
|
let componentKey4 = \`child\`;
|
||||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['child'];
|
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| context['child'];
|
||||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
|
||||||
w3 = new W3(parent, props3);
|
w4 = new W4(parent, props4);
|
||||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
parent.__owl__.cmap[templateId4] = w4.__owl__.id;
|
||||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
let def3 = w4.__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();}}});
|
let pvnode = h('dummy', {key: templateId4, hook: {insert(vn) { let nvn=w4.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});
|
||||||
const fiber = w3.__owl__.currentFiber;
|
const fiber = w4.__owl__.currentFiber;
|
||||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
def3.then(function () {if (w4.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w3.__owl__.pvnode = pvnode;
|
w4.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w3.__owl__.currentFiber || sibling;
|
sibling = w4.__owl__.currentFiber || sibling;
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
@@ -1036,7 +946,7 @@ exports[`random stuff/miscellaneous t-on with handler bound to dynamic argument
|
|||||||
var h = this.h;
|
var h = this.h;
|
||||||
let c1 = [], p1 = {key:1};
|
let c1 = [], p1 = {key:1};
|
||||||
var vn1 = h('div', p1, c1);
|
var vn1 = h('div', p1, c1);
|
||||||
var _2 = context['props'].items;
|
var _2 = context['items'];
|
||||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||||
var _3 = _4 = _2;
|
var _3 = _4 = _2;
|
||||||
if (!(_2 instanceof Array)) {
|
if (!(_2 instanceof Array)) {
|
||||||
@@ -1050,34 +960,34 @@ exports[`random stuff/miscellaneous t-on with handler bound to dynamic argument
|
|||||||
context.item_index = i1;
|
context.item_index = i1;
|
||||||
context.item = _3[i1];
|
context.item = _3[i1];
|
||||||
context.item_value = _4[i1];
|
context.item_value = _4[i1];
|
||||||
|
const nodeKey5 = context['item'];
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let key7 = 'key' + context['item'];
|
let templateId7 = \`__8__\` + nodeKey5;
|
||||||
let templateId6 = \`__8__\` + key7;
|
|
||||||
let arg9 = context['item'];
|
let arg9 = context['item'];
|
||||||
let w6 = templateId6 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId6]] : false;
|
let w7 = templateId7 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId7]] : false;
|
||||||
let props6 = {};
|
let props7 = {};
|
||||||
if (w6 && w6.__owl__.currentFiber && !w6.__owl__.vnode) {
|
if (w7 && w7.__owl__.currentFiber && !w7.__owl__.vnode) {
|
||||||
w6.destroy();
|
w7.destroy();
|
||||||
w6 = false;
|
w7 = false;
|
||||||
}
|
}
|
||||||
if (w6) {
|
if (w7) {
|
||||||
w6.__updateProps(props6, extra.fiber, undefined, undefined, sibling);
|
w7.__updateProps(props7, extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = w6.__owl__.pvnode;
|
let pvnode = w7.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey6 = \`Child\`;
|
let componentKey7 = \`Child\`;
|
||||||
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| context['Child'];
|
let W7 = context.constructor.components[componentKey7] || QWeb.components[componentKey7]|| context['Child'];
|
||||||
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
|
if (!W7) {throw new Error('Cannot find the definition of component \\"' + componentKey7 + '\\"')}
|
||||||
w6 = new W6(parent, props6);
|
w7 = new W7(parent, props7);
|
||||||
parent.__owl__.cmap[templateId6] = w6.__owl__.id;
|
parent.__owl__.cmap[templateId7] = w7.__owl__.id;
|
||||||
let def5 = w6.__prepare(extra.fiber, undefined, undefined, sibling);
|
let def6 = w7.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = h('dummy', {key: templateId6, hook: {insert(vn) { let nvn=w6.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w6.destroy();}}});
|
let pvnode = h('dummy', {key: templateId7, hook: {insert(vn) { let nvn=w7.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w7.destroy();}}});
|
||||||
const fiber = w6.__owl__.currentFiber;
|
const fiber = w7.__owl__.currentFiber;
|
||||||
def5.then(function () {if (w6.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {const fn = owner['onEv'];if (fn) { fn.call(owner, arg9, e); } else { owner.onEv; }});}};});
|
def6.then(function () {if (w7.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {const fn = owner['onEv'];if (fn) { fn.call(owner, arg9, e); } else { owner.onEv; }});}};});
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
w6.__owl__.pvnode = pvnode;
|
w7.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w6.__owl__.currentFiber || sibling;
|
sibling = w7.__owl__.currentFiber || sibling;
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -1541,37 +1451,37 @@ exports[`t-slot directive slots are rendered with proper context, part 2 2`] = `
|
|||||||
scope.user = context.user;
|
scope.user = context.user;
|
||||||
context.user_value = _5[i1];
|
context.user_value = _5[i1];
|
||||||
scope.user_value = context.user_value;
|
scope.user_value = context.user_value;
|
||||||
const nodeKey6 = context['user'].id
|
const nodeKey6 = context['user'].id;
|
||||||
let c6 = [], p6 = {key:nodeKey6};
|
let c7 = [], p7 = {key:nodeKey6};
|
||||||
var vn6 = h('li', p6, c6);
|
var vn7 = h('li', p7, c7);
|
||||||
c2.push(vn6);
|
c2.push(vn7);
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let templateId8 = \`__9__\` + nodeKey6;
|
let templateId9 = \`__10__\` + nodeKey6;
|
||||||
let w8 = templateId8 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId8]] : false;
|
let w9 = templateId9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId9]] : false;
|
||||||
let props8 = {to:'/user/'+context['user'].id};
|
let props9 = {to:'/user/'+context['user'].id};
|
||||||
if (w8 && w8.__owl__.currentFiber && !w8.__owl__.vnode) {
|
if (w9 && w9.__owl__.currentFiber && !w9.__owl__.vnode) {
|
||||||
w8.destroy();
|
w9.destroy();
|
||||||
w8 = false;
|
w9 = false;
|
||||||
}
|
}
|
||||||
if (w8) {
|
if (w9) {
|
||||||
w8.__updateProps(props8, extra.fiber, Object.assign({}, scope), undefined, sibling);
|
w9.__updateProps(props9, extra.fiber, Object.assign({}, scope), undefined, sibling);
|
||||||
let pvnode = w8.__owl__.pvnode;
|
let pvnode = w9.__owl__.pvnode;
|
||||||
c6.push(pvnode);
|
c7.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey8 = \`Link\`;
|
let componentKey9 = \`Link\`;
|
||||||
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| context['Link'];
|
let W9 = context.constructor.components[componentKey9] || QWeb.components[componentKey9]|| context['Link'];
|
||||||
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
if (!W9) {throw new Error('Cannot find the definition of component \\"' + componentKey9 + '\\"')}
|
||||||
w8 = new W8(parent, props8);
|
w9 = new W9(parent, props9);
|
||||||
parent.__owl__.cmap[templateId8] = w8.__owl__.id;
|
parent.__owl__.cmap[templateId9] = w9.__owl__.id;
|
||||||
w8.__owl__.slotId = 1;
|
w9.__owl__.slotId = 1;
|
||||||
let def7 = w8.__prepare(extra.fiber, Object.assign({}, scope), undefined, sibling);
|
let def8 = w9.__prepare(extra.fiber, Object.assign({}, scope), undefined, sibling);
|
||||||
let pvnode = h('dummy', {key: templateId8, hook: {insert(vn) { let nvn=w8.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w8.destroy();}}});
|
let pvnode = h('dummy', {key: templateId9, hook: {insert(vn) { let nvn=w9.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w9.destroy();}}});
|
||||||
const fiber = w8.__owl__.currentFiber;
|
const fiber = w9.__owl__.currentFiber;
|
||||||
def7.then(function () {if (w8.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
def8.then(function () {if (w9.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
c6.push(pvnode);
|
c7.push(pvnode);
|
||||||
w8.__owl__.pvnode = pvnode;
|
w9.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w8.__owl__.currentFiber || sibling;
|
sibling = w9.__owl__.currentFiber || sibling;
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -1582,12 +1492,12 @@ exports[`t-slot directive slots are rendered with proper context, part 2 3`] = `
|
|||||||
) {
|
) {
|
||||||
let sibling = null;
|
let sibling = null;
|
||||||
var h = this.h;
|
var h = this.h;
|
||||||
let c6 = extra.parentNode;
|
let c7 = extra.parentNode;
|
||||||
Object.assign(context, extra.fiber.scope);
|
Object.assign(context, extra.fiber.scope);
|
||||||
c6.push({text: \`User \`});
|
c7.push({text: \`User \`});
|
||||||
var _11 = context['user'].name;
|
var _12 = context['user'].name;
|
||||||
if (_11 || _11 === 0) {
|
if (_12 || _12 === 0) {
|
||||||
c6.push({text: _11});
|
c7.push({text: _12});
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
@@ -1644,38 +1554,38 @@ exports[`t-slot directive slots are rendered with proper context, part 3 2`] = `
|
|||||||
scope.user = context.user;
|
scope.user = context.user;
|
||||||
context.user_value = _5[i1];
|
context.user_value = _5[i1];
|
||||||
scope.user_value = context.user_value;
|
scope.user_value = context.user_value;
|
||||||
const nodeKey6 = context['user'].id
|
const nodeKey6 = context['user'].id;
|
||||||
let c6 = [], p6 = {key:nodeKey6};
|
let c7 = [], p7 = {key:nodeKey6};
|
||||||
var vn6 = h('li', p6, c6);
|
var vn7 = h('li', p7, c7);
|
||||||
c2.push(vn6);
|
c2.push(vn7);
|
||||||
var _7 = 'User '+context['user'].name;
|
var _8 = 'User '+context['user'].name;
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let templateId9 = \`__10__\` + nodeKey6;
|
let templateId10 = \`__11__\` + nodeKey6;
|
||||||
let w9 = templateId9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId9]] : false;
|
let w10 = templateId10 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId10]] : false;
|
||||||
let props9 = {to:'/user/'+context['user'].id};
|
let props10 = {to:'/user/'+context['user'].id};
|
||||||
if (w9 && w9.__owl__.currentFiber && !w9.__owl__.vnode) {
|
if (w10 && w10.__owl__.currentFiber && !w10.__owl__.vnode) {
|
||||||
w9.destroy();
|
w10.destroy();
|
||||||
w9 = false;
|
w10 = false;
|
||||||
}
|
}
|
||||||
if (w9) {
|
if (w10) {
|
||||||
w9.__updateProps(props9, extra.fiber, Object.assign({}, scope), {_7}, sibling);
|
w10.__updateProps(props10, extra.fiber, Object.assign({}, scope), {_8}, sibling);
|
||||||
let pvnode = w9.__owl__.pvnode;
|
let pvnode = w10.__owl__.pvnode;
|
||||||
c6.push(pvnode);
|
c7.push(pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey9 = \`Link\`;
|
let componentKey10 = \`Link\`;
|
||||||
let W9 = context.constructor.components[componentKey9] || QWeb.components[componentKey9]|| context['Link'];
|
let W10 = context.constructor.components[componentKey10] || QWeb.components[componentKey10]|| context['Link'];
|
||||||
if (!W9) {throw new Error('Cannot find the definition of component \\"' + componentKey9 + '\\"')}
|
if (!W10) {throw new Error('Cannot find the definition of component \\"' + componentKey10 + '\\"')}
|
||||||
w9 = new W9(parent, props9);
|
w10 = new W10(parent, props10);
|
||||||
parent.__owl__.cmap[templateId9] = w9.__owl__.id;
|
parent.__owl__.cmap[templateId10] = w10.__owl__.id;
|
||||||
w9.__owl__.slotId = 1;
|
w10.__owl__.slotId = 1;
|
||||||
let def8 = w9.__prepare(extra.fiber, Object.assign({}, scope), {_7}, sibling);
|
let def9 = w10.__prepare(extra.fiber, Object.assign({}, scope), {_8}, sibling);
|
||||||
let pvnode = h('dummy', {key: templateId9, hook: {insert(vn) { let nvn=w9.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w9.destroy();}}});
|
let pvnode = h('dummy', {key: templateId10, hook: {insert(vn) { let nvn=w10.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w10.destroy();}}});
|
||||||
const fiber = w9.__owl__.currentFiber;
|
const fiber = w10.__owl__.currentFiber;
|
||||||
def8.then(function () {if (w9.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
def9.then(function () {if (w10.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
c6.push(pvnode);
|
c7.push(pvnode);
|
||||||
w9.__owl__.pvnode = pvnode;
|
w10.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w9.__owl__.currentFiber || sibling;
|
sibling = w10.__owl__.currentFiber || sibling;
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -1686,11 +1596,11 @@ exports[`t-slot directive slots are rendered with proper context, part 3 3`] = `
|
|||||||
) {
|
) {
|
||||||
let sibling = null;
|
let sibling = null;
|
||||||
var h = this.h;
|
var h = this.h;
|
||||||
let c6 = extra.parentNode;
|
let c7 = extra.parentNode;
|
||||||
let _7 = extra.fiber.vars._7
|
let _8 = extra.fiber.vars._8
|
||||||
Object.assign(context, extra.fiber.scope);
|
Object.assign(context, extra.fiber.scope);
|
||||||
if (_7 || _7 === 0) {
|
if (_8 || _8 === 0) {
|
||||||
c6.push({text: _7});
|
c7.push({text: _8});
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
|
|||||||
w3 = false;
|
w3 = false;
|
||||||
}
|
}
|
||||||
if (w3) {
|
if (w3) {
|
||||||
utils.validateProps(w3.constructor, props3)
|
|
||||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = w3.__owl__.pvnode;
|
let pvnode = w3.__owl__.pvnode;
|
||||||
c1.push(pvnode);
|
c1.push(pvnode);
|
||||||
|
|||||||
+427
-355
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@ let dev: boolean = false;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
dev = QWeb.dev;
|
dev = QWeb.dev;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
});
|
});
|
||||||
@@ -35,17 +36,32 @@ describe("props validation", () => {
|
|||||||
static props = ["message"];
|
static props = ["message"];
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
}
|
}
|
||||||
|
class Parent extends Widget {
|
||||||
|
static components = { TestWidget };
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let error;
|
||||||
QWeb.dev = true;
|
QWeb.dev = true;
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env);
|
const p = new Parent();
|
||||||
}).toThrow();
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
|
||||||
QWeb.dev = false;
|
QWeb.dev = false;
|
||||||
|
try {
|
||||||
expect(() => {
|
const p = new Parent();
|
||||||
new TestWidget(env);
|
await p.mount(fixture);
|
||||||
}).not.toThrow();
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("props: list of strings", async () => {
|
test("props: list of strings", async () => {
|
||||||
@@ -53,10 +69,20 @@ describe("props validation", () => {
|
|||||||
static props = ["message"];
|
static props = ["message"];
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
}
|
}
|
||||||
|
class Parent extends Widget {
|
||||||
|
static components = { TestWidget };
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
try {
|
||||||
}).toThrow("Missing props 'message' (component 'TestWidget')");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("validate simple types", async () => {
|
test("validate simple types", async () => {
|
||||||
@@ -69,23 +95,50 @@ describe("props validation", () => {
|
|||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let props;
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
for (let test of Tests) {
|
for (let test of Tests) {
|
||||||
let TestWidget = class extends Widget {
|
let TestWidget = class extends Widget {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: test.type };
|
static props = { p: test.type };
|
||||||
};
|
};
|
||||||
|
Parent.components = { TestWidget };
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
props = {};
|
||||||
}).toThrow("Missing props 'p'");
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||||
|
|
||||||
expect(() => {
|
error = undefined;
|
||||||
new TestWidget(env, { p: test.ok });
|
props = { p: test.ok };
|
||||||
}).not.toThrow();
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
props = { p: test.ko };
|
||||||
new TestWidget(env, { p: test.ko });
|
try {
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,119 +152,305 @@ describe("props validation", () => {
|
|||||||
{ type: Function, ok: () => {}, ko: "1" }
|
{ type: Function, ok: () => {}, ko: "1" }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let props;
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
for (let test of Tests) {
|
for (let test of Tests) {
|
||||||
let TestWidget = class extends Widget {
|
let TestWidget = class extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
|
||||||
static props = { p: { type: test.type } };
|
static props = { p: { type: test.type } };
|
||||||
|
static template = xml`<div>hey</div>`;
|
||||||
};
|
};
|
||||||
|
Parent.components = { TestWidget };
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env);
|
props = {};
|
||||||
}).toThrow("Missing props 'p'");
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||||
|
|
||||||
expect(() => {
|
error = undefined;
|
||||||
new TestWidget(env, { p: test.ok });
|
props = { p: test.ok };
|
||||||
}).not.toThrow();
|
try {
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
props = { p: test.ko };
|
||||||
new TestWidget(env, { p: test.ko });
|
try {
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate a prop with multiple types", async () => {
|
test("can validate a prop with multiple types", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: [String, Boolean] };
|
static props = { p: [String, Boolean] };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: "string" });
|
let props;
|
||||||
new TestWidget(env, { p: true });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: "string" };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: 1 });
|
props = { p: true };
|
||||||
}).toThrow("Props 'p' of invalid type in component");
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: 1 };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an optional props", async () => {
|
test("can validate an optional props", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: String, optional: true } };
|
static props = { p: { type: String, optional: true } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: "hey" });
|
let props;
|
||||||
new TestWidget(env, {});
|
try {
|
||||||
}).not.toThrow();
|
props = { p: "key" };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: 1 });
|
props = {};
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: 1 };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with given primitive type", async () => {
|
test("can validate an array with given primitive type", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: String } };
|
static props = { p: { type: Array, element: String } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: [] });
|
let props;
|
||||||
new TestWidget(env, { p: ["string"] });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: [] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: [1] });
|
props = { p: ["string"] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: ["string", 1] });
|
props = { p: [1] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
try {
|
||||||
|
props = { p: ["string", 1] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an array with multiple sub element types", async () => {
|
test("can validate an array with multiple sub element types", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = { p: { type: Array, element: [String, Boolean] } };
|
static props = { p: { type: Array, element: [String, Boolean] } };
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: [] });
|
let props;
|
||||||
new TestWidget(env, { p: ["string"] });
|
try {
|
||||||
new TestWidget(env, { p: [false, true, "string"] });
|
props = { p: [] };
|
||||||
}).not.toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: [true, 1] });
|
props = { p: ["string"] };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: [false, true, "string"] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: [true, 1] };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate an object with simple shape", async () => {
|
test("can validate an object with simple shape", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: { type: Object, shape: { id: Number, url: String } }
|
p: { type: Object, shape: { id: Number, url: String } }
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: { id: 1, url: "url" } });
|
let props;
|
||||||
new TestWidget(env, { p: { id: 1, url: "url", extra: true } });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: { id: 1, url: "url" } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: "1", url: "url" } });
|
props = { p: { id: 1, url: "url", extra: true } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: 1 } });
|
props = { p: { id: "1", url: "url" } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
|
|
||||||
|
error = undefined;
|
||||||
|
try {
|
||||||
|
props = { p: { id: 1 } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("can validate recursively complicated prop def", async () => {
|
test("can validate recursively complicated prop def", async () => {
|
||||||
let TestWidget = class extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
static props = {
|
static props = {
|
||||||
p: {
|
p: {
|
||||||
@@ -222,16 +461,44 @@ describe("props validation", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
get p() {
|
||||||
|
return props.p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
expect(() => {
|
let error;
|
||||||
new TestWidget(env, { p: { id: 1, url: true } });
|
let props;
|
||||||
new TestWidget(env, { p: { id: 1, url: [12] } });
|
try {
|
||||||
}).not.toThrow();
|
props = { p: { id: 1, url: true } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
expect(() => {
|
try {
|
||||||
new TestWidget(env, { p: { id: 1, url: [12, true] } });
|
props = { p: { id: 1, url: [12] } };
|
||||||
}).toThrow();
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
|
||||||
|
try {
|
||||||
|
props = { p: { id: 1, url: [12, true] } };
|
||||||
|
const p = new Parent();
|
||||||
|
await p.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("props are validated in dev mode (code snapshot)", async () => {
|
test("props are validated in dev mode (code snapshot)", async () => {
|
||||||
@@ -249,7 +516,7 @@ describe("props validation", () => {
|
|||||||
class App extends Widget {
|
class App extends Widget {
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
// need to make sure there are 2 call to update props. one at component
|
// need to make sure there are 2 call to update props. one at component
|
||||||
@@ -322,17 +589,95 @@ describe("props validation", () => {
|
|||||||
QWeb.utils.validateProps(TestWidget, { message: null });
|
QWeb.utils.validateProps(TestWidget, { message: null });
|
||||||
}).toThrow();
|
}).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("missing required boolean prop causes an error", async () => {
|
||||||
|
class TestWidget extends Widget {
|
||||||
|
static props = ["p"];
|
||||||
|
static template = xml`<span><t t-if="props.p">hey</t></span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Widget {
|
||||||
|
static template = xml`<div><TestWidget/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new App(undefined, {});
|
||||||
|
let error;
|
||||||
|
try {
|
||||||
|
await w.mount(fixture);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("props are validated whenever component is updated", async () => {
|
||||||
|
let error;
|
||||||
|
class TestWidget extends Component<any, any> {
|
||||||
|
static props = { p: { type: Number } };
|
||||||
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
|
||||||
|
async __updateProps() {
|
||||||
|
try {
|
||||||
|
await Component.prototype.__updateProps.apply(this, arguments);
|
||||||
|
} catch (e) {
|
||||||
|
error = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
state: any = useState({ p: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new Parent();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
|
|
||||||
|
w.state.p = undefined;
|
||||||
|
await nextTick();
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("default values are applied before validating props at update", async () => {
|
||||||
|
class TestWidget extends Component<any, any> {
|
||||||
|
static props = { p: { type: Number } };
|
||||||
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
static defaultProps = { p: 4 };
|
||||||
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget p="state.p"/></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
|
state: any = useState({ p: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = new Parent();
|
||||||
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
|
|
||||||
|
w.state.p = undefined;
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("default props", () => {
|
describe("default props", () => {
|
||||||
test("can set default values", async () => {
|
test("can set default values", async () => {
|
||||||
class TestWidget extends Widget {
|
class TestWidget extends Component<any, any> {
|
||||||
static defaultProps = { p: 4 };
|
static defaultProps = { p: 4 };
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||||
|
}
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><TestWidget /></div>`;
|
||||||
|
static components = { TestWidget };
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new TestWidget(env, {});
|
const w = new Parent();
|
||||||
expect(w.props.p).toBe(4);
|
await w.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("default values are also set whenever component is updated", async () => {
|
test("default values are also set whenever component is updated", async () => {
|
||||||
@@ -346,7 +691,7 @@ describe("default props", () => {
|
|||||||
state: any = useState({ p: 1 });
|
state: any = useState({ p: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new Parent(env);
|
const w = new Parent();
|
||||||
await w.mount(fixture);
|
await w.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||||
|
|
||||||
@@ -367,7 +712,7 @@ describe("default props", () => {
|
|||||||
static components = { TestWidget };
|
static components = { TestWidget };
|
||||||
}
|
}
|
||||||
|
|
||||||
const w = new App(env, {});
|
const w = new App(undefined, {});
|
||||||
await w.mount(fixture);
|
await w.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>heyhey</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>heyhey</span></div>");
|
||||||
});
|
});
|
||||||
|
|||||||
+93
-12
@@ -1,5 +1,5 @@
|
|||||||
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||||
import { Component, Env } from "../src/component/component";
|
import { Component } from "../src/component/component";
|
||||||
import { Context, useContext } from "../src/context";
|
import { Context, useContext } from "../src/context";
|
||||||
import { xml } from "../src/tags";
|
import { xml } from "../src/tags";
|
||||||
import { useState } from "../src/hooks";
|
import { useState } from "../src/hooks";
|
||||||
@@ -11,14 +11,13 @@ import { useState } from "../src/hooks";
|
|||||||
// We create before each test:
|
// We create before each test:
|
||||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||||
// manipulations. Note that it is removed after each test.
|
// manipulations. Note that it is removed after each test.
|
||||||
// - env: a WEnv, necessary to create new components
|
// - a test env, necessary to create components, that is set as env
|
||||||
|
|
||||||
let fixture: HTMLElement;
|
let fixture: HTMLElement;
|
||||||
let env: Env;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
Component.env = makeTestEnv();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -37,7 +36,7 @@ describe("Context", () => {
|
|||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
const test = new Test(env);
|
const test = new Test();
|
||||||
await test.mount(fixture);
|
await test.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
});
|
});
|
||||||
@@ -49,7 +48,7 @@ describe("Context", () => {
|
|||||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||||
contextObj = useContext(testContext);
|
contextObj = useContext(testContext);
|
||||||
}
|
}
|
||||||
const test = new Test(env);
|
const test = new Test();
|
||||||
await test.mount(fixture);
|
await test.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||||
test.contextObj.value = 321;
|
test.contextObj.value = 321;
|
||||||
@@ -68,7 +67,7 @@ describe("Context", () => {
|
|||||||
static template = xml`<div><Child /><Child /></div>`;
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
testContext.state.value = 321;
|
testContext.state.value = 321;
|
||||||
@@ -76,6 +75,88 @@ describe("Context", () => {
|
|||||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("two async components are updated in parallel", async () => {
|
||||||
|
const testContext = new Context({ value: 123 });
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class Child extends Component<any, any> {
|
||||||
|
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||||
|
contextObj = useContext(testContext);
|
||||||
|
async render() {
|
||||||
|
steps.push("render");
|
||||||
|
await def;
|
||||||
|
return super.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
const parent = new Parent();
|
||||||
|
await parent.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
|
testContext.state.value = 321;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render", "render"]);
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("two async components on two levels are updated in parallel", async () => {
|
||||||
|
const testContext = new Context({ value: 123 });
|
||||||
|
const def = makeDeferred();
|
||||||
|
const steps: string[] = [];
|
||||||
|
|
||||||
|
class SlowComp extends Component<any, any> {
|
||||||
|
static template = xml`<p><t t-esc="props.value"/></p>`;
|
||||||
|
willUpdateProps() {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class Child extends Component<any, any> {
|
||||||
|
static template = xml`<span><SlowComp value="contextObj.value"/></span>`;
|
||||||
|
static components = { SlowComp };
|
||||||
|
contextObj = useContext(testContext);
|
||||||
|
|
||||||
|
render() {
|
||||||
|
steps.push("render");
|
||||||
|
return super.render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parent extends Component<any, any> {
|
||||||
|
static template = xml`<div><Child /><Child /></div>`;
|
||||||
|
static components = { Child };
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component<any, any> {
|
||||||
|
static template = xml`<div><Child /><Parent /></div>`;
|
||||||
|
static components = { Child, Parent };
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = new App();
|
||||||
|
await app.mount(fixture);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||||
|
);
|
||||||
|
testContext.state.value = 321;
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render"]);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||||
|
);
|
||||||
|
def.resolve();
|
||||||
|
await nextTick();
|
||||||
|
expect(steps).toEqual(["render", "render", "render"]);
|
||||||
|
expect(fixture.innerHTML).toBe(
|
||||||
|
"<div><span><p>321</p></span><div><span><p>321</p></span><span><p>321</p></span></div></div>"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("one components can subscribe twice to same context", async () => {
|
test("one components can subscribe twice to same context", async () => {
|
||||||
const testContext = new Context({ a: 1, b: 2 });
|
const testContext = new Context({ a: 1, b: 2 });
|
||||||
const steps: string[] = [];
|
const steps: string[] = [];
|
||||||
@@ -93,7 +174,7 @@ describe("Context", () => {
|
|||||||
static template = xml`<div><Child /></div>`;
|
static template = xml`<div><Child /></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||||
expect(steps).toEqual(["child"]);
|
expect(steps).toEqual(["child"]);
|
||||||
@@ -124,7 +205,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
||||||
expect(steps).toEqual(["parent", "child"]);
|
expect(steps).toEqual(["parent", "child"]);
|
||||||
@@ -158,7 +239,7 @@ describe("Context", () => {
|
|||||||
return super.__render(fiber);
|
return super.__render(fiber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
||||||
expect(steps).toEqual(["parent", "child"]);
|
expect(steps).toEqual(["parent", "child"]);
|
||||||
@@ -202,12 +283,12 @@ describe("Context", () => {
|
|||||||
context = useContext(testContext);
|
context = useContext(testContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new ComponentA(env);
|
const component = new ComponentA();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
|
|
||||||
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||||
testContext.state.key = "y";
|
testContext.state.key = "y";
|
||||||
testContext.state.y = {n: 2};
|
testContext.state.y = { n: 2 };
|
||||||
delete testContext.state.x;
|
delete testContext.state.x;
|
||||||
await nextTick();
|
await nextTick();
|
||||||
|
|
||||||
|
|||||||
@@ -8,13 +8,11 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(typeof obj).toBe("object");
|
expect(typeof obj).toBe("object");
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
const obj2: any = observer.observe({ a: 1 });
|
const obj2: any = observer.observe({ a: 1 });
|
||||||
expect(observer.revNumber(obj2)).toBe(1);
|
expect(observer.revNumber(obj2)).toBe(1);
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj2.a = 2;
|
obj2.a = 2;
|
||||||
@@ -33,23 +31,19 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ a: null, b: undefined });
|
const obj: any = observer.observe({ a: null, b: undefined });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.a = 3;
|
obj.a = 3;
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.b = 5;
|
obj.b = 5;
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
|
|
||||||
obj.a = null;
|
obj.a = null;
|
||||||
obj.b = undefined;
|
obj.b = undefined;
|
||||||
expect(observer.revNumber(obj)).toBe(5);
|
expect(observer.revNumber(obj)).toBe(5);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(5);
|
|
||||||
expect(observer.rev).toBe(5);
|
expect(observer.rev).toBe(5);
|
||||||
expect(obj).toEqual({
|
expect(obj).toEqual({
|
||||||
a: null,
|
a: null,
|
||||||
@@ -63,7 +57,6 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ date });
|
const obj: any = observer.observe({ date });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(typeof obj.date.getFullYear()).toBe("number");
|
expect(typeof obj.date.getFullYear()).toBe("number");
|
||||||
expect(obj.date).toBe(date);
|
expect(obj.date).toBe(date);
|
||||||
@@ -71,7 +64,6 @@ describe("observer", () => {
|
|||||||
obj.date = new Date();
|
obj.date = new Date();
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(obj.date).not.toBe(date);
|
expect(obj.date).not.toBe(date);
|
||||||
});
|
});
|
||||||
@@ -82,14 +74,11 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(Array.isArray(obj.arr)).toBe(true);
|
expect(Array.isArray(obj.arr)).toBe(true);
|
||||||
expect(observer.revNumber(obj.arr)).toBe(1);
|
expect(observer.revNumber(obj.arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj.arr)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.arr[0] = "nope";
|
obj.arr[0] = "nope";
|
||||||
expect(observer.revNumber(obj.arr)).toBe(2);
|
expect(observer.revNumber(obj.arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj.arr)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,24 +87,20 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({ a: 1 });
|
const obj: any = observer.observe({ a: 1 });
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.a = 2;
|
obj.a = 2;
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
// same value again
|
// same value again
|
||||||
obj.a = 2;
|
obj.a = 2;
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.a = 3;
|
obj.a = 3;
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -126,19 +111,16 @@ describe("observer", () => {
|
|||||||
expect(Array.isArray(arr)).toBe(true);
|
expect(Array.isArray(arr)).toBe(true);
|
||||||
expect(arr.length).toBe(0);
|
expect(arr.length).toBe(0);
|
||||||
expect(observer.revNumber(arr)).toBe(1);
|
expect(observer.revNumber(arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
arr.push(1);
|
arr.push(1);
|
||||||
expect(observer.revNumber(arr)).toBe(2);
|
expect(observer.revNumber(arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(arr.length).toBe(1);
|
expect(arr.length).toBe(1);
|
||||||
expect(arr).toEqual([1]);
|
expect(arr).toEqual([1]);
|
||||||
|
|
||||||
arr.splice(1, 0, "hey");
|
arr.splice(1, 0, "hey");
|
||||||
expect(observer.revNumber(arr)).toBe(3);
|
expect(observer.revNumber(arr)).toBe(3);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(arr).toEqual([1, "hey"]);
|
expect(arr).toEqual([1, "hey"]);
|
||||||
expect(arr.length).toBe(2);
|
expect(arr.length).toBe(2);
|
||||||
@@ -146,7 +128,6 @@ describe("observer", () => {
|
|||||||
arr.unshift("lindemans");
|
arr.unshift("lindemans");
|
||||||
//it generates 3 primitive operations
|
//it generates 3 primitive operations
|
||||||
expect(observer.revNumber(arr)).toBe(6);
|
expect(observer.revNumber(arr)).toBe(6);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(6);
|
|
||||||
expect(observer.rev).toBe(6);
|
expect(observer.rev).toBe(6);
|
||||||
expect(arr).toEqual(["lindemans", 1, "hey"]);
|
expect(arr).toEqual(["lindemans", 1, "hey"]);
|
||||||
expect(arr.length).toBe(3);
|
expect(arr.length).toBe(3);
|
||||||
@@ -154,21 +135,18 @@ describe("observer", () => {
|
|||||||
arr.reverse();
|
arr.reverse();
|
||||||
//it generates 2 primitive operations
|
//it generates 2 primitive operations
|
||||||
expect(observer.revNumber(arr)).toBe(8);
|
expect(observer.revNumber(arr)).toBe(8);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(8);
|
|
||||||
expect(observer.rev).toBe(8);
|
expect(observer.rev).toBe(8);
|
||||||
expect(arr).toEqual(["hey", 1, "lindemans"]);
|
expect(arr).toEqual(["hey", 1, "lindemans"]);
|
||||||
expect(arr.length).toBe(3);
|
expect(arr.length).toBe(3);
|
||||||
|
|
||||||
arr.pop(); // one set, one delete
|
arr.pop(); // one set, one delete
|
||||||
expect(observer.revNumber(arr)).toBe(10);
|
expect(observer.revNumber(arr)).toBe(10);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(10);
|
|
||||||
expect(observer.rev).toBe(10);
|
expect(observer.rev).toBe(10);
|
||||||
expect(arr).toEqual(["hey", 1]);
|
expect(arr).toEqual(["hey", 1]);
|
||||||
expect(arr.length).toBe(2);
|
expect(arr.length).toBe(2);
|
||||||
|
|
||||||
arr.shift(); // 2 sets, 1 delete
|
arr.shift(); // 2 sets, 1 delete
|
||||||
expect(observer.revNumber(arr)).toBe(13);
|
expect(observer.revNumber(arr)).toBe(13);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(13);
|
|
||||||
expect(observer.rev).toBe(13);
|
expect(observer.rev).toBe(13);
|
||||||
expect(arr).toEqual([1]);
|
expect(arr).toEqual([1]);
|
||||||
expect(arr.length).toBe(1);
|
expect(arr.length).toBe(1);
|
||||||
@@ -187,8 +165,7 @@ describe("observer", () => {
|
|||||||
arr[0].kriek = 6;
|
arr[0].kriek = 6;
|
||||||
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(arr)).toBe(2);
|
expect(observer.revNumber(arr)).toBe(3);
|
||||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
|
||||||
expect(observer.revNumber(arr[0])).toBe(3);
|
expect(observer.revNumber(arr[0])).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -238,7 +215,6 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state)).toBe(1);
|
|
||||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||||
|
|
||||||
state[1] = "b";
|
state[1] = "b";
|
||||||
@@ -247,7 +223,6 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(2);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state)).toBe(2);
|
|
||||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||||
|
|
||||||
expect(state).toEqual(["a", "b"]);
|
expect(state).toEqual(["a", "b"]);
|
||||||
@@ -259,13 +234,11 @@ describe("observer", () => {
|
|||||||
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
expect(observer.revNumber(state.arr)).toBe(1);
|
expect(observer.revNumber(state.arr)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state.arr)).toBe(1);
|
|
||||||
expect(state.arr.length).toBe(0);
|
expect(state.arr.length).toBe(0);
|
||||||
|
|
||||||
state.arr.push(1);
|
state.arr.push(1);
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state.arr)).toBe(2);
|
expect(observer.revNumber(state.arr)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state.arr)).toBe(2);
|
|
||||||
expect(state.arr.length).toBe(1);
|
expect(state.arr.length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -280,7 +253,7 @@ describe("observer", () => {
|
|||||||
|
|
||||||
state.arr[0].something = 2;
|
state.arr[0].something = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state.arr)).toBe(1);
|
expect(observer.revNumber(state.arr)).toBe(2);
|
||||||
expect(observer.revNumber(state.arr[0])).toBe(2);
|
expect(observer.revNumber(state.arr[0])).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -294,7 +267,7 @@ describe("observer", () => {
|
|||||||
|
|
||||||
state.a.b = 2;
|
state.a.b = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.revNumber(state.a)).toBe(2);
|
expect(observer.revNumber(state.a)).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -312,7 +285,7 @@ describe("observer", () => {
|
|||||||
expect(observer.revNumber(obj.a)).toBe(2);
|
expect(observer.revNumber(obj.a)).toBe(2);
|
||||||
obj.a.b = 3;
|
obj.a.b = 3;
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.revNumber(obj.a)).toBe(3);
|
expect(observer.revNumber(obj.a)).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -320,22 +293,18 @@ describe("observer", () => {
|
|||||||
const observer = new Observer();
|
const observer = new Observer();
|
||||||
const state: any = observer.observe({ o: { a: 1 }, arr: [1], n: 13 });
|
const state: any = observer.observe({ o: { a: 1 }, arr: [1], n: 13 });
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(1);
|
||||||
expect(observer.deepRevNumber(state)).toBe(1);
|
|
||||||
|
|
||||||
state.o.a = 2;
|
state.o.a = 2;
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(2);
|
||||||
expect(observer.deepRevNumber(state)).toBe(2);
|
|
||||||
|
|
||||||
state.arr.push(2);
|
state.arr.push(2);
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
expect(observer.revNumber(state)).toBe(1);
|
expect(observer.revNumber(state)).toBe(3);
|
||||||
expect(observer.deepRevNumber(state)).toBe(3);
|
|
||||||
|
|
||||||
state.n = 155;
|
state.n = 155;
|
||||||
expect(observer.rev).toBe(4);
|
expect(observer.rev).toBe(4);
|
||||||
expect(observer.revNumber(state)).toBe(2);
|
expect(observer.revNumber(state)).toBe(4);
|
||||||
expect(observer.deepRevNumber(state)).toBe(4);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("properly handle already observed state", () => {
|
test("properly handle already observed state", () => {
|
||||||
@@ -361,18 +330,15 @@ describe("observer", () => {
|
|||||||
const obj: any = observer.observe({});
|
const obj: any = observer.observe({});
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(1);
|
expect(observer.revNumber(obj)).toBe(1);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
|
||||||
expect(observer.rev).toBe(1);
|
expect(observer.rev).toBe(1);
|
||||||
|
|
||||||
obj.aku = "always finds annoying problems";
|
obj.aku = "always finds annoying problems";
|
||||||
expect(observer.revNumber(obj)).toBe(2);
|
expect(observer.revNumber(obj)).toBe(2);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
|
||||||
expect(observer.rev).toBe(2);
|
expect(observer.rev).toBe(2);
|
||||||
|
|
||||||
obj.aku = "always finds good problems";
|
obj.aku = "always finds good problems";
|
||||||
|
|
||||||
expect(observer.revNumber(obj)).toBe(3);
|
expect(observer.revNumber(obj)).toBe(3);
|
||||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
|
||||||
expect(observer.rev).toBe(3);
|
expect(observer.rev).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -416,7 +382,7 @@ describe("observer", () => {
|
|||||||
expect(observer.revNumber(obj2)).toBe(1);
|
expect(observer.revNumber(obj2)).toBe(1);
|
||||||
|
|
||||||
obj2.key = 3;
|
obj2.key = 3;
|
||||||
expect(observer.revNumber(obj1)).toBe(1);
|
expect(observer.revNumber(obj1)).toBe(2);
|
||||||
expect(observer.revNumber(obj2)).toBe(2);
|
expect(observer.revNumber(obj2)).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+124
-72
@@ -6,36 +6,9 @@
|
|||||||
*/
|
*/
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
|
|
||||||
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
|
//--------------------------------------------------------------------------
|
||||||
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
|
// Helpers
|
||||||
|
//--------------------------------------------------------------------------
|
||||||
// files to be checked
|
|
||||||
function getFiles(): string[] {
|
|
||||||
const DOCFILES = fs.readdirSync("doc").map(f => `doc/${f}`);
|
|
||||||
const MAINREADME = "README.md";
|
|
||||||
DOCFILES.push("roadmap.md", MAINREADME);
|
|
||||||
return DOCFILES;
|
|
||||||
}
|
|
||||||
|
|
||||||
test("All markdown links work", () => {
|
|
||||||
let linkNumber = 0;
|
|
||||||
let invalidLinkNumber = 0;
|
|
||||||
const files = getFiles();
|
|
||||||
const data = readDocData(files);
|
|
||||||
for (let file of data) {
|
|
||||||
for (let link of file.links) {
|
|
||||||
// DEBUG: uncomment next line
|
|
||||||
// console.warn(`Checking "${link.name}" in "${file.name}"`);
|
|
||||||
linkNumber++;
|
|
||||||
if (!isLinkValid(link, file, data)) {
|
|
||||||
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
|
||||||
invalidLinkNumber++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(invalidLinkNumber).toBe(0);
|
|
||||||
expect(linkNumber).toBeGreaterThan(10);
|
|
||||||
});
|
|
||||||
|
|
||||||
interface MarkDownLink {
|
interface MarkDownLink {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -49,38 +22,127 @@ interface MarkDownSection {
|
|||||||
|
|
||||||
interface FileData {
|
interface FileData {
|
||||||
name: string;
|
name: string;
|
||||||
|
path: string[];
|
||||||
|
fullName: string;
|
||||||
links: MarkDownLink[];
|
links: MarkDownLink[];
|
||||||
sections: MarkDownSection[];
|
sections: MarkDownSection[];
|
||||||
}
|
}
|
||||||
|
|
||||||
function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
|
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
|
||||||
|
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
|
||||||
|
|
||||||
|
export function addMardownData(fileData): void {
|
||||||
|
const sep = fileData.path.length > 0 ? "/" : "";
|
||||||
|
const fullName = fileData.path.join("/") + sep + fileData.name;
|
||||||
|
const content = fs.readFileSync(fullName, { encoding: "utf8" });
|
||||||
|
let m;
|
||||||
|
// get links info
|
||||||
|
do {
|
||||||
|
m = LINK_REGEXP.exec(content);
|
||||||
|
if (m) {
|
||||||
|
fileData.links.push({ name: m[0], link: m[2] });
|
||||||
|
}
|
||||||
|
} while (m);
|
||||||
|
// get sections info
|
||||||
|
do {
|
||||||
|
m = HEADING_REGEXP.exec(content);
|
||||||
|
if (m) {
|
||||||
|
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
|
||||||
|
}
|
||||||
|
} while (m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a list of FileData corresponding to all files that need to be
|
||||||
|
* validated.
|
||||||
|
*/
|
||||||
|
function getFiles(path: string[] = []): FileData[] {
|
||||||
|
if (path.length === 0) {
|
||||||
|
const baseFiles: FileData[] = [
|
||||||
|
{ name: "README.md", path: [], links: [], sections: [], fullName: "README.md" },
|
||||||
|
{ name: "roadmap.md", path: [], links: [], sections: [], fullName: "roadmap.md" }
|
||||||
|
];
|
||||||
|
const rest = getFiles(["doc"]);
|
||||||
|
const result = baseFiles.concat(rest);
|
||||||
|
result.forEach(addMardownData);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const files = fs.readdirSync(path.join("/"), { withFileTypes: true }).map(f => {
|
||||||
|
if (f.isDirectory()) {
|
||||||
|
return getFiles(path.concat(f.name));
|
||||||
|
}
|
||||||
|
const fullName = path.join("/") + (path.length > 0 ? "/" : "") + f.name;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: f.name,
|
||||||
|
path,
|
||||||
|
links: [],
|
||||||
|
sections: [],
|
||||||
|
fullName
|
||||||
|
}
|
||||||
|
];
|
||||||
|
});
|
||||||
|
return Array.prototype.concat(...files);
|
||||||
|
}
|
||||||
|
|
||||||
|
const LOCAL_FILES = ["LICENSE"];
|
||||||
|
export function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
|
||||||
if (link.link.startsWith("http")) {
|
if (link.link.startsWith("http")) {
|
||||||
// no check on external links
|
// no check on external links
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// Step 1: extract path, name, hash
|
||||||
|
// path = ['doc', 'architecture]
|
||||||
|
// name = 'rendering.md'
|
||||||
|
// hash = 'blabla' (or '' if no hash)
|
||||||
|
|
||||||
const parts = link.link.split("#");
|
const parts = link.link.split("#");
|
||||||
const currentParts = current.name.split("/");
|
const hash = parts[1] || "";
|
||||||
const path = currentParts.length > 1 ? currentParts[0] + "/" : "";
|
let name;
|
||||||
const fullName = path + parts[0];
|
let path;
|
||||||
if (parts.length === 1) {
|
if (parts[0]) {
|
||||||
// no # in url
|
let temp = parts[0].split("/");
|
||||||
if (parts[0].endsWith(".md")) {
|
name = temp[temp.length - 1];
|
||||||
// it is a local md file
|
temp.splice(-1);
|
||||||
if (!files.find(f => f.name === fullName)) {
|
path = current.path.slice();
|
||||||
return false;
|
for (let elem of temp) {
|
||||||
|
if (elem === "..") {
|
||||||
|
path.splice(-1);
|
||||||
|
} else if (elem !== ".") {
|
||||||
|
path.push(elem);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const file = parts[0] === "" ? current : files.find(f => f.name === fullName);
|
// there are no file name, so this is a relative link to the current file
|
||||||
if (!file) {
|
name = current.name;
|
||||||
return false;
|
path = current.path;
|
||||||
}
|
}
|
||||||
if (!file.sections.find(s => s.slug === parts[1])) {
|
|
||||||
|
// Step 2: build normalized link file name
|
||||||
|
const linkFullName = path.join("/") + (path.length > 0 ? "/" : "") + name;
|
||||||
|
|
||||||
|
// Step 3: check link name against white list of local files
|
||||||
|
if (LOCAL_FILES.includes(linkFullName)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 4: check if there is a matching file
|
||||||
|
let target: FileData | undefined = files.find(f => f.fullName === linkFullName);
|
||||||
|
if (!target) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 5: if necessary, check if there is a corresponding link inside the target
|
||||||
|
// link name
|
||||||
|
if (hash) {
|
||||||
|
if (!target.sections.find(s => s.slug === hash)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
|
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
|
||||||
function slugify(str) {
|
function slugify(str) {
|
||||||
const a = "àáäâãåăæçèéëêǵḧìíïîḿńǹñòóöôœøṕŕßśșțùúüûǘẃẍÿź·_,:;";
|
const a = "àáäâãåăæçèéëêǵḧìíïîḿńǹñòóöôœøṕŕßśșțùúüûǘẃẍÿź·_,:;";
|
||||||
@@ -99,33 +161,23 @@ function slugify(str) {
|
|||||||
.replace(/-+$/, ""); // Trim - from end of text
|
.replace(/-+$/, ""); // Trim - from end of text
|
||||||
}
|
}
|
||||||
|
|
||||||
function readDocData(files: string[]): FileData[] {
|
//--------------------------------------------------------------------------
|
||||||
const result: FileData[] = [];
|
// Test
|
||||||
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
for (let file of files) {
|
test("All markdown links work", () => {
|
||||||
const fileData: FileData = {
|
let linkNumber = 0;
|
||||||
name: file,
|
let invalidLinkNumber = 0;
|
||||||
links: [],
|
const data = getFiles();
|
||||||
sections: []
|
for (let file of data) {
|
||||||
};
|
for (let link of file.links) {
|
||||||
const content = fs.readFileSync(file, { encoding: "utf8" });
|
linkNumber++;
|
||||||
let m;
|
if (!isLinkValid(link, file, data)) {
|
||||||
// get links info
|
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
||||||
do {
|
invalidLinkNumber++;
|
||||||
m = LINK_REGEXP.exec(content);
|
|
||||||
if (m) {
|
|
||||||
fileData.links.push({ name: m[0], link: m[2] });
|
|
||||||
}
|
}
|
||||||
} while (m);
|
}
|
||||||
// get sections info
|
|
||||||
do {
|
|
||||||
m = HEADING_REGEXP.exec(content);
|
|
||||||
if (m) {
|
|
||||||
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
|
|
||||||
}
|
|
||||||
} while (m);
|
|
||||||
|
|
||||||
result.push(fileData);
|
|
||||||
}
|
}
|
||||||
return result;
|
expect(invalidLinkNumber).toBe(0);
|
||||||
}
|
expect(linkNumber).toBeGreaterThan(10);
|
||||||
|
});
|
||||||
|
|||||||
+2
-1
@@ -1,4 +1,5 @@
|
|||||||
import { Env, scheduler } from "../src/component/component";
|
import { Env } from "../src/component/component";
|
||||||
|
import { scheduler } from "../src/component/scheduler";
|
||||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||||
import { patch } from "../src/vdom";
|
import { patch } from "../src/vdom";
|
||||||
import "../src/qweb/base_directives";
|
import "../src/qweb/base_directives";
|
||||||
|
|||||||
+43
-42
@@ -28,6 +28,7 @@ let env: Env;
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -44,7 +45,7 @@ describe("hooks", () => {
|
|||||||
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
||||||
counter = useState({ value: 42 });
|
counter = useState({ value: 42 });
|
||||||
}
|
}
|
||||||
const counter = new Counter(env);
|
const counter = new Counter();
|
||||||
await counter.mount(fixture);
|
await counter.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>42</div>");
|
expect(fixture.innerHTML).toBe("<div>42</div>");
|
||||||
counter.counter.value = 3;
|
counter.counter.value = 3;
|
||||||
@@ -64,12 +65,12 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("mounted");
|
expect(component).not.toHaveProperty("mounted");
|
||||||
expect(component).not.toHaveProperty("willUnmount");
|
expect(component).not.toHaveProperty("willUnmount");
|
||||||
@@ -92,8 +93,8 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,7 +104,7 @@ describe("hooks", () => {
|
|||||||
static components = { MyComponent };
|
static components = { MyComponent };
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
}
|
}
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||||
expect(steps).toEqual(["mounted"]);
|
expect(steps).toEqual(["mounted"]);
|
||||||
@@ -126,8 +127,8 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -137,7 +138,7 @@ describe("hooks", () => {
|
|||||||
steps.push("comp:willunmount");
|
steps.push("comp:willunmount");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.unmount();
|
component.unmount();
|
||||||
@@ -157,8 +158,8 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -175,7 +176,7 @@ describe("hooks", () => {
|
|||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||||
parent.state.flag = false;
|
parent.state.flag = false;
|
||||||
@@ -197,13 +198,13 @@ describe("hooks", () => {
|
|||||||
}
|
}
|
||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey</div>`;
|
static template = xml`<div>hey</div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook(1);
|
useMyHook(1);
|
||||||
useMyHook(2);
|
useMyHook(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.unmount();
|
component.unmount();
|
||||||
@@ -226,7 +227,7 @@ describe("hooks", () => {
|
|||||||
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const counter = new Counter(env);
|
const counter = new Counter();
|
||||||
await counter.mount(fixture);
|
await counter.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
||||||
counter.increment();
|
counter.increment();
|
||||||
@@ -247,7 +248,7 @@ describe("hooks", () => {
|
|||||||
expect(this.spanRef.el).toBeNull();
|
expect(this.spanRef.el).toBeNull();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new TestRef(env);
|
const component = new TestRef();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
||||||
component.state.flag = false;
|
component.state.flag = false;
|
||||||
@@ -270,13 +271,13 @@ describe("hooks", () => {
|
|||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(component).not.toHaveProperty("patched");
|
expect(component).not.toHaveProperty("patched");
|
||||||
expect(component).not.toHaveProperty("willPatch");
|
expect(component).not.toHaveProperty("willPatch");
|
||||||
@@ -304,8 +305,8 @@ describe("hooks", () => {
|
|||||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||||
state = useState({ flag: true });
|
state = useState({ flag: true });
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook();
|
useMyHook();
|
||||||
}
|
}
|
||||||
willPatch() {
|
willPatch() {
|
||||||
@@ -315,7 +316,7 @@ describe("hooks", () => {
|
|||||||
steps.push("comp:patched");
|
steps.push("comp:patched");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||||
component.state.flag = false;
|
component.state.flag = false;
|
||||||
@@ -337,13 +338,13 @@ describe("hooks", () => {
|
|||||||
class MyComponent extends Component<any, any> {
|
class MyComponent extends Component<any, any> {
|
||||||
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useMyHook(1);
|
useMyHook(1);
|
||||||
useMyHook(2);
|
useMyHook(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new MyComponent(env);
|
const component = new MyComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
||||||
component.state.value++;
|
component.state.value++;
|
||||||
@@ -377,13 +378,13 @@ describe("hooks", () => {
|
|||||||
<input t-ref="input2"/>
|
<input t-ref="input2"/>
|
||||||
</div>`;
|
</div>`;
|
||||||
|
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useAutofocus("input2");
|
useAutofocus("input2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new SomeComponent(env);
|
const component = new SomeComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
||||||
const input2 = fixture.querySelectorAll("input")[1];
|
const input2 = fixture.querySelectorAll("input")[1];
|
||||||
@@ -399,13 +400,13 @@ describe("hooks", () => {
|
|||||||
</div>`;
|
</div>`;
|
||||||
|
|
||||||
state = useState({ flag: false });
|
state = useState({ flag: false });
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useAutofocus("input2");
|
useAutofocus("input2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const component = new SomeComponent(env);
|
const component = new SomeComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><input></div>");
|
expect(fixture.innerHTML).toBe("<div><input></div>");
|
||||||
expect(document.activeElement).toBe(document.body);
|
expect(document.activeElement).toBe(document.body);
|
||||||
@@ -420,12 +421,12 @@ describe("hooks", () => {
|
|||||||
test("can use sub env", async () => {
|
test("can use sub env", async () => {
|
||||||
class TestComponent extends Component<any, any> {
|
class TestComponent extends Component<any, any> {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useSubEnv({ val: 3 });
|
useSubEnv({ val: 3 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new TestComponent(env);
|
const component = new TestComponent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>3</div>");
|
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||||
expect(env).not.toHaveProperty("val");
|
expect(env).not.toHaveProperty("val");
|
||||||
@@ -435,8 +436,8 @@ describe("hooks", () => {
|
|||||||
test("parent and child env", async () => {
|
test("parent and child env", async () => {
|
||||||
class Child extends Component<any, any> {
|
class Child extends Component<any, any> {
|
||||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||||
constructor(env) {
|
constructor(parent, props) {
|
||||||
super(env);
|
super(parent, props);
|
||||||
useSubEnv({ val: 5 });
|
useSubEnv({ val: 5 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -444,12 +445,12 @@ describe("hooks", () => {
|
|||||||
class Parent extends Component<any, any> {
|
class Parent extends Component<any, any> {
|
||||||
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
||||||
static components = { Child };
|
static components = { Child };
|
||||||
constructor(env) {
|
constructor() {
|
||||||
super(env);
|
super();
|
||||||
useSubEnv({ val: 3 });
|
useSubEnv({ val: 3 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const component = new Parent(env);
|
const component = new Parent();
|
||||||
await component.mount(fixture);
|
await component.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
||||||
});
|
});
|
||||||
@@ -478,7 +479,7 @@ describe("hooks", () => {
|
|||||||
state = useState({ value: 1 });
|
state = useState({ value: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(app).not.toHaveProperty("willStart");
|
expect(app).not.toHaveProperty("willStart");
|
||||||
expect(app).not.toHaveProperty("willUpdateProps");
|
expect(app).not.toHaveProperty("willUpdateProps");
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { AsyncRoot } from "../../src/misc/async_root";
|
|||||||
import { useState } from "../../src/hooks";
|
import { useState } from "../../src/hooks";
|
||||||
import { xml } from "../../src/tags";
|
import { xml } from "../../src/tags";
|
||||||
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||||
import { Env, Component } from "../../src/component/component";
|
import { Component } from "../../src/component/component";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Setup and helpers
|
// Setup and helpers
|
||||||
@@ -11,14 +11,13 @@ import { Env, Component } from "../../src/component/component";
|
|||||||
// We create before each test:
|
// We create before each test:
|
||||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||||
// manipulations. Note that it is removed after each test.
|
// manipulations. Note that it is removed after each test.
|
||||||
// - env: a WEnv, necessary to create new components
|
// - a test env, necessary to create components, that is set as env
|
||||||
|
|
||||||
let fixture: HTMLElement;
|
let fixture: HTMLElement;
|
||||||
let env: Env;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
Component.env = makeTestEnv();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -55,7 +54,7 @@ describe("Asyncroot", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
|
|
||||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||||
@@ -103,7 +102,7 @@ describe("Asyncroot", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
|
|
||||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||||
@@ -158,7 +157,7 @@ describe("Asyncroot", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
|
|
||||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/0</span><span>0/0</span>");
|
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/0</span><span>0/0</span>");
|
||||||
|
|||||||
@@ -387,13 +387,13 @@ exports[`foreach iterate on items (on a element node) 1`] = `
|
|||||||
context.item_index = i1;
|
context.item_index = i1;
|
||||||
context.item = _3[i1];
|
context.item = _3[i1];
|
||||||
context.item_value = _4[i1];
|
context.item_value = _4[i1];
|
||||||
const nodeKey5 = context['item']
|
const nodeKey5 = context['item'];
|
||||||
let c5 = [], p5 = {key:nodeKey5};
|
let c6 = [], p6 = {key:nodeKey5};
|
||||||
var vn5 = h('span', p5, c5);
|
var vn6 = h('span', p6, c6);
|
||||||
c1.push(vn5);
|
c1.push(vn6);
|
||||||
var _6 = context['item'];
|
var _7 = context['item'];
|
||||||
if (_6 || _6 === 0) {
|
if (_7 || _7 === 0) {
|
||||||
c5.push({text: _6});
|
c6.push({text: _7});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
@@ -1643,14 +1643,14 @@ exports[`t-key can use t-key directive on a node 1`] = `
|
|||||||
) {
|
) {
|
||||||
let sibling = null;
|
let sibling = null;
|
||||||
var h = this.h;
|
var h = this.h;
|
||||||
const nodeKey1 = context['beer'].id
|
const nodeKey1 = context['beer'].id;
|
||||||
let c1 = [], p1 = {key:nodeKey1};
|
let c2 = [], p2 = {key:nodeKey1};
|
||||||
var vn1 = h('div', p1, c1);
|
var vn2 = h('div', p2, c2);
|
||||||
var _2 = context['beer'].name;
|
var _3 = context['beer'].name;
|
||||||
if (_2 || _2 === 0) {
|
if (_3 || _3 === 0) {
|
||||||
c1.push({text: _2});
|
c2.push({text: _3});
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn2;
|
||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1676,13 +1676,13 @@ exports[`t-key t-key directive in a list 1`] = `
|
|||||||
context.beer_index = i1;
|
context.beer_index = i1;
|
||||||
context.beer = _3[i1];
|
context.beer = _3[i1];
|
||||||
context.beer_value = _4[i1];
|
context.beer_value = _4[i1];
|
||||||
const nodeKey5 = context['beer'].id
|
const nodeKey5 = context['beer'].id;
|
||||||
let c5 = [], p5 = {key:nodeKey5};
|
let c6 = [], p6 = {key:nodeKey5};
|
||||||
var vn5 = h('li', p5, c5);
|
var vn6 = h('li', p6, c6);
|
||||||
c1.push(vn5);
|
c1.push(vn6);
|
||||||
var _6 = context['beer'].name;
|
var _7 = context['beer'].name;
|
||||||
if (_6 || _6 === 0) {
|
if (_7 || _7 === 0) {
|
||||||
c5.push({text: _6});
|
c6.push({text: _7});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
@@ -1774,16 +1774,16 @@ exports[`t-on can bind handlers with loop variable as argument 1`] = `
|
|||||||
context.action_index = i1;
|
context.action_index = i1;
|
||||||
context.action = _3[i1];
|
context.action = _3[i1];
|
||||||
context.action_value = _4[i1];
|
context.action_value = _4[i1];
|
||||||
const nodeKey5 = context['action_index']
|
const nodeKey5 = context['action_index'];
|
||||||
let c5 = [], p5 = {key:nodeKey5};
|
let c6 = [], p6 = {key:nodeKey5};
|
||||||
var vn5 = h('li', p5, c5);
|
var vn6 = h('li', p6, c6);
|
||||||
c1.push(vn5);
|
c1.push(vn6);
|
||||||
let c6 = [], p6 = {key:6,on:{}};
|
let c7 = [], p7 = {key:nodeKey5,on:{}};
|
||||||
var vn6 = h('a', p6, c6);
|
var vn7 = h('a', p7, c7);
|
||||||
c5.push(vn6);
|
c6.push(vn7);
|
||||||
const handler7 = context['activate'] && context['activate'].bind(owner, context['action']);
|
const handler8 = context['activate'] && context['activate'].bind(owner, context['action']);
|
||||||
p6.on['click'] = function (e) {if (handler7) { handler7(e); } else { context.activate(action); }};
|
p7.on['click'] = function (e) {if (handler8) { handler8(e); } else { context.activate(action); }};
|
||||||
c6.push({text: \`link\`});
|
c7.push({text: \`link\`});
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
}"
|
}"
|
||||||
@@ -2000,17 +2000,17 @@ exports[`t-on t-on with prevent modifier in t-foreach 1`] = `
|
|||||||
context.project_index = i1;
|
context.project_index = i1;
|
||||||
context.project = _3[i1];
|
context.project = _3[i1];
|
||||||
context.project_value = _4[i1];
|
context.project_value = _4[i1];
|
||||||
var _5 = '#';
|
const nodeKey5 = context['project'];
|
||||||
const nodeKey6 = context['project']
|
var _6 = '#';
|
||||||
let c6 = [], p6 = {key:nodeKey6,attrs:{href: _5},on:{}};
|
let c7 = [], p7 = {key:nodeKey5,attrs:{href: _6},on:{}};
|
||||||
var vn6 = h('a', p6, c6);
|
var vn7 = h('a', p7, c7);
|
||||||
c1.push(vn6);
|
c1.push(vn7);
|
||||||
const handler7 = context['onEdit'] && context['onEdit'].bind(owner, context['project'].id);
|
const handler8 = context['onEdit'] && context['onEdit'].bind(owner, context['project'].id);
|
||||||
p6.on['click'] = function (e) {e.preventDefault();if (handler7) { handler7(e); } else { context.onEdit(project.id); }};
|
p7.on['click'] = function (e) {e.preventDefault();if (handler8) { handler8(e); } else { context.onEdit(project.id); }};
|
||||||
c6.push({text: \` Edit \`});
|
c7.push({text: \` Edit \`});
|
||||||
var _8 = context['project'].name;
|
var _9 = context['project'].name;
|
||||||
if (_8 || _8 === 0) {
|
if (_9 || _9 === 0) {
|
||||||
c6.push({text: _8});
|
c7.push({text: _9});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
@@ -2207,22 +2207,22 @@ exports[`t-ref refs in a loop 1`] = `
|
|||||||
context.item_index = i1;
|
context.item_index = i1;
|
||||||
context.item = _3[i1];
|
context.item = _3[i1];
|
||||||
context.item_value = _4[i1];
|
context.item_value = _4[i1];
|
||||||
const nodeKey5 = context['item']
|
const nodeKey5 = context['item'];
|
||||||
let c5 = [], p5 = {key:nodeKey5};
|
let c6 = [], p6 = {key:nodeKey5};
|
||||||
var vn5 = h('div', p5, c5);
|
var vn6 = h('div', p6, c6);
|
||||||
c1.push(vn5);
|
c1.push(vn6);
|
||||||
const ref6 = (context['item']);
|
const ref7 = (context['item']);
|
||||||
p5.hook = {
|
p6.hook = {
|
||||||
create: (_, n) => {
|
create: (_, n) => {
|
||||||
context.__owl__.refs[ref6] = n.elm;
|
context.__owl__.refs[ref7] = n.elm;
|
||||||
},
|
},
|
||||||
destroy: () => {
|
destroy: () => {
|
||||||
delete context.__owl__.refs[ref6];
|
delete context.__owl__.refs[ref7];
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
var _7 = context['item'];
|
var _8 = context['item'];
|
||||||
if (_7 || _7 === 0) {
|
if (_8 || _8 === 0) {
|
||||||
c5.push({text: _7});
|
c6.push({text: _8});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return vn1;
|
return vn1;
|
||||||
@@ -2383,16 +2383,16 @@ exports[`t-set t-set should reuse variable if possible 1`] = `
|
|||||||
context.elem_index = i1;
|
context.elem_index = i1;
|
||||||
context.elem = _4[i1];
|
context.elem = _4[i1];
|
||||||
context.elem_value = _5[i1];
|
context.elem_value = _5[i1];
|
||||||
const nodeKey6 = context['elem_index']
|
const nodeKey6 = context['elem_index'];
|
||||||
let c6 = [], p6 = {key:nodeKey6};
|
let c7 = [], p7 = {key:nodeKey6};
|
||||||
var vn6 = h('div', p6, c6);
|
var vn7 = h('div', p7, c7);
|
||||||
c1.push(vn6);
|
c1.push(vn7);
|
||||||
let c7 = [], p7 = {key:7};
|
let c8 = [], p8 = {key:nodeKey6};
|
||||||
var vn7 = h('span', p7, c7);
|
var vn8 = h('span', p8, c8);
|
||||||
c6.push(vn7);
|
c7.push(vn8);
|
||||||
c7.push({text: \`v\`});
|
c8.push({text: \`v\`});
|
||||||
if (_2 || _2 === 0) {
|
if (_2 || _2 === 0) {
|
||||||
c7.push({text: _2});
|
c8.push({text: _2});
|
||||||
}
|
}
|
||||||
_2 = context['elem']
|
_2 = context['elem']
|
||||||
}
|
}
|
||||||
@@ -2415,6 +2415,73 @@ exports[`t-set value priority 1`] = `
|
|||||||
}"
|
}"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
exports[`translation support can translate node content 1`] = `
|
||||||
|
"function anonymous(context,extra
|
||||||
|
) {
|
||||||
|
let sibling = null;
|
||||||
|
var h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
var vn1 = h('div', p1, c1);
|
||||||
|
c1.push({text: \`mot\`});
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`translation support does not translate node content if disabled 1`] = `
|
||||||
|
"function anonymous(context,extra
|
||||||
|
) {
|
||||||
|
let sibling = null;
|
||||||
|
var h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
var vn1 = h('div', p1, c1);
|
||||||
|
let c2 = [], p2 = {key:2};
|
||||||
|
var vn2 = h('span', p2, c2);
|
||||||
|
c1.push(vn2);
|
||||||
|
c2.push({text: \`mot\`});
|
||||||
|
let c3 = [], p3 = {key:3};
|
||||||
|
var vn3 = h('span', p3, c3);
|
||||||
|
c1.push(vn3);
|
||||||
|
c3.push({text: \`word\`});
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`translation support some attributes are translated 1`] = `
|
||||||
|
"function anonymous(context,extra
|
||||||
|
) {
|
||||||
|
let sibling = null;
|
||||||
|
var h = this.h;
|
||||||
|
let c1 = [], p1 = {key:1};
|
||||||
|
var vn1 = h('div', p1, c1);
|
||||||
|
var _2 = 'mot';
|
||||||
|
let c3 = [], p3 = {key:3,attrs:{label: _2}};
|
||||||
|
var vn3 = h('p', p3, c3);
|
||||||
|
c1.push(vn3);
|
||||||
|
c3.push({text: \`mot\`});
|
||||||
|
var _4 = 'mot';
|
||||||
|
let c5 = [], p5 = {key:5,attrs:{title: _4}};
|
||||||
|
var vn5 = h('p', p5, c5);
|
||||||
|
c1.push(vn5);
|
||||||
|
c5.push({text: \`mot\`});
|
||||||
|
var _6 = 'mot';
|
||||||
|
let c7 = [], p7 = {key:7,attrs:{placeholder: _6}};
|
||||||
|
var vn7 = h('p', p7, c7);
|
||||||
|
c1.push(vn7);
|
||||||
|
c7.push({text: \`mot\`});
|
||||||
|
var _8 = 'mot';
|
||||||
|
let c9 = [], p9 = {key:9,attrs:{alt: _8}};
|
||||||
|
var vn9 = h('p', p9, c9);
|
||||||
|
c1.push(vn9);
|
||||||
|
c9.push({text: \`mot\`});
|
||||||
|
var _10 = 'word';
|
||||||
|
let c11 = [], p11 = {key:11,attrs:{something: _10}};
|
||||||
|
var vn11 = h('p', p11, c11);
|
||||||
|
c1.push(vn11);
|
||||||
|
c11.push({text: \`mot\`});
|
||||||
|
return vn1;
|
||||||
|
}"
|
||||||
|
`;
|
||||||
|
|
||||||
exports[`whitespace handling consecutives whitespaces are condensed into a single space 1`] = `
|
exports[`whitespace handling consecutives whitespaces are condensed into a single space 1`] = `
|
||||||
"function anonymous(context,extra
|
"function anonymous(context,extra
|
||||||
) {
|
) {
|
||||||
|
|||||||
+98
-11
@@ -1,5 +1,6 @@
|
|||||||
import { QWeb } from "../../src/qweb/index";
|
import { QWeb } from "../../src/qweb/index";
|
||||||
import { normalize, renderToDOM, renderToString, trim, nextTick } from "../helpers";
|
import { nextTick, normalize, renderToDOM, renderToString, trim } from "../helpers";
|
||||||
|
import { patch } from "../../src/vdom";
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Setup and helpers
|
// Setup and helpers
|
||||||
@@ -659,7 +660,7 @@ describe("t-call (template calling", () => {
|
|||||||
`);
|
`);
|
||||||
const expected = "<div><span>hey</span></div>";
|
const expected = "<div><span>hey</span></div>";
|
||||||
expect(renderToString(qweb, "recursive")).toBe(expected);
|
expect(renderToString(qweb, "recursive")).toBe(expected);
|
||||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -687,7 +688,7 @@ describe("t-call (template calling", () => {
|
|||||||
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
|
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
|
||||||
expected
|
expected
|
||||||
);
|
);
|
||||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -714,7 +715,7 @@ describe("t-call (template calling", () => {
|
|||||||
const expected =
|
const expected =
|
||||||
"<div><div><p>a</p><div><p>b</p><div><p>d</p></div></div><div><p>c</p></div></div></div>";
|
"<div><div><p>a</p><div><p>b</p><div><p>d</p></div></div><div><p>c</p></div></div></div>";
|
||||||
expect(renderToString(qweb, "Parent", { root }, { fiber: {} })).toBe(expected);
|
expect(renderToString(qweb, "Parent", { root }, { fiber: {} })).toBe(expected);
|
||||||
const recursiveFn = Object.values(qweb.recursiveFns)[0];
|
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
|
||||||
expect(recursiveFn.toString()).toMatchSnapshot();
|
expect(recursiveFn.toString()).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -837,6 +838,9 @@ describe("foreach", () => {
|
|||||||
);
|
);
|
||||||
renderToString(qweb, "test");
|
renderToString(qweb, "test");
|
||||||
expect(console.warn).toHaveBeenCalledTimes(1);
|
expect(console.warn).toHaveBeenCalledTimes(1);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith(
|
||||||
|
"Directive t-foreach should always be used with a t-key! (in template: 'test')"
|
||||||
|
);
|
||||||
console.warn = consoleWarn;
|
console.warn = consoleWarn;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1044,8 +1048,8 @@ describe("t-on", () => {
|
|||||||
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
|
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
|
||||||
let owner = {
|
let owner = {
|
||||||
state: {
|
state: {
|
||||||
counter: 0,
|
counter: 0
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.counter).toBe(0);
|
expect(owner.state.counter).toBe(0);
|
||||||
@@ -1058,8 +1062,10 @@ describe("t-on", () => {
|
|||||||
let owner = {
|
let owner = {
|
||||||
state: {
|
state: {
|
||||||
counter: 0,
|
counter: 0,
|
||||||
incrementCounter: (inc) => { owner.state.counter += inc; },
|
incrementCounter: inc => {
|
||||||
},
|
owner.state.counter += inc;
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
|
||||||
expect(owner.state.counter).toBe(0);
|
expect(owner.state.counter).toBe(0);
|
||||||
@@ -1223,7 +1229,7 @@ describe("t-on", () => {
|
|||||||
);
|
);
|
||||||
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
|
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
|
||||||
|
|
||||||
node.addEventListener('click', (e) => {
|
node.addEventListener("click", e => {
|
||||||
expect(e.defaultPrevented).toBe(true);
|
expect(e.defaultPrevented).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1303,12 +1309,12 @@ describe("t-ref", () => {
|
|||||||
|
|
||||||
describe("loading templates", () => {
|
describe("loading templates", () => {
|
||||||
test("can initialize qweb with a string", () => {
|
test("can initialize qweb with a string", () => {
|
||||||
const data = `
|
const templates = `
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<templates id="template" xml:space="preserve">
|
<templates id="template" xml:space="preserve">
|
||||||
<div t-name="hey">jupiler</div>
|
<div t-name="hey">jupiler</div>
|
||||||
</templates>`;
|
</templates>`;
|
||||||
const qweb = new QWeb(data);
|
const qweb = new QWeb({ templates });
|
||||||
expect(renderToString(qweb, "hey")).toBe("<div>jupiler</div>");
|
expect(renderToString(qweb, "hey")).toBe("<div>jupiler</div>");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1517,3 +1523,84 @@ describe("properly support svg", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("translation support", () => {
|
||||||
|
test("can translate node content", () => {
|
||||||
|
const translations = {
|
||||||
|
word: "mot"
|
||||||
|
};
|
||||||
|
const translateFn = expr => translations[expr] || expr;
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
qweb.addTemplate("test", "<div>word</div>");
|
||||||
|
expect(renderToString(qweb, "test")).toBe("<div>mot</div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not translate node content if disabled", () => {
|
||||||
|
const translations = {
|
||||||
|
word: "mot"
|
||||||
|
};
|
||||||
|
const translateFn = expr => translations[expr] || expr;
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<span>word</span>
|
||||||
|
<span t-translation="off">word</span>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
expect(renderToString(qweb, "test")).toBe("<div><span>mot</span><span>word</span></div>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("some attributes are translated", () => {
|
||||||
|
const translations = {
|
||||||
|
word: "mot"
|
||||||
|
};
|
||||||
|
const translateFn = expr => translations[expr] || expr;
|
||||||
|
const qweb = new QWeb({ translateFn });
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<p label="word">word</p>
|
||||||
|
<p title="word">word</p>
|
||||||
|
<p placeholder="word">word</p>
|
||||||
|
<p alt="word">word</p>
|
||||||
|
<p something="word">word</p>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
expect(renderToString(qweb, "test")).toBe(
|
||||||
|
'<div><p label="mot">mot</p><p title="mot">mot</p><p placeholder="mot">mot</p><p alt="mot">mot</p><p something="word">mot</p></div>'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("t-key tests", () => {
|
||||||
|
test("t-key on t-foreach", async () => {
|
||||||
|
qweb.addTemplate(
|
||||||
|
"test",
|
||||||
|
`
|
||||||
|
<div>
|
||||||
|
<t t-foreach="things" t-as="thing" t-key="thing">
|
||||||
|
<span/>
|
||||||
|
</t>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
|
||||||
|
let vnode = qweb.render("test", { things: [1, 2] });
|
||||||
|
vnode = patch(document.createElement("div"), vnode);
|
||||||
|
let elm = vnode.elm as HTMLElement;
|
||||||
|
|
||||||
|
expect(elm.outerHTML).toBe("<div><span></span><span></span></div>");
|
||||||
|
|
||||||
|
const first = elm.querySelectorAll("span")[0];
|
||||||
|
const second = elm.querySelectorAll("span")[1];
|
||||||
|
|
||||||
|
patch(vnode, qweb.render("test", { things: [2, 1] }));
|
||||||
|
|
||||||
|
expect(elm.outerHTML).toBe("<div><span></span><span></span></div>");
|
||||||
|
|
||||||
|
expect(first).toBe(elm.querySelectorAll("span")[1]);
|
||||||
|
expect(second).toBe(elm.querySelectorAll("span")[0]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -11,35 +11,35 @@ exports[`RouteComponent can render simple cases 1`] = `
|
|||||||
let result;
|
let result;
|
||||||
var h = this.h;
|
var h = this.h;
|
||||||
if (context['routeComponent']) {
|
if (context['routeComponent']) {
|
||||||
|
const nodeKey1 = context['env'].router.currentRouteName;
|
||||||
//COMPONENT
|
//COMPONENT
|
||||||
let key3 = 'key' + context['env'].router.currentRouteName;
|
let templateId3 = \`__4__\` + nodeKey1;
|
||||||
let templateId2 = \`__4__\` + key3;
|
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||||
let w2 = templateId2 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId2]] : false;
|
|
||||||
let vn5 = {};
|
let vn5 = {};
|
||||||
result = vn5;
|
result = vn5;
|
||||||
let props2 = Object.assign({}, context['env'].router.currentParams);
|
let props3 = Object.assign({}, context['env'].router.currentParams);
|
||||||
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
|
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||||
w2.destroy();
|
w3.destroy();
|
||||||
w2 = false;
|
w3 = false;
|
||||||
}
|
}
|
||||||
if (w2) {
|
if (w3) {
|
||||||
w2.__updateProps(props2, extra.fiber, undefined, undefined, sibling);
|
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||||
let pvnode = w2.__owl__.pvnode;
|
let pvnode = w3.__owl__.pvnode;
|
||||||
utils.defineProxy(vn5, pvnode);
|
utils.defineProxy(vn5, pvnode);
|
||||||
} else {
|
} else {
|
||||||
let componentKey2 = \`routeComponent\`;
|
let componentKey3 = \`routeComponent\`;
|
||||||
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| context['routeComponent'];
|
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['routeComponent'];
|
||||||
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
|
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||||
w2 = new W2(parent, props2);
|
w3 = new W3(parent, props3);
|
||||||
parent.__owl__.cmap[templateId2] = w2.__owl__.id;
|
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||||
let def1 = w2.__prepare(extra.fiber, undefined, undefined, sibling);
|
let def2 = w3.__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();}}});
|
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 = w2.__owl__.currentFiber;
|
const fiber = w3.__owl__.currentFiber;
|
||||||
def1.then(function () {if (w2.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||||
utils.defineProxy(vn5, pvnode);
|
utils.defineProxy(vn5, pvnode);
|
||||||
w2.__owl__.pvnode = pvnode;
|
w3.__owl__.pvnode = pvnode;
|
||||||
}
|
}
|
||||||
sibling = w2.__owl__.currentFiber || sibling;
|
sibling = w3.__owl__.currentFiber || sibling;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}"
|
}"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ describe("Link component", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = <RouterEnv>makeTestEnv();
|
env = <RouterEnv>makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -38,7 +39,7 @@ describe("Link component", () => {
|
|||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
router.navigate({ to: "users" });
|
router.navigate({ to: "users" });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe('<div><a href="/about">About</a></div>');
|
expect(fixture.innerHTML).toBe('<div><a href="/about">About</a></div>');
|
||||||
|
|
||||||
@@ -69,7 +70,7 @@ describe("Link component", () => {
|
|||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
router.navigate({ to: "users" });
|
router.navigate({ to: "users" });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
|
|
||||||
expect(window.location.pathname).toBe("/users");
|
expect(window.location.pathname).toBe("/users");
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ describe("RouteComponent", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = <RouterEnv>makeTestEnv();
|
env = <RouterEnv>makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -45,7 +46,7 @@ describe("RouteComponent", () => {
|
|||||||
|
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
await router.navigate({ to: "about" });
|
await router.navigate({ to: "about" });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>About</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>About</span></div>");
|
||||||
|
|
||||||
@@ -72,7 +73,7 @@ describe("RouteComponent", () => {
|
|||||||
const routes = [{ name: "book", path: "/book/{{title}}", component: Book }];
|
const routes = [{ name: "book", path: "/book/{{title}}", component: Book }];
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
await router.navigate({ to: "book", params: { title: "1984" } });
|
await router.navigate({ to: "book", params: { title: "1984" } });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>Book 1984</span></div>");
|
||||||
});
|
});
|
||||||
@@ -98,7 +99,7 @@ describe("RouteComponent", () => {
|
|||||||
const routes = [{ name: "book", path: "/book/{{title}}/{{val.number}}", component: Book }];
|
const routes = [{ name: "book", path: "/book/{{title}}/{{val.number}}", component: Book }];
|
||||||
router = new TestRouter(env, routes, { mode: "history" });
|
router = new TestRouter(env, routes, { mode: "history" });
|
||||||
await router.navigate({ to: "book", params: { title: "1984", val: "123" } });
|
await router.navigate({ to: "book", params: { title: "1984", val: "123" } });
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984|124</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>Book 1984|124</span></div>");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -52,6 +52,14 @@ describe("router miscellaneous", () => {
|
|||||||
expect(window.location.hash).toBe("#/users/5");
|
expect(window.location.hash).toBe("#/users/5");
|
||||||
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(2);
|
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("navigate in hash mode preserve location", async () => {
|
||||||
|
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }], { mode: "hash" });
|
||||||
|
window.history.pushState({}, "title", window.location.origin + "/test.html");
|
||||||
|
expect(window.location.href).toBe("http://localhost/test.html");
|
||||||
|
await router.navigate({ to: "users", params: { id: 3 } });
|
||||||
|
expect(window.location.href).toBe("http://localhost/test.html#/users/3");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("routeToPath", () => {
|
describe("routeToPath", () => {
|
||||||
|
|||||||
+25
-22
@@ -12,6 +12,7 @@ describe("connecting a component to store", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -37,7 +38,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div></div>");
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
@@ -69,7 +70,7 @@ describe("connecting a component to store", () => {
|
|||||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>1</span><span>2</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>1</span><span>2</span></div>");
|
||||||
@@ -101,7 +102,7 @@ describe("connecting a component to store", () => {
|
|||||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div></div>");
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
@@ -134,7 +135,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||||
@@ -163,7 +164,7 @@ describe("connecting a component to store", () => {
|
|||||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||||
@@ -198,7 +199,7 @@ describe("connecting a component to store", () => {
|
|||||||
todos = useStore(state => state.todos, { store });
|
todos = useStore(state => state.todos, { store });
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div></div>");
|
expect(fixture.innerHTML).toBe("<div></div>");
|
||||||
@@ -228,7 +229,7 @@ describe("connecting a component to store", () => {
|
|||||||
storeState = useStore(state => state);
|
storeState = useStore(state => state);
|
||||||
dispatch = useDispatch();
|
dispatch = useDispatch();
|
||||||
}
|
}
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><button>Inc</button><span>1</span></div>");
|
expect(fixture.innerHTML).toBe("<div><button>Inc</button><span>1</span></div>");
|
||||||
@@ -257,7 +258,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||||
@@ -294,7 +295,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new TodoList(env);
|
const app = new TodoList();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||||
@@ -347,7 +348,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new TodoList(env);
|
const app = new TodoList();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
@@ -370,7 +371,7 @@ describe("connecting a component to store", () => {
|
|||||||
const state = { beers: { 1: { name: "jupiler" }, 2: { name: "kwak" } } };
|
const state = { beers: { 1: { name: "jupiler" }, 2: { name: "kwak" } } };
|
||||||
const store = new Store({ state });
|
const store = new Store({ state });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||||
@@ -401,7 +402,7 @@ describe("connecting a component to store", () => {
|
|||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
|
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||||
@@ -446,7 +447,7 @@ describe("connecting a component to store", () => {
|
|||||||
};
|
};
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||||
@@ -513,7 +514,7 @@ describe("connecting a component to store", () => {
|
|||||||
};
|
};
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||||
@@ -588,7 +589,7 @@ describe("connecting a component to store", () => {
|
|||||||
|
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new Parent(env);
|
const app = new Parent();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>a</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>a</span></div>");
|
||||||
@@ -639,7 +640,7 @@ describe("connecting a component to store", () => {
|
|||||||
|
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new Parent(env);
|
const app = new Parent();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div><span>abc</span></div>");
|
expect(fixture.innerHTML).toBe("<div><span>abc</span></div>");
|
||||||
@@ -713,7 +714,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new TodoApp(env);
|
const app = new TodoApp();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
@@ -787,7 +788,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new TodoApp(env);
|
const app = new TodoApp();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe(
|
expect(fixture.innerHTML).toBe(
|
||||||
@@ -833,7 +834,7 @@ describe("connecting a component to store", () => {
|
|||||||
|
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>a</div>");
|
expect(fixture.innerHTML).toBe("<div>a</div>");
|
||||||
@@ -870,7 +871,7 @@ describe("connecting a component to store", () => {
|
|||||||
}
|
}
|
||||||
const store = new TestStore({ state: { val: 1 } });
|
const store = new TestStore({ state: { val: 1 } });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const parent = new Parent(env);
|
const parent = new Parent();
|
||||||
|
|
||||||
await parent.mount(fixture);
|
await parent.mount(fixture);
|
||||||
expect(steps).toEqual(["on:update"]);
|
expect(steps).toEqual(["on:update"]);
|
||||||
@@ -901,7 +902,7 @@ describe("connecting a component to store", () => {
|
|||||||
|
|
||||||
const store = new Store({ state, actions });
|
const store = new Store({ state, actions });
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
|
|
||||||
await app.mount(fixture);
|
await app.mount(fixture);
|
||||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||||
@@ -920,6 +921,7 @@ describe("various scenarios", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
fixture = makeTestFixture();
|
fixture = makeTestFixture();
|
||||||
env = makeTestEnv();
|
env = makeTestEnv();
|
||||||
|
Component.env = env;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -978,7 +980,8 @@ describe("various scenarios", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(<any>env).store = store;
|
(<any>env).store = store;
|
||||||
const message = new Message(env);
|
const message = new Message();
|
||||||
|
|
||||||
await message.mount(fixture);
|
await message.mount(fixture);
|
||||||
|
|
||||||
expect(fixture.innerHTML).toMatchSnapshot();
|
expect(fixture.innerHTML).toMatchSnapshot();
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ class Counter extends owl.Component {
|
|||||||
// Message Widget
|
// Message Widget
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
class Message extends owl.Component {
|
class Message extends owl.Component {
|
||||||
static components = { Counter };
|
|
||||||
|
|
||||||
shouldUpdate(nextProps) {
|
shouldUpdate(nextProps) {
|
||||||
return nextProps.message !== this.props.message;
|
return nextProps.message !== this.props.message;
|
||||||
}
|
}
|
||||||
@@ -26,12 +24,11 @@ class Message extends owl.Component {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Message.components = { Counter };
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Root Widget
|
// Root Widget
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
class App extends owl.Component {
|
class App extends owl.Component {
|
||||||
static components = { Message };
|
|
||||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||||
|
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -137,6 +134,7 @@ class App extends owl.Component {
|
|||||||
this.refs.log.innerHTML = "";
|
this.refs.log.innerHTML = "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
App.components = { Message };
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Application initialization
|
// Application initialization
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { buildData, startMeasure, stopMeasure, formatNumber } from "../shared/utils.js";
|
||||||
|
|
||||||
|
const { useState, useRef } = owl.hooks;
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Likes Counter Widget
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
class Counter extends owl.Component {
|
||||||
|
state = useState({ 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 = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
|
||||||
|
logRef = useRef("log");
|
||||||
|
|
||||||
|
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.logRef.el.appendChild(div);
|
||||||
|
this.logRef.el.scrollTop = this.logRef.el.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLog() {
|
||||||
|
this.logRef.el.innerHTML = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// Application initialization
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
async function start() {
|
||||||
|
const templates = await owl.utils.loadFile("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 v0.24.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>
|
||||||
@@ -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="state.multipleFlag"/>
|
||||||
|
<label for="multipleflag">Do it 20x</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" id="clearFlag" t-model="state.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>
|
||||||
@@ -16,8 +16,6 @@ class Counter extends owl.Component {
|
|||||||
// Message Widget
|
// Message Widget
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
class Message extends owl.Component {
|
class Message extends owl.Component {
|
||||||
static components = { Counter };
|
|
||||||
|
|
||||||
shouldUpdate(nextProps) {
|
shouldUpdate(nextProps) {
|
||||||
return nextProps.message !== this.props.message;
|
return nextProps.message !== this.props.message;
|
||||||
}
|
}
|
||||||
@@ -27,12 +25,12 @@ class Message extends owl.Component {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Message.components = { Counter };
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Root Widget
|
// Root Widget
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
class App extends owl.Component {
|
class App extends owl.Component {
|
||||||
static components = { Message };
|
|
||||||
state = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
|
state = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
|
||||||
logRef = useRef("log");
|
logRef = useRef("log");
|
||||||
|
|
||||||
@@ -139,16 +137,17 @@ class App extends owl.Component {
|
|||||||
this.logRef.el.innerHTML = "";
|
this.logRef.el.innerHTML = "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
App.components = { Message };
|
||||||
|
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Application initialization
|
// Application initialization
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
async function start() {
|
async function start() {
|
||||||
const templates = await owl.utils.loadFile("templates.xml");
|
const templates = await owl.utils.loadFile("templates.xml");
|
||||||
const env = {
|
App.env = {
|
||||||
qweb: new owl.QWeb(templates)
|
qweb: new owl.QWeb({ templates })
|
||||||
};
|
};
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,15 +44,17 @@ export function startMeasure(descr) {
|
|||||||
export function stopMeasure(cb) {
|
export function stopMeasure(cb) {
|
||||||
let last = lastMeasure;
|
let last = lastMeasure;
|
||||||
if (lastMeasure) {
|
if (lastMeasure) {
|
||||||
window.setTimeout(function() {
|
window.requestAnimationFrame(() => {
|
||||||
lastMeasure = null;
|
window.setTimeout(function() {
|
||||||
const stop = performance.now();
|
lastMeasure = null;
|
||||||
const delta = stop - startTime;
|
const stop = performance.now();
|
||||||
const msg = `[${last}] took ${formatNumber(delta)}ms`;
|
const delta = stop - startTime;
|
||||||
console.log(msg);
|
const msg = `[${last}] took ${formatNumber(delta)}ms`;
|
||||||
if (cb) {
|
console.log(msg);
|
||||||
cb({ msg, delta });
|
if (cb) {
|
||||||
}
|
cb({ msg, delta });
|
||||||
}, 0);
|
}
|
||||||
|
}, 0);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@
|
|||||||
<li><a href="benchmarks/owl-0.17.0">OWL 0.17.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.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-0.21.0">OWL 0.21.0</a></li>
|
||||||
|
<li><a href="benchmarks/owl-0.24.0">OWL 0.24.0</a></li>
|
||||||
<li><a href="benchmarks/owl-master">OWL Master</a></li>
|
<li><a href="benchmarks/owl-master">OWL Master</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
<ul>
|
<ul>
|
||||||
|
|||||||
+13
-3
@@ -90,7 +90,14 @@ function makeCodeIframe(js, css, xml, errorHandler) {
|
|||||||
owlScript.addEventListener("load", () => {
|
owlScript.addEventListener("load", () => {
|
||||||
const script = doc.createElement("script");
|
const script = doc.createElement("script");
|
||||||
script.type = "text/javascript";
|
script.type = "text/javascript";
|
||||||
const content = `owl.__info__.mode = 'dev';\nwindow.TEMPLATES = \`${sanitizedXML}\`\n${js}`;
|
const content = `
|
||||||
|
{
|
||||||
|
owl.__info__.mode = 'dev';
|
||||||
|
let templates = \`${sanitizedXML}\`;
|
||||||
|
const qweb = new owl.QWeb({ templates });
|
||||||
|
owl.Component.env = { qweb };
|
||||||
|
}
|
||||||
|
${js}`;
|
||||||
script.innerHTML = content;
|
script.innerHTML = content;
|
||||||
iframe.contentWindow.addEventListener("error", errorHandler);
|
iframe.contentWindow.addEventListener("error", errorHandler);
|
||||||
iframe.contentWindow.addEventListener("unhandledrejection", errorHandler);
|
iframe.contentWindow.addEventListener("unhandledrejection", errorHandler);
|
||||||
@@ -429,12 +436,15 @@ App.components = { TabbedEditor };
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
async function start() {
|
async function start() {
|
||||||
document.title = `${document.title} (v${owl.__info__.version})`;
|
document.title = `${document.title} (v${owl.__info__.version})`;
|
||||||
|
const commit = `https://github.com/odoo/owl/commit/${owl.__info__.hash}`;
|
||||||
|
console.info(`This application is using Owl built with the following commit:`, commit);
|
||||||
const [templates] = await Promise.all([
|
const [templates] = await Promise.all([
|
||||||
owl.utils.loadFile("templates.xml"),
|
owl.utils.loadFile("templates.xml"),
|
||||||
owl.utils.whenReady()
|
owl.utils.whenReady()
|
||||||
]);
|
]);
|
||||||
const qweb = new owl.QWeb(templates);
|
const qweb = new owl.QWeb({ templates });
|
||||||
const app = new App({ qweb });
|
owl.Component.env = { qweb };
|
||||||
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+27
-42
@@ -16,9 +16,7 @@ class App extends Component {
|
|||||||
App.components = { Greeter };
|
App.components = { Greeter };
|
||||||
|
|
||||||
// Application setup
|
// Application setup
|
||||||
// Note that the xml templates are injected into the global TEMPLATES variable.
|
const app = new App();
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -70,8 +68,7 @@ class App extends Component {
|
|||||||
}
|
}
|
||||||
App.components = { Counter };
|
App.components = { Counter };
|
||||||
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const app = new App({qweb});
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -228,8 +225,7 @@ class App extends Component {
|
|||||||
}
|
}
|
||||||
App.components = { DemoComponent };
|
App.components = { DemoComponent };
|
||||||
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -298,8 +294,7 @@ class App extends owl.Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Application setup
|
// Application setup
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -349,11 +344,9 @@ const themeContext = new Context({
|
|||||||
background: '#000',
|
background: '#000',
|
||||||
foreground: '#fff',
|
foreground: '#fff',
|
||||||
});
|
});
|
||||||
const env = {
|
// Add the themeContext the environment to make it available to all components
|
||||||
qweb: new owl.QWeb(TEMPLATES),
|
App.env.themeContext = themeContext;
|
||||||
themeContext: themeContext,
|
const app = new App();
|
||||||
};
|
|
||||||
const app = new App(env);
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -534,26 +527,25 @@ TodoApp.components = { TodoItem };
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// App Initialization
|
// App Initialization
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
function saveState(state) {
|
|
||||||
const str = JSON.stringify(state);
|
|
||||||
window.localStorage.setItem(LOCALSTORAGE_KEY, str);
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadState() {
|
function makeStore() {
|
||||||
const localState = window.localStorage.getItem(LOCALSTORAGE_KEY);
|
function saveState(state) {
|
||||||
return localState ? JSON.parse(localState) : initialState;
|
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 state = loadState();
|
||||||
const store = new owl.Store({ state, actions });
|
const store = new owl.Store({ state, actions });
|
||||||
store.on("update", null, () => saveState(store.state));
|
store.on("update", null, () => saveState(store.state));
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
return store;
|
||||||
return { qweb, store };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const env = makeEnv();
|
TodoApp.env.store = makeStore();
|
||||||
const app = new TodoApp(env);
|
const app = new TodoApp();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1040,12 +1032,9 @@ function setupResponsivePlugin(env) {
|
|||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
// Application Startup
|
// Application Startup
|
||||||
//------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------
|
||||||
const env = {
|
setupResponsivePlugin(App.env);
|
||||||
qweb: new owl.QWeb(TEMPLATES),
|
|
||||||
};
|
|
||||||
setupResponsivePlugin(env);
|
|
||||||
|
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1187,8 +1176,7 @@ class App extends Component {
|
|||||||
App.components = {Card, Counter};
|
App.components = {Card, Counter};
|
||||||
|
|
||||||
// Application setup
|
// Application setup
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);`;
|
app.mount(document.body);`;
|
||||||
|
|
||||||
const SLOTS_XML = `<templates>
|
const SLOTS_XML = `<templates>
|
||||||
@@ -1301,10 +1289,9 @@ class App extends Component {
|
|||||||
}, 3000);
|
}, 3000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
App.components = {SlowComponent, NotificationList};
|
App.components = {SlowComponent, NotificationList, AsyncRoot};
|
||||||
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const app = new App();
|
||||||
const app = new App({ qweb });
|
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1373,8 +1360,7 @@ class Form extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Application setup
|
// Application setup
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
const form = new Form();
|
||||||
const form = new Form({ qweb });
|
|
||||||
form.mount(document.body);
|
form.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -1540,7 +1526,6 @@ class App extends Component {
|
|||||||
}
|
}
|
||||||
App.components = { WindowManager };
|
App.components = { WindowManager };
|
||||||
|
|
||||||
const qweb = new owl.QWeb(TEMPLATES);
|
|
||||||
const windows = [
|
const windows = [
|
||||||
{
|
{
|
||||||
name: "Hello",
|
name: "Hello",
|
||||||
@@ -1558,8 +1543,8 @@ const windows = [
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
const env = { qweb, windows };
|
App.env.windows = windows;
|
||||||
const app = new App(env);
|
const app = new App();
|
||||||
app.mount(document.body);
|
app.mount(document.body);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@
|
|||||||
t-att-style="topEditorStyle"/>
|
t-att-style="topEditorStyle"/>
|
||||||
<t t-if="state.splitLayout">
|
<t t-if="state.splitLayout">
|
||||||
<div class="separator horizontal"/>
|
<div class="separator horizontal"/>
|
||||||
<TabbedEditor t-keepalive="1"
|
<TabbedEditor
|
||||||
js="false"
|
js="false"
|
||||||
css="state.css"
|
css="state.css"
|
||||||
xml="state.xml"
|
xml="state.xml"
|
||||||
|
|||||||
Reference in New Issue
Block a user