mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c1269288f5 | |||
| 8c17bb0411 | |||
| 7f6782d009 | |||
| 6e5d6aa226 | |||
| 9400c0adad | |||
| 85d4393242 | |||
| 6c8b401092 | |||
| 12be815342 | |||
| 65344dbf1f | |||
| a6f9b26057 | |||
| 6c753bb49f | |||
| 1f079b883e | |||
| 8fb35ed969 | |||
| a3f2d07b40 | |||
| c993278c80 | |||
| 3aa586db43 | |||
| 14db513f3b | |||
| 7bb04185c7 | |||
| 48744cfa87 | |||
| ff76747a05 | |||
| 7e6b1a28a0 | |||
| 58f6724194 | |||
| 3c0f8ac76f | |||
| cb11c0118c | |||
| 27b4eece66 | |||
| 2e3e8cd603 | |||
| 28ee790b3e | |||
| 2922cee6ea | |||
| 7749fd3b96 | |||
| f44b9a38ae | |||
| c7773bfd2a | |||
| bd39797f17 | |||
| 94a595ef5b | |||
| f83846e054 | |||
| a97144366d | |||
| 79983de4ed | |||
| 54e1734f2f | |||
| 4aea093ed9 | |||
| 56087b95cd | |||
| e5940b4b6b | |||
| bbdc9d90d7 | |||
| f2b3ebd1ec | |||
| 55bb09ba1a |
@@ -1,10 +1,10 @@
|
||||
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">Odoo Web Library</a> 🦉</h1>
|
||||
|
||||
_A no nonsense web framework for structured, dynamic and maintainable applications_
|
||||
_Class based components with hooks, reactive state and concurrent mode_
|
||||
|
||||
## Project Overview
|
||||
|
||||
The Odoo Web Library (OWL) is a smallish (~18kb gzipped) UI framework intended to
|
||||
The Odoo Web Library (OWL) is a smallish (~<20kb gzipped) UI framework intended to
|
||||
be the basis for the [Odoo](https://www.odoo.com/) Web Client. Owl is a modern
|
||||
framework, written in Typescript, taking the best ideas from React and Vue in a
|
||||
simple and consistent way. Owl's main features are:
|
||||
@@ -104,8 +104,8 @@ Submit a PR!
|
||||
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
- [owl-1.0.0-alpha3.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha3/owl.js)
|
||||
- [owl-1.0.0-alpha3.min.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha3/owl.min.js)
|
||||
- [owl-1.0.0-alpha5.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha5/owl.js)
|
||||
- [owl-1.0.0-alpha5.min.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha5/owl.min.js)
|
||||
|
||||
Some npm scripts are available:
|
||||
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
# 🦉 Testing and Debugging Owl components 🦉
|
||||
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Unit Tests](#unit-tests)
|
||||
- [Debugging](#debugging)
|
||||
|
||||
## Overview
|
||||
|
||||
It is a good practice to test applications and components to ensure that they
|
||||
behave as expected. There are many ways to test a user interface: manual
|
||||
testing, integration testing, unit testing, ...
|
||||
|
||||
In this section, we will discuss how to write unit tests for components, and
|
||||
how to debug them if necessary.
|
||||
|
||||
## Unit Tests
|
||||
|
||||
Writing unit tests for Owl components really depends on the testing framework
|
||||
used in a project. But usually, it involves the following steps:
|
||||
|
||||
- create a test file: for example `SomeComponent.test.js`,
|
||||
- in that file, import the code for `SomeComponent`,
|
||||
- add a test case:
|
||||
- create a real DOM element to use as test fixture,
|
||||
- create a test environment
|
||||
- create an instance of `SomeComponent`, mount it to the fixture
|
||||
- interact with the component and assert some properties.
|
||||
|
||||
To help with this, it is useful to have a `helper.js` file that contains some
|
||||
common utility functions:
|
||||
|
||||
```js
|
||||
export function makeTestFixture() {
|
||||
let fixture = document.createElement("div");
|
||||
document.body.appendChild(fixture);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
export function nextTick() {
|
||||
let requestAnimationFrame = owl.Component.scheduler.requestAnimationFrame;
|
||||
return new Promise(function(resolve) {
|
||||
setTimeout(() => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
export function makeTestEnv() {
|
||||
// application specific. It needs a way to load actual templates
|
||||
const templates = ...;
|
||||
|
||||
return {
|
||||
qweb: new QWeb(templates),
|
||||
..., // each service can be mocked here
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
With such a file, a typical test suite for Jest will look like this:
|
||||
|
||||
```js
|
||||
// in SomeComponent.test.js
|
||||
import { SomeComponent } from "../../src/ui/SomeComponent";
|
||||
import { nextTick, makeTestFixture, makeTestEnv} from '../helpers';
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup
|
||||
//------------------------------------------------------------------------------
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
// we set here the default environment for each component created in the test
|
||||
Component.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.remove();
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tests
|
||||
//------------------------------------------------------------------------------
|
||||
describe("SomeComponent", () => {
|
||||
test("component behaves as expected", async () => {
|
||||
const props = {...}; // depends on the component
|
||||
const comp = new SomeComponent(null, props);
|
||||
await comp.mount(fixture);
|
||||
|
||||
// do some assertions
|
||||
expect(...).toBe(...);
|
||||
|
||||
fixture.querySelector('button').click();
|
||||
await nextTick();
|
||||
|
||||
// some other assertions
|
||||
expect(...).toBe(...);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Note that Owl does wait for the next animation frame to actually update the DOM.
|
||||
This is why it is necessary to wait with the `nextTick` (or other methods) to
|
||||
make sure that the DOM is up-to-date.
|
||||
|
||||
It is sometimes useful to wait until Owl is completely done updating components
|
||||
(in particular, if we have a highly concurrent user interface). This next
|
||||
helper simply polls every 20ms the internal Owl task queue and returns a promise
|
||||
which resolves when it is empty:
|
||||
|
||||
```js
|
||||
function afterUpdates() {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = setTimeout(poll, 20);
|
||||
let counter = 0;
|
||||
function poll() {
|
||||
counter++;
|
||||
if (owl.Component.scheduler.tasks.length) {
|
||||
if (counter > 10) {
|
||||
reject(new Error("timeout"));
|
||||
} else {
|
||||
timer = setTimeout(poll);
|
||||
}
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
Non trivial applications become quickly more difficult to understand. It is then
|
||||
useful to have a solid understanding of what is going on. To help with that,
|
||||
the following code can simply be copy/pasted in an application. Once it is
|
||||
executed, it will log a lot of information on each component main hooks.
|
||||
|
||||
```js
|
||||
let current;
|
||||
Object.defineProperty(owl.Component, "current", {
|
||||
get() {
|
||||
return current;
|
||||
},
|
||||
set(comp) {
|
||||
current = comp;
|
||||
const name = comp.constructor.name;
|
||||
let __owl__;
|
||||
Object.defineProperty(current, "__owl__", {
|
||||
get() {
|
||||
return __owl__;
|
||||
},
|
||||
set(val) {
|
||||
__owl__ = val;
|
||||
debugComponent(comp, name, __owl__.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function toStr(props) {
|
||||
let str = JSON.stringify(props || {});
|
||||
if (str.length > 200) {
|
||||
str = str.slice(0, 200) + "...";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function debugComponent(component, name, id) {
|
||||
console.log(`[DEBUG] constructor ${name}<id=${id}>, props=${toStr(component.props)}`);
|
||||
owl.hooks.onWillStart(() => {
|
||||
console.log(`[DEBUG] willStart: '${name}<id=${id}>'`);
|
||||
});
|
||||
owl.hooks.onMounted(() => {
|
||||
console.log(`[DEBUG] mounted: '${name}<id=${id}>'`);
|
||||
});
|
||||
owl.hooks.onWillUpdateProps(nextProps => {
|
||||
console.log(`[DEBUG] willUpdateProps: '${name}<id=${id}> nextprops=${toStr(nextProps)}`);
|
||||
});
|
||||
owl.hooks.onWillPatch(() => {
|
||||
console.log(`[DEBUG] willPatch: '${name}<id=${id}>'`);
|
||||
});
|
||||
owl.hooks.onPatched(() => {
|
||||
console.log(`[DEBUG] patched: '${name}<id=${id}>'`);
|
||||
});
|
||||
owl.hooks.onWillUnmount(() => {
|
||||
console.log(`[DEBUG] willUnmount: '${name}<id=${id}>'`);
|
||||
});
|
||||
const __render = component.__render.bind(component);
|
||||
component.__render = function(...args) {
|
||||
console.log(`[DEBUG] rendering template: '${name}<id=${id}>'`);
|
||||
__render(...args);
|
||||
};
|
||||
const render = component.render.bind(component);
|
||||
component.render = function(...args) {
|
||||
console.log(`[DEBUG] render: '${name}<id=${id}>'`);
|
||||
return render(...args);
|
||||
};
|
||||
const mount = component.mount.bind(component);
|
||||
component.mount = function(...args) {
|
||||
console.log(`[DEBUG] mount: '${name}<id=${id}>'`);
|
||||
return mount(...args);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Note that it is certainly useful to run this code at some point in an application,
|
||||
just to get a feel of what each user action implies, for the framework.
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
- [Quick Start: create an (almost) empty Owl application](learning/quick_start.md)
|
||||
- [Tutorial: create a TodoList application](learning/tutorial_todoapp.md)
|
||||
- [Testing and Debugging Owl components](learning/testing_components.md)
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
|
||||
+44
-18
@@ -239,7 +239,7 @@ We explain here all the public methods of the `Component` class.
|
||||
|
||||
- **`mount(target)`** (async): this is the main way a
|
||||
component is added to the DOM: the root component is mounted to a target
|
||||
HTMLElement. Obviously, this is asynchronous, since each children need to be
|
||||
HTMLElement (or document fragment). Obviously, this is asynchronous, since each children need to be
|
||||
created as well. Most applications will need to call `mount` exactly once, on
|
||||
the root component.
|
||||
|
||||
@@ -247,6 +247,20 @@ We explain here all the public methods of the `Component` class.
|
||||
automatically re-rendered to ensure that changes in its state (or something
|
||||
in the environment, or in the store, or ...) will be taken into account.
|
||||
|
||||
If a component is mounted inside an element or a fragment which is not in the
|
||||
DOM, then it will be rendered fully, but not active: the `mounted` hooks will
|
||||
not be called. This is sometimes useful if we want to load an application in
|
||||
memory. In that case, we need to mount the root component again in an element
|
||||
which is in the DOM:
|
||||
|
||||
```js
|
||||
const app = new App();
|
||||
await app.mount(document.createDocumentFragment());
|
||||
// app is rendered in memory, but not active
|
||||
await app.mount(document.body);
|
||||
// app is now visible
|
||||
```
|
||||
|
||||
- **`unmount()`**: in case a component needs to be detached/removed from the DOM, this
|
||||
method can be used. Most applications should not call `unmount`, this is more
|
||||
useful to the underlying component system.
|
||||
@@ -567,11 +581,13 @@ A _business_ DOM event is triggered by a call to `trigger` on a component.
|
||||
}
|
||||
```
|
||||
|
||||
The call to `trigger` generates a [_CustomEvent_](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
|
||||
of type `menu-loaded` and dispatches it on the component's DOM element
|
||||
(`this.el`). The event bubbles and is cancelable. The parent component listening
|
||||
to event `menu-loaded` will receive the payload in its `someMethod` handler
|
||||
(in the `detail` property of the event), whenever the event is triggered.
|
||||
The call to `trigger` generates an `OwlEvent`, a subclass of [_CustomEvent_](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
|
||||
with an additional attribute `originalComponent` (the component that triggered
|
||||
the event). The generated event is of type `menu-loaded` and dispatches it on
|
||||
the component's DOM element (`this.el`). The event bubbles and is cancelable.
|
||||
The parent component listening to event `menu-loaded` will receive the payload
|
||||
in its `someMethod` handler (in the `detail` property of the event), whenever
|
||||
the event is triggered.
|
||||
|
||||
```js
|
||||
class ParentComponent {
|
||||
@@ -765,15 +781,14 @@ component (with some code like `app.mount(document.body)`).
|
||||
1. `willStart` is called on `E`
|
||||
2. template `E` is rendered
|
||||
|
||||
3. component `A` is patched into a detached DOM element. This will create the actual
|
||||
component `A` DOM structure. The patching process will cause recursively the
|
||||
patching of the `B`, `C`, `D` and `E` DOM trees. (so the actual full DOM tree is created
|
||||
3. each components are patched into a detached DOM element, in the following order:
|
||||
`E`, `D`, `C`, `B`, `A`. (so the actual full DOM tree is created
|
||||
in one pass)
|
||||
|
||||
4. the component `A` root element is actually appended to `document.body`
|
||||
|
||||
5. The method `mounted` is called recursively on all components in the following
|
||||
order: `B`, `D`, `E`, `C`, `A`.
|
||||
order: `E`, `D`, `C`, `B`, `A`.
|
||||
|
||||
**Scenario 2: rerendering a component**. Now, let's assume that the user clicked on some
|
||||
button in `C`, and this results in a state update, which is supposed to:
|
||||
@@ -807,14 +822,14 @@ Here is what Owl will do:
|
||||
3. `willPatch` hooks are called recursively on components `C`, `D` (not on `F`,
|
||||
because it is not mounted yet)
|
||||
|
||||
4. component `C` is patched, which will cause recursively:
|
||||
4. components `F`, `D` are patched in that order
|
||||
|
||||
2. `willUnmount` hook on `E`, then destruction of `E`,
|
||||
3. (initial) patching of `F`, then hook `mounted` is called on `F`
|
||||
5. component `C` is patched, which will cause recursively:
|
||||
|
||||
5. patching of `D`
|
||||
1. `willUnmount` hook on `E`
|
||||
2. destruction of `E`,
|
||||
|
||||
6. `patched` hooks are called on `D`, `C`
|
||||
6. `mounted` hook is called on `F`, `patched` hooks are called on `D`, `C`
|
||||
|
||||
### Props Validation
|
||||
|
||||
@@ -875,10 +890,12 @@ For each key, a `prop` definition is either a boolean, a constructor, a list of
|
||||
- a list of constructors. In that case, this means that we allow more than one
|
||||
type. For example, `id: [Number, String]` means that `id` can be either a string
|
||||
or a number.
|
||||
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed:
|
||||
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed (but not mandatory):
|
||||
- `type`: the main type of the prop being validated
|
||||
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. It is optional (not set means that we only validate the array, not its elements),
|
||||
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. It is optional (not set means that we only validate the object, not its elements)
|
||||
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. If it is not set, then we only validate the array, not its elements,
|
||||
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. If it is not set, then we only validate the object, not its elements,
|
||||
- `validate`: this is a function which should return a boolean to determine if
|
||||
the value is valid or not. Useful for custom validation logic.
|
||||
|
||||
Examples:
|
||||
|
||||
@@ -908,6 +925,13 @@ Examples:
|
||||
someFlag: Boolean, // a boolean, mandatory (even if `false`)
|
||||
someVal: [Boolean, Date], // either a boolean or a date
|
||||
otherValue: true, // indicates that it is a prop
|
||||
kindofsmallnumber: {
|
||||
type: Number,
|
||||
validate: n => (0 <= n && n <= 10)
|
||||
},
|
||||
size: {
|
||||
validate: e => ["small", "medium", "large"].includes(e)
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
@@ -1066,6 +1090,8 @@ class App extends Component<any, any, any> {
|
||||
In this example, the component `App` selects dynamically the concrete sub
|
||||
component class.
|
||||
|
||||
Note that the `t-component` directive can only be used on `<t>` nodes.
|
||||
|
||||
### Asynchronous Rendering
|
||||
|
||||
Working with asynchronous code always adds a lot of complexity to a system. Whenever
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Setting an Environment](#setting-an-environment)
|
||||
- [Using a sub environment](#using-a-sub-environment)
|
||||
- [Content of an Environment](#content-of-an-environment)
|
||||
|
||||
## Overview
|
||||
@@ -65,6 +66,27 @@ by simply doing this:
|
||||
Component.env = myEnv; // will be the default env for all components
|
||||
```
|
||||
|
||||
Note that this environment is the global owl environment for an application. The
|
||||
next section explains how to extend an environment for a specific sub component
|
||||
and its children.
|
||||
|
||||
## Using a sub environment
|
||||
|
||||
It is sometimes useful to add one (or more) specific keys to the environment,
|
||||
from the perspective of a specific component and its children. In that case, the
|
||||
solution presented above will not work, since it sets the global environment.
|
||||
|
||||
There is a hook for this situation: [`useSubEnv`](hooks.md#usesubenv).
|
||||
|
||||
```js
|
||||
class FormComponent extends Component {
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
useSubEnv({ myKey: someValue });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Content of an Environment
|
||||
|
||||
Some good use cases for additional keys in the environment are:
|
||||
|
||||
@@ -152,9 +152,15 @@ class SomeComponent extends Component {
|
||||
}
|
||||
```
|
||||
|
||||
In a hook, the `Component.current` static property is the reference to the
|
||||
component instance that is currently being created. Hooks need to be called in
|
||||
the constructor to ensure that this reference is properly set.
|
||||
As you can see, the `useState` hook does not need to be given a reference to
|
||||
the component. This is possible because there is a way to get a reference to the
|
||||
current component: the `Component.current` static property is the reference to the
|
||||
component instance that is currently being created.
|
||||
|
||||
Hooks need to be called in the constructor to ensure that this reference is
|
||||
properly set. This is also a good thing for performance reasons (Owl can use
|
||||
this to optimize its implementation), and for a clean architecture (this makes
|
||||
it easier for developers to understand what is really happening in a component).
|
||||
|
||||
### `useState`
|
||||
|
||||
|
||||
+21
-10
@@ -252,19 +252,30 @@ The `useStore` hook is used to select some part of the store state. It accepts
|
||||
two arguments:
|
||||
|
||||
- a selector function, which takes the store state as first argument (and the
|
||||
component props as second argument) and returns
|
||||
an object or an array (which will be then observed),
|
||||
- optionally, an object with a `store` key (if we want to override the default
|
||||
store) and an equality function (if we want to specialize the comparison).
|
||||
component props as second argument) and which must return the part of the
|
||||
store state that will be made available and observed for changes,
|
||||
- optionally, an object which can have the following optional keys:
|
||||
- a `store` key containing a store object if we want to use another store than
|
||||
the default store,
|
||||
- an `isEqual` key containing an equality function if we want to specialize
|
||||
the comparison (the function must accept two arguments: the previous result
|
||||
and the new result, and must return whether they are equal),
|
||||
- and an `onUpdate` key containing an update function if we want to execute an
|
||||
arbitrary code every time the selected state changes (the function will
|
||||
receive one argument, the new result, and can execute arbitrary code).
|
||||
|
||||
If the `useStore` callback selects a sub part of the store state, the component
|
||||
If the `useStore` selector returns a sub part of the store state, the component
|
||||
will only be rerendered whenever this part of the state changes. Otherwise, it
|
||||
will perform a strict equality check and will update the component every time this
|
||||
check fails.
|
||||
will perform a strict equality check (unless the `isEqual` option is defined,
|
||||
then it will call it) and will update the component every time this check fails.
|
||||
|
||||
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.
|
||||
Note that if the selector function returns a primitive type, the result of
|
||||
`useStore` will be immutable and it will not react to changes. In this case, it
|
||||
is important to define the `onUpdate` option to properly update the value
|
||||
manually when it changes.
|
||||
|
||||
Also, the return value from `useStore` is not supposed to be modified. The store
|
||||
state should only be updated with actions.
|
||||
|
||||
### `useDispatch`
|
||||
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "owl-framework",
|
||||
"version": "1.0.0-alpha3",
|
||||
"version": "1.0.0-alpha5",
|
||||
"description": "Odoo Web Library (OWL)",
|
||||
"main": "src/index.ts",
|
||||
"engines": {
|
||||
@@ -39,12 +39,13 @@
|
||||
"jest-environment-jsdom": "^24.7.1",
|
||||
"live-server": "^1.2.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^1.19.1",
|
||||
"rollup": "^1.6.0",
|
||||
"rollup-plugin-typescript2": "^0.20.1",
|
||||
"sass": "^1.16.1",
|
||||
"source-map-support": "^0.5.10",
|
||||
"ts-jest": "^23.10.5",
|
||||
"typescript": "^3.6.4",
|
||||
"typescript": "^3.7.2",
|
||||
"uglify-es": "^3.3.9"
|
||||
},
|
||||
"jest": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# 🦉 OWL Roadmap 🦉
|
||||
|
||||
- Current version: 1.0.0-alpha3
|
||||
- Current version: 1.0.0-alpha5
|
||||
- Status: mostly stable
|
||||
|
||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||
|
||||
+102
-106
@@ -1,6 +1,7 @@
|
||||
import { Observer } from "../core/observer";
|
||||
import { OwlEvent } from "../core/owl_event";
|
||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
||||
import { h, patch, VNode } from "../vdom/index";
|
||||
import { patch, VNode } from "../vdom/index";
|
||||
import "./directive";
|
||||
import { Fiber } from "./fiber";
|
||||
import "./props_validation";
|
||||
@@ -60,6 +61,15 @@ interface Internal<T extends Env, Props> {
|
||||
cmap: { [key: number]: number };
|
||||
|
||||
currentFiber: Fiber | null;
|
||||
// parentLastFiberId is there to help the parent component to detect, among
|
||||
// its children, those that are not used anymore and thus can be destroyed
|
||||
parentLastFiberId: number;
|
||||
|
||||
// when a rendering is initiated by a parent, it may set variables in 'scope'
|
||||
// and 'vars' (typically when the component is rendered in a slot). We need to
|
||||
// store that information in case the component would be re-rendered later on.
|
||||
scope: any;
|
||||
vars: any;
|
||||
|
||||
boundHandlers: { [key: number]: any };
|
||||
observer: Observer | null;
|
||||
@@ -169,6 +179,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
children: {},
|
||||
cmap: {},
|
||||
currentFiber: null,
|
||||
parentLastFiberId: 0,
|
||||
boundHandlers: {},
|
||||
mountedCB: null,
|
||||
willUnmountCB: null,
|
||||
@@ -179,7 +190,9 @@ export class Component<T extends Env, Props extends {}> {
|
||||
observer: null,
|
||||
renderFn: qweb.render.bind(qweb, template),
|
||||
classObj: null,
|
||||
refs: null
|
||||
refs: null,
|
||||
scope: null,
|
||||
vars: null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -276,38 +289,24 @@ export class Component<T extends Env, Props extends {}> {
|
||||
*
|
||||
* Note that a component can be mounted an unmounted several times
|
||||
*/
|
||||
async mount(target: HTMLElement): Promise<void> {
|
||||
async mount(target: HTMLElement | DocumentFragment): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.isMounted) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
if (!(target instanceof HTMLElement || target instanceof DocumentFragment)) {
|
||||
let message = `Component '${this.constructor.name}' cannot be mounted: the target is not a valid DOM node.`;
|
||||
message += `\nMaybe the DOM is not ready yet? (in that case, you can use owl.utils.whenReady)`;
|
||||
throw new Error(message);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const fiber = new Fiber(null, this, undefined, undefined, false);
|
||||
scheduler.addFiber(fiber, err => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
if (!__owl__.isDestroyed) {
|
||||
this.__patch(fiber.vnode);
|
||||
target.appendChild(this.el!);
|
||||
if (document.body.contains(target)) {
|
||||
this.__callMounted();
|
||||
}
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
if (!__owl__.vnode) {
|
||||
this.__prepareAndRender(fiber);
|
||||
} else {
|
||||
this.__render(fiber);
|
||||
}
|
||||
});
|
||||
const fiber = new Fiber(null, this, false, target);
|
||||
fiber.shouldPatch = false;
|
||||
if (!__owl__.vnode) {
|
||||
this.__prepareAndRender(fiber);
|
||||
} else {
|
||||
this.__render(fiber);
|
||||
}
|
||||
return scheduler.addFiber(fiber);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,26 +331,34 @@ export class Component<T extends Env, Props extends {}> {
|
||||
*/
|
||||
async render(force: boolean = false): Promise<void> {
|
||||
const __owl__ = this.__owl__;
|
||||
if (
|
||||
(!__owl__.isMounted && !__owl__.currentFiber) ||
|
||||
(__owl__.currentFiber && !__owl__.currentFiber.isRendered)
|
||||
) {
|
||||
if (!__owl__.isMounted && !__owl__.currentFiber) {
|
||||
// if we get here, this means that the component was either never mounted,
|
||||
// or was unmounted and some state change triggered a render. Either way,
|
||||
// we do not want to actually render anything in this case.
|
||||
return;
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const fiber = new Fiber(null, this, undefined, undefined, force);
|
||||
scheduler.addFiber(fiber.root, err => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
if (__owl__.isMounted && fiber === fiber.root) {
|
||||
fiber.patchComponents();
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
this.__render(fiber);
|
||||
if (__owl__.currentFiber && !__owl__.currentFiber.isRendered) {
|
||||
return scheduler.addFiber(__owl__.currentFiber.root);
|
||||
}
|
||||
// if we aren't mounted at this point, it implies that there is a
|
||||
// currentFiber that is already rendered (isRendered is true), so we are
|
||||
// about to be mounted
|
||||
const isMounted = __owl__.isMounted;
|
||||
const fiber = new Fiber(null, this, force, null);
|
||||
Promise.resolve().then(() => {
|
||||
if (__owl__.isMounted || !isMounted) {
|
||||
// we are mounted (__owl__.isMounted), or if we are currently being
|
||||
// mounted (!isMounted), so we call __render
|
||||
this.__render(fiber);
|
||||
} else {
|
||||
// we were mounted when render was called, but we aren't anymore, so we
|
||||
// were actually about to be unmounted ; we can thus forget about this
|
||||
// fiber
|
||||
fiber.isCompleted = true;
|
||||
__owl__.currentFiber = null;
|
||||
}
|
||||
});
|
||||
return scheduler.addFiber(fiber);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -391,7 +398,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
*/
|
||||
trigger(eventType: string, payload?: any) {
|
||||
if (this.el) {
|
||||
const ev = new CustomEvent(eventType, {
|
||||
const ev = new OwlEvent(this, eventType, {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
detail: payload
|
||||
@@ -437,27 +444,18 @@ export class Component<T extends Env, Props extends {}> {
|
||||
__owl__.isDestroyed = true;
|
||||
delete __owl__.vnode;
|
||||
if (__owl__.currentFiber) {
|
||||
__owl__.currentFiber.isCancelled = true;
|
||||
__owl__.currentFiber.isCompleted = true;
|
||||
}
|
||||
}
|
||||
|
||||
__callMounted() {
|
||||
const __owl__ = this.__owl__;
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
const comp = children[id];
|
||||
if (!comp.__owl__.isMounted && this.el!.contains(comp.el)) {
|
||||
comp.__callMounted();
|
||||
}
|
||||
}
|
||||
|
||||
__owl__.isMounted = true;
|
||||
try {
|
||||
this.mounted();
|
||||
if (__owl__.mountedCB) {
|
||||
__owl__.mountedCB();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e); // TODO : add a test
|
||||
__owl__.currentFiber = null;
|
||||
this.mounted();
|
||||
if (__owl__.mountedCB) {
|
||||
__owl__.mountedCB();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +466,10 @@ export class Component<T extends Env, Props extends {}> {
|
||||
}
|
||||
this.willUnmount();
|
||||
__owl__.isMounted = false;
|
||||
if (this.__owl__.currentFiber) {
|
||||
this.__owl__.currentFiber.isCompleted = true;
|
||||
this.__owl__.currentFiber.root.counter = 0;
|
||||
}
|
||||
const children = __owl__.children;
|
||||
for (let id in children) {
|
||||
const comp = children[id];
|
||||
@@ -481,22 +483,19 @@ export class Component<T extends Env, Props extends {}> {
|
||||
* The __updateProps method is called by the t-component directive whenever
|
||||
* it updates a component (so, when the parent template is rerendered).
|
||||
*/
|
||||
async __updateProps(
|
||||
nextProps: Props,
|
||||
parentFiber: Fiber,
|
||||
scope: any,
|
||||
vars: any,
|
||||
previousSibling?: Fiber | null
|
||||
): Promise<void> {
|
||||
async __updateProps(nextProps: Props, parentFiber: Fiber, scope: any, vars: any): Promise<void> {
|
||||
this.__owl__.scope = scope;
|
||||
this.__owl__.vars = vars;
|
||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||
if (shouldUpdate) {
|
||||
const __owl__ = this.__owl__;
|
||||
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null);
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
} else {
|
||||
previousSibling!.sibling = fiber;
|
||||
parentFiber.lastChild!.sibling = fiber;
|
||||
}
|
||||
parentFiber.lastChild = fiber;
|
||||
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
if (defaultProps) {
|
||||
@@ -509,7 +508,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
this.willUpdateProps(nextProps),
|
||||
__owl__.willUpdatePropsCB && __owl__.willUpdatePropsCB(nextProps)
|
||||
]);
|
||||
if (fiber.isCancelled) {
|
||||
if (fiber.isCompleted) {
|
||||
return;
|
||||
}
|
||||
this.props = nextProps;
|
||||
@@ -522,11 +521,10 @@ export class Component<T extends Env, Props extends {}> {
|
||||
* Main patching method. We call the virtual dom patch method here to convert
|
||||
* a virtual dom vnode into some actual dom.
|
||||
*/
|
||||
__patch(vnode) {
|
||||
__patch(vnode: VNode) {
|
||||
const __owl__ = this.__owl__;
|
||||
const target = __owl__.vnode || document.createElement(vnode.sel!);
|
||||
__owl__.vnode = patch(target, vnode);
|
||||
__owl__.currentFiber = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -534,14 +532,17 @@ export class Component<T extends Env, Props extends {}> {
|
||||
* subcomponent is created. It gets its scope and vars, if any, from the
|
||||
* parent template.
|
||||
*/
|
||||
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
||||
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||
__prepare(parentFiber: Fiber, scope: any, vars: any) {
|
||||
this.__owl__.scope = scope;
|
||||
this.__owl__.vars = vars;
|
||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null);
|
||||
fiber.shouldPatch = false;
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
} else {
|
||||
previousSibling!.sibling = fiber;
|
||||
parentFiber.lastChild!.sibling = fiber;
|
||||
}
|
||||
parentFiber.lastChild = fiber;
|
||||
return this.__prepareAndRender(fiber);
|
||||
}
|
||||
|
||||
@@ -569,13 +570,12 @@ export class Component<T extends Env, Props extends {}> {
|
||||
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
|
||||
} catch (e) {
|
||||
fiber.handleError(e);
|
||||
fiber.vnode = h("div"); // -> we render this div at the end
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this.__owl__.isDestroyed) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!fiber.isCancelled) {
|
||||
if (!fiber.isCompleted) {
|
||||
this.__render(fiber);
|
||||
}
|
||||
}
|
||||
@@ -585,49 +585,45 @@ export class Component<T extends Env, Props extends {}> {
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = false;
|
||||
}
|
||||
let vnode;
|
||||
let error;
|
||||
try {
|
||||
vnode = __owl__.renderFn!(this, {
|
||||
let vnode = __owl__.renderFn!(this, {
|
||||
handlers: __owl__.boundHandlers,
|
||||
fiber: fiber
|
||||
});
|
||||
// we iterate over the children to detect those that no longer belong to the
|
||||
// current rendering: those ones, if not mounted yet, can (and have to) be
|
||||
// destroyed right now, because they are not in the DOM, and thus we won't
|
||||
// be notified later on (when patching), that they are removed from the DOM
|
||||
for (let childKey in __owl__.children) {
|
||||
let child = __owl__.children[childKey];
|
||||
if (!child.__owl__.isMounted && child.__owl__.parentLastFiberId < fiber.id) {
|
||||
child.destroy();
|
||||
}
|
||||
}
|
||||
if (!vnode) {
|
||||
throw new Error(`Rendering '${this.constructor.name}' did not return anything`);
|
||||
}
|
||||
fiber.vnode = vnode;
|
||||
// we apply here the class information described on the component by the
|
||||
// template (so, something like <MyComponent class="..."/>) to the actual
|
||||
// root vnode
|
||||
if (__owl__.classObj) {
|
||||
const data = vnode.data!;
|
||||
data.class = Object.assign(data.class || {}, __owl__.classObj);
|
||||
}
|
||||
} catch (e) {
|
||||
vnode = __owl__.vnode || h("div");
|
||||
fiber.handleError(e);
|
||||
error = e;
|
||||
}
|
||||
fiber.vnode = vnode;
|
||||
if (__owl__.observer) {
|
||||
__owl__.observer.allowMutations = true;
|
||||
}
|
||||
|
||||
// we apply here the class information described on the component by the
|
||||
// template (so, something like <MyComponent class="..."/>) to the actual
|
||||
// root vnode
|
||||
if (__owl__.classObj) {
|
||||
vnode.data.class = Object.assign(vnode.data.class || {}, __owl__.classObj);
|
||||
}
|
||||
fiber.root.counter--;
|
||||
fiber.isRendered = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only called by qweb t-component directive
|
||||
*/
|
||||
__mount(fiber: Fiber, elm: HTMLElement): VNode {
|
||||
if (fiber !== this.__owl__.currentFiber) {
|
||||
fiber = this.__owl__.currentFiber!; // TODO: check if we can remove fiber arg
|
||||
if (error) {
|
||||
fiber.handleError(error);
|
||||
}
|
||||
const vnode = fiber.vnode!;
|
||||
const __owl__ = this.__owl__;
|
||||
if (__owl__.classObj) {
|
||||
(<any>vnode).data.class = Object.assign((<any>vnode).data.class || {}, __owl__.classObj);
|
||||
}
|
||||
__owl__.vnode = patch(elm, vnode);
|
||||
__owl__.currentFiber = null;
|
||||
if (__owl__.parent!.__owl__.isMounted && !__owl__.isMounted) {
|
||||
this.__callMounted();
|
||||
}
|
||||
return __owl__.vnode;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+16
-24
@@ -229,19 +229,7 @@ QWeb.addDirective({
|
||||
let defID = ctx.generateID();
|
||||
let componentID = ctx.generateID();
|
||||
|
||||
let locationExpr = `\`__${ctx.generateID()}__`;
|
||||
for (let i = 0; i < ctx.loopNumber - 1; i++) {
|
||||
locationExpr += `\${i${i + 1}}__`;
|
||||
}
|
||||
if (ctx.lastNodeKey || ctx.currentKey) {
|
||||
const k = ctx.lastNodeKey || ctx.currentKey;
|
||||
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
|
||||
} else {
|
||||
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
|
||||
ctx.addLine(`let templateId${componentID} = ${locationExpr};`);
|
||||
}
|
||||
const templateId = `templateId${componentID}`;
|
||||
|
||||
const templateKey = ctx.generateTemplateKey();
|
||||
let ref = node.getAttribute("t-ref");
|
||||
let refExpr = "";
|
||||
let refKey: string = "";
|
||||
@@ -251,10 +239,6 @@ QWeb.addDirective({
|
||||
ctx.addLine(`const ${refKey} = ${ctx.interpolate(ref)};`);
|
||||
refExpr = `context.__owl__.refs[${refKey}] = w${componentID};`;
|
||||
}
|
||||
let transitionsInsertCode = "";
|
||||
if (transition) {
|
||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
||||
}
|
||||
let finalizeComponentCode = `w${componentID}.destroy();`;
|
||||
if (ref) {
|
||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||
@@ -263,6 +247,7 @@ QWeb.addDirective({
|
||||
finalizeComponentCode = `let finalize = () => {
|
||||
${finalizeComponentCode}
|
||||
};
|
||||
delete w${componentID}.__owl__.transitionInserted;
|
||||
utils.transitionRemove(vn, '${transition}', finalize);`;
|
||||
}
|
||||
|
||||
@@ -334,7 +319,7 @@ QWeb.addDirective({
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let w${componentID} = ${templateId} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateId}]] : false;`
|
||||
`let w${componentID} = ${templateKey} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateKey}]] : false;`
|
||||
);
|
||||
let shouldProxy = !ctx.parentNode;
|
||||
if (shouldProxy) {
|
||||
@@ -393,7 +378,7 @@ QWeb.addDirective({
|
||||
}
|
||||
ctx.addLine(
|
||||
`w${componentID}.__updateProps(props${componentID}, extra.fiber${scopeVars &&
|
||||
", " + scopeVars}, sibling)${styleCode};`
|
||||
", " + scopeVars})${styleCode};`
|
||||
);
|
||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
||||
if (registerCode) {
|
||||
@@ -421,7 +406,13 @@ QWeb.addDirective({
|
||||
`if (!W${componentID}) {throw new Error('Cannot find the definition of component "' + componentKey${componentID} + '"')}`
|
||||
);
|
||||
ctx.addLine(`w${componentID} = new W${componentID}(parent, props${componentID});`);
|
||||
ctx.addLine(`parent.__owl__.cmap[${templateId}] = w${componentID}.__owl__.id;`);
|
||||
if (transition) {
|
||||
ctx.addLine(`const __patch${componentID} = w${componentID}.__patch;`);
|
||||
ctx.addLine(
|
||||
`w${componentID}.__patch = fiber => {__patch${componentID}.call(w${componentID}, fiber); if(!w${componentID}.__owl__.transitionInserted){w${componentID}.__owl__.transitionInserted = true;utils.transitionInsert(w${componentID}.__owl__.vnode, '${transition}');}};`
|
||||
);
|
||||
}
|
||||
ctx.addLine(`parent.__owl__.cmap[${templateKey}] = w${componentID}.__owl__.id;`);
|
||||
|
||||
if (hasSlots) {
|
||||
const clone = <Element>node.cloneNode(true);
|
||||
@@ -448,14 +439,15 @@ QWeb.addDirective({
|
||||
}
|
||||
}
|
||||
|
||||
ctx.addLine(`let def${defID} = w${componentID}.__prepare(extra.fiber, ${scopeVars}, sibling);`);
|
||||
ctx.addLine(`let def${defID} = w${componentID}.__prepare(extra.fiber, ${scopeVars});`);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
const insertHook = refExpr ? `insert(vn) {${refExpr}},` : "";
|
||||
ctx.addLine(
|
||||
`let pvnode = h('dummy', {key: ${templateId}, hook: {insert(vn) { let nvn=w${componentID}.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeComponentCode}}}});`
|
||||
`let pvnode = h('dummy', {key: ${templateKey}, hook: {${insertHook}remove() {},destroy(vn) {${finalizeComponentCode}}}});`
|
||||
);
|
||||
ctx.addLine(`const fiber = w${componentID}.__owl__.currentFiber;`);
|
||||
ctx.addLine(
|
||||
`def${defID}.then(function () {if (fiber.isCancelled) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
`def${defID}.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
);
|
||||
if (registerCode) {
|
||||
ctx.addLine(registerCode);
|
||||
@@ -471,7 +463,7 @@ QWeb.addDirective({
|
||||
ctx.addLine(`w${componentID}.__owl__.classObj=${classObj};`);
|
||||
}
|
||||
|
||||
ctx.addLine(`sibling = w${componentID}.__owl__.currentFiber || sibling;`);
|
||||
ctx.addLine(`w${componentID}.__owl__.parentLastFiberId = extra.fiber.id;`);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
+102
-41
@@ -1,4 +1,4 @@
|
||||
import { VNode } from "../vdom/index";
|
||||
import { h, VNode } from "../vdom/index";
|
||||
import { Component } from "./component";
|
||||
import { scheduler } from "./scheduler";
|
||||
|
||||
@@ -16,13 +16,17 @@ import { scheduler } from "./scheduler";
|
||||
*/
|
||||
|
||||
export class Fiber {
|
||||
static nextId: number = 1;
|
||||
id: number = Fiber.nextId++;
|
||||
|
||||
// The force attribute determines if a rendering should bypass the `shouldUpdate`
|
||||
// method potentially implemented by a component. It is usually set to false.
|
||||
force: boolean;
|
||||
|
||||
// isCancelled means that the rendering corresponding to this fiber and its
|
||||
// children is cancelled. No extra work should be done.
|
||||
isCancelled: boolean = false;
|
||||
// isCompleted means that the rendering corresponding to this fiber's work is
|
||||
// done, either because the component has been mounted or patched, or because
|
||||
// fiber has been cancelled.
|
||||
isCompleted: boolean = false;
|
||||
|
||||
// the fibers corresponding to component updates (updateProps) need to call
|
||||
// the willPatch and patched hooks from the corresponding component. However,
|
||||
@@ -42,6 +46,8 @@ export class Fiber {
|
||||
// scheduler.
|
||||
counter: number = 0;
|
||||
|
||||
target: HTMLElement | null;
|
||||
|
||||
scope: any;
|
||||
vars: any;
|
||||
|
||||
@@ -51,27 +57,59 @@ export class Fiber {
|
||||
root: Fiber;
|
||||
child: Fiber | null = null;
|
||||
sibling: Fiber | null = null;
|
||||
lastChild: Fiber | null = null;
|
||||
parent: Fiber | null = null;
|
||||
|
||||
error?: Error;
|
||||
|
||||
constructor(parent: Fiber | null, component: Component<any, any>, scope, vars, force) {
|
||||
this.force = force;
|
||||
this.scope = scope;
|
||||
this.vars = vars;
|
||||
constructor(parent: Fiber | null, component: Component<any, any>, force, target) {
|
||||
this.component = component;
|
||||
this.force = force;
|
||||
this.target = target;
|
||||
|
||||
const __owl__ = component.__owl__;
|
||||
this.scope = __owl__.scope;
|
||||
this.vars = __owl__.vars;
|
||||
|
||||
this.root = parent ? parent.root : this;
|
||||
this.parent = parent;
|
||||
|
||||
let oldFiber = component.__owl__.currentFiber;
|
||||
if (oldFiber && !oldFiber.isCancelled) {
|
||||
this._remapFiber(oldFiber);
|
||||
let oldFiber = __owl__.currentFiber;
|
||||
if (oldFiber && !oldFiber.isCompleted) {
|
||||
if (oldFiber.root === oldFiber && !parent) {
|
||||
// both oldFiber and this fiber are root fibers
|
||||
this._reuseFiber(oldFiber);
|
||||
return oldFiber;
|
||||
} else {
|
||||
this._remapFiber(oldFiber);
|
||||
}
|
||||
}
|
||||
|
||||
this.root.counter++;
|
||||
|
||||
component.__owl__.currentFiber = this;
|
||||
__owl__.currentFiber = this;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the oldFiber is not completed yet, and both oldFiber and this fiber
|
||||
* are root fibers, we want to reuse the oldFiber instead of creating a new
|
||||
* one. Doing so will guarantee that the initiator(s) of those renderings will
|
||||
* be notified (the promise will resolve) when the last rendering will be done.
|
||||
*
|
||||
* This function thus assumes that oldFiber is a root fiber.
|
||||
*/
|
||||
_reuseFiber(oldFiber: Fiber) {
|
||||
oldFiber.cancel(); // cancel children fibers
|
||||
oldFiber.isCompleted = false; // keep the root fiber alive
|
||||
oldFiber.isRendered = false; // the fiber has to be re-rendered
|
||||
if (oldFiber.child) {
|
||||
// remove relation to children
|
||||
oldFiber.child.parent = null;
|
||||
oldFiber.child = null;
|
||||
oldFiber.lastChild = null;
|
||||
}
|
||||
oldFiber.counter = 1; // re-initialize counter
|
||||
oldFiber.id = Fiber.nextId++;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,14 +120,18 @@ export class Fiber {
|
||||
*/
|
||||
_remapFiber(oldFiber: Fiber) {
|
||||
oldFiber.cancel();
|
||||
this.shouldPatch = oldFiber.shouldPatch;
|
||||
if (oldFiber === oldFiber.root) {
|
||||
oldFiber.root.counter++;
|
||||
oldFiber.counter++;
|
||||
}
|
||||
if (oldFiber.parent && !this.parent) {
|
||||
// re-map links
|
||||
this.parent = oldFiber.parent;
|
||||
this.root = this.parent.root;
|
||||
this.sibling = oldFiber.sibling;
|
||||
if (this.parent.lastChild === oldFiber) {
|
||||
this.parent.lastChild = this;
|
||||
}
|
||||
if (this.parent.child === oldFiber) {
|
||||
this.parent.child = this;
|
||||
} else {
|
||||
@@ -132,48 +174,68 @@ export class Fiber {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the given patch queue from a fiber.
|
||||
* 1) Call 'willPatch' on the component of each patch
|
||||
* 2) Call '__patch' on the component of each patch
|
||||
* 3) Call 'patched' on the component of each patch, in reverse order
|
||||
* Successfully complete the work of the fiber: call the mount or patch hooks
|
||||
* and patch the DOM. This function is called once the fiber and its children
|
||||
* are ready, and the scheduler decides to process it.
|
||||
*/
|
||||
patchComponents() {
|
||||
complete() {
|
||||
let component = this.component;
|
||||
this.isCompleted = true;
|
||||
if (!this.target && !component.__owl__.isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
// build patchQueue
|
||||
const patchQueue: Fiber[] = [];
|
||||
const doWork: (Fiber) => Fiber | null = function(f) {
|
||||
if (f.shouldPatch) {
|
||||
patchQueue.push(f);
|
||||
}
|
||||
patchQueue.push(f);
|
||||
return f.child;
|
||||
};
|
||||
this._walk(doWork);
|
||||
let component: Component<any, any> = this.component;
|
||||
const patchLen = patchQueue.length;
|
||||
try {
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
component = patchQueue[i].component;
|
||||
|
||||
// call willPatch hook on each fiber of patchQueue
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
const fiber = patchQueue[i];
|
||||
if (fiber.shouldPatch) {
|
||||
component = fiber.component;
|
||||
if (component.__owl__.willPatchCB) {
|
||||
component.__owl__.willPatchCB();
|
||||
}
|
||||
component.willPatch();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
for (let i = 0; i < patchLen; i++) {
|
||||
|
||||
// call __patch on each fiber of (reversed) patchQueue
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
const fiber = patchQueue[i];
|
||||
component = fiber.component;
|
||||
component.__patch(fiber.vnode);
|
||||
component.__patch(fiber.vnode!);
|
||||
if (!fiber.shouldPatch && (!fiber.target || i !== 0)) {
|
||||
component.__owl__.pvnode!.elm = component.__owl__.vnode!.elm;
|
||||
}
|
||||
component.__owl__.currentFiber = null;
|
||||
}
|
||||
try {
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
component = patchQueue[i].component;
|
||||
|
||||
// insert into the DOM (mount case)
|
||||
let inDOM = false;
|
||||
if (this.target) {
|
||||
this.target.appendChild(this.component.el!);
|
||||
inDOM = document.body.contains(this.target);
|
||||
}
|
||||
|
||||
// call patched/mounted hook on each fiber of (reversed) patchQueue
|
||||
for (let i = patchLen - 1; i >= 0; i--) {
|
||||
const fiber = patchQueue[i];
|
||||
component = fiber.component;
|
||||
if (fiber.shouldPatch && !this.target) {
|
||||
component.patched();
|
||||
if (component.__owl__.patchedCB) {
|
||||
component.__owl__.patchedCB();
|
||||
}
|
||||
} else if (this.target ? inDOM : true) {
|
||||
component.__callMounted();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +247,7 @@ export class Fiber {
|
||||
if (!f.isRendered) {
|
||||
f.root.counter--;
|
||||
}
|
||||
f.isCancelled = true;
|
||||
f.isCompleted = true;
|
||||
return f.child;
|
||||
});
|
||||
}
|
||||
@@ -199,10 +261,12 @@ export class Fiber {
|
||||
* being in a corrupted state.
|
||||
*/
|
||||
handleError(error: Error) {
|
||||
let canCatch = false;
|
||||
let component = this.component;
|
||||
let qweb = component.env.qweb;
|
||||
this.vnode = component.__owl__.vnode || h("div");
|
||||
|
||||
const qweb = component.env.qweb;
|
||||
let root = component;
|
||||
let canCatch = false;
|
||||
while (component && !(canCatch = !!component.catchError)) {
|
||||
root = component;
|
||||
component = component.__owl__.parent!;
|
||||
@@ -210,10 +274,7 @@ export class Fiber {
|
||||
qweb.trigger("error", error);
|
||||
|
||||
if (canCatch) {
|
||||
setTimeout(() => {
|
||||
console.error(error);
|
||||
component.catchError!(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
|
||||
|
||||
@@ -48,7 +48,7 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
|
||||
throw e;
|
||||
}
|
||||
if (!isValid) {
|
||||
throw new Error(`Props '${propName}' of invalid type in component '${Widget.name}'`);
|
||||
throw new Error(`Invalid Prop '${propName}' in component '${Widget.name}'`);
|
||||
}
|
||||
}
|
||||
for (let propName in props) {
|
||||
@@ -89,13 +89,16 @@ function isValidProp(prop, propDef): boolean {
|
||||
if (propDef.optional && prop === undefined) {
|
||||
return true;
|
||||
}
|
||||
let result = isValidProp(prop, propDef.type);
|
||||
if (propDef.type === Array) {
|
||||
let result = propDef.type ? isValidProp(prop, propDef.type) : true;
|
||||
if (propDef.validate) {
|
||||
result = result && propDef.validate(prop);
|
||||
}
|
||||
if (propDef.type === Array && propDef.element) {
|
||||
for (let i = 0, iLen = prop.length; i < iLen; i++) {
|
||||
result = result && isValidProp(prop[i], propDef.element);
|
||||
}
|
||||
}
|
||||
if (propDef.type === Object) {
|
||||
if (propDef.type === Object && propDef.shape) {
|
||||
const shape = propDef.shape;
|
||||
for (let key in shape) {
|
||||
result = result && isValidProp(prop[key], shape[key]);
|
||||
|
||||
@@ -25,12 +25,27 @@ export class Scheduler {
|
||||
this.requestAnimationFrame = requestAnimationFrame;
|
||||
}
|
||||
|
||||
addFiber(fiber, callback) {
|
||||
this.tasks.push({ fiber, callback });
|
||||
if (this.isRunning) {
|
||||
return;
|
||||
}
|
||||
this.scheduleTasks();
|
||||
addFiber(fiber): Promise<void> {
|
||||
// if the fiber was remapped into a larger rendering fiber, it may not be a
|
||||
// root fiber. But we only want to register root fibers
|
||||
fiber = fiber.root;
|
||||
return new Promise((resolve, reject) => {
|
||||
if (fiber.error) {
|
||||
return reject(fiber.error);
|
||||
}
|
||||
this.tasks.push({
|
||||
fiber,
|
||||
callback: () => {
|
||||
if (fiber.error) {
|
||||
return reject(fiber.error);
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
if (!this.isRunning) {
|
||||
this.scheduleTasks();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,11 +56,19 @@ export class Scheduler {
|
||||
let tasks = this.tasks;
|
||||
this.tasks = [];
|
||||
tasks = tasks.filter(task => {
|
||||
if (task.fiber.isCancelled) {
|
||||
if (task.fiber.isCompleted) {
|
||||
task.callback();
|
||||
return false;
|
||||
}
|
||||
if (task.fiber.counter === 0) {
|
||||
task.callback(task.fiber.error);
|
||||
if (!task.fiber.error) {
|
||||
try {
|
||||
task.fiber.complete();
|
||||
} catch (e) {
|
||||
task.fiber.handleError(e);
|
||||
}
|
||||
}
|
||||
task.callback();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
+17
-12
@@ -2,7 +2,7 @@ import { Component } from "./component/component";
|
||||
import { scheduler } from "./component/scheduler";
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { onWillUnmount } from "./hooks";
|
||||
|
||||
/**
|
||||
* The `Context` object provides a way to share data between an arbitrary number
|
||||
* of component. Usually, data is passed from a parent to its children component,
|
||||
@@ -45,7 +45,16 @@ export class Context extends EventBus {
|
||||
constructor(state: Object = {}) {
|
||||
super();
|
||||
this.observer = new Observer();
|
||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
||||
this.observer.notifyCB = () => {
|
||||
// notify components in the next microtask tick to ensure that subscribers
|
||||
// are notified only once for all changes that occur in the same micro tick
|
||||
let rev = this.rev;
|
||||
return Promise.resolve().then(() => {
|
||||
if (rev === this.rev) {
|
||||
this.__notifyComponents();
|
||||
}
|
||||
});
|
||||
};
|
||||
this.state = this.observer.observe(state);
|
||||
this.subscriptions.update = [];
|
||||
}
|
||||
@@ -72,13 +81,7 @@ export class Context extends EventBus {
|
||||
const subscriptions = this.subscriptions.update;
|
||||
const groups = partitionBy(subscriptions, s => (s.owner ? s.owner.__owl__.depth : -1));
|
||||
for (let group of groups) {
|
||||
const proms = Promise.all(
|
||||
group.map(sub => {
|
||||
if (sub.owner ? sub.owner.__owl__.isMounted : true) {
|
||||
return sub.callback.call(sub.owner, rev);
|
||||
}
|
||||
})
|
||||
);
|
||||
const proms = group.map(sub => sub.callback.call(sub.owner, rev));
|
||||
// at this point, each component in the current group has registered a
|
||||
// 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
|
||||
@@ -87,7 +90,7 @@ export class Context extends EventBus {
|
||||
// promise to resolve earlier, which means that there is a chance of
|
||||
// processing the next group in the same frame.
|
||||
scheduler.flush();
|
||||
await proms;
|
||||
await Promise.all(proms);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,9 +138,11 @@ export function useContextWithCB(ctx: Context, component: Component<any, any>, m
|
||||
await method();
|
||||
}
|
||||
});
|
||||
onWillUnmount(() => {
|
||||
const __destroy = component.__destroy;
|
||||
component.__destroy = parent => {
|
||||
ctx.off("update", component);
|
||||
delete mapping[id];
|
||||
});
|
||||
__destroy.call(component, parent);
|
||||
};
|
||||
return ctx.state;
|
||||
}
|
||||
|
||||
+2
-10
@@ -24,14 +24,6 @@ export class Observer {
|
||||
weakMap: WeakMap<any, any> = new WeakMap();
|
||||
|
||||
notifyCB() {}
|
||||
async notifyChange() {
|
||||
this.dirty = true;
|
||||
await Promise.resolve();
|
||||
if (this.dirty) {
|
||||
this.dirty = false;
|
||||
this.notifyCB();
|
||||
}
|
||||
}
|
||||
|
||||
observe<T>(value: T, parent?: any): T {
|
||||
if (value === null || typeof value !== "object" || value instanceof Date) {
|
||||
@@ -65,7 +57,7 @@ export class Observer {
|
||||
}
|
||||
self._updateRevNumber(target);
|
||||
target[key] = newVal;
|
||||
self.notifyChange();
|
||||
self.notifyCB();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
@@ -73,7 +65,7 @@ export class Observer {
|
||||
if (key in target) {
|
||||
delete target[key];
|
||||
self._updateRevNumber(target);
|
||||
self.notifyChange();
|
||||
self.notifyCB();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Component } from "../component/component";
|
||||
|
||||
/**
|
||||
* We define here OwlEvent, a subclass of CustomEvent, with an additional
|
||||
* attribute:
|
||||
* - originalComponent: the component that triggered the event
|
||||
*/
|
||||
|
||||
export class OwlEvent<T> extends CustomEvent<T> {
|
||||
originalComponent: Component<any, any>;
|
||||
constructor(component, eventType, options) {
|
||||
super(eventType, options);
|
||||
this.originalComponent = component;
|
||||
}
|
||||
}
|
||||
+24
-19
@@ -1,5 +1,4 @@
|
||||
import { CompilationContext } from "./compilation_context";
|
||||
import { QWebExprVar } from "./expression_parser";
|
||||
import { QWeb } from "./qweb";
|
||||
import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||
|
||||
@@ -29,12 +28,15 @@ QWeb.utils.getFragment = function(str: string): DocumentFragment {
|
||||
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
||||
if (value === "0" && ctx.caller) {
|
||||
qweb._compileNode(ctx.caller, ctx);
|
||||
return;
|
||||
if (value === "0") {
|
||||
const caller = ctx.getCaller();
|
||||
if (caller) {
|
||||
qweb._compileNode(caller, ctx.getInliningContext());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (value.xml instanceof NodeList) {
|
||||
if (value.xml instanceof NodeList && !value.id) {
|
||||
for (let node of Array.from(value.xml)) {
|
||||
qweb._compileNode(<ChildNode>node, ctx);
|
||||
}
|
||||
@@ -71,6 +73,12 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Compilatio
|
||||
qweb._compileChildren(node, ctx);
|
||||
}
|
||||
|
||||
if (value.xml instanceof NodeList && value.id) {
|
||||
ctx.addElse();
|
||||
for (let node of Array.from(value.xml)) {
|
||||
qweb._compileNode(<ChildNode>node, ctx);
|
||||
}
|
||||
}
|
||||
ctx.closeIf();
|
||||
}
|
||||
|
||||
@@ -104,22 +112,21 @@ QWeb.addDirective({
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
const variable = node.getAttribute("t-set")!;
|
||||
let value = node.getAttribute("t-value")!;
|
||||
ctx.variables[variable] = ctx.variables[variable] || {};
|
||||
let qwebvar = ctx.variables[variable];
|
||||
|
||||
if (value) {
|
||||
const formattedValue = ctx.formatExpression(value);
|
||||
if (ctx.variables.hasOwnProperty(variable)) {
|
||||
ctx.addLine(`${(<QWebExprVar>ctx.variables[variable]).id} = ${formattedValue}`);
|
||||
if (ctx.variables.hasOwnProperty(variable) && qwebvar.id) {
|
||||
ctx.addLine(`${qwebvar.id} = ${formattedValue}`);
|
||||
} else {
|
||||
const varName = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
||||
ctx.variables[variable] = {
|
||||
id: varName,
|
||||
expr: formattedValue
|
||||
};
|
||||
qwebvar.id = varName;
|
||||
qwebvar.expr = formattedValue;
|
||||
}
|
||||
} else {
|
||||
ctx.variables[variable] = {
|
||||
xml: node.childNodes
|
||||
};
|
||||
qwebvar.xml = node.childNodes;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -133,7 +140,7 @@ QWeb.addDirective({
|
||||
priority: 20,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : cond.id);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : cond.id!);
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
@@ -188,11 +195,9 @@ QWeb.addDirective({
|
||||
|
||||
// extract variables from nodecopy
|
||||
const tempCtx = new CompilationContext();
|
||||
tempCtx.nextID = ctx.rootContext.nextID;
|
||||
tempCtx.allowMultipleRoots = true;
|
||||
qweb._compileNode(nodeCopy, tempCtx);
|
||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
||||
ctx.rootContext.nextID = tempCtx.nextID;
|
||||
|
||||
const templateMap = Object.create(ctx.templates);
|
||||
// open new scope, if necessary
|
||||
@@ -244,8 +249,8 @@ QWeb.addDirective({
|
||||
// add new variables, if any
|
||||
for (let key in tempCtx.variables) {
|
||||
const v = tempCtx.variables[key];
|
||||
if ((<QWebExprVar>v).expr) {
|
||||
ctx.addLine(`let ${(<QWebExprVar>v).id} = ${(<QWebExprVar>v).expr};`);
|
||||
if (v.expr) {
|
||||
ctx.addLine(`let ${v.id} = ${v.expr};`);
|
||||
}
|
||||
// todo: handle XML variables...
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { compileExpr, QWebVar, QWebExprVar } from "./expression_parser";
|
||||
import { compileExpr, QWebVar } from "./expression_parser";
|
||||
|
||||
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -6,7 +6,7 @@ export const INTERP_REGEXP = /\{\{.*?\}\}/g;
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export class CompilationContext {
|
||||
nextID: number = 1;
|
||||
static nextID: number = 1;
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: QWebVar } = {};
|
||||
escaping: boolean = false;
|
||||
@@ -22,7 +22,6 @@ export class CompilationContext {
|
||||
shouldDefineUtils: boolean = false;
|
||||
shouldDefineRefs: boolean = false;
|
||||
shouldDefineResult: boolean = true;
|
||||
shouldDefineSibling: boolean = true;
|
||||
shouldProtectContext: boolean = false;
|
||||
shouldTrackScope: boolean = false;
|
||||
loopNumber: number = 0;
|
||||
@@ -32,8 +31,9 @@ export class CompilationContext {
|
||||
hasParentWidget: boolean = false;
|
||||
scopeVars: any[] = [];
|
||||
currentKey: string = "";
|
||||
lastNodeKey: string = ""; // temp variable to communicate to previous caller
|
||||
templates: { [key: string]: boolean } = {};
|
||||
callingLevel: number = 0;
|
||||
inliningLevel: number = 0;
|
||||
|
||||
constructor(name?: string) {
|
||||
this.rootContext = this;
|
||||
@@ -43,8 +43,31 @@ export class CompilationContext {
|
||||
}
|
||||
|
||||
generateID(): number {
|
||||
const id = this.rootContext.nextID++;
|
||||
return id;
|
||||
return CompilationContext.nextID++;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method generates a "template key", which is basically a unique key
|
||||
* which depends on the currently set keys, and on the iteration numbers (if
|
||||
* we are in a loop).
|
||||
*
|
||||
* Such a key is necessary when we need to associate an id to some element
|
||||
* generated by a template (for example, a component)
|
||||
*/
|
||||
generateTemplateKey(): string {
|
||||
const id = this.generateID();
|
||||
let locationExpr = `\`__${this.generateID()}__`;
|
||||
for (let i = 0; i < this.loopNumber - 1; i++) {
|
||||
locationExpr += `\${i${i + 1}}__`;
|
||||
}
|
||||
if (this.currentKey) {
|
||||
const k = this.currentKey;
|
||||
this.addLine(`let k${id} = ${locationExpr}\` + ${k};`);
|
||||
} else {
|
||||
locationExpr += this.loopNumber ? `\${i${this.loopNumber}}__\`` : "`";
|
||||
this.addLine(`let k${id} = ${locationExpr};`);
|
||||
}
|
||||
return `k${id}`;
|
||||
}
|
||||
|
||||
generateCode(): string[] {
|
||||
@@ -64,9 +87,6 @@ export class CompilationContext {
|
||||
if (this.shouldDefineResult) {
|
||||
this.code.unshift(" let result;");
|
||||
}
|
||||
if (this.shouldDefineSibling) {
|
||||
this.code.unshift(" let sibling = null;");
|
||||
}
|
||||
if (this.shouldDefineRefs) {
|
||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
||||
}
|
||||
@@ -111,6 +131,10 @@ export class CompilationContext {
|
||||
subContext(key: keyof CompilationContext, value: any): CompilationContext {
|
||||
const newContext = Object.create(this);
|
||||
newContext[key] = value;
|
||||
if (key === "caller") {
|
||||
newContext.callingLevel++;
|
||||
newContext.inliningLevel++;
|
||||
}
|
||||
return newContext;
|
||||
}
|
||||
|
||||
@@ -148,8 +172,29 @@ export class CompilationContext {
|
||||
this.dedent();
|
||||
this.addLine("}");
|
||||
}
|
||||
/**
|
||||
* Recursively (inverse) fetches the `caller` of a context
|
||||
* Useful to determine to which t-call a t-raw="0" refers
|
||||
*/
|
||||
getCaller(targetLevel?: number): Element | null {
|
||||
if (targetLevel === undefined) {
|
||||
targetLevel = this.inliningLevel;
|
||||
}
|
||||
if (targetLevel === this.callingLevel) {
|
||||
return this.caller || null;
|
||||
}
|
||||
const proto = (this as any).__proto__;
|
||||
return proto ? proto.getCaller(targetLevel) : null;
|
||||
}
|
||||
/**
|
||||
* Marks the context with the current recursive level
|
||||
* in which we are for inlining archs (t-raw="0")
|
||||
*/
|
||||
getInliningContext(): CompilationContext {
|
||||
return this.subContext("inliningLevel", this.inliningLevel - 1);
|
||||
}
|
||||
|
||||
getValue(val: any): QWebExprVar | string {
|
||||
getValue(val: any): QWebVar | string {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
// Misc types, constants and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,typeof,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||
","
|
||||
);
|
||||
|
||||
@@ -38,17 +38,12 @@ const WORD_REPLACEMENT = {
|
||||
lte: "<="
|
||||
};
|
||||
|
||||
export interface QWebExprVar {
|
||||
id: string;
|
||||
expr: string;
|
||||
export interface QWebVar {
|
||||
id?: string;
|
||||
expr?: string;
|
||||
xml?: NodeList;
|
||||
}
|
||||
|
||||
export interface QWebXMLVar {
|
||||
xml: NodeList;
|
||||
}
|
||||
|
||||
export type QWebVar = QWebExprVar | QWebXMLVar;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tokenizer
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -82,7 +77,9 @@ const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
||||
")": "RIGHT_PAREN"
|
||||
};
|
||||
|
||||
const OPERATORS = ".,===,==,+,!==,!=,!,||,&&,>=,>,<=,<,?,-,*,/,%".split(",");
|
||||
// note that the space after typeof is relevant. It makes sure that the formatted
|
||||
// expression has a space after typeof
|
||||
const OPERATORS = ".,===,==,+,!==,!=,!,||,&&,>=,>,<=,<,?,-,*,/,%,typeof ".split(",");
|
||||
|
||||
type Tokenizer = (expr: string) => Token | false;
|
||||
|
||||
@@ -165,9 +162,9 @@ const tokenizeOperator: Tokenizer = function(expr) {
|
||||
const TOKENIZERS = [
|
||||
tokenizeString,
|
||||
tokenizeNumber,
|
||||
tokenizeOperator,
|
||||
tokenizeSymbol,
|
||||
tokenizeStatic,
|
||||
tokenizeOperator
|
||||
tokenizeStatic
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -252,7 +249,7 @@ export function compileExpr(expr: string, vars: { [key: string]: QWebVar }): str
|
||||
}
|
||||
if (isVar) {
|
||||
if (token.value in vars && "id" in vars[token.value]) {
|
||||
token.value = (<QWebExprVar>vars[token.value]).id;
|
||||
token.value = vars[token.value].id!;
|
||||
} else {
|
||||
token.value = `context['${token.value}']`;
|
||||
}
|
||||
|
||||
+21
-8
@@ -105,6 +105,8 @@ QWeb.utils.transitionInsert = function(vn: VNode, name: string) {
|
||||
|
||||
elm.classList.add(name + "-enter");
|
||||
elm.classList.add(name + "-enter-active");
|
||||
elm.classList.remove(name + "-leave-active");
|
||||
elm.classList.remove(name + "-leave-to");
|
||||
const finalize = () => {
|
||||
elm.classList.remove(name + "-enter-active");
|
||||
elm.classList.remove(name + "-enter-to");
|
||||
@@ -123,6 +125,9 @@ QWeb.utils.transitionRemove = function(vn: VNode, name: string, rm: () => void)
|
||||
elm.classList.add(name + "-leave");
|
||||
elm.classList.add(name + "-leave-active");
|
||||
const finalize = () => {
|
||||
if (!elm.classList.contains(name + "-leave-active")) {
|
||||
return;
|
||||
}
|
||||
elm.classList.remove(name + "-leave-active");
|
||||
elm.classList.remove(name + "-leave-to");
|
||||
rm();
|
||||
@@ -201,12 +206,12 @@ QWeb.addDirective({
|
||||
if (!ctx.parentNode) {
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
parentNode = `children${ctx.nextID++}`;
|
||||
parentNode = `children${ctx.generateID()}`;
|
||||
ctx.addLine(`let ${parentNode}= []`);
|
||||
ctx.addLine(`result = {}`);
|
||||
}
|
||||
ctx.addLine(
|
||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, vars: extra.vars, parent: owner}));`
|
||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, vars: extra.vars, parent: extra.parent || owner}));`
|
||||
);
|
||||
if (!ctx.parentNode) {
|
||||
ctx.addLine(`utils.defineProxy(result, ${parentNode}[0]);`);
|
||||
@@ -231,7 +236,17 @@ QWeb.addDirective({
|
||||
const type = node.getAttribute("type");
|
||||
let handler;
|
||||
let event = fullName.includes(".lazy") ? "change" : "input";
|
||||
const expr = ctx.formatExpression(value);
|
||||
|
||||
// we keep here a reference to the "base expression" (if the expression
|
||||
// is `t-model="some.expr.value", then the base expression is "some.expr").
|
||||
// This is necessary so we can capture it in the handler closure.
|
||||
let expr = ctx.formatExpression(value);
|
||||
const index = expr.lastIndexOf(".");
|
||||
const baseExpr = expr.slice(0, index);
|
||||
ctx.addLine(`let expr${nodeID} = ${baseExpr};`);
|
||||
|
||||
expr = `expr${nodeID}.${expr.slice(index + 1)}`;
|
||||
const key = ctx.generateTemplateKey();
|
||||
if (node.tagName === "select") {
|
||||
ctx.addLine(`p${nodeID}.props = {value: ${expr}};`);
|
||||
addNodeHook("create", `n.elm.value=${expr};`);
|
||||
@@ -255,10 +270,8 @@ QWeb.addDirective({
|
||||
}
|
||||
handler = `(ev) => {${expr} = ${valueCode}}`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`extra.handlers['${event}' + ${nodeID}] = extra.handlers['${event}' + ${nodeID}] || (${handler});`
|
||||
);
|
||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
|
||||
ctx.addLine(`extra.handlers[${key}] = extra.handlers[${key}] || (${handler});`);
|
||||
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers[${key}];`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -271,6 +284,6 @@ QWeb.addDirective({
|
||||
atNodeEncounter({ ctx, value }) {
|
||||
let id = ctx.generateID();
|
||||
ctx.addLine(`const nodeKey${id} = ${ctx.formatExpression(value)};`);
|
||||
ctx.lastNodeKey = `nodeKey${id}`;
|
||||
ctx.currentKey = `nodeKey${id}`;
|
||||
}
|
||||
});
|
||||
|
||||
+10
-4
@@ -362,8 +362,7 @@ export class QWeb extends EventBus {
|
||||
if (parentContext) {
|
||||
ctx.templates = Object.create(parentContext.templates);
|
||||
ctx.variables = Object.create(parentContext.variables);
|
||||
ctx.nextID = parentContext.nextID + 1;
|
||||
ctx.parentNode = parentContext.parentNode || ctx.nextID++;
|
||||
ctx.parentNode = parentContext.parentNode || ctx.generateID();
|
||||
ctx.allowMultipleRoots = true;
|
||||
ctx.hasParentWidget = true;
|
||||
ctx.shouldDefineResult = false;
|
||||
@@ -455,11 +454,19 @@ export class QWeb extends EventBus {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx !== ctx.rootContext) {
|
||||
ctx = ctx.subContext("currentKey", ctx.currentKey);
|
||||
}
|
||||
|
||||
const firstLetter = node.tagName[0];
|
||||
if (firstLetter === firstLetter.toUpperCase()) {
|
||||
// this is a component, we modify in place the xml document to change
|
||||
// <SomeComponent ... /> to <t t-component="SomeComponent" ... />
|
||||
node.setAttribute("t-component", node.tagName);
|
||||
} else if (node.tagName !== "t" && node.hasAttribute("t-component")) {
|
||||
throw new Error(
|
||||
`Directive 't-component' can only be used on <t> nodes (used on a <${node.tagName}>)`
|
||||
);
|
||||
}
|
||||
const attributes = (<Element>node).attributes;
|
||||
|
||||
@@ -540,7 +547,6 @@ export class QWeb extends EventBus {
|
||||
if (node.nodeName !== "t") {
|
||||
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
|
||||
ctx = ctx.withParent(nodeID);
|
||||
ctx = ctx.subContext("currentKey", ctx.lastNodeKey);
|
||||
let nodeHooks = {};
|
||||
let addNodeHook = function(hook, handler) {
|
||||
nodeHooks[hook] = nodeHooks[hook] || [];
|
||||
@@ -724,7 +730,7 @@ export class QWeb extends EventBus {
|
||||
}
|
||||
}
|
||||
let nodeID = ctx.generateID();
|
||||
let nodeKey = ctx.lastNodeKey || nodeID;
|
||||
let nodeKey = ctx.currentKey || nodeID;
|
||||
const parts = [`key:${nodeKey}`];
|
||||
if (attrs.length + tattrs.length > 0) {
|
||||
parts.push(`attrs:{${attrs.join(",")}}`);
|
||||
|
||||
+29
-17
@@ -77,58 +77,70 @@ export class Store extends Context {
|
||||
interface SelectorOptions {
|
||||
store?: Store;
|
||||
isEqual?: (a: any, b: any) => boolean;
|
||||
onUpdate?: (result: any) => any;
|
||||
}
|
||||
|
||||
const isStrictEqual = (a, b) => a === b;
|
||||
|
||||
export function useStore(selector, options: SelectorOptions = {}): any {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
const componentId = component.__owl__.id;
|
||||
const store = options.store || (component.env.store as Store);
|
||||
if (!(store instanceof Store)) {
|
||||
throw new Error(`No store found when connecting '${component.constructor.name}'`);
|
||||
}
|
||||
let result = selector(store.state, component.props);
|
||||
const hashFn = store.observer.revNumber.bind(store.observer);
|
||||
let revNumber = hashFn(result) || result;
|
||||
let revNumber = hashFn(result);
|
||||
const isEqual = options.isEqual || isStrictEqual;
|
||||
if (!store.updateFunctions[component.__owl__.id]) {
|
||||
store.updateFunctions[component.__owl__.id] = [];
|
||||
if (!store.updateFunctions[componentId]) {
|
||||
store.updateFunctions[componentId] = [];
|
||||
}
|
||||
const updateFunctions = store.updateFunctions[component.__owl__.id];
|
||||
updateFunctions.push(function(): boolean {
|
||||
function selectCompareUpdate(state, props): boolean {
|
||||
const oldResult = result;
|
||||
result = selector(store!.state, component.props);
|
||||
result = selector(state, props);
|
||||
const newRevNumber = hashFn(result);
|
||||
if (
|
||||
(newRevNumber > 0 && revNumber !== newRevNumber) ||
|
||||
(newRevNumber === 0 && !isEqual(oldResult, result))
|
||||
) {
|
||||
if ((newRevNumber > 0 && revNumber !== newRevNumber) || !isEqual(oldResult, result)) {
|
||||
revNumber = newRevNumber;
|
||||
if (options.onUpdate) {
|
||||
options.onUpdate(result);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
store.updateFunctions[componentId].push(function(): boolean {
|
||||
return selectCompareUpdate(store!.state, component.props);
|
||||
});
|
||||
|
||||
useContextWithCB(store, component, function(): Promise<void> | void {
|
||||
let shouldRender = false;
|
||||
updateFunctions.forEach(function(updateFn) {
|
||||
shouldRender = updateFn() || shouldRender;
|
||||
});
|
||||
for (let fn of store.updateFunctions[componentId]) {
|
||||
shouldRender = fn() || shouldRender;
|
||||
}
|
||||
if (shouldRender) {
|
||||
return component.render();
|
||||
}
|
||||
});
|
||||
onWillUpdateProps(props => {
|
||||
delete store.updateFunctions[component.__owl__.id];
|
||||
result = selector(store.state, props);
|
||||
selectCompareUpdate(store.state, props);
|
||||
});
|
||||
|
||||
const __destroy = component.__destroy;
|
||||
component.__destroy = parent => {
|
||||
delete store.updateFunctions[componentId];
|
||||
__destroy.call(component, parent);
|
||||
};
|
||||
|
||||
if (typeof result !== "object") {
|
||||
return result;
|
||||
}
|
||||
return new Proxy(result, {
|
||||
get(target, k) {
|
||||
return result[k];
|
||||
},
|
||||
set(target, k, v) {
|
||||
result[k] = v;
|
||||
return true;
|
||||
throw new Error("Store state should only be modified through actions");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,10 +20,8 @@ function htmlToVNode(node: ChildNode): VNode {
|
||||
attrs[attr.name] = attr.textContent;
|
||||
}
|
||||
const children: VNode[] = [];
|
||||
if (node.hasChildNodes) {
|
||||
for (let c of node.childNodes) {
|
||||
children.push(htmlToVNode(c));
|
||||
}
|
||||
for (let c of node.childNodes) {
|
||||
children.push(htmlToVNode(c));
|
||||
}
|
||||
return h((node as Element).tagName, { attrs }, children);
|
||||
}
|
||||
|
||||
+7
-5
@@ -101,7 +101,7 @@ function isVnode(vnode: any): vnode is VNode {
|
||||
|
||||
type KeyToIndexMap = { [key: string]: number };
|
||||
|
||||
type ArraysOf<T> = { [K in keyof T]: (T[K])[] };
|
||||
type ArraysOf<T> = { [K in keyof T]: T[K][] };
|
||||
|
||||
type ModuleHooks = ArraysOf<Module>;
|
||||
|
||||
@@ -176,10 +176,12 @@ export function init(modules: Array<Partial<Module>>, domApi?: DOMAPI) {
|
||||
}
|
||||
vnode.elm = api.createComment(vnode.text as string);
|
||||
} else if (sel !== undefined) {
|
||||
const elm = (vnode.elm =
|
||||
isDef(data) && isDef((i = (data as VNodeData).ns))
|
||||
? api.createElementNS(i, sel)
|
||||
: api.createElement(sel));
|
||||
const elm =
|
||||
vnode.elm ||
|
||||
(vnode.elm =
|
||||
isDef(data) && isDef((i = (data as VNodeData).ns))
|
||||
? api.createElementNS(i, sel)
|
||||
: api.createElement(sel));
|
||||
for (i = 0, iLen = cbs.create.length; i < iLen; ++i) cbs.create[i](emptyNode, vnode);
|
||||
if (array(children)) {
|
||||
for (i = 0, iLen = children.length; i < iLen; ++i) {
|
||||
|
||||
@@ -7,20 +7,19 @@ exports[`animations t-transition combined with component 1`] = `
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let k4 = \`__5__\`;
|
||||
let w3 = k4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k4]] : false;
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
@@ -28,18 +27,21 @@ exports[`animations t-transition combined with component 1`] = `
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
const __patch3 = w3.__patch;
|
||||
w3.__patch = fiber => {__patch3.call(w3, fiber); if(!w3.__owl__.transitionInserted){w3.__owl__.transitionInserted = true;utils.transitionInsert(w3.__owl__.vnode, 'chimay');}};
|
||||
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined);
|
||||
let pvnode = h('dummy', {key: k4, hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||
w3.destroy();
|
||||
};
|
||||
delete w3.__owl__.transitionInserted;
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (fiber.isCancelled) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
def2.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
@@ -51,21 +53,20 @@ exports[`animations t-transition combined with t-component and t-if 1`] = `
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['state'].display) {
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let k4 = \`__5__\`;
|
||||
let w3 = k4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k4]] : false;
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
@@ -73,18 +74,69 @@ exports[`animations t-transition combined with t-component and t-if 1`] = `
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
const __patch3 = w3.__patch;
|
||||
w3.__patch = fiber => {__patch3.call(w3, fiber); if(!w3.__owl__.transitionInserted){w3.__owl__.transitionInserted = true;utils.transitionInsert(w3.__owl__.vnode, 'chimay');}};
|
||||
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined);
|
||||
let pvnode = h('dummy', {key: k4, hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||
w3.destroy();
|
||||
};
|
||||
delete w3.__owl__.transitionInserted;
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (fiber.isCancelled) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
def2.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`animations t-transition combined with t-component, remove and re-add before transitionend 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['state'].flag) {
|
||||
//COMPONENT
|
||||
let k4 = \`__5__\`;
|
||||
let w3 = k4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k4]] : false;
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
let componentKey3 = \`Child\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
const __patch3 = w3.__patch;
|
||||
w3.__patch = fiber => {__patch3.call(w3, fiber); if(!w3.__owl__.transitionInserted){w3.__owl__.transitionInserted = true;utils.transitionInsert(w3.__owl__.vnode, 'chimay');}};
|
||||
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined);
|
||||
let pvnode = h('dummy', {key: k4, hook: {remove() {},destroy(vn) {let finalize = () => {
|
||||
w3.destroy();
|
||||
};
|
||||
delete w3.__owl__.transitionInserted;
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
@@ -94,7 +146,6 @@ exports[`animations t-transition with no delay/duration 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('span', p1, c1);
|
||||
@@ -115,7 +166,6 @@ exports[`animations t-transition, on a simple node (insert) 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('span', p1, c1);
|
||||
|
||||
+74
-25
@@ -1,13 +1,15 @@
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { QWeb } from "../src/qweb/index";
|
||||
import { useState, useRef } from "../src/hooks";
|
||||
import { xml } from "../src/tags";
|
||||
import {
|
||||
makeDeferred,
|
||||
makeTestFixture,
|
||||
makeTestEnv,
|
||||
patchNextFrame,
|
||||
renderToDOM,
|
||||
unpatchNextFrame
|
||||
unpatchNextFrame,
|
||||
nextTick
|
||||
} from "./helpers";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -252,11 +254,11 @@ describe("animations", () => {
|
||||
widget.state.display = false;
|
||||
patchNextFrame(cb => {
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__4__">blue</span></div>'
|
||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="__5__">blue</span></div>'
|
||||
);
|
||||
cb();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__4__">blue</span></div>'
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__5__">blue</span></div>'
|
||||
);
|
||||
def.resolve();
|
||||
});
|
||||
@@ -321,30 +323,23 @@ describe("animations", () => {
|
||||
});
|
||||
|
||||
test("t-transition combined with t-component, remove and re-add before transitionend", async () => {
|
||||
expect.assertions(11);
|
||||
expect.assertions(12);
|
||||
|
||||
env.qweb.addTemplates(
|
||||
`<templates>
|
||||
<div t-name="Parent">
|
||||
<button t-on-click="toggle">Toggle</button>
|
||||
<t t-if="state.flag" t-component="Child" t-transition="chimay"/>
|
||||
</div>
|
||||
<span t-name="Child">blue</span>
|
||||
</templates>`
|
||||
);
|
||||
class Child extends Widget {}
|
||||
class Child extends Widget {
|
||||
static template = xml`<span>blue</span>`;
|
||||
}
|
||||
class Parent extends Widget {
|
||||
static template = xml`
|
||||
<div t-name="Parent">
|
||||
<t t-if="state.flag" t-component="Child" t-transition="chimay"/>
|
||||
</div>`;
|
||||
static components = { Child };
|
||||
state = useState({ flag: false });
|
||||
|
||||
toggle() {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new Parent();
|
||||
await widget.mount(fixture);
|
||||
let button = widget.el!.querySelector("button");
|
||||
expect(env.qweb.templates[Parent.template].fn.toString()).toMatchSnapshot();
|
||||
|
||||
let def = makeDeferred();
|
||||
let phase = "enter";
|
||||
@@ -357,24 +352,78 @@ describe("animations", () => {
|
||||
def.resolve();
|
||||
});
|
||||
|
||||
// click display the span
|
||||
button!.click();
|
||||
// display the span
|
||||
widget.state.flag = true;
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
||||
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
||||
|
||||
// click to remove the span, and click again to re-add it before transitionend
|
||||
def = makeDeferred();
|
||||
phase = "leave";
|
||||
button!.click();
|
||||
|
||||
widget.state.flag = false;
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
def = makeDeferred();
|
||||
phase = "enter";
|
||||
button!.click();
|
||||
widget.state.flag = true;
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe('<div><button>Toggle</button><span class="">blue</span></div>');
|
||||
expect(fixture.innerHTML).toBe('<div><span class="" data-owl-key="__5__">blue</span></div>');
|
||||
});
|
||||
|
||||
test("transitionInsert is called the correct amount of times", async () => {
|
||||
const oldTransitionInsert = QWeb.utils.transitionInsert;
|
||||
QWeb.utils.transitionInsert = jest.fn(oldTransitionInsert);
|
||||
|
||||
class Child extends Widget {
|
||||
static template = xml`<span>blue</span>`;
|
||||
}
|
||||
class Parent extends Widget {
|
||||
static template = xml`
|
||||
<div t-name="Parent">
|
||||
<Child t-if="state.flag" t-transition="chimay"/>
|
||||
</div>`;
|
||||
static components = { Child };
|
||||
state = useState({ flag: false });
|
||||
}
|
||||
|
||||
patchNextFrame(cb => cb());
|
||||
|
||||
const widget = new Parent();
|
||||
await widget.mount(fixture);
|
||||
|
||||
widget.state.flag = true;
|
||||
|
||||
await nextTick();
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||
expect(fixture.innerHTML).toBe('<div><span class="">blue</span></div>');
|
||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||
|
||||
widget.state.flag = false;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="__5__">blue</span></div>'
|
||||
);
|
||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(1);
|
||||
|
||||
widget.state.flag = true;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-enter-active chimay-enter-to" data-owl-key="__5__">blue</span></div>'
|
||||
);
|
||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(2);
|
||||
|
||||
widget.state.flag = false;
|
||||
await nextTick();
|
||||
widget.state.flag = true;
|
||||
await nextTick();
|
||||
|
||||
expect(QWeb.utils.transitionInsert).toBeCalledTimes(3);
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend"));
|
||||
expect(fixture.innerHTML).toBe('<div><span class="" data-owl-key="__5__">blue</span></div>');
|
||||
QWeb.utils.transitionInsert = oldTransitionInsert;
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,20 +7,19 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let k4 = \`__5__\`;
|
||||
let w3 = k4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k4]] : false;
|
||||
let props3 = {message:1};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
@@ -28,15 +27,15 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['Child'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});
|
||||
parent.__owl__.cmap[k4] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined);
|
||||
let pvnode = h('dummy', {key: k4, hook: {remove() {},destroy(vn) {w3.destroy();}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (fiber.isCancelled) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
def2.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
w3.__owl__.parentLastFiberId = extra.fiber.id;
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -138,7 +138,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component '_a'");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -195,7 +195,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component '_a'");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -240,7 +240,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe("Props 'p' of invalid type in component 'TestWidget'");
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
});
|
||||
|
||||
test("can validate an optional props", async () => {
|
||||
@@ -284,7 +284,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
});
|
||||
|
||||
test("can validate an array with given primitive type", async () => {
|
||||
@@ -389,7 +389,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
});
|
||||
|
||||
test("can validate an object with simple shape", async () => {
|
||||
@@ -436,7 +436,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
|
||||
error = undefined;
|
||||
try {
|
||||
@@ -447,7 +447,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
});
|
||||
|
||||
test("can validate recursively complicated prop def", async () => {
|
||||
@@ -499,7 +499,7 @@ describe("props validation", () => {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
expect(error.message).toBe("Invalid Prop 'p' in component 'TestWidget'");
|
||||
});
|
||||
|
||||
test("can validate optional attributes in nested sub props", () => {
|
||||
@@ -535,6 +535,70 @@ describe("props validation", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("can validate with a custom validator", () => {
|
||||
class TestComponent extends Component<any, any> {
|
||||
static props = {
|
||||
size: {
|
||||
validate: e => ["small", "medium", "large"].includes(e)
|
||||
}
|
||||
};
|
||||
}
|
||||
let error;
|
||||
try {
|
||||
QWeb.utils.validateProps(TestComponent, { size: "small" });
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
QWeb.utils.validateProps(TestComponent, { size: "abcdef" });
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe("Invalid Prop 'size' in component 'TestComponent'");
|
||||
});
|
||||
|
||||
test("can validate with a custom validator, and a type", () => {
|
||||
const validator = jest.fn(n => 0 <= n && n <= 10);
|
||||
class TestComponent extends Component<any, any> {
|
||||
static props = {
|
||||
n: {
|
||||
type: Number,
|
||||
validate: validator
|
||||
}
|
||||
};
|
||||
}
|
||||
let error;
|
||||
try {
|
||||
QWeb.utils.validateProps(TestComponent, { n: 3 });
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
expect(validator).toBeCalledTimes(1);
|
||||
|
||||
try {
|
||||
QWeb.utils.validateProps(TestComponent, { n: "str" });
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe("Invalid Prop 'n' in component 'TestComponent'");
|
||||
expect(validator).toBeCalledTimes(1);
|
||||
|
||||
error = null;
|
||||
try {
|
||||
QWeb.utils.validateProps(TestComponent, { n: 100 });
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe("Invalid Prop 'n' in component 'TestComponent'");
|
||||
expect(validator).toBeCalledTimes(2);
|
||||
});
|
||||
|
||||
test("props are validated in dev mode (code snapshot)", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
@@ -581,6 +645,32 @@ describe("props validation", () => {
|
||||
}).toThrow();
|
||||
});
|
||||
|
||||
test("props with type array, and no element", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = { myprop: { type: Array } };
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { myprop: [1] });
|
||||
}).not.toThrow();
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { myprop: 1 });
|
||||
}).toThrow(`Invalid Prop 'myprop' in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("props with type object, and no shape", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = { myprop: { type: Object } };
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { myprop: { a: 3 } });
|
||||
}).not.toThrow();
|
||||
expect(() => {
|
||||
QWeb.utils.validateProps(TestWidget, { myprop: false });
|
||||
}).toThrow(`Invalid Prop 'myprop' in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("props: extra props cause an error", async () => {
|
||||
class TestWidget extends Widget {
|
||||
static props = ["message"];
|
||||
|
||||
+35
-1
@@ -106,7 +106,7 @@ describe("Context", () => {
|
||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||
});
|
||||
|
||||
test("two async components on two levels are updated in parallel", async () => {
|
||||
test("two async components on two levels are updated (mostly) in parallel", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
const def = makeDeferred();
|
||||
const steps: string[] = [];
|
||||
@@ -151,6 +151,11 @@ describe("Context", () => {
|
||||
);
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
// we need to wait for an extra tick because it could happen (even though it
|
||||
// is rare) that the second batch of renderings is not done yet, because
|
||||
// the initial promise has been given to the macrotask queue, so a small
|
||||
// delay happens.
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["render", "render", "render"]);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><span><p>321</p></span><div><span><p>321</p></span><span><p>321</p></span></div></div>"
|
||||
@@ -255,6 +260,35 @@ describe("Context", () => {
|
||||
expect(testContext.subscriptions.update.length).toBe(0);
|
||||
});
|
||||
|
||||
test("destroyed component before being mounted is inactive", async () => {
|
||||
const testContext = new Context({ a: 123 });
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj.a"/></span>`;
|
||||
contextObj = useContext(testContext);
|
||||
willStart() {
|
||||
return makeDeferred();
|
||||
}
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child t-if="state.flag"/></div>`;
|
||||
static components = { Child };
|
||||
state = useState({ flag: true });
|
||||
}
|
||||
|
||||
const parent = new Parent();
|
||||
const prom = parent.mount(fixture);
|
||||
await nextTick(); // wait for Child to be instantiated
|
||||
expect(testContext.subscriptions.update.length).toBe(1);
|
||||
parent.state.flag = false;
|
||||
await prom;
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
// kind of whitebox...
|
||||
// we make sure we do not have any pending subscriptions to the 'update'
|
||||
// event
|
||||
expect(testContext.subscriptions.update.length).toBe(0);
|
||||
});
|
||||
|
||||
test("concurrent renderings", async () => {
|
||||
const testContext = new Context({ x: { n: 1 }, key: "x" });
|
||||
const def = makeDeferred();
|
||||
|
||||
@@ -408,7 +408,7 @@ describe("observer", () => {
|
||||
obj.a = 111;
|
||||
obj.f = 222;
|
||||
await nextMicroTick();
|
||||
expect(observer.notifyCB).toBeCalledTimes(4);
|
||||
expect(observer.notifyCB).toBeCalledTimes(5);
|
||||
});
|
||||
|
||||
test("throw error when state is mutated in object if allowMutation=false", async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Env } from "../src/component/component";
|
||||
import { scheduler } from "../src/component/scheduler";
|
||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||
import { CompilationContext } from "../src/qweb/compilation_context";
|
||||
import { patch } from "../src/vdom";
|
||||
import "../src/qweb/base_directives";
|
||||
import "../src/qweb/extensions";
|
||||
@@ -20,6 +21,7 @@ let TEMPLATES;
|
||||
|
||||
beforeEach(() => {
|
||||
nextSlotId = QWeb.nextSlotId;
|
||||
CompilationContext.nextID = 1;
|
||||
slots = Object.assign({}, QWeb.slots);
|
||||
nextId = QWeb.nextId;
|
||||
TEMPLATES = Object.assign({}, QWeb.TEMPLATES);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+64
-1
@@ -242,6 +242,32 @@ describe("t-set", () => {
|
||||
);
|
||||
expect(renderToString(qweb, "test", { somevariable: 43 })).toBe("<div>45</div>");
|
||||
});
|
||||
|
||||
test("t-set, t-if, and mix of expression/body lookup, 1", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div>
|
||||
<t t-if="flag" t-set="ourvar">1</t>
|
||||
<t t-else="" t-set="ourvar" t-value="0"></t>
|
||||
<t t-esc="ourvar"/>
|
||||
</div>`
|
||||
);
|
||||
expect(renderToString(qweb, "test", { flag: true })).toBe("<div>1</div>");
|
||||
expect(renderToString(qweb, "test", { flag: false })).toBe("<div>0</div>");
|
||||
});
|
||||
|
||||
test("t-set, t-if, and mix of expression/body lookup, 2", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div>
|
||||
<t t-if="flag" t-set="ourvar" t-value="1"></t>
|
||||
<t t-else="" t-set="ourvar">0</t>
|
||||
<t t-esc="ourvar"/>
|
||||
</div>`
|
||||
);
|
||||
expect(renderToString(qweb, "test", { flag: true })).toBe("<div>1</div>");
|
||||
expect(renderToString(qweb, "test", { flag: false })).toBe("<div>0</div>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("t-if", () => {
|
||||
@@ -647,6 +673,40 @@ describe("t-call (template calling", () => {
|
||||
expect(renderToString(qweb, "main")).toBe(expected);
|
||||
});
|
||||
|
||||
test("cascading t-call t-raw='0'", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="finalTemplate">
|
||||
<span>cascade 2</span>
|
||||
<t t-raw="0"/>
|
||||
</div>
|
||||
|
||||
<div t-name="subSubTemplate">
|
||||
<t t-call="finalTemplate">
|
||||
<span>cascade 1</span>
|
||||
<t t-raw="0"/>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<div t-name="SubTemplate">
|
||||
<t t-call="subSubTemplate">
|
||||
<span>cascade 0</span>
|
||||
<t t-raw="0"/>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<div t-name="main">
|
||||
<t t-call="SubTemplate">
|
||||
<span>hey</span> <span>yay</span>
|
||||
</t>
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
const expected =
|
||||
"<div><div><div><div><span>cascade 2</span><span>cascade 1</span><span>cascade 0</span><span>hey</span> <span>yay</span></div></div></div></div>";
|
||||
expect(renderToString(qweb, "main")).toBe(expected);
|
||||
});
|
||||
|
||||
test("recursive template, part 1", () => {
|
||||
qweb.addTemplates(`
|
||||
<templates>
|
||||
@@ -1199,7 +1259,10 @@ describe("t-on", () => {
|
||||
);
|
||||
const steps: string[] = [];
|
||||
const owner = {
|
||||
projects: [{ id: 1, name: "Project 1" }, { id: 2, name: "Project 2" }],
|
||||
projects: [
|
||||
{ id: 1, name: "Project 1" },
|
||||
{ id: 2, name: "Project 2" }
|
||||
],
|
||||
|
||||
onEdit(projectId, ev) {
|
||||
expect(ev.defaultPrevented).toBe(true);
|
||||
|
||||
@@ -27,7 +27,10 @@ describe("tokenizer", () => {
|
||||
{ type: "VALUE", value: "2" },
|
||||
{ type: "RIGHT_BRACE", value: "}" }
|
||||
]);
|
||||
expect(tokenize("a,")).toEqual([{ type: "SYMBOL", value: "a" }, { type: "COMMA", value: "," }]);
|
||||
expect(tokenize("a,")).toEqual([
|
||||
{ type: "SYMBOL", value: "a" },
|
||||
{ type: "COMMA", value: "," }
|
||||
]);
|
||||
expect(tokenize("][")).toEqual([
|
||||
{ type: "RIGHT_BRACKET", value: "]" },
|
||||
{ type: "LEFT_BRACKET", value: "[" }
|
||||
@@ -43,6 +46,10 @@ describe("tokenizer", () => {
|
||||
{ type: "OPERATOR", value: "!==" },
|
||||
{ type: "OPERATOR", value: "!=" }
|
||||
]);
|
||||
expect(tokenize("typeof a")).toEqual([
|
||||
{ type: "OPERATOR", value: "typeof " },
|
||||
{ type: "SYMBOL", value: "a" }
|
||||
]);
|
||||
});
|
||||
|
||||
test("strings", () => {
|
||||
@@ -112,6 +119,7 @@ describe("expression evaluation", () => {
|
||||
expect(compileExpr("!flag", {})).toBe("!context['flag']");
|
||||
expect(compileExpr("-3", {})).toBe("-3");
|
||||
expect(compileExpr("-a", {})).toBe("-context['a']");
|
||||
expect(compileExpr("typeof a", {})).toBe("typeof context['a']");
|
||||
});
|
||||
|
||||
test("various binary operators", () => {
|
||||
|
||||
@@ -5,18 +5,17 @@ exports[`Link component can render simple cases 1`] = `
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let _1 = utils.toObj({'router-link-active':context['isActive']});
|
||||
var _2 = context['href'];
|
||||
let c3 = [], p3 = {key:3,attrs:{href: _2},class:_1,on:{}};
|
||||
var vn3 = h('a', p3, c3);
|
||||
extra.handlers['click' + 3] = extra.handlers['click' + 3] || function (e) {const fn = context['navigate'];if (fn) { fn.call(owner, e); } else { context.navigate; }};
|
||||
p3.on['click'] = extra.handlers['click' + 3];
|
||||
const slot4 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||
if (slot4) {
|
||||
slot4.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c3, vars: extra.vars, parent: owner}));
|
||||
let _6 = utils.toObj({'router-link-active':context['isActive']});
|
||||
var _7 = context['href'];
|
||||
let c8 = [], p8 = {key:8,attrs:{href: _7},class:_6,on:{}};
|
||||
var vn8 = h('a', p8, c8);
|
||||
extra.handlers['click' + 8] = extra.handlers['click' + 8] || function (e) {const fn = context['navigate'];if (fn) { fn.call(owner, e); } else { context.navigate; }};
|
||||
p8.on['click'] = extra.handlers['click' + 8];
|
||||
const slot9 = this.constructor.slots[context.__owl__.slotId + '_' + 'default'];
|
||||
if (slot9) {
|
||||
slot9.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c8, vars: extra.vars, parent: extra.parent || owner}));
|
||||
}
|
||||
return vn3;
|
||||
return vn8;
|
||||
}"
|
||||
`;
|
||||
|
||||
@@ -7,39 +7,38 @@ exports[`RouteComponent can render simple cases 1`] = `
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
let result;
|
||||
var h = this.h;
|
||||
if (context['routeComponent']) {
|
||||
const nodeKey1 = context['env'].router.currentRouteName;
|
||||
const nodeKey6 = context['env'].router.currentRouteName;
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\` + nodeKey1;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
let vn5 = {};
|
||||
result = vn5;
|
||||
let props3 = Object.assign({}, context['env'].router.currentParams);
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
let k9 = \`__10__\` + nodeKey6;
|
||||
let w8 = k9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[k9]] : false;
|
||||
let vn11 = {};
|
||||
result = vn11;
|
||||
let props8 = Object.assign({}, context['env'].router.currentParams);
|
||||
if (w8 && w8.__owl__.currentFiber && !w8.__owl__.vnode) {
|
||||
w8.destroy();
|
||||
w8 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
utils.defineProxy(vn5, pvnode);
|
||||
if (w8) {
|
||||
w8.__updateProps(props8, extra.fiber, undefined, undefined);
|
||||
let pvnode = w8.__owl__.pvnode;
|
||||
utils.defineProxy(vn11, pvnode);
|
||||
} else {
|
||||
let componentKey3 = \`routeComponent\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['routeComponent'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (fiber.isCancelled) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
utils.defineProxy(vn5, pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
let componentKey8 = \`routeComponent\`;
|
||||
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| context['routeComponent'];
|
||||
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
|
||||
w8 = new W8(parent, props8);
|
||||
parent.__owl__.cmap[k9] = w8.__owl__.id;
|
||||
let def7 = w8.__prepare(extra.fiber, undefined, undefined);
|
||||
let pvnode = h('dummy', {key: k9, hook: {remove() {},destroy(vn) {w8.destroy();}}});
|
||||
const fiber = w8.__owl__.currentFiber;
|
||||
def7.then(function () { if (fiber.isCompleted) { return; } const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
utils.defineProxy(vn11, pvnode);
|
||||
w8.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
w8.__owl__.parentLastFiberId = extra.fiber.id;
|
||||
}
|
||||
return result;
|
||||
}"
|
||||
|
||||
@@ -35,7 +35,10 @@ describe("Link component", () => {
|
||||
static components = { Link: Link };
|
||||
}
|
||||
|
||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
||||
const routes = [
|
||||
{ name: "about", path: "/about" },
|
||||
{ name: "users", path: "/users" }
|
||||
];
|
||||
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
router.navigate({ to: "users" });
|
||||
@@ -66,7 +69,10 @@ describe("Link component", () => {
|
||||
static components = { Link: Link };
|
||||
}
|
||||
|
||||
const routes = [{ name: "about", path: "/about" }, { name: "users", path: "/users" }];
|
||||
const routes = [
|
||||
{ name: "about", path: "/about" },
|
||||
{ name: "users", path: "/users" }
|
||||
];
|
||||
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
router.navigate({ to: "users" });
|
||||
|
||||
+191
-2
@@ -48,6 +48,42 @@ describe("connecting a component to store", () => {
|
||||
expect(fixture.innerHTML).toBe("<div><span>hello</span></div>");
|
||||
});
|
||||
|
||||
test("useStore can observe primitive types and call onUpdate", async () => {
|
||||
const state = { isBoolean: false };
|
||||
const actions = {
|
||||
setTrue({ state }) {
|
||||
state.isBoolean = true;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`
|
||||
<div>
|
||||
<span t-if="isBoolean">ok</span>
|
||||
</div>`;
|
||||
isBoolean: boolean;
|
||||
constructor() {
|
||||
super();
|
||||
this.isBoolean = useStore(state => state.isBoolean, {
|
||||
onUpdate: isBoolean => {
|
||||
this.isBoolean = isBoolean;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
|
||||
store.dispatch("setTrue");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>ok</span></div>");
|
||||
});
|
||||
|
||||
test("throw error if no store is found", async () => {
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div></div>`;
|
||||
@@ -64,6 +100,24 @@ describe("connecting a component to store", () => {
|
||||
expect(error.message).toBe("No store found when connecting 'App'");
|
||||
});
|
||||
|
||||
test("cannot modify state returned by usestore", async () => {
|
||||
const state = { a: { b: 1 } };
|
||||
const actions = {};
|
||||
const store = new Store({ state, actions });
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div/>`;
|
||||
storeState = useStore(state => state.a);
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App();
|
||||
expect(app.storeState.b).toBe(1);
|
||||
expect(() => (app.storeState.b = 2)).toThrow(
|
||||
"Store state should only be modified through actions"
|
||||
);
|
||||
});
|
||||
|
||||
test("can use useStore twice in a component", async () => {
|
||||
const state = { a: 1, b: 2 };
|
||||
const actions = {
|
||||
@@ -257,7 +311,12 @@ describe("connecting a component to store", () => {
|
||||
});
|
||||
|
||||
test("useStore can use props", async () => {
|
||||
const state = { todos: [{ id: 1, text: "jupiler" }, { id: 2, text: "chimay" }] };
|
||||
const state = {
|
||||
todos: [
|
||||
{ id: 1, text: "jupiler" },
|
||||
{ id: 2, text: "chimay" }
|
||||
]
|
||||
};
|
||||
const store = new Store({ state, actions: {} });
|
||||
|
||||
class TodoItem extends Component<any, any> {
|
||||
@@ -324,7 +383,10 @@ describe("connecting a component to store", () => {
|
||||
test("can call useGetters to receive store getters", async () => {
|
||||
const state = {
|
||||
importantID: 1,
|
||||
todos: [{ id: 1, text: "jupiler" }, { id: 2, text: "bertinchamps" }]
|
||||
todos: [
|
||||
{ id: 1, text: "jupiler" },
|
||||
{ id: 2, text: "bertinchamps" }
|
||||
]
|
||||
};
|
||||
const getters = {
|
||||
importantTodoText({ state }) {
|
||||
@@ -428,6 +490,68 @@ describe("connecting a component to store", () => {
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span><span>kwak</span></div>");
|
||||
});
|
||||
|
||||
test("connected component is updated when mixing store and props changes", async () => {
|
||||
let counter = 0;
|
||||
|
||||
class Beer extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="beer.name"/></span>`;
|
||||
beer = useStore((state, props) => state.beers[props.id], {
|
||||
onUpdate: result => {
|
||||
++counter;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><Beer id="state.beerId"/></div>`;
|
||||
static components = { Beer };
|
||||
state = useState({ beerId: 1 });
|
||||
}
|
||||
|
||||
const state = { beers: { 1: { name: "jupiler" }, 2: { name: "kwak" } } };
|
||||
const actions = {
|
||||
renameBeer({ state }, { id, name }) {
|
||||
state.beers[id].name = name;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
expect(counter).toBe(0);
|
||||
|
||||
app.state.beerId = 2;
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>kwak</span></div>");
|
||||
expect(counter).toBe(1);
|
||||
|
||||
store.dispatch("renameBeer", { id: 2, name: "orval" });
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>orval</span></div>");
|
||||
expect(counter).toBe(2);
|
||||
});
|
||||
|
||||
test("connected component is properly cleaned up on destroy", async () => {
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div></div>`;
|
||||
state = useStore((state, props) => state);
|
||||
}
|
||||
|
||||
const store = new Store({ state: {} });
|
||||
(<any>env).store = store;
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(store.updateFunctions[app.__owl__.id].length).toBe(1);
|
||||
|
||||
app.destroy();
|
||||
|
||||
expect(store.updateFunctions[app.__owl__.id]).toBe(undefined);
|
||||
});
|
||||
|
||||
test("connected component with undefined, null and string props", async () => {
|
||||
class Beer extends Component<any, any> {
|
||||
static template = xml`
|
||||
@@ -572,6 +696,31 @@ describe("connecting a component to store", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("store changes occuring when mounting a component are notified", async () => {
|
||||
const initialState = { x: { val: 1 } };
|
||||
const actions = {
|
||||
setValue({ state }, val) {
|
||||
state.x.val = val;
|
||||
}
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="x.val"/></div>`;
|
||||
x = useStore(state => {
|
||||
return Object.assign({}, state.x);
|
||||
});
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
Parent.prototype.__render = jest.fn(Parent.prototype.__render);
|
||||
Parent.env.store = new Store({ state: initialState, actions });
|
||||
|
||||
const parent = new Parent();
|
||||
const prom = parent.mount(fixture);
|
||||
parent.dispatch("setValue", 2);
|
||||
await prom;
|
||||
expect(fixture.innerHTML).toBe("<div>2</div>");
|
||||
expect(Parent.prototype.__render).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("correct update order when parent/children are connected", async () => {
|
||||
const steps: string[] = [];
|
||||
|
||||
@@ -899,6 +1048,46 @@ describe("connecting a component to store", () => {
|
||||
expect(steps).toEqual(["on:update", "off:update"]);
|
||||
});
|
||||
|
||||
test("connected child component destroyed by dispatched action", async () => {
|
||||
let steps: any = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="store.val"/></div>`;
|
||||
store = useStore(s => {
|
||||
steps.push("child selector");
|
||||
return s;
|
||||
});
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child t-if="store.child" /></div>`;
|
||||
static components = { Child };
|
||||
store = useStore(s => {
|
||||
steps.push("parent selector");
|
||||
return s;
|
||||
});
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const state = { child: true, val: 1 };
|
||||
const actions = {
|
||||
toggleChild({ state }) {
|
||||
state.child = !state.child;
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const parent = new Parent();
|
||||
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
expect(steps).toEqual(["parent selector", "child selector"]);
|
||||
|
||||
parent.dispatch("toggleChild");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(steps).toEqual(["parent selector", "child selector", "parent selector"]);
|
||||
});
|
||||
|
||||
test("dispatch an action", async () => {
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="store.counter"/></div>`;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<title>OWL v0.24.0 Benchmark</title>
|
||||
<link href="../shared/main.css" rel="stylesheet"/>
|
||||
<script src='../../owl.js'></script>
|
||||
<script src='owl.js'></script>
|
||||
</head>
|
||||
<body>
|
||||
<script src='app.js' type="module"></script>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+25
-11
@@ -120,20 +120,34 @@ async function makeApp(js, css, xml) {
|
||||
.join("\n");
|
||||
|
||||
const JS = `
|
||||
async function loadTemplates() {
|
||||
try {
|
||||
return owl.utils.loadFile('app.xml');
|
||||
} catch(e) {
|
||||
console.error(\`This app requires a static server. If you have python installed, try 'python app.py'\`);
|
||||
}
|
||||
}
|
||||
|
||||
function start([TEMPLATES]) {
|
||||
// Application code
|
||||
/**
|
||||
* This is the javascript code defined in the playground.
|
||||
* In a larger application, this code should probably be moved in different
|
||||
* sub files.
|
||||
*/
|
||||
function app() {
|
||||
${processedJS}
|
||||
}
|
||||
|
||||
Promise.all([loadTemplates(), owl.utils.whenReady()]).then(start);
|
||||
/**
|
||||
* Initialization code
|
||||
* This code load templates, and make sure everything is properly connected.
|
||||
*/
|
||||
async function start() {
|
||||
let templates;
|
||||
try {
|
||||
templates = await owl.utils.loadFile('app.xml');
|
||||
} catch(e) {
|
||||
console.error(\`This app requires a static server. If you have python installed, try 'python app.py'\`);
|
||||
return;
|
||||
}
|
||||
const env = { qweb: new owl.QWeb({templates})};
|
||||
owl.Component.env = env;
|
||||
await owl.utils.whenReady();
|
||||
app();
|
||||
}
|
||||
|
||||
start();
|
||||
`;
|
||||
|
||||
zip.file("app.js", JS);
|
||||
|
||||
+88
-38
@@ -2,7 +2,10 @@ const COMPONENTS = `// In this example, we show how components can be defined an
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Greeter extends Component {
|
||||
state = useState({ word: 'Hello' });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ word: 'Hello' });
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.state.word = this.state.word === 'Hi' ? 'Hello' : 'Hi';
|
||||
@@ -11,7 +14,10 @@ class Greeter extends Component {
|
||||
|
||||
// Main root component
|
||||
class App extends Component {
|
||||
state = useState({ name: 'World'});
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ name: 'World'});
|
||||
}
|
||||
}
|
||||
App.components = { Greeter };
|
||||
|
||||
@@ -47,7 +53,10 @@ const ANIMATION = `// The goal of this component is to see how the t-transition
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Counter extends Component {
|
||||
state = useState({ value: 0 });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
@@ -55,7 +64,10 @@ class Counter extends Component {
|
||||
}
|
||||
|
||||
class App extends Component {
|
||||
state = useState({ flag: false, componentFlag: false, numbers: [] });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ flag: false, componentFlag: false, numbers: [] });
|
||||
}
|
||||
|
||||
toggle(key) {
|
||||
this.state[key] = !this.state[key];
|
||||
@@ -213,7 +225,10 @@ class DemoComponent extends Component {
|
||||
}
|
||||
|
||||
class App extends Component {
|
||||
state = useState({ n: 0, flag: true });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ n: 0, flag: true });
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.state.n++;
|
||||
@@ -282,11 +297,14 @@ function useMouse() {
|
||||
|
||||
// Main root component
|
||||
class App extends owl.Component {
|
||||
// simple state hook (reactive object)
|
||||
counter = useState({ value: 0 });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
// simple state hook (reactive object)
|
||||
this.counter = useState({ value: 0 });
|
||||
|
||||
// this hooks is bound to the 'mouse' property.
|
||||
mouse = useMouse();
|
||||
// this hooks is bound to the 'mouse' property.
|
||||
this.mouse = useMouse();
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.counter.value++;
|
||||
@@ -318,7 +336,10 @@ const { Component, Context } = owl;
|
||||
const { useContext } = owl.hooks;
|
||||
|
||||
class ToolbarButton extends Component {
|
||||
theme = useContext(this.env.themeContext);
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.theme = useContext(this.env.themeContext);
|
||||
}
|
||||
|
||||
get style () {
|
||||
const theme = this.theme;
|
||||
@@ -451,12 +472,11 @@ const actions = {
|
||||
// TodoItem
|
||||
//------------------------------------------------------------------------------
|
||||
class TodoItem extends Component {
|
||||
state = useState({ isEditing: false });
|
||||
dispatch = useDispatch();
|
||||
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
useAutofocus("input");
|
||||
this.state = useState({ isEditing: false });
|
||||
this.dispatch = useDispatch();
|
||||
}
|
||||
|
||||
handleKeyup(ev) {
|
||||
@@ -483,9 +503,12 @@ class TodoItem extends Component {
|
||||
// TodoApp
|
||||
//------------------------------------------------------------------------------
|
||||
class TodoApp extends Component {
|
||||
state = useState({ filter: "all" });
|
||||
todos = useStore(state => state.todos);
|
||||
dispatch = useDispatch();
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ filter: "all" });
|
||||
this.todos = useStore(state => state.todos);
|
||||
this.dispatch = useDispatch();
|
||||
}
|
||||
|
||||
get visibleTodos() {
|
||||
switch (this.state.filter) {
|
||||
@@ -1008,7 +1031,10 @@ class FormView extends owl.Component {}
|
||||
FormView.components = { AdvancedComponent };
|
||||
|
||||
class Chatter extends owl.Component {
|
||||
messages = Array.from(Array(100).keys());
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.messages = Array.from(Array(100).keys());
|
||||
}
|
||||
}
|
||||
|
||||
class App extends owl.Component {}
|
||||
@@ -1150,7 +1176,10 @@ const SLOTS = `// We show here how slots can be used to create generic component
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Card extends Component {
|
||||
state = useState({ showContent: true });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ showContent: true });
|
||||
}
|
||||
|
||||
toggleDisplay() {
|
||||
this.state.showContent = !this.state.showContent;
|
||||
@@ -1158,7 +1187,10 @@ class Card extends Component {
|
||||
}
|
||||
|
||||
class Counter extends Component {
|
||||
state = useState({val: 1});
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({val: 1});
|
||||
}
|
||||
|
||||
inc() {
|
||||
this.state.val++;
|
||||
@@ -1167,7 +1199,10 @@ class Counter extends Component {
|
||||
|
||||
// Main root component
|
||||
class App extends Component {
|
||||
state = useState({a: 1, b: 3});
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({a: 1, b: 3});
|
||||
}
|
||||
|
||||
inc(key, delta) {
|
||||
this.state[key] += delta;
|
||||
@@ -1277,7 +1312,10 @@ class SlowComponent extends Component {
|
||||
class NotificationList extends Component {}
|
||||
|
||||
class App extends Component {
|
||||
state = useState({ value: 0, notifs: [] });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ value: 0, notifs: [] });
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.state.value++;
|
||||
@@ -1350,13 +1388,16 @@ const FORM = `// This example illustrate how the t-model directive can be used t
|
||||
const { Component, useState } = owl;
|
||||
|
||||
class Form extends Component {
|
||||
state = useState({
|
||||
text: "",
|
||||
othertext: "",
|
||||
number: 11,
|
||||
color: "",
|
||||
bool: false
|
||||
});
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({
|
||||
text: "",
|
||||
othertext: "",
|
||||
number: 11,
|
||||
color: "",
|
||||
bool: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Application setup
|
||||
@@ -1419,7 +1460,10 @@ const { useRef } = owl.hooks;
|
||||
class HelloWorld extends Component {}
|
||||
|
||||
class Counter extends Component {
|
||||
state = useState({ value: 0 });
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.state = useState({ value: 0 });
|
||||
}
|
||||
|
||||
inc() {
|
||||
this.state.value++;
|
||||
@@ -1470,11 +1514,14 @@ class Window extends Component {
|
||||
}
|
||||
|
||||
class WindowManager extends Component {
|
||||
windows = [];
|
||||
nextId = 1;
|
||||
currentZindex = 1;
|
||||
nextLeft = 0;
|
||||
nextTop = 0;
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.windows = [];
|
||||
this.nextId = 1;
|
||||
this.currentZindex = 1;
|
||||
this.nextLeft = 0;
|
||||
this.nextTop = 0;
|
||||
}
|
||||
|
||||
addWindow(name) {
|
||||
const info = this.env.windows.find(w => w.name === name);
|
||||
@@ -1518,7 +1565,10 @@ class WindowManager extends Component {
|
||||
WindowManager.components = { Window };
|
||||
|
||||
class App extends Component {
|
||||
wmRef = useRef("wm");
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.wmRef = useRef("wm");
|
||||
}
|
||||
|
||||
addWindow(name) {
|
||||
this.wmRef.comp.addWindow(name);
|
||||
@@ -1552,7 +1602,7 @@ const WMS_XML = `<templates>
|
||||
<div t-name="Window" class="window" t-att-style="style" t-on-click="updateZIndex">
|
||||
<div class="header">
|
||||
<span t-on-mousedown="startDragAndDrop"><t t-esc="props.info.title"/></span>
|
||||
<span class="close" t-on-click="close">×</span>
|
||||
<span class="close" t-on-click.stop="close">×</span>
|
||||
</div>
|
||||
<t t-slot="default"/>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user