mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fc71cfb62 | |||
| 08cb83149e | |||
| 7d249d6f09 | |||
| 0addca63a0 | |||
| 5ba73cc09d | |||
| 9106c19066 | |||
| 9f93da4765 | |||
| 9e37b968e8 | |||
| fa6801b523 | |||
| 9edf29a3a1 | |||
| 6a434310ee | |||
| e7967d0779 |
@@ -28,7 +28,7 @@ Owl is currently mostly stable. Possible future changes are explained in the
|
||||
Here is a short example to illustrate interactive components:
|
||||
|
||||
```javascript
|
||||
const { Component, QWeb, useState } = owl;
|
||||
const { Component, useState } = owl;
|
||||
const { xml } = owl.tags;
|
||||
|
||||
class Counter extends Component {
|
||||
@@ -50,7 +50,7 @@ class App extends Component {
|
||||
static components = { Counter };
|
||||
}
|
||||
|
||||
const app = new App({ qweb: new QWeb() });
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
@@ -92,7 +92,7 @@ A complete documentation for Owl can be found here:
|
||||
|
||||
The most important sections are:
|
||||
|
||||
- [Quick Start](doc/quick_start.md)
|
||||
- [Quick Start](doc/learning/quick_start.md)
|
||||
- [Component](doc/reference/component.md)
|
||||
- [Hooks](doc/reference/hooks.md)
|
||||
|
||||
@@ -103,8 +103,8 @@ Submit a PR!
|
||||
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
- [owl-0.24.1.js](https://github.com/odoo/owl/releases/download/v0.24.1/owl.js)
|
||||
- [owl-0.24.1.min.js](https://github.com/odoo/owl/releases/download/v0.24.1/owl.min.js)
|
||||
- [owl-1.0.0-alpha.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha/owl.js)
|
||||
- [owl-1.0.0-alpha.min.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha/owl.min.js)
|
||||
|
||||
Some npm scripts are available:
|
||||
|
||||
@@ -127,23 +127,6 @@ Owl components in an application are used to define a (dynamic) tree of componen
|
||||
C D
|
||||
```
|
||||
|
||||
**Environment:** the root component is special: it is created with an environment,
|
||||
which should contain a [`QWeb` instance](doc/reference/qweb.md). The environment is then automatically
|
||||
propagated to each sub components (and accessible in the `this.env` property).
|
||||
|
||||
```js
|
||||
const env = { qweb: new QWeb() };
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
The environment is mostly static. Each application is free to add anything to
|
||||
the environment, which is very useful, since this can be accessed by each sub
|
||||
component. Some good use case for that is some configuration keys, session
|
||||
information or generic services (such as doing rpcs, or accessing local storage).
|
||||
Doing it this way means that components are easily testable: we can simply
|
||||
create a test environment with mock services.
|
||||
|
||||
**State:** each component can manage its own local state. It is a simple ES6
|
||||
class, there are no special rules:
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ A rendering occurs in two phases:
|
||||
- virtual rendering: this generates the virtual dom in memory, asynchronously
|
||||
- patch: applies a virtual tree to the screen (synchronously)
|
||||
|
||||
|
||||
There are several classes involved in a rendering:
|
||||
|
||||
- components
|
||||
@@ -21,9 +20,9 @@ There are several classes involved in a rendering:
|
||||
- fibers: small objects containing some metadata, associated with a rendering of
|
||||
a specific component
|
||||
|
||||
|
||||
Components are organized in a dynamic component tree, visible in the user
|
||||
interface. Whenever a rendering is initiated in a component `C`:
|
||||
interface. Whenever a rendering is initiated in a component `C`:
|
||||
|
||||
- a fiber is created on `C` with the rendering props information
|
||||
- the virtual rendering phase starts on C (will asynchronously render all the
|
||||
child components)
|
||||
@@ -31,4 +30,3 @@ interface. Whenever a rendering is initiated in a component `C`:
|
||||
animation frame, if the fiber is done
|
||||
- once it is done, the scheduler will call the task callback, which will apply
|
||||
the patch (if it was not cancelled in the meantime).
|
||||
|
||||
|
||||
+2
-1
@@ -274,7 +274,8 @@ class Counter extends Component {
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
|
||||
const counter = new Counter({ store, qweb });
|
||||
owl.config.env.store = store;
|
||||
const counter = new Counter();
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# 🦉 Environment 🦉
|
||||
|
||||
An environment is an object which contains a [`QWeb` instance](../reference/qweb.md).
|
||||
Whenever a root component is created, it is assigned an environment (see the
|
||||
reference section on [environment](../reference/environment.md). This environment
|
||||
is then automatically given to each sub components (and accessible in the `this.env` property).
|
||||
|
||||
The environment is mostly static. Each application is free to add anything to
|
||||
the environment, which is very useful, since this can be accessed by each sub
|
||||
component.
|
||||
|
||||
Some good use cases for the environment is:
|
||||
|
||||
- some configuration keys,
|
||||
- session information,
|
||||
- generic services (such as doing rpcs, or accessing local storage).
|
||||
|
||||
Doing it this way means that components are easily testable: we can simply
|
||||
create a test environment with mock services.
|
||||
|
||||
For example:
|
||||
|
||||
|
||||
```js
|
||||
async function myEnv() {
|
||||
const templates = await loadTemplates();
|
||||
const qweb = new QWeb({templates});
|
||||
const session = getSession();
|
||||
|
||||
return {
|
||||
_t: myTranslateFunction,
|
||||
session: session,
|
||||
qweb: qweb,
|
||||
services: {
|
||||
localStorage: localStorage,
|
||||
rpc: rpc,
|
||||
},
|
||||
debug: false,
|
||||
inMobileMode: true,
|
||||
};
|
||||
}
|
||||
|
||||
async function start() {
|
||||
owl.config.env = await myEnv();
|
||||
const app = new App();
|
||||
await app.mount(document.body);
|
||||
}
|
||||
```
|
||||
@@ -2,8 +2,17 @@
|
||||
|
||||
## Static Server
|
||||
|
||||
Let us assume that we have a static server running somewhere. We could then
|
||||
simply add an html page with a few extra files.
|
||||
Let us assume that we have a static server running somewhere. Let us start by
|
||||
adding an html page with a few extra files:
|
||||
|
||||
```
|
||||
my-app/
|
||||
index.html
|
||||
app.css
|
||||
app.js
|
||||
owl-X.Y.Z.js
|
||||
templates.xml
|
||||
```
|
||||
|
||||
### HTML and CSS
|
||||
|
||||
@@ -88,10 +97,9 @@ class ClickCounter extends owl.Component {
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadFile("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb({ templates })
|
||||
};
|
||||
const counter = new ClickCounter(env);
|
||||
const qweb = new owl.QWeb({ templates });
|
||||
owl.config.env.qweb = qweb;
|
||||
const counter = new ClickCounter();
|
||||
const target = document.getElementById("main");
|
||||
await counter.mount(target);
|
||||
}
|
||||
+10
-4
@@ -12,6 +12,9 @@ owl
|
||||
QWeb
|
||||
Store
|
||||
useState
|
||||
config
|
||||
mode
|
||||
env
|
||||
core
|
||||
EventBus
|
||||
Observer
|
||||
@@ -48,11 +51,18 @@ owl
|
||||
|
||||
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
|
||||
|
||||
## Learning Resources
|
||||
|
||||
- [Quick Start: create an (almost) empty Owl application](learning/quick_start.md)
|
||||
- [Environment: what it is and what it should contain](learning/environment.md)
|
||||
|
||||
## Reference
|
||||
|
||||
- [Animations](reference/animations.md)
|
||||
- [Component](reference/component.md)
|
||||
- [Configuration](reference/config.md)
|
||||
- [Context](reference/context.md)
|
||||
- [Environment](reference/environment.md)
|
||||
- [Event Bus](reference/event_bus.md)
|
||||
- [Hooks](reference/hooks.md)
|
||||
- [Misc](reference/misc.md)
|
||||
@@ -63,10 +73,6 @@ Note that for convenience, the `useState` hook is also exported at the root of t
|
||||
- [Tags](reference/tags.md)
|
||||
- [Utils](reference/utils.md)
|
||||
|
||||
## Learning Resources
|
||||
|
||||
- [Quick Start](quick_start.md)
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
- [Comparison with React/Vue](comparison.md)
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
- [Methods](#methods)
|
||||
- [Lifecycle](#lifecycle)
|
||||
- [Root Component](#root-component)
|
||||
- [Environment](#environment)
|
||||
- [Composition](#composition)
|
||||
- [Event Handling](#event-handling)
|
||||
- [Form Input Bindings](#form-input-bindings)
|
||||
@@ -81,8 +80,8 @@ a state object is defined, by using the `useState` hook. It is not mandatory to
|
||||
## Reference
|
||||
|
||||
An Owl component is a small class which represents a component or some UI element.
|
||||
It exists in the context of an environment (`env`), which is propagated from a
|
||||
parent to its children. The environment needs to have a QWeb instance, which
|
||||
It exists in the context of an [environment](environment.md) (`env`), which is propagated from a
|
||||
parent to its children. The environment needs to have a [QWeb](qweb.md) instance, which
|
||||
will be used to render the component template.
|
||||
|
||||
Be aware that the name of the component may be significant: if a component does
|
||||
@@ -392,8 +391,7 @@ scrollbar.
|
||||
|
||||
Note that modifying the state is not allowed here. This method is called just
|
||||
before an actual DOM patch, and is only intended to be used to save some local
|
||||
DOM state. Also, it will not be called if the component is not in the DOM (this can
|
||||
happen with components with `t-keepalive`).
|
||||
DOM state. Also, it will not be called if the component is not in the DOM.
|
||||
|
||||
#### `patched(snapshot)`
|
||||
|
||||
@@ -403,7 +401,7 @@ likely via a change in its state/props or environment).
|
||||
This method is not called on the initial render. It is useful to interact
|
||||
with the DOM (for example, through an external library) whenever the
|
||||
component was patched. Note that this hook will not be called if the compoent is
|
||||
not in the DOM (this can happen with components with `t-keepalive`).
|
||||
not in the DOM.
|
||||
|
||||
Updating the component state in this hook is possible, but not encouraged.
|
||||
One needs to be careful, because updates here will create an additional rendering, which in
|
||||
@@ -441,49 +439,12 @@ of an Owl application has to be created manually:
|
||||
```js
|
||||
class App extends owl.Component { ... }
|
||||
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES });
|
||||
const env = { qweb: qweb };
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
```
|
||||
|
||||
The root component needs an environment.
|
||||
|
||||
### Environment
|
||||
|
||||
In Owl, an environment is an object with a `qweb` key, which has to be a
|
||||
[QWeb](qweb.md) instance. This qweb instance will be used to render everything.
|
||||
|
||||
The environment is meant to contain (mostly) static global information and
|
||||
methods for the whole application. For example, settings keys (`mode` to determine
|
||||
if we are in desktop or mobile mode, or `theme`: dark or light), `rpc` methods,
|
||||
session information, ...
|
||||
|
||||
The environment will be given to each child, unchanged, in the `env` property.
|
||||
This can be very useful to share common information/methods. For example, all
|
||||
rpcs can be made through a `rpc` method in the environment. This makes it very
|
||||
easy to test a component.
|
||||
|
||||
Updating the environment is not as simple as changing a component's state: its
|
||||
content is not observed, so updates will not be reflected immediately in the
|
||||
user interface. There is however a mechanism to force root widgets to rerender
|
||||
themselves whenever the environment is modified: one only needs to call the
|
||||
`forceUpdate` method on the QWeb instance. For example, a responsive environment
|
||||
could be done like this:
|
||||
|
||||
```js
|
||||
function setupResponsivePlugin(env) {
|
||||
const isMobile = () => window.innerWidth <= 768;
|
||||
env.isMobile = isMobile();
|
||||
const updateEnv = owl.utils.debounce(() => {
|
||||
if (env.isMobile !== isMobile()) {
|
||||
env.isMobile = !env.isMobile;
|
||||
env.qweb.forceUpdate();
|
||||
}
|
||||
}, 15);
|
||||
window.addEventListener("resize", updateEnv);
|
||||
}
|
||||
```
|
||||
The root component does not have a parent nor props. It will be setup with an
|
||||
[environment](environment.md) (located in `owl.config.env`).
|
||||
|
||||
### Composition
|
||||
|
||||
@@ -986,7 +947,7 @@ of the props. Here is how it works in Owl:
|
||||
- `props` key is a static key (so, different from `this.props` in a component instance)
|
||||
- it is optional: it is ok for a component to not define a `props` key.
|
||||
- props are validated whenever a component is created/updated
|
||||
- props are only validated in `dev` mode (see [tooling page](../tooling.md#development-mode))
|
||||
- props are only validated in `dev` mode (see [config page](config.md#mode))
|
||||
- if a key does not match the description, an error is thrown
|
||||
- it validates keys defined in (static) `props`. Additional keys given by the
|
||||
parent will cause an error.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# 🦉 Config 🦉
|
||||
|
||||
The Owl framework is designed to work in many situations. However, it is
|
||||
sometimes necessary to customize some behaviour. This is done by using the
|
||||
global `config` object. It currently has two keys:
|
||||
|
||||
- [`mode`](#mode),
|
||||
- [`env`](#env).
|
||||
|
||||
## Mode
|
||||
|
||||
By default, Owl is in _production_ mode, this means that it will try to do its
|
||||
job fast, and skip some expensive operations. However, it is sometimes necessary
|
||||
to have better information on what is going on, this is the purpose
|
||||
of the `dev` mode.
|
||||
|
||||
Owl has a mode flag, in `owl.config.mode`. Its default value is `prod`, but
|
||||
it can be set to `dev`:
|
||||
|
||||
```js
|
||||
owl.config.mode = "dev";
|
||||
```
|
||||
|
||||
Note that templates compiled with the `prod` settings will not be recompiled.
|
||||
So, changing this setting is best done at startup.
|
||||
|
||||
An important job done by the `dev` mode is to validate props for each component
|
||||
creation and update. Also, extra props will cause an error.
|
||||
|
||||
## Env
|
||||
|
||||
An Owl application needs an [environment](environment.md) to be executed. The
|
||||
environment has an important key: the [QWeb](qweb.md) instance, which will render
|
||||
all templates.
|
||||
|
||||
Whenever a root component is mounted, Owl will take the environment from
|
||||
`owl.config.env` and use it to setup the component (and its children).
|
||||
|
||||
- if no environment was setup, an empty environment will be generated,
|
||||
- if an environment exists, but does not have a QWeb key, a new QWeb instance
|
||||
will then be added to the environment.
|
||||
|
||||
The correct way to customize an environment is to simply modify `owl.config.env`
|
||||
before the first component is created:
|
||||
|
||||
```js
|
||||
owl.config.env = {
|
||||
_t: myTranslateFunction,
|
||||
user: {...},
|
||||
services: {
|
||||
...
|
||||
},
|
||||
};
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
```
|
||||
@@ -28,10 +28,7 @@ context, and add it to the environment:
|
||||
|
||||
```js
|
||||
const deviceContext = new Context({ isMobile: true });
|
||||
const env = {
|
||||
qweb: new QWeb({ templates: TEMPLATES }),
|
||||
deviceContext
|
||||
};
|
||||
owl.config.env.deviceContext = deviceContext;
|
||||
```
|
||||
|
||||
If we want to make it completely responsive, we need to update its value whenever
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# 🦉 Environment 🦉
|
||||
|
||||
An environment is an object which contains a [`QWeb` instance](qweb.md). Whenever a root component is created, it is assigned an environment. This environment
|
||||
is then automatically given to each sub component (and accessible in the `this.env` property).
|
||||
|
||||
```
|
||||
Root
|
||||
/ \
|
||||
A B
|
||||
```
|
||||
|
||||
This way, all components share the same `QWeb` instance.
|
||||
|
||||
Note: some additional information can be found here:
|
||||
|
||||
- [What should go into an environment?](../learning/environment.md)
|
||||
- [Customizing an environment](config.md#env)
|
||||
|
||||
+10
-10
@@ -67,15 +67,15 @@ We present here a list of all standard QWeb directives:
|
||||
The component system in Owl requires additional directives, to express various
|
||||
needs. Here is a list of all Owl specific directives:
|
||||
|
||||
| Name | Description |
|
||||
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `t-component`, `t-props`, `t-keepalive`, `t-asyncroot` | [Defining a sub component](component.md#composition) |
|
||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
| Name | Description |
|
||||
| ------------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `t-component`, `t-props` | [Defining a sub component](component.md#composition) |
|
||||
| `t-ref` | [Setting a reference to a dom node or a sub component](component.md#references) |
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
| `t-model` | [Form input bindings](component.md#form-input-bindings) |
|
||||
|
||||
## QWeb Engine
|
||||
|
||||
@@ -159,7 +159,7 @@ Its API is quite simple:
|
||||
```
|
||||
|
||||
In some way, a `QWeb` instance is the core of an Owl application. It is the only
|
||||
mandatory element of an [environment](component.md#environment). As such, it
|
||||
mandatory element of an [environment](environment.md). As such, it
|
||||
has an extra responsibility: it can act as an event bus for internal communication
|
||||
between Owl classes. This is the reason why `QWeb` actually extends [EventBus](event_bus.md).
|
||||
|
||||
|
||||
@@ -67,6 +67,9 @@ function makeEnvironment() {
|
||||
await env.router.start();
|
||||
return env;
|
||||
}
|
||||
|
||||
owl.config.env = makeEnvironment();
|
||||
// create root component here
|
||||
```
|
||||
|
||||
Notice that the router needs to be started. This is an asynchronous operation
|
||||
|
||||
@@ -263,7 +263,7 @@ will perform a strict equality check and will update the component every time th
|
||||
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
|
||||
function should return an object or an array. The reason is that it needs to be
|
||||
observed, otherwise the component would not be able to react to changes.
|
||||
|
||||
### `useDispatch`
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
## Content
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Development Mode](#development-mode)
|
||||
- [Playground](#playground)
|
||||
- [Benchmarks](#benchmarks)
|
||||
- [Single File Component](#single-file-component)
|
||||
@@ -21,26 +20,6 @@ by using a static http server. A simple python
|
||||
server is available in `server.py`. There is also a npm script to start it:
|
||||
`npm run tools` (and its version with a watcher: `npm run tools:watch`).
|
||||
|
||||
## Development Mode
|
||||
|
||||
By default, Owl is in _production_ mode, this means that it will try to do its
|
||||
job fast, and skip some expensive operations. However, in some cases, it is
|
||||
convenient to have better information on what is going on, this is the purpose
|
||||
of the dev mode.
|
||||
|
||||
Owl has a mode flag, in `owl.__info__.mode`. Its default value is `prod`, but
|
||||
it can be set to `dev`:
|
||||
|
||||
```js
|
||||
owl.__info__.mode = "dev";
|
||||
```
|
||||
|
||||
Note that templates compiled with the `prod` settings will not be recompiled.
|
||||
So, changing this setting is best done at startup.
|
||||
|
||||
An important job done by the `dev` mode is to validate props for each component
|
||||
creation and update. Also, extra props will cause an error.
|
||||
|
||||
## Playground
|
||||
|
||||
The playground is an important application designed to help learning and
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "owl-framework",
|
||||
"version": "0.24.1",
|
||||
"version": "1.0.0-alpha",
|
||||
"description": "Odoo Web Library (OWL)",
|
||||
"main": "src/index.ts",
|
||||
"engines": {
|
||||
@@ -18,7 +18,7 @@
|
||||
"tools": "npm run build && npm run tools:serve",
|
||||
"pretools:watch": "npm run build",
|
||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\"",
|
||||
"prettier": "prettier {src/**/*.ts,tests/**/*.ts,doc/**/*.md} --write"
|
||||
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
+12
-10
@@ -1,23 +1,25 @@
|
||||
# 🦉 OWL Roadmap 🦉
|
||||
|
||||
- Current version: 0.24.1
|
||||
- Current version: 1.0.0-alpha
|
||||
- Status: mostly stable
|
||||
|
||||
This roadmap is only an attempt at predicting Owl's future. Everything may
|
||||
change!
|
||||
|
||||
### October 2019
|
||||
|
||||
We plan to complete the following tasks:
|
||||
|
||||
- improve API for root widgets (issue #306),
|
||||
- replace `t-keepalive`, and maybe `t-transition` by components (issue #295).
|
||||
|
||||
### November 2019
|
||||
|
||||
Once the previous tasks are done, release version 1.0alpha. This means that the
|
||||
API should be stable. But it could change a little bit if we need it for our
|
||||
work on Odoo.
|
||||
Owl will be used in various Odoo projects. We plan to:
|
||||
|
||||
- fix any issues encountered
|
||||
- maybe cleanup slightly the router API
|
||||
- improve the documentation
|
||||
- improve error handling, add more helpful error messages
|
||||
|
||||
### December 2019
|
||||
|
||||
If all goes well, Owl will be upgraded to beta status. From then, no API change,
|
||||
even small, is expected.
|
||||
|
||||
### End of 2019
|
||||
|
||||
|
||||
+36
-45
@@ -1,10 +1,11 @@
|
||||
import { Observer } from "../core/observer";
|
||||
import { CompiledTemplate, QWeb } from "../qweb/index";
|
||||
import { h, patch, VNode } from "../vdom/index";
|
||||
import { config } from "../config";
|
||||
import "./directive";
|
||||
import { Fiber } from "./fiber";
|
||||
import "./props_validation";
|
||||
import { Scheduler } from "./scheduler";
|
||||
import { scheduler } from "./scheduler";
|
||||
|
||||
/**
|
||||
* Owl Component System
|
||||
@@ -20,8 +21,6 @@ import { Scheduler } from "./scheduler";
|
||||
//------------------------------------------------------------------------------
|
||||
// Types/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
const raf = window.requestAnimationFrame.bind(window);
|
||||
export const scheduler = new Scheduler(raf);
|
||||
|
||||
/**
|
||||
* An Env (environment) is an object that will be (mostly) shared between all
|
||||
@@ -46,6 +45,7 @@ interface Internal<T extends Env, Props> {
|
||||
// each component has a unique id, useful mostly to handle parent/child
|
||||
// relationships
|
||||
readonly id: number;
|
||||
depth: number;
|
||||
vnode: VNode | null;
|
||||
pvnode: VNode | null;
|
||||
isMounted: boolean;
|
||||
@@ -107,44 +107,32 @@ export class Component<T extends Env, Props extends {}> {
|
||||
/**
|
||||
* Creates an instance of Component.
|
||||
*
|
||||
* The root component of a component tree needs an environment:
|
||||
*
|
||||
* ```javascript
|
||||
* const root = new RootComponent(env, props);
|
||||
* ```
|
||||
*
|
||||
* Every other component simply needs a reference to its parent:
|
||||
*
|
||||
* ```javascript
|
||||
* const child = new SomeComponent(parent, props);
|
||||
* ```
|
||||
*
|
||||
* Note that most of the time, only the root component needs to be created by
|
||||
* hand. Other components should be created automatically by the framework (with
|
||||
* the t-component directive in a template)
|
||||
*/
|
||||
constructor(parent: Component<T, any> | T, props?: Props) {
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
constructor(parent?: Component<T, any>, props?: Props) {
|
||||
Component.current = this;
|
||||
if (defaultProps) {
|
||||
props = this.__applyDefaultProps(props, defaultProps);
|
||||
}
|
||||
// is this a good idea?
|
||||
// Pro: if props is empty, we can create easily a component
|
||||
// Con: this is not really safe
|
||||
// Pro: but creating component (by a template) is always unsafe anyway
|
||||
this.props = <Props>props || <Props>{};
|
||||
if (QWeb.dev) {
|
||||
QWeb.utils.validateProps(this.constructor, this.props);
|
||||
}
|
||||
let id: number = nextId++;
|
||||
let p: Component<T, any> | null = null;
|
||||
if (parent instanceof Component) {
|
||||
p = parent;
|
||||
|
||||
const id: number = nextId++;
|
||||
let depth;
|
||||
if (parent) {
|
||||
const defaultProps = (<any>this.constructor).defaultProps;
|
||||
if (defaultProps) {
|
||||
props = this.__applyDefaultProps(props, defaultProps);
|
||||
}
|
||||
this.props = <Props>props;
|
||||
if (QWeb.dev) {
|
||||
QWeb.utils.validateProps(this.constructor, this.props);
|
||||
}
|
||||
this.env = parent.env;
|
||||
parent.__owl__.children[id] = this;
|
||||
const __powl__ = parent.__owl__;
|
||||
__powl__.children[id] = this;
|
||||
depth = __powl__.depth + 1;
|
||||
} else {
|
||||
this.env = parent;
|
||||
// we are the root component
|
||||
this.env = config.env as T;
|
||||
this.props = undefined as unknown as Props;
|
||||
this.env.qweb.on("update", this, () => {
|
||||
if (this.__owl__.isMounted) {
|
||||
this.render(true);
|
||||
@@ -158,16 +146,19 @@ export class Component<T extends Env, Props extends {}> {
|
||||
this.env.qweb.off("update", this);
|
||||
}
|
||||
});
|
||||
depth = 0;
|
||||
}
|
||||
|
||||
const qweb = this.env.qweb;
|
||||
|
||||
this.__owl__ = {
|
||||
id: id,
|
||||
depth: depth,
|
||||
vnode: null,
|
||||
pvnode: null,
|
||||
isMounted: false,
|
||||
isDestroyed: false,
|
||||
parent: p,
|
||||
parent: parent || null,
|
||||
children: {},
|
||||
cmap: {},
|
||||
currentFiber: null,
|
||||
@@ -290,13 +281,8 @@ export class Component<T extends Env, Props extends {}> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, false);
|
||||
if (!__owl__.vnode) {
|
||||
this.__prepareAndRender(fiber);
|
||||
} else {
|
||||
this.__render(fiber);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const fiber = new Fiber(null, this, undefined, undefined, false);
|
||||
scheduler.addFiber(fiber, err => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
@@ -311,6 +297,11 @@ export class Component<T extends Env, Props extends {}> {
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
if (!__owl__.vnode) {
|
||||
this.__prepareAndRender(fiber);
|
||||
} else {
|
||||
this.__render(fiber);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -342,9 +333,8 @@ export class Component<T extends Env, Props extends {}> {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const fiber = new Fiber(null, this, this.props, undefined, undefined, force);
|
||||
this.__render(fiber);
|
||||
return new Promise((resolve, reject) => {
|
||||
const fiber = new Fiber(null, this, undefined, undefined, force);
|
||||
scheduler.addFiber(fiber.root, err => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
@@ -355,6 +345,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
this.__render(fiber);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -492,7 +483,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||
if (shouldUpdate) {
|
||||
const __owl__ = this.__owl__;
|
||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
||||
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
} else {
|
||||
@@ -536,7 +527,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
* parent template.
|
||||
*/
|
||||
__prepare(parentFiber: Fiber, scope: any, vars: any, previousSibling?: Fiber | null) {
|
||||
const fiber = new Fiber(parentFiber, this, this.props, scope, vars, parentFiber.force);
|
||||
const fiber = new Fiber(parentFiber, this, scope, vars, parentFiber.force);
|
||||
fiber.shouldPatch = false;
|
||||
if (!parentFiber.child) {
|
||||
parentFiber.child = fiber;
|
||||
|
||||
@@ -186,7 +186,7 @@ QWeb.utils.defineProxy = function defineProxy(target, source) {
|
||||
|
||||
QWeb.addDirective({
|
||||
name: "component",
|
||||
extraNames: ["props", "keepalive"],
|
||||
extraNames: ["props"],
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
ctx.addLine("//COMPONENT");
|
||||
@@ -194,7 +194,6 @@ QWeb.addDirective({
|
||||
ctx.rootContext.shouldDefineQWeb = true;
|
||||
ctx.rootContext.shouldDefineParent = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
let keepAlive = node.getAttribute("t-keepalive") ? true : false;
|
||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||
|
||||
// t-on- events and t-transition
|
||||
@@ -256,8 +255,8 @@ QWeb.addDirective({
|
||||
if (transition) {
|
||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
||||
}
|
||||
let finalizeComponentCode = `w${componentID}.${keepAlive ? "unmount" : "destroy"}();`;
|
||||
if (ref && !keepAlive) {
|
||||
let finalizeComponentCode = `w${componentID}.destroy();`;
|
||||
if (ref) {
|
||||
finalizeComponentCode += `delete context.__owl__.refs[${refKey}];`;
|
||||
}
|
||||
if (transition) {
|
||||
@@ -338,11 +337,6 @@ QWeb.addDirective({
|
||||
`let w${componentID} = ${templateId} in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[${templateId}]] : false;`
|
||||
);
|
||||
let shouldProxy = !ctx.parentNode;
|
||||
if (keepAlive) {
|
||||
ctx.addLine(
|
||||
`const fiber${componentID} = Object.assign(Object.create(extra.fiber), {patchQueue: []});`
|
||||
);
|
||||
}
|
||||
if (shouldProxy) {
|
||||
let id = ctx.generateID();
|
||||
ctx.rootContext.rootNode = id;
|
||||
@@ -393,28 +387,15 @@ QWeb.addDirective({
|
||||
ctx.addIf(`w${componentID}`);
|
||||
|
||||
// need to update component
|
||||
let patchQueueCode = keepAlive ? `fiber${componentID}` : "extra.fiber";
|
||||
if (keepAlive) {
|
||||
// if we have t-keepalive="1", the component could be unmounted, but then
|
||||
// we __updateProps is called. This is ok, but we do not want to call
|
||||
// the willPatch/patched hooks of the component in this case, so we
|
||||
// disable the patch queue
|
||||
patchQueueCode = `w${componentID}.__owl__.isMounted ? extra.fiber : fiber${componentID}`;
|
||||
}
|
||||
let styleCode = "";
|
||||
if (tattStyle) {
|
||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
|
||||
`w${componentID}.__updateProps(props${componentID}, extra.fiber${scopeVars &&
|
||||
", " + scopeVars}, sibling)${styleCode};`
|
||||
);
|
||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
||||
let keepAliveCode = "";
|
||||
if (keepAlive) {
|
||||
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${componentID}.el,vn.elm);vn.elm=w${componentID}.el;w${componentID}.__remount();};`;
|
||||
ctx.addLine(keepAliveCode);
|
||||
}
|
||||
if (registerCode) {
|
||||
ctx.addLine(registerCode);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { VNode } from "../vdom/index";
|
||||
import { Component } from "./component";
|
||||
import { scheduler } from "./scheduler";
|
||||
|
||||
/**
|
||||
* Owl Fiber Class
|
||||
@@ -43,7 +44,6 @@ export class Fiber {
|
||||
|
||||
scope: any;
|
||||
vars: any;
|
||||
props: any;
|
||||
|
||||
component: Component<any, any>;
|
||||
vnode: VNode | null = null;
|
||||
@@ -55,11 +55,10 @@ export class Fiber {
|
||||
|
||||
error?: Error;
|
||||
|
||||
constructor(parent: Fiber | null, component: Component<any, any>, props, scope, vars, force) {
|
||||
constructor(parent: Fiber | null, component: Component<any, any>, scope, vars, force) {
|
||||
this.force = force;
|
||||
this.scope = scope;
|
||||
this.vars = vars;
|
||||
this.props = props;
|
||||
this.component = component;
|
||||
|
||||
this.root = parent ? parent.root : this;
|
||||
@@ -216,7 +215,11 @@ export class Fiber {
|
||||
component.catchError!(error);
|
||||
});
|
||||
} else {
|
||||
// the 3 next lines aim to mark the root fiber as being in error, and
|
||||
// to force it to end, without waiting for its children
|
||||
this.root.counter = 0;
|
||||
this.root.error = error;
|
||||
scheduler.flush();
|
||||
root.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,3 +65,6 @@ export class Scheduler {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const raf = window.requestAnimationFrame.bind(window);
|
||||
export const scheduler = new Scheduler(raf);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { QWeb } from "./qweb/index";
|
||||
import { Env } from "./component/component";
|
||||
|
||||
/**
|
||||
* This file creates and exports the OWL 'config' object, with keys:
|
||||
* - 'mode': 'prod' or 'dev',
|
||||
* - 'env': the environment to use in root components.
|
||||
*/
|
||||
|
||||
interface Config {
|
||||
env: Env;
|
||||
mode: string;
|
||||
}
|
||||
|
||||
export const config = {} as Config;
|
||||
|
||||
Object.defineProperty(config, "mode", {
|
||||
get() {
|
||||
return QWeb.dev ? "dev" : "prod";
|
||||
},
|
||||
set(mode: string) {
|
||||
QWeb.dev = mode === "dev";
|
||||
if (QWeb.dev) {
|
||||
const url = `https://github.com/odoo/owl/blob/master/doc/tooling.md#development-mode`;
|
||||
console.warn(
|
||||
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
||||
);
|
||||
} else {
|
||||
console.log(`Owl is now running in 'prod' mode.`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
let env:Env;
|
||||
Object.defineProperty(config, "env", {
|
||||
get() {
|
||||
if (!env) {
|
||||
env = {} as Env;
|
||||
}
|
||||
if (!env.qweb) {
|
||||
env.qweb = new QWeb();
|
||||
}
|
||||
return env;
|
||||
},
|
||||
set(newEnv: Env) {
|
||||
env = newEnv;
|
||||
},
|
||||
});
|
||||
+54
-22
@@ -1,4 +1,5 @@
|
||||
import { Component, scheduler } from "./component/component";
|
||||
import { Component } from "./component/component";
|
||||
import { scheduler } from "./component/scheduler";
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { onWillUnmount } from "./hooks";
|
||||
@@ -12,6 +13,28 @@ import { onWillUnmount } from "./hooks";
|
||||
* With a `Context` object, each component can subscribe (with the `useContext`
|
||||
* hook) to its state, and will be updated whenever the context state is updated.
|
||||
*/
|
||||
|
||||
function partitionBy<T>(arr: T[], fn: (t: T) => boolean) {
|
||||
let lastGroup: T[] | false = false;
|
||||
let lastValue;
|
||||
return arr.reduce((acc: T[][], cur) => {
|
||||
let curVal = fn(cur);
|
||||
if (lastGroup) {
|
||||
if (curVal === lastValue) {
|
||||
lastGroup.push(cur);
|
||||
} else {
|
||||
lastGroup = false;
|
||||
}
|
||||
}
|
||||
if (!lastGroup) {
|
||||
lastGroup = [cur];
|
||||
acc.push(lastGroup);
|
||||
}
|
||||
lastValue = curVal;
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
export class Context extends EventBus {
|
||||
state: any;
|
||||
observer: Observer;
|
||||
@@ -24,38 +47,47 @@ export class Context extends EventBus {
|
||||
this.observer = new Observer();
|
||||
this.observer.notifyCB = this.__notifyComponents.bind(this);
|
||||
this.state = this.observer.observe(state);
|
||||
this.subscriptions.update = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Instead of using trigger to emit an update event, we actually implement
|
||||
* our own function to do that. The reason is that we need to be smarter than
|
||||
* a simple trigger function: we need to wait for parent components to be
|
||||
* done before doing children components. The reason is that if an update
|
||||
* as an effect of destroying a children, we do not want to call the
|
||||
* mapStoreToProps function of the child, nor rendering it.
|
||||
* done before doing children components. More precisely, if an update
|
||||
* as an effect of destroying a children, we do not want to call any code
|
||||
* from the child, and certainly not render it.
|
||||
*
|
||||
* This method is not optimal if we have a bunch of asynchronous components:
|
||||
* we wait sequentially for each component to be completed before updating the
|
||||
* next. However, the only things that matters is that children are updated
|
||||
* after their parents. So, this could be optimized by being smarter, and
|
||||
* updating all widgets concurrently, except for parents/children.
|
||||
* This method implements a simple grouping algorithm by depth. If we have
|
||||
* connected components of depths [2, 4,4,4,4, 3,8,8], the Context will notify
|
||||
* them in the following groups: [2], [4,4,4,4], [3], [8,8]. Each group will
|
||||
* be updated sequentially, but each components in a given group will be done in
|
||||
* parallel.
|
||||
*
|
||||
* A potential cheap way to improve this situation is to keep track of the
|
||||
* depth of a component in the component tree. A root component has a depth of
|
||||
* 1, then its children of 2 and so on... Then, we can update all components
|
||||
* with the same depth in parallel.
|
||||
* This is a very simple algorithm, but it avoids checking if a given
|
||||
* component is a child of another.
|
||||
*/
|
||||
async __notifyComponents() {
|
||||
const rev = ++this.rev;
|
||||
const subs = this.subscriptions.update || [];
|
||||
for (let i = 0, iLen = subs.length; i < iLen; i++) {
|
||||
const sub = subs[i];
|
||||
const shouldCallback = sub.owner ? sub.owner.__owl__.isMounted : true;
|
||||
if (shouldCallback) {
|
||||
const render = sub.callback.call(sub.owner, rev);
|
||||
scheduler.flush();
|
||||
await render;
|
||||
}
|
||||
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);
|
||||
}
|
||||
})
|
||||
);
|
||||
// at this point, each component in the current group has registered a
|
||||
// top level fiber in the scheduler. It could happen that rendering these
|
||||
// components is done (if they have no children). This is why we manually
|
||||
// flush the scheduler. This will force the scheduler to check
|
||||
// immediately if they are done, which will cause their rendering
|
||||
// promise to resolve earlier, which means that there is a chance of
|
||||
// processing the next group in the same frame.
|
||||
scheduler.flush();
|
||||
await proms;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,10 +46,6 @@ export class Observer {
|
||||
const metadata = this.weakMap.get(value);
|
||||
return metadata ? metadata.rev : 0;
|
||||
}
|
||||
deepRevNumber(value): number {
|
||||
const metadata = this.weakMap.get(value);
|
||||
return metadata ? metadata.deepRev : 0;
|
||||
}
|
||||
|
||||
_observe(value, parent) {
|
||||
var self = this;
|
||||
@@ -87,7 +83,6 @@ export class Observer {
|
||||
value,
|
||||
proxy,
|
||||
rev: this.rev,
|
||||
deepRev: this.rev,
|
||||
parent
|
||||
};
|
||||
|
||||
@@ -99,11 +94,10 @@ export class Observer {
|
||||
_updateRevNumber(target: any) {
|
||||
this.rev++;
|
||||
let metadata = this.weakMap.get(target);
|
||||
metadata.rev!++;
|
||||
let parent = target;
|
||||
do {
|
||||
metadata = this.weakMap.get(parent);
|
||||
metadata.deepRev++;
|
||||
metadata.rev++;
|
||||
} while ((parent = metadata.parent) && parent !== target);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-17
@@ -7,6 +7,7 @@
|
||||
import { EventBus } from "./core/event_bus";
|
||||
import { Observer } from "./core/observer";
|
||||
import { QWeb } from "./qweb/index";
|
||||
import { config } from "./config";
|
||||
import * as _store from "./store";
|
||||
import * as _utils from "./utils";
|
||||
import * as _tags from "./tags";
|
||||
@@ -19,6 +20,7 @@ import { Router } from "./router/router";
|
||||
|
||||
export { Component } from "./component/component";
|
||||
export { QWeb };
|
||||
export { config };
|
||||
|
||||
export const Context = _context.Context;
|
||||
export const useState = _hooks.useState;
|
||||
@@ -35,20 +37,3 @@ export const hooks = Object.assign({}, _hooks, {
|
||||
useStore: _store.useStore
|
||||
});
|
||||
export const __info__ = {};
|
||||
|
||||
Object.defineProperty(__info__, "mode", {
|
||||
get() {
|
||||
return QWeb.dev ? "dev" : "prod";
|
||||
},
|
||||
set(mode: string) {
|
||||
QWeb.dev = mode === "dev";
|
||||
if (QWeb.dev) {
|
||||
const url = `https://github.com/odoo/owl/blob/master/doc/tooling.md#development-mode`;
|
||||
console.warn(
|
||||
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
|
||||
);
|
||||
} else {
|
||||
console.log(`Owl is now running in 'prod' mode.`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+1
-2
@@ -85,7 +85,7 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
||||
const component: Component<any, any> = Component.current!;
|
||||
const store = options.store || (component.env.store as Store);
|
||||
let result = selector(store.state, component.props);
|
||||
const hashFn = store.observer.deepRevNumber.bind(store.observer);
|
||||
const hashFn = store.observer.revNumber.bind(store.observer);
|
||||
let revNumber = hashFn(result) || result;
|
||||
const isEqual = options.isEqual || isStrictEqual;
|
||||
if (!store.updateFunctions[component.__owl__.id]) {
|
||||
@@ -116,7 +116,6 @@ export function useStore(selector, options: SelectorOptions = {}): any {
|
||||
}
|
||||
});
|
||||
onWillUpdateProps(props => {
|
||||
// FIXME: only do that if not keepalive + do it in destroy in that case
|
||||
delete store.updateFunctions[component.__owl__.id];
|
||||
result = selector(store.state, props);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { config } from "../src/config";
|
||||
import { QWeb } from "../src/qweb/index";
|
||||
import { useState, useRef } from "../src/hooks";
|
||||
import {
|
||||
@@ -29,6 +30,7 @@ let cssEl: HTMLElement;
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = env;
|
||||
qweb = new QWeb();
|
||||
});
|
||||
|
||||
@@ -108,7 +110,7 @@ describe("animations", () => {
|
||||
class TestWidget extends Widget {
|
||||
state = useState({ hide: false });
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
const widget = new TestWidget();
|
||||
|
||||
// insert widget into the DOM
|
||||
let def = makeDeferred();
|
||||
@@ -151,7 +153,7 @@ describe("animations", () => {
|
||||
state = useState({ hide: false });
|
||||
span = useRef("span");
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
const widget = new TestWidget();
|
||||
|
||||
// insert widget into the DOM
|
||||
let def = makeDeferred();
|
||||
@@ -180,7 +182,7 @@ describe("animations", () => {
|
||||
class Parent extends Widget {
|
||||
static components = { Child: Child };
|
||||
}
|
||||
const widget = new Parent(env);
|
||||
const widget = new Parent();
|
||||
|
||||
let def = makeDeferred();
|
||||
var spanNode;
|
||||
@@ -220,7 +222,7 @@ describe("animations", () => {
|
||||
static components = { Child: Child };
|
||||
state = useState({ display: true });
|
||||
}
|
||||
const widget = new Parent(env);
|
||||
const widget = new Parent();
|
||||
|
||||
let def = makeDeferred();
|
||||
var spanNode;
|
||||
@@ -283,7 +285,7 @@ describe("animations", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new Parent(env);
|
||||
const widget = new Parent();
|
||||
await widget.mount(fixture);
|
||||
let button = widget.el!.querySelector("button");
|
||||
|
||||
@@ -341,7 +343,7 @@ describe("animations", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new Parent(env);
|
||||
const widget = new Parent();
|
||||
await widget.mount(fixture);
|
||||
let button = widget.el!.querySelector("button");
|
||||
|
||||
|
||||
@@ -234,51 +234,6 @@ exports[`class and style attributes with t-component t-att-class is properly add
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`composition sub components dom state with t-keepalive is preserved 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['state'].ok) {
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
const fiber3 = Object.assign(Object.create(extra.fiber), {patchQueue: []});
|
||||
let props3 = {};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, w3.__owl__.isMounted ? extra.fiber : fiber3, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w3.el,vn.elm);vn.elm=w3.el;w3.__remount();};
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
let componentKey3 = \`InputWidget\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['InputWidget'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.unmount();}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`composition sub components with some state rendered in a loop 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
@@ -460,51 +415,6 @@ exports[`dynamic t-props basic use 1`] = `
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`lifecycle hooks willPatch/patched hook with t-keepalive 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.constructor.utils;
|
||||
let QWeb = this.constructor;
|
||||
let parent = context;
|
||||
let owner = context;
|
||||
let sibling = null;
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['state'].flag) {
|
||||
//COMPONENT
|
||||
let templateId3 = \`__4__\`;
|
||||
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
|
||||
const fiber3 = Object.assign(Object.create(extra.fiber), {patchQueue: []});
|
||||
let props3 = {v:context['state'].n};
|
||||
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
|
||||
w3.destroy();
|
||||
w3 = false;
|
||||
}
|
||||
if (w3) {
|
||||
w3.__updateProps(props3, w3.__owl__.isMounted ? extra.fiber : fiber3, undefined, undefined, sibling);
|
||||
let pvnode = w3.__owl__.pvnode;
|
||||
pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w3.el,vn.elm);vn.elm=w3.el;w3.__remount();};
|
||||
c1.push(pvnode);
|
||||
} else {
|
||||
let componentKey3 = \`ChildWidget\`;
|
||||
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['ChildWidget'];
|
||||
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
|
||||
w3 = new W3(parent, props3);
|
||||
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
|
||||
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
|
||||
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.unmount();}}});
|
||||
const fiber = w3.__owl__.currentFiber;
|
||||
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
|
||||
c1.push(pvnode);
|
||||
w3.__owl__.pvnode = pvnode;
|
||||
}
|
||||
sibling = w3.__owl__.currentFiber || sibling;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`other directives with t-component t-on with getter as handler 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
@@ -1036,7 +946,7 @@ exports[`random stuff/miscellaneous t-on with handler bound to dynamic argument
|
||||
var h = this.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['props'].items;
|
||||
var _2 = context['items'];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
|
||||
+215
-327
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
import { Component, Env } from "../../src/component/component";
|
||||
import { makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||
import { useState } from "../../src/hooks";
|
||||
import { config } from "../../src/config";
|
||||
import { QWeb } from "../../src/qweb";
|
||||
import { xml } from "../../src/tags";
|
||||
|
||||
@@ -15,6 +16,7 @@ let dev: boolean = false;
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = env;
|
||||
dev = QWeb.dev;
|
||||
QWeb.dev = true;
|
||||
});
|
||||
@@ -35,17 +37,32 @@ describe("props validation", () => {
|
||||
static props = ["message"];
|
||||
static template = xml`<div>hey</div>`;
|
||||
}
|
||||
class Parent extends Widget {
|
||||
static components = { TestWidget };
|
||||
static template = xml`<div><TestWidget /></div>`;
|
||||
}
|
||||
|
||||
let error;
|
||||
QWeb.dev = true;
|
||||
expect(() => {
|
||||
new TestWidget(env);
|
||||
}).toThrow();
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||
|
||||
error = undefined;
|
||||
|
||||
QWeb.dev = false;
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env);
|
||||
}).not.toThrow();
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
test("props: list of strings", async () => {
|
||||
@@ -53,10 +70,20 @@ describe("props validation", () => {
|
||||
static props = ["message"];
|
||||
static template = xml`<div>hey</div>`;
|
||||
}
|
||||
class Parent extends Widget {
|
||||
static components = { TestWidget };
|
||||
static template = xml`<div><TestWidget /></div>`;
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env);
|
||||
}).toThrow("Missing props 'message' (component 'TestWidget')");
|
||||
let error;
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Missing props 'message' (component 'TestWidget')`);
|
||||
});
|
||||
|
||||
test("validate simple types", async () => {
|
||||
@@ -69,23 +96,50 @@ describe("props validation", () => {
|
||||
{ type: Function, ok: () => {}, ko: "1" }
|
||||
];
|
||||
|
||||
let props;
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
}
|
||||
for (let test of Tests) {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: test.type };
|
||||
};
|
||||
Parent.components = { TestWidget };
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env);
|
||||
}).toThrow("Missing props 'p'");
|
||||
let error;
|
||||
props = {};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: test.ok });
|
||||
}).not.toThrow();
|
||||
error = undefined;
|
||||
props = {p: test.ok};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: test.ko });
|
||||
}).toThrow("Props 'p' of invalid type in component");
|
||||
props = {p: test.ko};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -99,119 +153,305 @@ describe("props validation", () => {
|
||||
{ type: Function, ok: () => {}, ko: "1" }
|
||||
];
|
||||
|
||||
let props;
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
}
|
||||
for (let test of Tests) {
|
||||
let TestWidget = class extends Widget {
|
||||
static template = xml`<div>hey</div>`;
|
||||
let TestWidget = class extends Component<any, any> {
|
||||
static props = { p: { type: test.type } };
|
||||
static template = xml`<div>hey</div>`;
|
||||
};
|
||||
Parent.components = { TestWidget };
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env);
|
||||
}).toThrow("Missing props 'p'");
|
||||
let error;
|
||||
props = {};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Missing props 'p' (component '_a')`);
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: test.ok });
|
||||
}).not.toThrow();
|
||||
error = undefined;
|
||||
props = {p: test.ok};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: test.ko });
|
||||
}).toThrow("Props 'p' of invalid type in component");
|
||||
props = {p: test.ko};
|
||||
try {
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component '_a'`);
|
||||
}
|
||||
});
|
||||
|
||||
test("can validate a prop with multiple types", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: [String, Boolean] };
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
};
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: "string" });
|
||||
new TestWidget(env, { p: true });
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: "string" };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: 1 });
|
||||
}).toThrow("Props 'p' of invalid type in component");
|
||||
try {
|
||||
props = { p: true };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
props = { p: 1 };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("can validate an optional props", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: String, optional: true } };
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
};
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: "hey" });
|
||||
new TestWidget(env, {});
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: "key" };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: 1 });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = {};
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
props = { p: 1 };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("can validate an array with given primitive type", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: Array, element: String } };
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
};
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: [] });
|
||||
new TestWidget(env, { p: ["string"] });
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: [] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: [1] });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: ["string"] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: ["string", 1] });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: [1] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
|
||||
error = undefined;
|
||||
try {
|
||||
props = { p: ["string", 1] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
});
|
||||
|
||||
test("can validate an array with multiple sub element types", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = { p: { type: Array, element: [String, Boolean] } };
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: [] });
|
||||
new TestWidget(env, { p: ["string"] });
|
||||
new TestWidget(env, { p: [false, true, "string"] });
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: [] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: [true, 1] });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: ["string"] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
props = { p: [false, true, "string"] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
props = { p: [true, 1] };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("can validate an object with simple shape", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = {
|
||||
p: { type: Object, shape: { id: Number, url: String } }
|
||||
};
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: { id: 1, url: "url" } });
|
||||
new TestWidget(env, { p: { id: 1, url: "url", extra: true } });
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: { id: 1, url: "url" } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: { id: "1", url: "url" } });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: { id: 1, url: "url", extra: true } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: { id: 1 } });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: { id: "1", url: "url" } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
|
||||
error = undefined;
|
||||
try {
|
||||
props = { p: { id: 1 } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("can validate recursively complicated prop def", async () => {
|
||||
let TestWidget = class extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
static props = {
|
||||
p: {
|
||||
@@ -223,15 +463,43 @@ describe("props validation", () => {
|
||||
}
|
||||
};
|
||||
};
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget p="p"/></div>`;
|
||||
static components = { TestWidget };
|
||||
get p() {
|
||||
return props.p;
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: { id: 1, url: true } });
|
||||
new TestWidget(env, { p: { id: 1, url: [12] } });
|
||||
}).not.toThrow();
|
||||
let error;
|
||||
let props;
|
||||
try {
|
||||
props = { p: { id: 1, url: true } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
expect(() => {
|
||||
new TestWidget(env, { p: { id: 1, url: [12, true] } });
|
||||
}).toThrow();
|
||||
try {
|
||||
props = { p: { id: 1, url: [12] } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeUndefined();
|
||||
|
||||
try {
|
||||
props = { p: { id: 1, url: [12, true] } };
|
||||
const p = new Parent();
|
||||
await p.mount(fixture);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).toBeDefined();
|
||||
expect(error.message).toBe(`Props 'p' of invalid type in component 'TestWidget'`);
|
||||
});
|
||||
|
||||
test("props are validated in dev mode (code snapshot)", async () => {
|
||||
@@ -249,7 +517,7 @@ describe("props validation", () => {
|
||||
class App extends Widget {
|
||||
static components = { Child };
|
||||
}
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
// need to make sure there are 2 call to update props. one at component
|
||||
@@ -334,7 +602,7 @@ describe("props validation", () => {
|
||||
static components = { TestWidget };
|
||||
}
|
||||
|
||||
const w = new App(env, {});
|
||||
const w = new App(undefined, {});
|
||||
let error;
|
||||
try {
|
||||
await w.mount(fixture);
|
||||
@@ -354,7 +622,7 @@ describe("props validation", () => {
|
||||
async __updateProps() {
|
||||
try {
|
||||
await Component.prototype.__updateProps.apply(this, arguments);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
}
|
||||
@@ -365,7 +633,7 @@ describe("props validation", () => {
|
||||
state: any = useState({ p: 1 });
|
||||
}
|
||||
|
||||
const w = new Parent(env);
|
||||
const w = new Parent();
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
|
||||
@@ -387,7 +655,7 @@ describe("props validation", () => {
|
||||
state: any = useState({ p: 1 });
|
||||
}
|
||||
|
||||
const w = new Parent(env);
|
||||
const w = new Parent();
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
|
||||
@@ -399,13 +667,18 @@ describe("props validation", () => {
|
||||
|
||||
describe("default props", () => {
|
||||
test("can set default values", async () => {
|
||||
class TestWidget extends Widget {
|
||||
class TestWidget extends Component<any, any> {
|
||||
static defaultProps = { p: 4 };
|
||||
static template = xml`<div>hey</div>`;
|
||||
static template = xml`<div><t t-esc="props.p"/></div>`;
|
||||
}
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><TestWidget /></div>`;
|
||||
static components = { TestWidget };
|
||||
}
|
||||
|
||||
const w = new TestWidget(env, {});
|
||||
expect(w.props.p).toBe(4);
|
||||
const w = new Parent();
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe('<div><div>4</div></div>');
|
||||
});
|
||||
|
||||
test("default values are also set whenever component is updated", async () => {
|
||||
@@ -419,7 +692,7 @@ describe("default props", () => {
|
||||
state: any = useState({ p: 1 });
|
||||
}
|
||||
|
||||
const w = new Parent(env);
|
||||
const w = new Parent();
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
|
||||
|
||||
@@ -440,7 +713,7 @@ describe("default props", () => {
|
||||
static components = { TestWidget };
|
||||
}
|
||||
|
||||
const w = new App(env, {});
|
||||
const w = new App(undefined, {});
|
||||
await w.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>heyhey</span></div>");
|
||||
});
|
||||
|
||||
+93
-11
@@ -1,6 +1,7 @@
|
||||
import { makeDeferred, makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { Component } from "../src/component/component";
|
||||
import { Context, useContext } from "../src/context";
|
||||
import { config } from "../src/config";
|
||||
import { xml } from "../src/tags";
|
||||
import { useState } from "../src/hooks";
|
||||
|
||||
@@ -11,14 +12,13 @@ import { useState } from "../src/hooks";
|
||||
// We create before each test:
|
||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||
// manipulations. Note that it is removed after each test.
|
||||
// - env: a WEnv, necessary to create new components
|
||||
// - a test env, necessary to create components, that is set as env
|
||||
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -37,7 +37,7 @@ describe("Context", () => {
|
||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||
contextObj = useContext(testContext);
|
||||
}
|
||||
const test = new Test(env);
|
||||
const test = new Test();
|
||||
await test.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||
});
|
||||
@@ -49,7 +49,7 @@ describe("Context", () => {
|
||||
static template = xml`<div><t t-esc="contextObj.value"/></div>`;
|
||||
contextObj = useContext(testContext);
|
||||
}
|
||||
const test = new Test(env);
|
||||
const test = new Test();
|
||||
await test.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>123</div>");
|
||||
test.contextObj.value = 321;
|
||||
@@ -68,7 +68,7 @@ describe("Context", () => {
|
||||
static template = xml`<div><Child /><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||
testContext.state.value = 321;
|
||||
@@ -76,6 +76,88 @@ describe("Context", () => {
|
||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||
});
|
||||
|
||||
test("two async components are updated in parallel", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
const def = makeDeferred();
|
||||
const steps: string[] = [];
|
||||
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><t t-esc="contextObj.value"/></span>`;
|
||||
contextObj = useContext(testContext);
|
||||
async render() {
|
||||
steps.push("render");
|
||||
await def;
|
||||
return super.render();
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child /><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||
testContext.state.value = 321;
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["render", "render"]);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span><span>123</span></div>");
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div><span>321</span><span>321</span></div>");
|
||||
});
|
||||
|
||||
test("two async components on two levels are updated in parallel", async () => {
|
||||
const testContext = new Context({ value: 123 });
|
||||
const def = makeDeferred();
|
||||
const steps: string[] = [];
|
||||
|
||||
class SlowComp extends Component<any, any> {
|
||||
static template = xml`<p><t t-esc="props.value"/></p>`;
|
||||
willUpdateProps() {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<span><SlowComp value="contextObj.value"/></span>`;
|
||||
static components = { SlowComp };
|
||||
contextObj = useContext(testContext);
|
||||
|
||||
render() {
|
||||
steps.push("render");
|
||||
return super.render();
|
||||
}
|
||||
}
|
||||
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><Child /><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
|
||||
class App extends Component<any, any> {
|
||||
static template = xml`<div><Child /><Parent /></div>`;
|
||||
static components = { Child, Parent };
|
||||
}
|
||||
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||
);
|
||||
testContext.state.value = 321;
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["render"]);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><span><p>123</p></span><div><span><p>123</p></span><span><p>123</p></span></div></div>"
|
||||
);
|
||||
def.resolve();
|
||||
await nextTick();
|
||||
expect(steps).toEqual(["render", "render", "render"]);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><span><p>321</p></span><div><span><p>321</p></span><span><p>321</p></span></div></div>"
|
||||
);
|
||||
});
|
||||
|
||||
test("one components can subscribe twice to same context", async () => {
|
||||
const testContext = new Context({ a: 1, b: 2 });
|
||||
const steps: string[] = [];
|
||||
@@ -93,7 +175,7 @@ describe("Context", () => {
|
||||
static template = xml`<div><Child /></div>`;
|
||||
static components = { Child };
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
|
||||
expect(steps).toEqual(["child"]);
|
||||
@@ -124,7 +206,7 @@ describe("Context", () => {
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span>321</div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
@@ -158,7 +240,7 @@ describe("Context", () => {
|
||||
return super.__render(fiber);
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>123</span></div>");
|
||||
expect(steps).toEqual(["parent", "child"]);
|
||||
@@ -202,7 +284,7 @@ describe("Context", () => {
|
||||
context = useContext(testContext);
|
||||
}
|
||||
|
||||
const component = new ComponentA(env);
|
||||
const component = new ComponentA();
|
||||
await component.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><p><span>1a</span></p></div>");
|
||||
|
||||
@@ -8,13 +8,11 @@ describe("observer", () => {
|
||||
|
||||
expect(typeof obj).toBe("object");
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
const obj2: any = observer.observe({ a: 1 });
|
||||
expect(observer.revNumber(obj2)).toBe(1);
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
obj2.a = 2;
|
||||
@@ -33,23 +31,19 @@ describe("observer", () => {
|
||||
const obj: any = observer.observe({ a: null, b: undefined });
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
obj.a = 3;
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
|
||||
obj.b = 5;
|
||||
expect(observer.revNumber(obj)).toBe(3);
|
||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
||||
expect(observer.rev).toBe(3);
|
||||
|
||||
obj.a = null;
|
||||
obj.b = undefined;
|
||||
expect(observer.revNumber(obj)).toBe(5);
|
||||
expect(observer.deepRevNumber(obj)).toBe(5);
|
||||
expect(observer.rev).toBe(5);
|
||||
expect(obj).toEqual({
|
||||
a: null,
|
||||
@@ -63,7 +57,6 @@ describe("observer", () => {
|
||||
const obj: any = observer.observe({ date });
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(typeof obj.date.getFullYear()).toBe("number");
|
||||
expect(obj.date).toBe(date);
|
||||
@@ -71,7 +64,6 @@ describe("observer", () => {
|
||||
obj.date = new Date();
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(obj.date).not.toBe(date);
|
||||
});
|
||||
@@ -82,14 +74,11 @@ describe("observer", () => {
|
||||
|
||||
expect(Array.isArray(obj.arr)).toBe(true);
|
||||
expect(observer.revNumber(obj.arr)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj.arr)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
obj.arr[0] = "nope";
|
||||
expect(observer.revNumber(obj.arr)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj.arr)).toBe(2);
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
});
|
||||
|
||||
@@ -98,24 +87,20 @@ describe("observer", () => {
|
||||
const obj: any = observer.observe({ a: 1 });
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
obj.a = 2;
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
|
||||
// same value again
|
||||
obj.a = 2;
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
|
||||
obj.a = 3;
|
||||
expect(observer.revNumber(obj)).toBe(3);
|
||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
||||
expect(observer.rev).toBe(3);
|
||||
});
|
||||
|
||||
@@ -126,19 +111,16 @@ describe("observer", () => {
|
||||
expect(Array.isArray(arr)).toBe(true);
|
||||
expect(arr.length).toBe(0);
|
||||
expect(observer.revNumber(arr)).toBe(1);
|
||||
expect(observer.deepRevNumber(arr)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
arr.push(1);
|
||||
expect(observer.revNumber(arr)).toBe(2);
|
||||
expect(observer.deepRevNumber(arr)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(arr.length).toBe(1);
|
||||
expect(arr).toEqual([1]);
|
||||
|
||||
arr.splice(1, 0, "hey");
|
||||
expect(observer.revNumber(arr)).toBe(3);
|
||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
||||
expect(observer.rev).toBe(3);
|
||||
expect(arr).toEqual([1, "hey"]);
|
||||
expect(arr.length).toBe(2);
|
||||
@@ -146,7 +128,6 @@ describe("observer", () => {
|
||||
arr.unshift("lindemans");
|
||||
//it generates 3 primitive operations
|
||||
expect(observer.revNumber(arr)).toBe(6);
|
||||
expect(observer.deepRevNumber(arr)).toBe(6);
|
||||
expect(observer.rev).toBe(6);
|
||||
expect(arr).toEqual(["lindemans", 1, "hey"]);
|
||||
expect(arr.length).toBe(3);
|
||||
@@ -154,21 +135,18 @@ describe("observer", () => {
|
||||
arr.reverse();
|
||||
//it generates 2 primitive operations
|
||||
expect(observer.revNumber(arr)).toBe(8);
|
||||
expect(observer.deepRevNumber(arr)).toBe(8);
|
||||
expect(observer.rev).toBe(8);
|
||||
expect(arr).toEqual(["hey", 1, "lindemans"]);
|
||||
expect(arr.length).toBe(3);
|
||||
|
||||
arr.pop(); // one set, one delete
|
||||
expect(observer.revNumber(arr)).toBe(10);
|
||||
expect(observer.deepRevNumber(arr)).toBe(10);
|
||||
expect(observer.rev).toBe(10);
|
||||
expect(arr).toEqual(["hey", 1]);
|
||||
expect(arr.length).toBe(2);
|
||||
|
||||
arr.shift(); // 2 sets, 1 delete
|
||||
expect(observer.revNumber(arr)).toBe(13);
|
||||
expect(observer.deepRevNumber(arr)).toBe(13);
|
||||
expect(observer.rev).toBe(13);
|
||||
expect(arr).toEqual([1]);
|
||||
expect(arr.length).toBe(1);
|
||||
@@ -187,8 +165,7 @@ describe("observer", () => {
|
||||
arr[0].kriek = 6;
|
||||
|
||||
expect(observer.rev).toBe(3);
|
||||
expect(observer.revNumber(arr)).toBe(2);
|
||||
expect(observer.deepRevNumber(arr)).toBe(3);
|
||||
expect(observer.revNumber(arr)).toBe(3);
|
||||
expect(observer.revNumber(arr[0])).toBe(3);
|
||||
});
|
||||
|
||||
@@ -238,7 +215,6 @@ describe("observer", () => {
|
||||
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(observer.revNumber(state)).toBe(1);
|
||||
expect(observer.deepRevNumber(state)).toBe(1);
|
||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||
|
||||
state[1] = "b";
|
||||
@@ -247,7 +223,6 @@ describe("observer", () => {
|
||||
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.revNumber(state)).toBe(2);
|
||||
expect(observer.deepRevNumber(state)).toBe(2);
|
||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||
|
||||
expect(state).toEqual(["a", "b"]);
|
||||
@@ -259,13 +234,11 @@ describe("observer", () => {
|
||||
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(observer.revNumber(state.arr)).toBe(1);
|
||||
expect(observer.deepRevNumber(state.arr)).toBe(1);
|
||||
expect(state.arr.length).toBe(0);
|
||||
|
||||
state.arr.push(1);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.revNumber(state.arr)).toBe(2);
|
||||
expect(observer.deepRevNumber(state.arr)).toBe(2);
|
||||
expect(state.arr.length).toBe(1);
|
||||
});
|
||||
|
||||
@@ -280,7 +253,7 @@ describe("observer", () => {
|
||||
|
||||
state.arr[0].something = 2;
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.revNumber(state.arr)).toBe(1);
|
||||
expect(observer.revNumber(state.arr)).toBe(2);
|
||||
expect(observer.revNumber(state.arr[0])).toBe(2);
|
||||
});
|
||||
|
||||
@@ -294,7 +267,7 @@ describe("observer", () => {
|
||||
|
||||
state.a.b = 2;
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.revNumber(state)).toBe(1);
|
||||
expect(observer.revNumber(state)).toBe(2);
|
||||
expect(observer.revNumber(state.a)).toBe(2);
|
||||
});
|
||||
|
||||
@@ -312,7 +285,7 @@ describe("observer", () => {
|
||||
expect(observer.revNumber(obj.a)).toBe(2);
|
||||
obj.a.b = 3;
|
||||
expect(observer.rev).toBe(3);
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.revNumber(obj)).toBe(3);
|
||||
expect(observer.revNumber(obj.a)).toBe(3);
|
||||
});
|
||||
|
||||
@@ -320,22 +293,18 @@ describe("observer", () => {
|
||||
const observer = new Observer();
|
||||
const state: any = observer.observe({ o: { a: 1 }, arr: [1], n: 13 });
|
||||
expect(observer.revNumber(state)).toBe(1);
|
||||
expect(observer.deepRevNumber(state)).toBe(1);
|
||||
|
||||
state.o.a = 2;
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.revNumber(state)).toBe(1);
|
||||
expect(observer.deepRevNumber(state)).toBe(2);
|
||||
expect(observer.revNumber(state)).toBe(2);
|
||||
|
||||
state.arr.push(2);
|
||||
expect(observer.rev).toBe(3);
|
||||
expect(observer.revNumber(state)).toBe(1);
|
||||
expect(observer.deepRevNumber(state)).toBe(3);
|
||||
expect(observer.revNumber(state)).toBe(3);
|
||||
|
||||
state.n = 155;
|
||||
expect(observer.rev).toBe(4);
|
||||
expect(observer.revNumber(state)).toBe(2);
|
||||
expect(observer.deepRevNumber(state)).toBe(4);
|
||||
expect(observer.revNumber(state)).toBe(4);
|
||||
});
|
||||
|
||||
test("properly handle already observed state", () => {
|
||||
@@ -361,18 +330,15 @@ describe("observer", () => {
|
||||
const obj: any = observer.observe({});
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(1);
|
||||
expect(observer.deepRevNumber(obj)).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
|
||||
obj.aku = "always finds annoying problems";
|
||||
expect(observer.revNumber(obj)).toBe(2);
|
||||
expect(observer.deepRevNumber(obj)).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
|
||||
obj.aku = "always finds good problems";
|
||||
|
||||
expect(observer.revNumber(obj)).toBe(3);
|
||||
expect(observer.deepRevNumber(obj)).toBe(3);
|
||||
expect(observer.rev).toBe(3);
|
||||
});
|
||||
|
||||
@@ -416,7 +382,7 @@ describe("observer", () => {
|
||||
expect(observer.revNumber(obj2)).toBe(1);
|
||||
|
||||
obj2.key = 3;
|
||||
expect(observer.revNumber(obj1)).toBe(1);
|
||||
expect(observer.revNumber(obj1)).toBe(2);
|
||||
expect(observer.revNumber(obj2)).toBe(2);
|
||||
});
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ interface MarkDownSection {
|
||||
interface FileData {
|
||||
name: string;
|
||||
path: string[];
|
||||
fullName: string
|
||||
fullName: string;
|
||||
links: MarkDownLink[];
|
||||
sections: MarkDownSection[];
|
||||
}
|
||||
@@ -31,30 +31,27 @@ interface FileData {
|
||||
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
|
||||
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
|
||||
|
||||
|
||||
|
||||
export function addMardownData(fileData): void {
|
||||
const sep = fileData.path.length > 0 ? '/' : '';
|
||||
const fullName = fileData.path.join('/') + sep + fileData.name;
|
||||
const content = fs.readFileSync(fullName, { encoding: "utf8" });
|
||||
let m;
|
||||
// get links info
|
||||
do {
|
||||
m = LINK_REGEXP.exec(content);
|
||||
if (m) {
|
||||
fileData.links.push({ name: m[0], link: m[2] });
|
||||
}
|
||||
} while (m);
|
||||
// get sections info
|
||||
do {
|
||||
m = HEADING_REGEXP.exec(content);
|
||||
if (m) {
|
||||
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
|
||||
}
|
||||
} while (m);
|
||||
const sep = fileData.path.length > 0 ? "/" : "";
|
||||
const fullName = fileData.path.join("/") + sep + fileData.name;
|
||||
const content = fs.readFileSync(fullName, { encoding: "utf8" });
|
||||
let m;
|
||||
// get links info
|
||||
do {
|
||||
m = LINK_REGEXP.exec(content);
|
||||
if (m) {
|
||||
fileData.links.push({ name: m[0], link: m[2] });
|
||||
}
|
||||
} while (m);
|
||||
// get sections info
|
||||
do {
|
||||
m = HEADING_REGEXP.exec(content);
|
||||
if (m) {
|
||||
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
|
||||
}
|
||||
} while (m);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a list of FileData corresponding to all files that need to be
|
||||
* validated.
|
||||
@@ -74,7 +71,7 @@ function getFiles(path: string[] = []): FileData[] {
|
||||
if (f.isDirectory()) {
|
||||
return getFiles(path.concat(f.name));
|
||||
}
|
||||
const fullName = path.join('/') + (path.length > 0 ? '/' : '') + f.name;
|
||||
const fullName = path.join("/") + (path.length > 0 ? "/" : "") + f.name;
|
||||
return [
|
||||
{
|
||||
name: f.name,
|
||||
@@ -88,62 +85,62 @@ function getFiles(path: string[] = []): FileData[] {
|
||||
return Array.prototype.concat(...files);
|
||||
}
|
||||
|
||||
const LOCAL_FILES = ['LICENSE'];
|
||||
const LOCAL_FILES = ["LICENSE"];
|
||||
export function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
|
||||
if (link.link.startsWith("http")) {
|
||||
// no check on external links
|
||||
return true;
|
||||
}
|
||||
// Step 1: extract path, name, hash
|
||||
// path = ['doc', 'architecture]
|
||||
// name = 'rendering.md'
|
||||
// hash = 'blabla' (or '' if no hash)
|
||||
// Step 1: extract path, name, hash
|
||||
// path = ['doc', 'architecture]
|
||||
// name = 'rendering.md'
|
||||
// hash = 'blabla' (or '' if no hash)
|
||||
|
||||
const parts = link.link.split('#');
|
||||
const hash = parts[1] || '';
|
||||
let name;
|
||||
let path;
|
||||
if (parts[0]) {
|
||||
let temp = parts[0].split('/');
|
||||
name = temp[temp.length - 1];
|
||||
temp.splice(-1);
|
||||
path = current.path.slice();
|
||||
for (let elem of temp) {
|
||||
if (elem === '..') {
|
||||
path.splice(-1);
|
||||
} else if (elem !== '.') {
|
||||
path.push(elem);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// there are no file name, so this is a relative link to the current file
|
||||
name = current.name;
|
||||
path = current.path;
|
||||
const parts = link.link.split("#");
|
||||
const hash = parts[1] || "";
|
||||
let name;
|
||||
let path;
|
||||
if (parts[0]) {
|
||||
let temp = parts[0].split("/");
|
||||
name = temp[temp.length - 1];
|
||||
temp.splice(-1);
|
||||
path = current.path.slice();
|
||||
for (let elem of temp) {
|
||||
if (elem === "..") {
|
||||
path.splice(-1);
|
||||
} else if (elem !== ".") {
|
||||
path.push(elem);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// there are no file name, so this is a relative link to the current file
|
||||
name = current.name;
|
||||
path = current.path;
|
||||
}
|
||||
|
||||
// Step 2: build normalized link file name
|
||||
const linkFullName = path.join('/') + (path.length > 0 ? '/' : '') + name;
|
||||
|
||||
// Step 3: check link name against white list of local files
|
||||
if (LOCAL_FILES.includes(linkFullName)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Step 4: check if there is a matching file
|
||||
let target: FileData | undefined = files.find(f => f.fullName === linkFullName);
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 5: if necessary, check if there is a corresponding link inside the target
|
||||
// link name
|
||||
if (hash) {
|
||||
if (!target.sections.find(s => s.slug === hash)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Step 2: build normalized link file name
|
||||
const linkFullName = path.join("/") + (path.length > 0 ? "/" : "") + name;
|
||||
|
||||
// Step 3: check link name against white list of local files
|
||||
if (LOCAL_FILES.includes(linkFullName)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Step 4: check if there is a matching file
|
||||
let target: FileData | undefined = files.find(f => f.fullName === linkFullName);
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 5: if necessary, check if there is a corresponding link inside the target
|
||||
// link name
|
||||
if (hash) {
|
||||
if (!target.sections.find(s => s.slug === hash)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
|
||||
@@ -164,25 +161,23 @@ function slugify(str) {
|
||||
.replace(/-+$/, ""); // Trim - from end of text
|
||||
}
|
||||
|
||||
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Test
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
test("All markdown links work", () => {
|
||||
let linkNumber = 0;
|
||||
let invalidLinkNumber = 0;
|
||||
const data = getFiles();
|
||||
for (let file of data) {
|
||||
for (let link of file.links) {
|
||||
linkNumber++;
|
||||
if (!isLinkValid(link, file, data)) {
|
||||
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
||||
invalidLinkNumber++;
|
||||
}
|
||||
let linkNumber = 0;
|
||||
let invalidLinkNumber = 0;
|
||||
const data = getFiles();
|
||||
for (let file of data) {
|
||||
for (let link of file.links) {
|
||||
linkNumber++;
|
||||
if (!isLinkValid(link, file, data)) {
|
||||
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
||||
invalidLinkNumber++;
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(invalidLinkNumber).toBe(0);
|
||||
expect(linkNumber).toBeGreaterThan(10);
|
||||
}
|
||||
expect(invalidLinkNumber).toBe(0);
|
||||
expect(linkNumber).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
import { Env, scheduler } from "../src/component/component";
|
||||
import { Env } from "../src/component/component";
|
||||
import { scheduler } from "../src/component/scheduler";
|
||||
import { EvalContext, QWeb } from "../src/qweb/qweb";
|
||||
import { patch } from "../src/vdom";
|
||||
import "../src/qweb/base_directives";
|
||||
|
||||
+44
-42
@@ -1,5 +1,6 @@
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "./helpers";
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { config } from "../src/config";
|
||||
import {
|
||||
useState,
|
||||
onMounted,
|
||||
@@ -28,6 +29,7 @@ let env: Env;
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -44,7 +46,7 @@ describe("hooks", () => {
|
||||
static template = xml`<div><t t-esc="counter.value"/></div>`;
|
||||
counter = useState({ value: 42 });
|
||||
}
|
||||
const counter = new Counter(env);
|
||||
const counter = new Counter();
|
||||
await counter.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>42</div>");
|
||||
counter.counter.value = 3;
|
||||
@@ -64,12 +66,12 @@ describe("hooks", () => {
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(component).not.toHaveProperty("mounted");
|
||||
expect(component).not.toHaveProperty("willUnmount");
|
||||
@@ -92,8 +94,8 @@ describe("hooks", () => {
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
@@ -103,7 +105,7 @@ describe("hooks", () => {
|
||||
static components = { MyComponent };
|
||||
state = useState({ flag: true });
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||
expect(steps).toEqual(["mounted"]);
|
||||
@@ -126,8 +128,8 @@ describe("hooks", () => {
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook();
|
||||
}
|
||||
mounted() {
|
||||
@@ -137,7 +139,7 @@ describe("hooks", () => {
|
||||
steps.push("comp:willunmount");
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.unmount();
|
||||
@@ -157,8 +159,8 @@ describe("hooks", () => {
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
useMyHook();
|
||||
}
|
||||
mounted() {
|
||||
@@ -175,7 +177,7 @@ describe("hooks", () => {
|
||||
state = useState({ flag: true });
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div>hey</div></div>");
|
||||
parent.state.flag = false;
|
||||
@@ -197,13 +199,13 @@ describe("hooks", () => {
|
||||
}
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey</div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook(1);
|
||||
useMyHook(2);
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.unmount();
|
||||
@@ -226,7 +228,7 @@ describe("hooks", () => {
|
||||
(this.button.el as HTMLButtonElement).innerHTML = String(this.value);
|
||||
}
|
||||
}
|
||||
const counter = new Counter(env);
|
||||
const counter = new Counter();
|
||||
await counter.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><button>0</button></div>");
|
||||
counter.increment();
|
||||
@@ -247,7 +249,7 @@ describe("hooks", () => {
|
||||
expect(this.spanRef.el).toBeNull();
|
||||
}
|
||||
}
|
||||
const component = new TestRef(env);
|
||||
const component = new TestRef();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>owl</span></div>");
|
||||
component.state.flag = false;
|
||||
@@ -270,13 +272,13 @@ describe("hooks", () => {
|
||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||
state = useState({ flag: true });
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook();
|
||||
}
|
||||
}
|
||||
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(component).not.toHaveProperty("patched");
|
||||
expect(component).not.toHaveProperty("willPatch");
|
||||
@@ -304,8 +306,8 @@ describe("hooks", () => {
|
||||
static template = xml`<div><t t-if="state.flag">hey</t></div>`;
|
||||
state = useState({ flag: true });
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook();
|
||||
}
|
||||
willPatch() {
|
||||
@@ -315,7 +317,7 @@ describe("hooks", () => {
|
||||
steps.push("comp:patched");
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey</div>");
|
||||
component.state.flag = false;
|
||||
@@ -337,13 +339,13 @@ describe("hooks", () => {
|
||||
class MyComponent extends Component<any, any> {
|
||||
static template = xml`<div>hey<t t-esc="state.value"/></div>`;
|
||||
state = useState({ value: 1 });
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useMyHook(1);
|
||||
useMyHook(2);
|
||||
}
|
||||
}
|
||||
const component = new MyComponent(env);
|
||||
const component = new MyComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>hey1</div>");
|
||||
component.state.value++;
|
||||
@@ -377,13 +379,13 @@ describe("hooks", () => {
|
||||
<input t-ref="input2"/>
|
||||
</div>`;
|
||||
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useAutofocus("input2");
|
||||
}
|
||||
}
|
||||
|
||||
const component = new SomeComponent(env);
|
||||
const component = new SomeComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><input><input></div>");
|
||||
const input2 = fixture.querySelectorAll("input")[1];
|
||||
@@ -399,13 +401,13 @@ describe("hooks", () => {
|
||||
</div>`;
|
||||
|
||||
state = useState({ flag: false });
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useAutofocus("input2");
|
||||
}
|
||||
}
|
||||
|
||||
const component = new SomeComponent(env);
|
||||
const component = new SomeComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><input></div>");
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
@@ -420,12 +422,12 @@ describe("hooks", () => {
|
||||
test("can use sub env", async () => {
|
||||
class TestComponent extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useSubEnv({ val: 3 });
|
||||
}
|
||||
}
|
||||
const component = new TestComponent(env);
|
||||
const component = new TestComponent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>3</div>");
|
||||
expect(env).not.toHaveProperty("val");
|
||||
@@ -435,8 +437,8 @@ describe("hooks", () => {
|
||||
test("parent and child env", async () => {
|
||||
class Child extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/></div>`;
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor(parent, props) {
|
||||
super(parent, props);
|
||||
useSubEnv({ val: 5 });
|
||||
}
|
||||
}
|
||||
@@ -444,12 +446,12 @@ describe("hooks", () => {
|
||||
class Parent extends Component<any, any> {
|
||||
static template = xml`<div><t t-esc="env.val"/><Child/></div>`;
|
||||
static components = { Child };
|
||||
constructor(env) {
|
||||
super(env);
|
||||
constructor() {
|
||||
super();
|
||||
useSubEnv({ val: 3 });
|
||||
}
|
||||
}
|
||||
const component = new Parent(env);
|
||||
const component = new Parent();
|
||||
await component.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>3<div>5</div></div>");
|
||||
});
|
||||
@@ -478,7 +480,7 @@ describe("hooks", () => {
|
||||
state = useState({ value: 1 });
|
||||
}
|
||||
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(app).not.toHaveProperty("willStart");
|
||||
expect(app).not.toHaveProperty("willUpdateProps");
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { AsyncRoot } from "../../src/misc/async_root";
|
||||
import { config } from "../../src/config";
|
||||
import { useState } from "../../src/hooks";
|
||||
import { xml } from "../../src/tags";
|
||||
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
|
||||
import { Env, Component } from "../../src/component/component";
|
||||
import { Component } from "../../src/component/component";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Setup and helpers
|
||||
@@ -11,14 +12,13 @@ import { Env, Component } from "../../src/component/component";
|
||||
// We create before each test:
|
||||
// - fixture: a div, appended to the DOM, intended to be the target of dom
|
||||
// manipulations. Note that it is removed after each test.
|
||||
// - env: a WEnv, necessary to create new components
|
||||
// - a test env, necessary to create components, that is set as env
|
||||
|
||||
let fixture: HTMLElement;
|
||||
let env: Env;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = makeTestEnv();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -55,7 +55,7 @@ describe("Asyncroot", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||
@@ -103,7 +103,7 @@ describe("Asyncroot", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0</span><span>0</span>");
|
||||
@@ -158,7 +158,7 @@ describe("Asyncroot", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.querySelector(".children")!.innerHTML).toBe("<span>0/0</span><span>0/0</span>");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Component } from "../../src/component/component";
|
||||
import { config } from "../../src/config";
|
||||
import { Link } from "../../src/router/link";
|
||||
import { RouterEnv } from "../../src/router/router";
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
||||
@@ -12,6 +13,7 @@ describe("Link component", () => {
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = <RouterEnv>makeTestEnv();
|
||||
config.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -38,7 +40,7 @@ describe("Link component", () => {
|
||||
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
router.navigate({ to: "users" });
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe('<div><a href="/about">About</a></div>');
|
||||
|
||||
@@ -69,7 +71,7 @@ describe("Link component", () => {
|
||||
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
router.navigate({ to: "users" });
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
|
||||
expect(window.location.pathname).toBe("/users");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Component } from "../../src/component/component";
|
||||
import { config } from "../../src/config";
|
||||
import { RouterEnv } from "../../src/router/router";
|
||||
import { RouteComponent } from "../../src/router/route_component";
|
||||
import { makeTestEnv, makeTestFixture, nextTick } from "../helpers";
|
||||
@@ -12,6 +13,7 @@ describe("RouteComponent", () => {
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = <RouterEnv>makeTestEnv();
|
||||
config.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -45,7 +47,7 @@ describe("RouteComponent", () => {
|
||||
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
await router.navigate({ to: "about" });
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>About</span></div>");
|
||||
|
||||
@@ -72,7 +74,7 @@ describe("RouteComponent", () => {
|
||||
const routes = [{ name: "book", path: "/book/{{title}}", component: Book }];
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
await router.navigate({ to: "book", params: { title: "1984" } });
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984</span></div>");
|
||||
});
|
||||
@@ -98,7 +100,7 @@ describe("RouteComponent", () => {
|
||||
const routes = [{ name: "book", path: "/book/{{title}}/{{val.number}}", component: Book }];
|
||||
router = new TestRouter(env, routes, { mode: "history" });
|
||||
await router.navigate({ to: "book", params: { title: "1984", val: "123" } });
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>Book 1984|124</span></div>");
|
||||
});
|
||||
|
||||
@@ -54,13 +54,12 @@ describe("router miscellaneous", () => {
|
||||
});
|
||||
|
||||
test("navigate in hash mode preserve location", async () => {
|
||||
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }], {mode: "hash"});
|
||||
window.history.pushState({}, "title", window.location.origin + '/test.html');
|
||||
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }], { mode: "hash" });
|
||||
window.history.pushState({}, "title", window.location.origin + "/test.html");
|
||||
expect(window.location.href).toBe("http://localhost/test.html");
|
||||
await router.navigate({ to: "users", params: { id: 3 } });
|
||||
expect(window.location.href).toBe("http://localhost/test.html#/users/3");
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("routeToPath", () => {
|
||||
|
||||
+26
-22
@@ -1,4 +1,5 @@
|
||||
import { Component, Env } from "../src/component/component";
|
||||
import { config } from "../src/config";
|
||||
import { Store, useStore, useDispatch, useGetters } from "../src/store";
|
||||
import { useState } from "../src/hooks";
|
||||
import { xml } from "../src/tags";
|
||||
@@ -12,6 +13,7 @@ describe("connecting a component to store", () => {
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -37,7 +39,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
@@ -69,7 +71,7 @@ describe("connecting a component to store", () => {
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>1</span><span>2</span></div>");
|
||||
@@ -101,7 +103,7 @@ describe("connecting a component to store", () => {
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
@@ -134,7 +136,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
@@ -163,7 +165,7 @@ describe("connecting a component to store", () => {
|
||||
App.prototype.__render = jest.fn(App.prototype.__render);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
@@ -198,7 +200,7 @@ describe("connecting a component to store", () => {
|
||||
todos = useStore(state => state.todos, { store });
|
||||
}
|
||||
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
@@ -228,7 +230,7 @@ describe("connecting a component to store", () => {
|
||||
storeState = useStore(state => state);
|
||||
dispatch = useDispatch();
|
||||
}
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><button>Inc</button><span>1</span></div>");
|
||||
@@ -257,7 +259,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
@@ -294,7 +296,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoList(env);
|
||||
const app = new TodoList();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
@@ -347,7 +349,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoList(env);
|
||||
const app = new TodoList();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
@@ -370,7 +372,7 @@ describe("connecting a component to store", () => {
|
||||
const state = { beers: { 1: { name: "jupiler" }, 2: { name: "kwak" } } };
|
||||
const store = new Store({ state });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
@@ -401,7 +403,7 @@ describe("connecting a component to store", () => {
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>jupiler</span></div>");
|
||||
@@ -446,7 +448,7 @@ describe("connecting a component to store", () => {
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||
@@ -513,7 +515,7 @@ describe("connecting a component to store", () => {
|
||||
};
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><div><span>taster:aaron</span></div></div>");
|
||||
@@ -588,7 +590,7 @@ describe("connecting a component to store", () => {
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new Parent(env);
|
||||
const app = new Parent();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>a</span></div>");
|
||||
@@ -639,7 +641,7 @@ describe("connecting a component to store", () => {
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new Parent(env);
|
||||
const app = new Parent();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div><span>abc</span></div>");
|
||||
@@ -713,7 +715,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoApp(env);
|
||||
const app = new TodoApp();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
@@ -787,7 +789,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new TodoApp(env);
|
||||
const app = new TodoApp();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe(
|
||||
@@ -833,7 +835,7 @@ describe("connecting a component to store", () => {
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>a</div>");
|
||||
@@ -870,7 +872,7 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
const store = new TestStore({ state: { val: 1 } });
|
||||
(<any>env).store = store;
|
||||
const parent = new Parent(env);
|
||||
const parent = new Parent();
|
||||
|
||||
await parent.mount(fixture);
|
||||
expect(steps).toEqual(["on:update"]);
|
||||
@@ -901,7 +903,7 @@ describe("connecting a component to store", () => {
|
||||
|
||||
const store = new Store({ state, actions });
|
||||
(<any>env).store = store;
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toBe("<div>0</div>");
|
||||
@@ -920,6 +922,7 @@ describe("various scenarios", () => {
|
||||
beforeEach(() => {
|
||||
fixture = makeTestFixture();
|
||||
env = makeTestEnv();
|
||||
config.env = env;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -978,7 +981,8 @@ describe("various scenarios", () => {
|
||||
}
|
||||
|
||||
(<any>env).store = store;
|
||||
const message = new Message(env);
|
||||
const message = new Message();
|
||||
|
||||
await message.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
|
||||
@@ -145,10 +145,10 @@ class App extends owl.Component {
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadFile("templates.xml");
|
||||
const env = {
|
||||
owl.config.env = {
|
||||
qweb: new owl.QWeb({ templates })
|
||||
};
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -90,7 +90,14 @@ function makeCodeIframe(js, css, xml, errorHandler) {
|
||||
owlScript.addEventListener("load", () => {
|
||||
const script = doc.createElement("script");
|
||||
script.type = "text/javascript";
|
||||
const content = `owl.__info__.mode = 'dev';\nwindow.TEMPLATES = \`${sanitizedXML}\`;\n${js}`;
|
||||
const content = `
|
||||
{
|
||||
owl.__info__.mode = 'dev';
|
||||
let templates = \`${sanitizedXML}\`;
|
||||
const qweb = new owl.QWeb({ templates });
|
||||
owl.config.env = { qweb };
|
||||
}
|
||||
${js}`;
|
||||
script.innerHTML = content;
|
||||
iframe.contentWindow.addEventListener("error", errorHandler);
|
||||
iframe.contentWindow.addEventListener("unhandledrejection", errorHandler);
|
||||
@@ -436,7 +443,8 @@ async function start() {
|
||||
owl.utils.whenReady()
|
||||
]);
|
||||
const qweb = new owl.QWeb({ templates });
|
||||
const app = new App({ qweb });
|
||||
owl.config.env = { qweb };
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
|
||||
+27
-42
@@ -16,9 +16,7 @@ class App extends Component {
|
||||
App.components = { Greeter };
|
||||
|
||||
// Application setup
|
||||
// Note that the xml templates are injected into the global TEMPLATES variable.
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({ qweb });
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -70,8 +68,7 @@ class App extends Component {
|
||||
}
|
||||
App.components = { Counter };
|
||||
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({qweb});
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -228,8 +225,7 @@ class App extends Component {
|
||||
}
|
||||
App.components = { DemoComponent };
|
||||
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({ qweb });
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -298,8 +294,7 @@ class App extends owl.Component {
|
||||
}
|
||||
|
||||
// Application setup
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({ qweb });
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -349,11 +344,9 @@ const themeContext = new Context({
|
||||
background: '#000',
|
||||
foreground: '#fff',
|
||||
});
|
||||
const env = {
|
||||
qweb: new owl.QWeb({ templates: TEMPLATES}),
|
||||
themeContext: themeContext,
|
||||
};
|
||||
const app = new App(env);
|
||||
// Add the themeContext the environment to make it available to all components
|
||||
owl.config.env.themeContext = themeContext;
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -534,26 +527,25 @@ TodoApp.components = { TodoItem };
|
||||
//------------------------------------------------------------------------------
|
||||
// App Initialization
|
||||
//------------------------------------------------------------------------------
|
||||
function saveState(state) {
|
||||
const str = JSON.stringify(state);
|
||||
window.localStorage.setItem(LOCALSTORAGE_KEY, str);
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
const localState = window.localStorage.getItem(LOCALSTORAGE_KEY);
|
||||
return localState ? JSON.parse(localState) : initialState;
|
||||
}
|
||||
function makeStore() {
|
||||
function saveState(state) {
|
||||
const str = JSON.stringify(state);
|
||||
window.localStorage.setItem(LOCALSTORAGE_KEY, str);
|
||||
}
|
||||
function loadState() {
|
||||
const localState = window.localStorage.getItem(LOCALSTORAGE_KEY);
|
||||
return localState ? JSON.parse(localState) : initialState;
|
||||
}
|
||||
|
||||
function makeEnv() {
|
||||
const state = loadState();
|
||||
const store = new owl.Store({ state, actions });
|
||||
store.on("update", null, () => saveState(store.state));
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
return { qweb, store };
|
||||
return store;
|
||||
}
|
||||
|
||||
const env = makeEnv();
|
||||
const app = new TodoApp(env);
|
||||
owl.config.env.store = makeStore();
|
||||
const app = new TodoApp();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -1040,12 +1032,9 @@ function setupResponsivePlugin(env) {
|
||||
//------------------------------------------------------------------------------
|
||||
// Application Startup
|
||||
//------------------------------------------------------------------------------
|
||||
const env = {
|
||||
qweb: new owl.QWeb({ templates: TEMPLATES}),
|
||||
};
|
||||
setupResponsivePlugin(env);
|
||||
setupResponsivePlugin(owl.config.env);
|
||||
|
||||
const app = new App(env);
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -1187,8 +1176,7 @@ class App extends Component {
|
||||
App.components = {Card, Counter};
|
||||
|
||||
// Application setup
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({ qweb });
|
||||
const app = new App();
|
||||
app.mount(document.body);`;
|
||||
|
||||
const SLOTS_XML = `<templates>
|
||||
@@ -1301,10 +1289,9 @@ class App extends Component {
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
App.components = {SlowComponent, NotificationList};
|
||||
App.components = {SlowComponent, NotificationList, AsyncRoot};
|
||||
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const app = new App({ qweb });
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -1373,8 +1360,7 @@ class Form extends Component {
|
||||
}
|
||||
|
||||
// Application setup
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const form = new Form({ qweb });
|
||||
const form = new Form();
|
||||
form.mount(document.body);
|
||||
`;
|
||||
|
||||
@@ -1540,7 +1526,6 @@ class App extends Component {
|
||||
}
|
||||
App.components = { WindowManager };
|
||||
|
||||
const qweb = new owl.QWeb({ templates: TEMPLATES});
|
||||
const windows = [
|
||||
{
|
||||
name: "Hello",
|
||||
@@ -1558,8 +1543,8 @@ const windows = [
|
||||
}
|
||||
];
|
||||
|
||||
const env = { qweb, windows };
|
||||
const app = new App(env);
|
||||
owl.config.env.windows = windows;
|
||||
const app = new App();
|
||||
app.mount(document.body);
|
||||
`;
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
t-att-style="topEditorStyle"/>
|
||||
<t t-if="state.splitLayout">
|
||||
<div class="separator horizontal"/>
|
||||
<TabbedEditor t-keepalive="1"
|
||||
<TabbedEditor
|
||||
js="false"
|
||||
css="state.css"
|
||||
xml="state.xml"
|
||||
|
||||
Reference in New Issue
Block a user