Compare commits

..

41 Commits

Author SHA1 Message Date
Géry Debongnie bd3c1265d3 [REL] v1.0.0-alpha2 2019-11-01 09:12:33 +01:00
Géry Debongnie 2413c98f50 [REF] component: small optimization in rare cases
When we have default props, we do not need to allocate a new
props object and copy it. This commit simply modify the props
object in place, which is fine, since the props object is always
a new one any way, generated by the directive.
2019-11-01 09:03:30 +01:00
Géry Debongnie d74b5a03db [IMP] component: add props on root components
This is a partial revert of commit 7d249d6f09.

The reason is that this changes made it much harder to unit test
components.  Before, we could simply instantiate a component
like this:
const my|Comp = new MyComponent(null, props);

and then simply test it.  This commit reestablish that possibility.
2019-11-01 09:03:27 +01:00
Géry Debongnie 83532db48f [DOC] adapt documentation to env changes
part of #430
2019-11-01 09:03:27 +01:00
Géry Debongnie 534152eff7 [REF] component: small improvement
and run prettier
2019-11-01 08:39:35 +01:00
Aaron Bohy 05a678c039 [IMP] component: get env from constructor
closes #430
2019-11-01 08:39:35 +01:00
Géry Debongnie 8fbf2172c5 [DOC] slightly reorganize main documentation page 2019-10-31 12:32:26 +01:00
Géry Debongnie ea1376d0ca [FIX] tools: make benchmarks work on firefox
Firefox does not support the static keyword yet, so the benchmark code should be modified to make it work.
2019-10-31 12:32:26 +01:00
Géry Debongnie ba483b6e2c [FIX] component tests: make them work on windows
For an unknown reason, it looks like the way ticks, micro task ticks or other subtle scheduling issues are different on a windows machine (it may be because of other difference, such as a specific version of nodejs).

Anyway, I could not find the cause of the issue, but
simply waiting an extra microtask tick seems to work.
2019-10-31 12:32:26 +01:00
Géry Debongnie 2fc71cfb62 [REL] v1.0.0-alpha
v1.0alpha

The Alpha release!

Owl is finally getting stable. This relase is all about cleaning Owl
API.  We
are pretty happy with the current state, and hopefully, we won't have to
make
any non trivial change for a while.

QWeb

- add an option to setup a translate function
- implement `t-key` with a directive (it now works on `t` tags)

Component

- properly handle errors in `mount` and `render`
- fix: make sure props are validated in all cases
- fix: make sure default props are applied at the proper time
- fix: better error handling with sub components
- imp: simplify constructor API: does not take an `env`
- imp: do not set `props` in root components
- remove `t-keepalive` directive

Context

- update components concurrently, instead of sequentially

Observer

- remove `revNumber` (and rename `deepRevNumber` into `revNumber`)

Router

- fix: preserve pathname in hash mode

Config

- create new config object, with `mode` and `env` keys

Playground

- log git commit hash in console
2019-10-30 16:35:45 +01:00
Aaron Bohy 08cb83149e [REM] component: remove t-keepalive directive
We don't see any usecase for it, it makes the code more complex,
and there were still potential unresolved concurrency issues with
it.

Part of task #295
2019-10-30 16:35:45 +01:00
Aaron Bohy 7d249d6f09 [IMP] component: do not set props in root components
Also remove props from Fiber, as it was not useful anymore.
2019-10-30 15:09:10 +01:00
Géry Debongnie 0addca63a0 [DOC] update the documentation to new config and env
part of #306
2019-10-30 15:09:10 +01:00
Géry Debongnie 5ba73cc09d [DOC] move quick_start into learning/ sub folder 2019-10-30 15:09:10 +01:00
Aaron Bohy 9106c19066 [IMP] component: simplify constructor API
It now takes two arguments: parent (optional, only for non-root
components) and props (optional). In the case of the root component,
the env is taken from the config (config.defaultEnv). If it doesn't
exists, the default env is created on the fly.

Closes #306
2019-10-30 15:09:10 +01:00
Aaron Bohy 9f93da4765 [REF] config: move mode from owl.__info__ to owl.config
and move it to its own file.
2019-10-30 15:09:10 +01:00
Aaron Bohy 9e37b968e8 [FIX] component: error handling: rendering with sub components
Closes #425
2019-10-30 13:27:48 +01:00
Aaron Bohy fa6801b523 [REF] observer: remove revNumber
Closes #257
2019-10-30 11:13:52 +01:00
Géry Debongnie 9edf29a3a1 [IMP] context: group components by depth
closes #399
2019-10-29 16:02:51 +01:00
Géry Debongnie 6a434310ee [FIX] *: run prettier 2019-10-29 16:02:51 +01:00
Géry Debongnie e7967d0779 [FIX] package.json: improve prettier task
to take into account files at more than one level
2019-10-29 16:02:51 +01:00
Géry Debongnie b0e2ef82f7 [REL] bump to v0.24.1 2019-10-28 14:58:52 +01:00
Aaron Bohy c9c2b3fa6d [IMP] tests: add concurrency test 2019-10-28 14:46:21 +01:00
Géry Debongnie 62608cbb0d [DOC] add architecture notes on rendering pipeline 2019-10-28 14:23:02 +01:00
Géry Debongnie 3035a9f009 [DOC] move reference doc in subfolder 2019-10-28 14:23:02 +01:00
Géry Debongnie c2adb429bd [FIX] package.json: update node and typescript version
closes #414
2019-10-28 13:58:44 +01:00
Géry Debongnie da9dda5eca [DOC] component: add more information on t-key
closes #353
2019-10-28 11:45:51 +01:00
Géry Debongnie 5614c85b04 [IMP] qweb: implement t-key with a directive
closes #331
2019-10-28 11:45:51 +01:00
Aaron Bohy 5d57a7bf13 [FIX] component: updateProps: validation and default values
Before this rev., default values weren't taken into account when
validating props whenever a component was updated. Moreover, there
was no test attesting that props were validated at update.
2019-10-28 11:32:43 +01:00
Géry Debongnie 4ebe419c56 [FIX] component: make sure props are validated in all cases
closes #379
2019-10-28 11:32:43 +01:00
Géry Debongnie 9779cd196c [REF] fiber: small cleanups 2019-10-28 11:32:43 +01:00
Géry Debongnie 9cee12d7b4 [IMP] component: propagate error to mount and render 2019-10-28 11:32:43 +01:00
Géry Debongnie 2c563ee380 [REF] component: move error handling into the fiber 2019-10-28 11:32:43 +01:00
Géry Debongnie 2aa705f5c8 [FIX] router: preserve pathname in hash mode
closes #397
2019-10-28 11:32:43 +01:00
Géry Debongnie 5911c8e3f6 [DOC] store,hooks: useState/useStore should return object
or array

closes #404
2019-10-28 11:32:43 +01:00
Géry Debongnie 2279dafbec [IMP] qweb: add an option to setup a translate function
closes #393
2019-10-28 11:32:41 +01:00
Géry Debongnie f07ec21a07 [FIX] playground: add missing ;
Because of that missing ";", the playground application tried to inject
this:

window.TEMPLATES = `...`

instead of this:

window.TEMPLATES = `...`;

So, when the following line started with a (, then the javascript code
was interpreted as a function call. And it could happen, because some
people like to use the IIFE syntax to have some contained code.
2019-10-26 09:34:51 +02:00
Géry Debongnie b5b6b7342e [DOC] improve main readme.md 2019-10-26 09:27:35 +02:00
Géry Debongnie 97b914b9cd [IMP] playground: log url for current owl commit
closes #405
2019-10-26 09:21:04 +02:00
Géry Debongnie 9dfcfda365 [DOC] add more info on xml tag and single file component
closes #401
2019-10-26 09:10:50 +02:00
Géry Debongnie e026f537ae [ADD] tools: add benchmarks for v0.24.0 2019-10-25 17:17:20 +02:00
66 changed files with 2610 additions and 1554 deletions
+12 -33
View File
@@ -28,20 +28,16 @@ Owl is currently mostly stable. Possible future changes are explained in the
Here is a short example to illustrate interactive components:
```javascript
import { Component, QWeb, useState } from "owl";
import { xml } from "owl/tags";
const { Component, useState } = owl;
const { xml } = owl.tags;
class Counter extends Component {
static template = xml`
<button t-on-click="increment">
<button t-on-click="state.value++">
Click Me! [<t t-esc="state.value"/>]
</button>`;
state = useState({ value: 0 });
increment() {
this.state.value++;
}
}
class App extends Component {
@@ -54,12 +50,12 @@ class App extends Component {
static components = { Counter };
}
const app = new App({ qweb: new QWeb() });
const app = new App();
app.mount(document.body);
```
Note that the counter component is made reactive with the [`useState`](doc/hooks.md#usestate)
hook. Also, all examples here uses the `xml` helper to define inline templates.
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
Also, all examples here uses the [`xml` helper](doc/reference/tags.md#xml-tag) to define inline templates.
But this is not mandatory, many applications will load templates separately.
More interesting examples can be found on the
@@ -96,9 +92,9 @@ A complete documentation for Owl can be found here:
The most important sections are:
- [Quick Start](doc/quick_start.md)
- [Component](doc/component.md)
- [Hooks](doc/hooks.md)
- [Quick Start](doc/learning/quick_start.md)
- [Component](doc/reference/component.md)
- [Hooks](doc/reference/hooks.md)
Found an issue in the documentation? A broken link? Some outdated information?
Submit a PR!
@@ -107,8 +103,8 @@ Submit a PR!
If you want to use a simple `<script>` tag, the last release can be downloaded here:
- [owl-0.24.0.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.js)
- [owl-0.24.0.min.js](https://github.com/odoo/owl/releases/download/v0.24.0/owl.min.js)
- [owl-1.0.0-alpha2.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha2/owl.js)
- [owl-1.0.0-alpha2.min.js](https://github.com/odoo/owl/releases/download/v1.0.0-alpha2/owl.min.js)
Some npm scripts are available:
@@ -131,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. 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:
@@ -259,7 +238,7 @@ class Parent extends Component {
In this example, the `OrderLine` component trigger a `add-to-order` event. This
will generate a DOM event which will bubble along the DOM tree. It will then be
intercepted by the parent component, which will then get the line (from the
`detail` key) and then increment its quantity. See the section on [event handling](doc/component.md#event-handling)
`detail` key) and then increment its quantity. See the section on [event handling](doc/reference/component.md#event-handling)
for more details on how events work.
Note that this example would have also worked if the `OrderLine` component
+32
View File
@@ -0,0 +1,32 @@
# 🦉 Rendering Pipeline 🦉
We explain here how Owl is designed, from the perspective of its rendering
pipeline.
Warning: these notes are technical by nature, and intended for people working
on Owl (or interested in understanding its design).
## Overview
A rendering occurs in two phases:
- virtual rendering: this generates the virtual dom in memory, asynchronously
- patch: applies a virtual tree to the screen (synchronously)
There are several classes involved in a rendering:
- components
- a scheduler
- fibers: small objects containing some metadata, associated with a rendering of
a specific component
Components are organized in a dynamic component tree, visible in the user
interface. Whenever a rendering is initiated in a component `C`:
- a fiber is created on `C` with the rendering props information
- the virtual rendering phase starts on C (will asynchronously render all the
child components)
- the fiber is added to the scheduler, which will poll continuously, every
animation frame, if the fiber is done
- once it is done, the scheduler will call the task callback, which will apply
the patch (if it was not cancelled in the meantime).
+6 -5
View File
@@ -79,7 +79,7 @@ additional tools, we made a lot of effort to make the most of the web platform.
For example, Owl uses the standard `xml` parser that comes with every browser.
Because of that, Owl did not have to write its own template parser. Another
example is the [`xml`](tags.md#xml-tag) tag helper function, which makes use of
example is the [`xml`](reference/tags.md#xml-tag) tag helper function, which makes use of
native template literals to allow in a natural way to write `xml` templates
directly in the javascript code. This can be easily integrated with editor
plugins to have autocompletion inside the template.
@@ -127,7 +127,7 @@ structured than a template language. Note that the tooling is quite impressive:
there is a syntax highlighter for jsx here on github!
By comparison, here is the equivalent Owl component, written with the
[`xml`](tags.md#xml-tag) tag helper:
[`xml`](reference/tags.md#xml-tag) tag helper:
```js
class Clock extends Component {
@@ -251,7 +251,7 @@ keeps track of who get data, and retrigger a render when it was changed.
Owl store is a little bit like a mix of redux and vuex: it has actions (but not
mutations), and like VueX, it keeps track of the state changes. However, it does
not notify a component when the state changes. Instead, components need to connect
to the store like in redux, with the `useStore` hook (see the [store documentation](store.md#connecting-a-component)).
to the store like in redux, with the `useStore` hook (see the [store documentation](reference/store.md#connecting-a-component)).
```javascript
const actions = {
@@ -274,7 +274,8 @@ class Counter extends Component {
dispatch = useDispatch();
}
const counter = new Counter({ store, qweb });
Counter.env.store = store;
const counter = new Counter();
```
## Hooks
@@ -314,7 +315,7 @@ This work is based on the new ideas introduced by React hooks.
From the way React and Vue introduce their hooks, it may look like hooks are not
compatible with class components. However, this is not the case, as shown by
Owl [hooks](hooks.md). They are inspired by both React and Vue. For example,
Owl [hooks](reference/hooks.md). They are inspired by both React and Vue. For example,
the `useState` hook is named after React, but its API is closer to the `reactive`
Vue hook.
+47
View File
@@ -0,0 +1,47 @@
# 🦉 Environment 🦉
An environment is an object which contains a [`QWeb` instance](../reference/qweb.md).
Whenever a root component is created, it is assigned an environment (see the
reference section on [environment](../reference/environment.md). This environment
is then automatically given to each sub components (and accessible in the `this.env` property).
The environment is mostly static. Each application is free to add anything to
the environment, which is very useful, since this can be accessed by each sub
component.
Some good use cases for the environment is:
- some configuration keys,
- session information,
- generic services (such as doing rpcs, or accessing local storage).
Doing it this way means that components are easily testable: we can simply
create a test environment with mock services.
For example:
```js
async function myEnv() {
const templates = await loadTemplates();
const qweb = new QWeb({ templates });
const session = getSession();
return {
_t: myTranslateFunction,
session: session,
qweb: qweb,
services: {
localStorage: localStorage,
rpc: rpc
},
debug: false,
inMobileMode: true
};
}
async function start() {
App.env = await myEnv();
const app = new App();
await app.mount(document.body);
}
```
@@ -2,8 +2,17 @@
## Static Server
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,8 @@ 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);
ClickCounter.env = { qweb: new owl.QWeb({ templates }) };
const counter = new ClickCounter();
const target = document.getElementById("main");
await counter.mount(target);
}
+59 -62
View File
@@ -1,75 +1,72 @@
# 🦉 OWL Documentation 🦉
## Owl Content
Owl is a javascript library that contains some core classes and function to help
build applications. Here is a complete representation of its content:
```
owl
Component
Context
QWeb
Store
useState
core
EventBus
Observer
hooks
onWillStart
onMounted
onWillUpdateProps
onWillPatch
onPatched
onWillUnmount
useContext
useState
useRef
useSubEnv
useStore
useDispatch
useGetters
misc
AsyncRoot
router
Link
RouteComponent
Router
tags
xml
utils
debounce
escape
loadJS
loadFile
shallowEqual
whenReady
```
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
## Reference
- [Animations](animations.md)
- [Component](component.md)
- [Context](context.md)
- [Event Bus](event_bus.md)
- [Hooks](hooks.md)
- [Misc](misc.md)
- [Observer](observer.md)
- [QWeb](qweb.md)
- [Router](router.md)
- [Store](store.md)
- [Tags](tags.md)
- [Utils](utils.md)
- [Virtual DOM](vdom.md)
- [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)
- [Observer](reference/observer.md)
- [QWeb](reference/qweb.md)
- [Router](reference/router.md)
- [Store](reference/store.md)
- [Tags](reference/tags.md)
- [Utils](reference/utils.md)
## Learning Resources
- [Quick Start](quick_start.md)
- [Quick Start: create an (almost) empty Owl application](learning/quick_start.md)
- [Environment: what it is and what it should contain](learning/environment.md)
## Miscellaneous
- [Comparison with React/Vue](comparison.md)
- [Tooling](tooling.md)
- [Templates to start Owl applications (external link)](https://github.com/ged-odoo/owl-templates)
## Architecture
This section explains in more detail the inner workings of Owl. It is targeted
for developers working on Owl itself.
- [Virtual DOM](architecture/vdom.md)
- [Rendering](architecture/rendering.md)
## Owl Content
Here is a complete visual representation of everything exported by the `owl`
global object (so, for example, `Component` is available at `owl.Component`,
and `EventBus` is exported as `owl.core.EventBus`):
```
Component misc
Context AsyncRoot
QWeb router
Store Link
useState RouteComponent
config Router
mode tags
core xml
EventBus utils
Observer debounce
hooks escape
onWillStart loadJS
onMounted loadFile
onWillUpdateProps shallowEqual
onWillPatch whenReady
onPatched
onWillUnmount
useContext
useState
useRef
useSubEnv
useStore
useDispatch
useGetters
```
Note that for convenience, the `useState` hook is also exported at the root of the `owl` object.
+79 -73
View File
@@ -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
@@ -370,8 +369,8 @@ will slightly slow down the component.
#### `willUpdateProps(nextProps)`
The willUpdateProps is an asynchronous hook, called just before new props
are set. This is useful if the component needs some asynchronous task
performed, depending on the props (for example, assuming that the props are
are set. This is useful if the component needs to perform an asynchronous task,
depending on the props (for example, assuming that the props are
some record Id, fetching the record data).
```javascript
@@ -386,14 +385,13 @@ and performs a similar job).
#### `willPatch()`
The willPatch hook is called just before the DOM patching process starts.
It is not called on the initial render. This is useful to read some
It is not called on the initial render. This is useful to read
information from the DOM. For example, the current position of the
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
@@ -413,7 +411,7 @@ careful at avoiding endless cycles.
#### `willUnmount()`
willUnmount is a hook that is called each time just before a component is unmounted from
the DOM. This is a good place to remove some listeners, for example.
the DOM. This is a good place to remove listeners, for example.
```javascript
mounted() {
@@ -441,49 +439,17 @@ of an Owl application has to be created manually:
```js
class App extends owl.Component { ... }
const qweb = new owl.QWeb(TEMPLATES);
const env = { qweb: qweb };
const app = new App(env);
const app = new App();
app.mount(document.body);
```
The root component needs an environment.
The root component does not have a parent nor `props` (see note below). It will be setup with an
[environment](environment.md) (either the `env` defined on its class, or a
default empty environment).
### Environment
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);
}
```
Note: a root component can however be given a `props` object in its constructor,
like this: `new App(null, {some: 'object'});`. It will not be a true `props`
object, managed by Owl (so, for example, it will never be updated).
### Composition
@@ -539,7 +505,7 @@ constructor. This will be assigned to the `props` variable, which can be accesse
on the component (and also, in the template). Whenever the state is updated, then
the sub component will also be updated automatically.
Note that there are some restrictions on prop names: `class`, `style` and any
Note that there are restrictions on valid prop names: `class`, `style` and any
string which starts with `t-` are not allowed.
It is not common, but sometimes we need a dynamic component name and/or dynamic props. In this case,
@@ -598,7 +564,7 @@ class App extends Component<any, any, any> {
In this example, the component `App` selects dynamically the concrete sub
component class.
**CSS and style:** there is some specific support to allow the parent to declare
**CSS and style:** Owl allows the parent to declare
additional css classes or style for the sub component: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
root component element.
@@ -611,7 +577,7 @@ root component element.
Warning: there is a small caveat with dynamic class attributes: since Owl needs
to be able to add/remove proper classes whenever necessary, it needs to be aware
of the possible classes. Otherwise, it will not be able to make the difference
between a valid css class added by the component, or some custom code, and a
between a valid css class added by the component, or other custom code, and a
class that need to be removed. This is why we only support the explicit syntax
with a class object:
@@ -621,7 +587,7 @@ with a class object:
### Event Handling
In a component's template, it is useful to be able to register handlers on some
In a component's template, it is useful to be able to register handlers on DOM
elements to some specific events. This is what makes a template _alive_. There
are four different use cases.
@@ -677,8 +643,7 @@ to event `menu-loaded` will receive the payload in its `someMethod` handler
By convention, we use KebabCase for the name of _business_ events.
The `t-on` directive allows to prebind some arguments. For example,
The `t-on` directive allows to prebind its arguments. For example,
```xml
<button t-on-click="someMethod(expr)">Do something</button>
@@ -695,10 +660,12 @@ One can also directly specify inline statements. For example,
Here, `state` must be defined in the rendering context (typically the component)
as it will be translated to:
```js
button.addEventListener("click", () => { component.state.counter++; });
```
```js
button.addEventListener("click", () => {
component.state.counter++;
});
```
In order to remove the DOM event details from the event handlers (like calls to
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
@@ -802,7 +769,7 @@ The `t-model` directive works with `<input>`, `<input type="checkbox">`,
</div>
```
Like event handling, the `t-model` directive accepts some modifiers:
Like event handling, the `t-model` directive accepts the following modifiers:
| Modifier | Description |
| --------- | -------------------------------------------------------------------- |
@@ -827,24 +794,63 @@ Even though Owl tries to be as declarative as possible, the DOM does not fully
expose its state declaratively in the DOM tree. For example, the scrolling state,
the current user selection, the focused element or the state of an input are not
set as attribute in the DOM tree. This is why we use a virtual dom
algorithm to keep the actual DOM node as much as possible. However, this is
sometimes not enough, and we need to help Owl decide if an element is actually
the same, or is different. The `t-key` directive is used to give an identity to an element.
algorithm to keep the actual DOM node as much as possible.
There are three main use cases:
However, in some situations, this is not enough, and we need to help Owl decide
if an element is actually the same, or is a different element with the same
properties.
- _elements in a list_:
Consider the following situation: we have a list of two items `[{text: "a"}, {text: "b"}]`
and we render them in this template:
```xml
<span t-foreach="todos" t-as="todo" t-key="todo.id">
<t t-esc="todo.text" />
</span>
```
```xml
<p t-foreach="items" t-as="item"><t t-esc="item.text"/></p>
```
- _`t-if`/`t-else`_
The result will be two `<p>` tags with text `a` and `b`. Now, if we swap them,
and rerender the template, Owl needs to know what the intent is:
- _animations_: give a different identity to a component. Ex: thread id with
animations on add/remove message.
- should Owl actually swap the DOM nodes,
- or should it keep the DOM nodes, but with an updated text content?
This might look trivial, but it actually matters. These two possibilities lead
to different results in some cases. For example, if the user selected the text
of the first `p`, swapping them will keep the selection while updating the
text content will not.
There are many other cases where this is important: `input` tags with their
value, css classes and animations, scroll position...
So, the `t-key` directive is used to give an identity to an element. It allows
Owl to understand if different elements of a list are actually different or not.
The above example could be modified by adding an ID: `[{id: 1, text: "a"}, {id: 2, text: "b"}]`.
Then, the template could look like this:
```xml
<p t-foreach="items" t-as="item" t-key="item.id"><t t-esc="item.text"/></p>
```
The `t-key` directive is useful for lists (`t-foreach`). A key should be
a unique number or string (objects will not work: they will be cast to the
`"[object Object]"` string, which is obviously not unique).
Also, the key can be set on a `t` tag or on its children. The following variations
are all equivalent:
```xml
<p t-foreach="items" t-as="item" t-key="item.id">
<t t-esc="item.text"/>
</p>
<t t-foreach="items" t-as="item" t-key="item.id">
<p t-esc="item.text"/>
</t>
<t t-foreach="items" t-as="item">
<p t-key="item.id" t-esc="item.text"/>
</t>
```
### Semantics
@@ -946,7 +952,7 @@ of the props. Here is how it works in Owl:
- `props` key is a static key (so, different from `this.props` in a component instance)
- 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.
+27
View File
@@ -0,0 +1,27 @@
# 🦉 Config 🦉
The Owl framework is designed to work in many situations. However, it is
sometimes necessary to customize some behaviour. This is done by using the
global `config` object. It currently has one key:
- [`mode`](#mode).
## Mode
By default, Owl is in _production_ mode, this means that it will try to do its
job fast, and skip some expensive operations. However, it is sometimes necessary
to have better information on what is going on, this is the purpose
of the `dev` mode.
Owl has a mode flag, in `owl.config.mode`. Its default value is `prod`, but
it can be set to `dev`:
```js
owl.config.mode = "dev";
```
Note that templates compiled with the `prod` settings will not be recompiled.
So, changing this setting is best done at startup.
An important job done by the `dev` mode is to validate props for each component
creation and update. Also, extra props will cause an error.
+9 -12
View File
@@ -28,10 +28,7 @@ context, and add it to the environment:
```js
const deviceContext = new Context({ isMobile: true });
const env = {
qweb: new QWeb(TEMPLATES),
deviceContext
};
App.env.deviceContext = deviceContext;
```
If we want to make it completely responsive, we need to update its value whenever
@@ -56,14 +53,14 @@ fact that we are in a mobile or desktop mode.
```js
class SomeComponent extends Component {
static template = xml`
<div>
<t t-if=device.isMobile>
some simplified user interface
</t>
<t t-else="1">
some more sopthisticated user interface
</t>
`;
<div>
<t t-if=device.isMobile>
some simplified user interface
</t>
<t t-else="1">
a more advanced user interface
</t>
</div>`;
device = useContext(this.env.deviceContext);
}
```
+53
View File
@@ -0,0 +1,53 @@
# 🦉 Environment 🦉
An environment is an object which contains a [`QWeb` instance](qweb.md). Whenever
a root component is created, it is assigned an environment (see
[below](#setting-an-environment) for more info on this). This environment is
then automatically given to each sub component (and accessible in the `this.env`
property).
```
Root
/ \
A B
```
This way, all components share the same `QWeb` instance.
Note: some additional information about what should go into an environment
can be found in the [learning section](../learning/environment.md).
## Setting an environment
An Owl application needs an [environment](environment.md) to be executed. The
environment has an important key: the [QWeb](qweb.md) instance, which will render
all templates.
Whenever a root component `App` is mounted, Owl will setup a valid environment by
following the next steps:
- take the `env` object defined on `App.env` (if no `env` was explicitely setup,
this will be return the empty `env` object defined on `Component`)
- if `env.qweb` is not set, then Owl will create a `QWeb` instance.
The correct way to customize an environment is to simply set it up on the root
component class, before the first component is created:
```js
App.env = {
_t: myTranslateFunction,
user: {...},
services: {
...
},
};
const app = new App();
app.mount(document.body);
```
It is also possible to simply share an environment between all root components,
by simply doing this:
```js
Component.env = myEnv; // will be the default env for all components
```
+3
View File
@@ -181,6 +181,9 @@ class Counter extends owl.Component {
}
```
It is important to remember that `useState` only works with objects or arrays. It
is necessary, since Owl needs to react to a change in state.
### `onMounted`
`onMounted` is not a user hook, but is a building block designed to help make useful
+90 -24
View File
@@ -16,6 +16,7 @@
- [Dynamic Attributes](#dynamic-attributes)
- [Loops](#loops)
- [Rendering Sub Templates](#rendering-sub-templates)
- [Translations](#translations)
- [Debugging](#debugging)
## Overview
@@ -60,20 +61,21 @@ We present here a list of all standard QWeb directives:
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
| `t-call` | [Rendering sub templates](#rendering-sub-templates) |
| `t-debug`, `t-log` | [Debugging](#debugging) |
| `t-translation` | [Disabling the translation of a node](#translations) |
| `t-name` | [Defining a template (not really a directive)](#qweb-engine) |
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
@@ -87,11 +89,14 @@ const qweb = new owl.QWeb();
Its API is quite simple:
- **`constructor(data)`**: constructor. Takes an optional string to add initial
templates (see `addTemplates` for more information on format of the string).
- **`constructor(config)`**: constructor. Takes an optional configuration object
with an optional `templates` string to add initial
templates (see `addTemplates` for more information on format of the string)
and an optional `translateFn` translate function (see the section on
[translations](#translations)).
```js
const qweb = new owl.QWeb(TEMPLATES);
const qweb = new owl.QWeb({ templates: TEMPLATES, translateFn: _t });
```
- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template.
@@ -116,7 +121,7 @@ Its API is quite simple:
```
- **`render(name, context, extra)`**: renders a template. This returns a `vnode`,
which is a virtual representation of the DOM (see [vdom doc](vdom.md)).
which is a virtual representation of the DOM (see [vdom doc](../architecture/vdom.md)).
```js
const vnode = qweb.render("App", component);
@@ -154,7 +159,7 @@ Its API is quite simple:
```
In some way, a `QWeb` instance is the core of an Owl application. It is the only
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).
@@ -201,7 +206,7 @@ root nodes.
### Expression Evaluation
QWeb expressions are strings that will be processed at compile time. Each variable in
the javascript expression will be replaced by a lookup in the context (so, the
the javascript expression will be replaced with a lookup in the context (so, the
component). For example, `a + b.c(d)` will be converted into:
```js
@@ -234,14 +239,14 @@ It is useful to explain the various rules that apply on these expressions:
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
`&` or `|`. This is useful to make sure that we still write valid XML.
| Word | will be replaced by |
| ----- | ------------------- |
| `and` | `&&` |
| `or` | `\|\|` |
| `gt` | `>` |
| `gte` | `>=` |
| `lt` | `<` |
| `lte` | `<=` |
| Word | replaced with |
| ----- | ------------- |
| `and` | `&&` |
| `or` | `\|\|` |
| `gt` | `>` |
| `gte` | `>=` |
| `lt` | `<` |
| `lte` | `<=` |
So, one can write this:
@@ -443,7 +448,7 @@ is equivalent to the previous example.
or an object (the current item will be the current key).
In addition to the name passed via t-as, `t-foreach` provides a few other
variables for various data points (note: `$as` will be replaced by the name
variables for various data points (note: `$as` will be replaced with the name
passed to `t-as`):
- `$as_value`: the current iteration value, identical to `$as` for lists and
@@ -474,6 +479,20 @@ into the global context.
<!-- new_variable undefined -->
```
Owl QWeb is used as the template engine for components. Components are frequently
updated, and reuse as much of the previous DOM as possible. Loops offer a specific
problem for this usecase: how does the template engine know if two rows have
been swapped, or if the content of these rows was changed? To help Owl with that,
there is an additional directive: [`t-key`](component.md#t-key-directive).
```xml
<p t-foreach="state.things" t-as="thing" t-key="thing.id">
<t t-esc="thing.content"/>
</p>
```
If there is no `t-key` directive, Owl will use the index as a default key.
### Rendering Sub Templates
QWeb templates can be used for top level rendering, but they can also be used
@@ -522,6 +541,53 @@ will result in :
</div>
```
### Translations
If properly setup, Owl QWeb engine can translate all rendered templates. To do
so, it needs a translate function, which takes a string and returns a string.
For example:
```js
const translations = {
hello: "bonjour",
yes: "oui",
no: "non"
};
const translateFn = str => translations[str] || str;
const qweb = new QWeb({ translateFn });
```
Once setup, all rendered templates will be translated using `translateFn`:
- each text node will be replaced with its translation,
- each of the following attribute values will be translated as well: `title`,
`placeholder`, `label` and `alt`,
- translating text nodes can be disabled with the special attribute `t-translation`,
if its value is `off`.
So, with the above `translateFn`, the following templates:
```xml
<div>hello</div>
<div t-translation="off">hello</div>
<div>Are you sure?</div>
<input placeholder="hello" other="yes"/>
```
will be rendered as:
```xml
<div>bonjour</div>
<div>hello</div>
<div>Are you sure?</div>
<input placeholder="bonjour" other="yes"/>
```
Note that the translation is done during the compilation of the template, not
when it is rendered.
### Debugging
The javascript QWeb implementation provides two useful debugging directives:
@@ -67,6 +67,9 @@ function makeEnvironment() {
await env.router.start();
return env;
}
App.env = makeEnvironment();
// create root component here
```
Notice that the router needs to be started. This is an asynchronous operation
+4
View File
@@ -262,6 +262,10 @@ will only be rerendered whenever this part of the state changes. Otherwise, it
will perform a strict equality check and will update the component every time this
check fails.
Also, it may not be obvious, but it is crucial to remember that the selector
function should return an object or an array. The reason is that it needs to be
observed, otherwise the component would not be able to react to changes.
### `useDispatch`
The `useDispatch` hook is useful when a component needs to be able to dispatch
+10 -3
View File
@@ -1,8 +1,15 @@
# 🦉 Tags 🦉
## Content
- [Overview](#overview)
- [`xml` tag](#xml-tag)
## Overview
Tags are very small helpers to make it easy to write inline templates. There is
only one currently available tag: `xml`, but we plan to add other tags later,
such as a `css` tag, which will be used to write single file components.
such as a `css` tag, which will be used to write [single file components](../tooling.md#single-file-component).
## XML tag
@@ -31,8 +38,8 @@ With tags, this process is slightly simplified. The name is uniquely generated,
and the template is automatically registered:
```js
import { Component } from 'owl'
import { xml } from 'owl/tags'
const { Component } = owl;
const { xml } = owl.tags;
class MyComponent extends Component {
static template = xml`
+2 -2
View File
@@ -20,7 +20,7 @@ argument, it executes it as soon as the DOM ready (or directly).
```js
Promise.all([loadFile("templates.xml"), owl.utils.whenReady()]).then(function([templates]) {
const qweb = new owl.QWeb(templates);
const qweb = new owl.QWeb({ templates });
const app = new App({ qweb });
app.mount(document.body);
});
@@ -62,7 +62,7 @@ initial usecase for this function is to load a template file. For example:
```js
async function makeEnv() {
const templates = await owl.utils.loadFile("templates.xml");
const qweb = new owl.QWeb(templates);
const qweb = new owl.QWeb({ templates });
return { qweb };
}
```
+18 -25
View File
@@ -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
@@ -60,12 +39,21 @@ useful to compare various performance metrics on some tasks.
## Single File Component
If you want to have `xml` syntax highlighting while using the `xml` helper which
helps you define inline templates, there is a VS Code addon `Comment tagged template`
which, if installed, does exactly that. To enable it, you need to add a comment,
like this:
It is very useful to group code by feature instead of by type of file. It makes
it easier to scale application to larger size.
To do so, Owl currently has a small helper that makes it easy to define a
template inside a javascript (or typescript) file: the [`xml`](reference/tags.md#xml-tag)
helper. With this, a template is automatically registered to [QWeb](reference/qweb.md).
This means that the template and the javascript code can be defined in the same
file. It is not currently possible to add css to the same file, but Owl may
get a `css` tag helper later.
```js
const { Component } = owl;
const { xml } = owl.tags;
// -----------------------------------------------------------------------------
// TEMPLATE
// -----------------------------------------------------------------------------
@@ -85,3 +73,8 @@ class MyComponent extends Component {
// rest of component...
}
```
Note that the above example has an inline xml comment, just after the `xml` call.
This is useful for some editor plugins, such as the VS Code addon
`Comment tagged template`, which, if installed, add syntax highlighting to the
content of the template string.
+6 -3
View File
@@ -1,8 +1,11 @@
{
"name": "owl-framework",
"version": "0.24.0",
"version": "1.0.0-alpha2",
"description": "Odoo Web Library (OWL)",
"main": "src/index.ts",
"engines": {
"node": ">=10.15.3"
},
"scripts": {
"build:js": "tsc --target esnext --module es6 --outDir dist/owl",
"build:bundle": "rollup -c",
@@ -15,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",
@@ -41,7 +44,7 @@
"sass": "^1.16.1",
"source-map-support": "^0.5.10",
"ts-jest": "^23.10.5",
"typescript": "^3.2.2",
"typescript": "^3.6.4",
"uglify-es": "^3.3.9"
},
"jest": {
+12 -10
View File
@@ -1,23 +1,25 @@
# 🦉 OWL Roadmap 🦉
- Current version: 0.24.0
- Current version: 1.0.0-alpha2
- 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
+75 -110
View File
@@ -4,7 +4,7 @@ import { h, patch, VNode } from "../vdom/index";
import "./directive";
import { Fiber } from "./fiber";
import "./props_validation";
import { Scheduler } from "./scheduler";
import { scheduler } from "./scheduler";
/**
* Owl Component System
@@ -20,8 +20,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 +44,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;
@@ -88,6 +87,7 @@ export class Component<T extends Env, Props extends {}> {
static components = {};
static props?: any;
static defaultProps?: any;
static env: any = {};
/**
* The `el` is the root element of the component. Note that it could be null:
@@ -107,45 +107,36 @@ export class Component<T extends Env, Props extends {}> {
/**
* Creates an instance of Component.
*
* 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> | null, props?: Props) {
Component.current = this;
let constr = this.constructor as any;
const defaultProps = constr.defaultProps;
if (defaultProps) {
props = this.__applyDefaultProps(props, defaultProps);
props = props || {} as 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>{};
let id: number = nextId++;
let p: Component<T, any> | null = null;
if (parent instanceof Component) {
p = parent;
this.props = <Props>props;
if (QWeb.dev) {
QWeb.utils.validateProps(constr, this.props);
}
const id: number = nextId++;
let depth;
if (parent) {
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;
if (QWeb.dev) {
// we only validate props for root widgets here. "Regular" widget
// props are validated by the t-component directive
QWeb.utils.validateProps(this.constructor, this.props);
// we are the root component
this.env = (this.constructor as any).env;
if (!this.env.qweb) {
this.env.qweb = new QWeb();
}
this.env.qweb.on("update", this, () => {
if (this.__owl__.isMounted) {
@@ -160,16 +151,19 @@ export class Component<T extends Env, Props extends {}> {
this.env.qweb.off("update", this);
}
});
depth = 0;
}
const qweb = this.env.qweb;
const qweb = this.env.qweb;
const template = constr.template || this.__getTemplate(qweb);
this.__owl__ = {
id: id,
depth: depth,
vnode: null,
pvnode: null,
isMounted: false,
isDestroyed: false,
parent: p,
parent: parent || null,
children: {},
cmap: {},
currentFiber: null,
@@ -181,7 +175,7 @@ export class Component<T extends Env, Props extends {}> {
willStartCB: null,
willUpdatePropsCB: null,
observer: null,
renderFn: qweb.render.bind(qweb, this.__getTemplate(qweb)),
renderFn: qweb.render.bind(qweb, template),
classObj: null,
refs: null
};
@@ -262,8 +256,11 @@ export class Component<T extends Env, Props extends {}> {
/**
* catchError is a method called whenever some error happens in the rendering or
* lifecycle hooks of a child.
*
* It needs to be implemented by a component that is designed to handle the
* error properly.
*/
catchError(error: Error): void {}
catchError?(error?: Error): void;
//--------------------------------------------------------------------------
// Public
@@ -289,14 +286,13 @@ 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 => {
scheduler.addFiber(fiber, () => {
return new Promise((resolve, reject) => {
const fiber = new Fiber(null, this, undefined, undefined, false);
scheduler.addFiber(fiber, err => {
if (err) {
reject(err);
return;
}
if (!__owl__.isDestroyed) {
this.__patch(fiber.vnode);
target.appendChild(this.el!);
@@ -306,6 +302,11 @@ export class Component<T extends Env, Props extends {}> {
}
resolve();
});
if (!__owl__.vnode) {
this.__prepareAndRender(fiber);
} else {
this.__render(fiber);
}
});
}
@@ -337,15 +338,19 @@ 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 => {
scheduler.addFiber(fiber.root, () => {
return new Promise((resolve, reject) => {
const fiber = new Fiber(null, this, undefined, undefined, force);
scheduler.addFiber(fiber.root, err => {
if (err) {
reject(err);
return;
}
if (__owl__.isMounted && fiber === fiber.root) {
fiber.patchComponents();
}
resolve();
});
this.__render(fiber);
});
}
@@ -483,7 +488,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 {
@@ -492,7 +497,10 @@ export class Component<T extends Env, Props extends {}> {
const defaultProps = (<any>this.constructor).defaultProps;
if (defaultProps) {
nextProps = this.__applyDefaultProps(nextProps, defaultProps);
this.__applyDefaultProps(nextProps, defaultProps);
}
if (QWeb.dev) {
QWeb.utils.validateProps(this.constructor, nextProps);
}
await Promise.all([
this.willUpdateProps(nextProps),
@@ -524,7 +532,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;
@@ -537,22 +545,18 @@ export class Component<T extends Env, Props extends {}> {
__getTemplate(qweb: QWeb): string {
let p = (<any>this).constructor;
if (!p.hasOwnProperty("_template")) {
if (p.template) {
p._template = p.template;
} else {
// here, the component and none of its superclasses defines a static `template`
// key. So we fall back on looking for a template matching its name (or
// one of its subclass).
// here, the component and none of its superclasses defines a static `template`
// key. So we fall back on looking for a template matching its name (or
// one of its subclass).
let template: string;
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
p = p.__proto__;
}
if (p === Component) {
throw new Error(`Could not find template for component "${this.constructor.name}"`);
} else {
p._template = template;
}
let template: string;
while ((template = p.name) && !(template in qweb.templates) && p !== Component) {
p = p.__proto__;
}
if (p === Component) {
throw new Error(`Could not find template for component "${this.constructor.name}"`);
} else {
p._template = template;
}
}
return p._template;
@@ -561,7 +565,7 @@ export class Component<T extends Env, Props extends {}> {
try {
await Promise.all([this.willStart(), this.__owl__.willStartCB && this.__owl__.willStartCB()]);
} catch (e) {
errorHandler(e, fiber);
fiber.handleError(e);
fiber.vnode = h("div"); // -> we render this div at the end
return Promise.resolve();
}
@@ -586,7 +590,7 @@ export class Component<T extends Env, Props extends {}> {
});
} catch (e) {
vnode = __owl__.vnode || h("div");
errorHandler(e, fiber);
fiber.handleError(e);
}
fiber.vnode = vnode;
if (__owl__.observer) {
@@ -637,52 +641,13 @@ export class Component<T extends Env, Props extends {}> {
/**
* Apply default props (only top level).
*
* Note that this method does not modify in place the props, it returns a new
* prop object
* Note that this method does modify in place the props
*/
__applyDefaultProps(props: Object | undefined, defaultProps: Object): Props {
props = props ? Object.assign({}, props) : {};
__applyDefaultProps(props: Object, defaultProps: Object) {
for (let propName in defaultProps) {
if (props![propName] === undefined) {
props![propName] = defaultProps[propName];
}
}
return <Props>props;
}
}
//------------------------------------------------------------------------------
// Error handling
//------------------------------------------------------------------------------
Fiber.prototype.handleError = function(error) {
errorHandler(error, this);
};
/**
* This is the global error handler for errors occurring in Owl main lifecycle
* methods. Caught errors are triggered on the QWeb instance, and are
* potentially given to some parent component which implements `catchError`.
*
* If there are no such component, we destroy everything. This is better than
* being in a corrupted state.
*/
function errorHandler(error: Error, fiber: Fiber) {
let canCatch = false;
let component = fiber.component;
let qweb = component.env.qweb;
let root = component;
while (component && !(canCatch = component.catchError !== Component.prototype.catchError)) {
root = component;
component = component.__owl__.parent!;
}
console.error(error);
qweb.trigger("error", error);
if (canCatch) {
setTimeout(() => {
component.catchError(error);
});
} else {
root.destroy();
}
}
+6 -39
View File
@@ -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
@@ -223,30 +222,19 @@ QWeb.addDirective({
}
}
let key = node.getAttribute("t-key");
if (key) {
key = ctx.formatExpression(key);
}
// computing the props string representing the props object
let propStr = Object.keys(props)
.map(k => k + ":" + props[k])
.join(",");
let defID = ctx.generateID();
let componentID = ctx.generateID();
let keyID = key && ctx.generateID();
if (key) {
// we bind a variable to the key (could be a complex expression, so we
// want to evaluate it only once)
ctx.addLine(`let key${keyID} = 'key' + ${key};`);
}
let locationExpr = `\`__${ctx.generateID()}__`;
for (let i = 0; i < ctx.loopNumber - 1; i++) {
locationExpr += `\${i${i + 1}}__`;
}
if (key || ctx.currentKey) {
const k = key ? `key${keyID}` : ctx.currentKey;
if (ctx.lastNodeKey || ctx.currentKey) {
const k = ctx.lastNodeKey || ctx.currentKey;
ctx.addLine(`let templateId${componentID} = ${locationExpr}\` + ${k};`);
} else {
locationExpr += ctx.loopNumber ? `\${i${ctx.loopNumber}}__\`` : "`";
@@ -267,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) {
@@ -349,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;
@@ -404,31 +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}`;
}
if (QWeb.dev) {
ctx.addLine(`utils.validateProps(w${componentID}.constructor, props${componentID})`);
}
let styleCode = "";
if (tattStyle) {
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
}
ctx.addLine(
`w${componentID}.__updateProps(props${componentID}, ${patchQueueCode}${scopeVars &&
`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);
}
+41 -14
View File
@@ -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;
@@ -53,11 +53,12 @@ export class Fiber {
sibling: Fiber | null = null;
parent: Fiber | null = null;
constructor(parent: Fiber | null, component: Component<any, any>, props, scope, vars, force) {
error?: Error;
constructor(parent: Fiber | null, component: Component<any, any>, scope, vars, force) {
this.force = force;
this.scope = scope;
this.vars = vars;
this.props = props;
this.component = component;
this.root = parent ? parent.root : this;
@@ -146,7 +147,6 @@ export class Fiber {
};
this._walk(doWork);
let component: Component<any, any> = this.component;
this.shouldPatch = false;
const patchLen = patchQueue.length;
try {
for (let i = 0; i < patchLen; i++) {
@@ -159,14 +159,10 @@ export class Fiber {
} catch (e) {
console.error(e);
}
try {
for (let i = 0; i < patchLen; i++) {
const fiber = patchQueue[i];
component = fiber.component;
component.__patch(fiber.vnode);
}
} catch (e) {
this.handleError(e);
for (let i = 0; i < patchLen; i++) {
const fiber = patchQueue[i];
component = fiber.component;
component.__patch(fiber.vnode);
}
try {
for (let i = patchLen - 1; i >= 0; i--) {
@@ -179,7 +175,6 @@ export class Fiber {
} catch (e) {
console.error(e);
}
this.shouldPatch = true;
}
/**
@@ -195,5 +190,37 @@ export class Fiber {
});
}
handleError(e: Error) {}
/**
* This is the global error handler for errors occurring in Owl main lifecycle
* methods. Caught errors are triggered on the QWeb instance, and are
* potentially given to some parent component which implements `catchError`.
*
* If there are no such component, we destroy everything. This is better than
* being in a corrupted state.
*/
handleError(error: Error) {
let canCatch = false;
let component = this.component;
let qweb = component.env.qweb;
let root = component;
while (component && !(canCatch = !!component.catchError)) {
root = component;
component = component.__owl__.parent!;
}
qweb.trigger("error", error);
if (canCatch) {
setTimeout(() => {
console.error(error);
component.catchError!(error);
});
} else {
// the 3 next lines aim to mark the root fiber as being in error, and
// to force it to end, without waiting for its children
this.root.counter = 0;
this.root.error = error;
scheduler.flush();
root.destroy();
}
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ QWeb.utils.validateProps = function(Widget, props: Object) {
// optional prop
break;
}
if (!props[propName]) {
if (!(propName in props)) {
throw new Error(`Missing props '${propsDef[i]}' (component '${Widget.name}')`);
}
}
+5 -2
View File
@@ -13,7 +13,7 @@ import { Fiber } from "./fiber";
interface Task {
fiber: Fiber;
callback: () => void;
callback: (err?: Error) => void;
}
export class Scheduler {
@@ -45,7 +45,7 @@ export class Scheduler {
return false;
}
if (task.fiber.counter === 0) {
task.callback();
task.callback(task.fiber.error);
return false;
}
return true;
@@ -65,3 +65,6 @@ export class Scheduler {
});
}
}
const raf = window.requestAnimationFrame.bind(window);
export const scheduler = new Scheduler(raf);
+30
View File
@@ -0,0 +1,30 @@
import { QWeb } from "./qweb/index";
/**
* This file creates and exports the OWL 'config' object, with keys:
* - 'mode': 'prod' or 'dev',
* - 'env': the environment to use in root components.
*/
interface Config {
mode: string;
}
export const config = {} as Config;
Object.defineProperty(config, "mode", {
get() {
return QWeb.dev ? "dev" : "prod";
},
set(mode: string) {
QWeb.dev = mode === "dev";
if (QWeb.dev) {
const url = `https://github.com/odoo/owl/blob/master/doc/reference/config.md#mode`;
console.warn(
`Owl is running in 'dev' mode. This is not suitable for production use. See ${url} for more information.`
);
} else {
console.log(`Owl is now running in 'prod' mode.`);
}
}
});
+63 -31
View File
@@ -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;
}
}
}
@@ -81,15 +113,15 @@ export function useContextWithCB(ctx: Context, component: Component<any, any>, m
__owl__.observer.notifyCB = component.render.bind(component);
}
const currentCB = __owl__.observer.notifyCB;
__owl__.observer.notifyCB = function () {
if (ctx.rev > mapping[id]) {
// in this case, the context has been updated since we were rendering
// last, and we do not need to render here with the observer. A
// rendering is coming anyway, with the correct props.
return;
}
currentCB();
}
__owl__.observer.notifyCB = function() {
if (ctx.rev > mapping[id]) {
// in this case, the context has been updated since we were rendering
// last, and we do not need to render here with the observer. A
// rendering is coming anyway, with the correct props.
return;
}
currentCB();
};
mapping[id] = 0;
const renderFn = __owl__.renderFn;
+1 -7
View File
@@ -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);
}
}
+4 -19
View File
@@ -7,10 +7,11 @@
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";
import {AsyncRoot} from "./misc/async_root";
import { AsyncRoot } from "./misc/async_root";
import * as _hooks from "./hooks";
import * as _context from "./context";
import { Link } from "./router/link";
@@ -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;
@@ -27,7 +29,7 @@ export const router = { Router, RouteComponent, Link };
export const Store = _store.Store;
export const utils = _utils;
export const tags = _tags;
export const misc = { AsyncRoot};
export const misc = { AsyncRoot };
export const hooks = Object.assign({}, _hooks, {
useContext: _context.useContext,
useDispatch: _store.useDispatch,
@@ -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.`);
}
}
});
+6 -14
View File
@@ -294,25 +294,17 @@ QWeb.addDirective({
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
const nodeCopy = <Element>node.cloneNode(true);
let shouldWarn = nodeCopy.tagName !== "t" && !nodeCopy.hasAttribute("t-key");
if (!shouldWarn && node.tagName === "t") {
if (node.hasAttribute("t-component") && !node.hasAttribute("t-key")) {
shouldWarn = true;
}
if (
!shouldWarn &&
node.children.length === 1 &&
node.children[0].tagName !== "t" &&
!node.children[0].hasAttribute("t-key")
) {
shouldWarn = true;
}
}
let shouldWarn =
!nodeCopy.hasAttribute("t-key") &&
node.children.length === 1 &&
node.children[0].tagName !== "t" &&
!node.children[0].hasAttribute("t-key");
if (shouldWarn) {
console.warn(
`Directive t-foreach should always be used with a t-key! (in template: '${ctx.templateName}')`
);
}
nodeCopy.removeAttribute("t-foreach");
qweb._compileNode(nodeCopy, ctx);
ctx.dedent();
+16 -1
View File
@@ -58,7 +58,9 @@ QWeb.addDirective({
ctx.addLine(`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`);
} else {
const handlerKey = `handler${ctx.generateID()}`;
ctx.addLine(`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`);
ctx.addLine(
`const ${handlerKey} = context['${handlerName}'] && context['${handlerName}'].bind(${params});`
);
handler += `if (${handlerKey}) { ${handlerKey}(e); } else { context.${value}; }`;
handler += `}`;
ctx.addLine(`p${nodeID}.on['${eventName}'] = ${handler};`);
@@ -259,3 +261,16 @@ QWeb.addDirective({
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
}
});
//------------------------------------------------------------------------------
// t-key
//------------------------------------------------------------------------------
QWeb.addDirective({
name: "key",
priority: 45,
atNodeEncounter({ ctx, value }) {
let id = ctx.generateID();
ctx.addLine(`const nodeKey${id} = ${ctx.formatExpression(value)};`);
ctx.lastNodeKey = `nodeKey${id}`;
}
});
+27 -13
View File
@@ -57,12 +57,19 @@ export interface Directive {
finalize?(info: CompilationInfo): void;
}
interface QWebConfig {
templates?: string;
translateFn?(text: string): string;
}
//------------------------------------------------------------------------------
// Const/global stuff/helpers
//------------------------------------------------------------------------------
const DISABLED_TAGS = ["input", "textarea", "button", "select", "option", "optgroup"];
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
const lineBreakRE = /[\r\n]/;
const whitespaceRE = /\s+/g;
@@ -134,6 +141,7 @@ function parseXML(xml: string): Document {
//------------------------------------------------------------------------------
// QWeb rendering engine
//------------------------------------------------------------------------------
export class QWeb extends EventBus {
templates: { [name: string]: Template };
static utils = UTILS;
@@ -143,7 +151,7 @@ export class QWeb extends EventBus {
name: 1,
att: 1,
attf: 1,
key: 1
translation: 1
};
static DIRECTIVES: Directive[] = [];
@@ -166,12 +174,16 @@ export class QWeb extends EventBus {
recursiveFns = {};
isUpdating: boolean = false;
translateFn?: QWebConfig["translateFn"];
constructor(data?: string) {
constructor(config: QWebConfig = {}) {
super();
this.templates = Object.create(QWeb.TEMPLATES);
if (data) {
this.addTemplates(data);
if (config.templates) {
this.addTemplates(config.templates);
}
if (config.translateFn) {
this.translateFn = config.translateFn;
}
}
@@ -418,6 +430,11 @@ export class QWeb extends EventBus {
}
text = text.replace(whitespaceRE, " ");
}
if (this.translateFn) {
if ((node.parentNode as any).getAttribute("t-translation") !== "off") {
text = this.translateFn(text);
}
}
if (ctx.parentNode) {
if (node.nodeType === 3) {
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
@@ -617,7 +634,11 @@ export class QWeb extends EventBus {
for (let i = 0; i < attributes.length; i++) {
let name = attributes[i].name;
const value = attributes[i].textContent!;
let value = attributes[i].textContent!;
if (this.translateFn && TRANSLATABLE_ATTRS.includes(name)) {
value = this.translateFn(value);
}
// regular attributes
if (!name.startsWith("t-") && !(<Element>node).getAttribute("t-attf-" + name)) {
@@ -703,14 +724,7 @@ export class QWeb extends EventBus {
}
}
let nodeID = ctx.generateID();
let nodeKey: any = (<Element>node).getAttribute("t-key");
if (nodeKey) {
ctx.addLine(`const nodeKey${nodeID} = ${ctx.formatExpression(nodeKey)}`);
nodeKey = `nodeKey${nodeID}`;
ctx.lastNodeKey = nodeKey;
} else {
nodeKey = nodeID;
}
let nodeKey = ctx.lastNodeKey || nodeID;
const parts = [`key:${nodeKey}`];
if (attrs.length + tattrs.length > 0) {
parts.push(`attrs:{${attrs.join(",")}}`);
+1 -1
View File
@@ -148,7 +148,7 @@ export class Router {
//--------------------------------------------------------------------------
private setUrlFromPath(path: string) {
const separator = this.mode === "hash" ? "/" : "";
const separator = this.mode === "hash" ? location.pathname : "";
const url = location.origin + separator + path;
if (url !== window.location.href) {
window.history.pushState({}, path, url);
+1 -2
View File
@@ -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);
});
+7 -6
View File
@@ -29,6 +29,7 @@ let cssEl: HTMLElement;
beforeEach(() => {
fixture = makeTestFixture();
env = makeTestEnv();
Component.env = env;
qweb = new QWeb();
});
@@ -108,7 +109,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 +152,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 +181,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 +221,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 +284,7 @@ describe("animations", () => {
}
}
const widget = new Parent(env);
const widget = new Parent();
await widget.mount(fixture);
let button = widget.el!.querySelector("button");
@@ -341,7 +342,7 @@ describe("animations", () => {
}
}
const widget = new Parent(env);
const widget = new Parent();
await widget.mount(fixture);
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
) {
@@ -305,33 +260,33 @@ exports[`composition sub components with some state rendered in a loop 1`] = `
context.number_index = i1;
context.number = _3[i1];
context.number_value = _4[i1];
const nodeKey5 = context['number'];
//COMPONENT
let key7 = 'key' + context['number'];
let templateId6 = \`__8__\` + key7;
let w6 = templateId6 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId6]] : false;
let props6 = {};
if (w6 && w6.__owl__.currentFiber && !w6.__owl__.vnode) {
w6.destroy();
w6 = false;
let templateId7 = \`__8__\` + nodeKey5;
let w7 = templateId7 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId7]] : false;
let props7 = {};
if (w7 && w7.__owl__.currentFiber && !w7.__owl__.vnode) {
w7.destroy();
w7 = false;
}
if (w6) {
w6.__updateProps(props6, extra.fiber, undefined, undefined, sibling);
let pvnode = w6.__owl__.pvnode;
if (w7) {
w7.__updateProps(props7, extra.fiber, undefined, undefined, sibling);
let pvnode = w7.__owl__.pvnode;
c1.push(pvnode);
} else {
let componentKey6 = \`ChildWidget\`;
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| context['ChildWidget'];
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
w6 = new W6(parent, props6);
parent.__owl__.cmap[templateId6] = w6.__owl__.id;
let def5 = w6.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId6, hook: {insert(vn) { let nvn=w6.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w6.destroy();}}});
const fiber = w6.__owl__.currentFiber;
def5.then(function () {if (w6.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
let componentKey7 = \`ChildWidget\`;
let W7 = context.constructor.components[componentKey7] || QWeb.components[componentKey7]|| context['ChildWidget'];
if (!W7) {throw new Error('Cannot find the definition of component \\"' + componentKey7 + '\\"')}
w7 = new W7(parent, props7);
parent.__owl__.cmap[templateId7] = w7.__owl__.id;
let def6 = w7.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId7, hook: {insert(vn) { let nvn=w7.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w7.destroy();}}});
const fiber = w7.__owl__.currentFiber;
def6.then(function () {if (w7.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c1.push(pvnode);
w6.__owl__.pvnode = pvnode;
w7.__owl__.pvnode = pvnode;
}
sibling = w6.__owl__.currentFiber || sibling;
sibling = w7.__owl__.currentFiber || sibling;
}
return vn1;
}"
@@ -460,51 +415,6 @@ exports[`dynamic t-props basic use 1`] = `
}"
`;
exports[`lifecycle hooks willPatch/patched hook with t-keepalive 1`] = `
"function anonymous(context,extra
) {
let utils = this.constructor.utils;
let QWeb = this.constructor;
let parent = context;
let owner = context;
let sibling = null;
var h = this.h;
let c1 = [], p1 = {key:1};
var vn1 = h('div', p1, c1);
if (context['state'].flag) {
//COMPONENT
let templateId3 = \`__4__\`;
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
const fiber3 = Object.assign(Object.create(extra.fiber), {patchQueue: []});
let props3 = {v:context['state'].n};
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
w3.destroy();
w3 = false;
}
if (w3) {
w3.__updateProps(props3, w3.__owl__.isMounted ? extra.fiber : fiber3, undefined, undefined, sibling);
let pvnode = w3.__owl__.pvnode;
pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w3.el,vn.elm);vn.elm=w3.el;w3.__remount();};
c1.push(pvnode);
} else {
let componentKey3 = \`ChildWidget\`;
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['ChildWidget'];
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
w3 = new W3(parent, props3);
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.unmount();}}});
const fiber = w3.__owl__.currentFiber;
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c1.push(pvnode);
w3.__owl__.pvnode = pvnode;
}
sibling = w3.__owl__.currentFiber || sibling;
}
return vn1;
}"
`;
exports[`other directives with t-component t-on with getter as handler 1`] = `
"function anonymous(context,extra
) {
@@ -993,33 +903,33 @@ exports[`random stuff/miscellaneous snapshotting compiled code 1`] = `
var h = this.h;
let c1 = [], p1 = {key:1};
var vn1 = h('div', p1, c1);
const nodeKey2 = 'somestring';
//COMPONENT
let key4 = 'key' + 'somestring';
let templateId3 = \`__5__\` + key4;
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
let props3 = {flag:context['state'].flag};
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
w3.destroy();
w3 = false;
let templateId4 = \`__5__\` + nodeKey2;
let w4 = templateId4 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId4]] : false;
let props4 = {flag:context['state'].flag};
if (w4 && w4.__owl__.currentFiber && !w4.__owl__.vnode) {
w4.destroy();
w4 = false;
}
if (w3) {
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
let pvnode = w3.__owl__.pvnode;
if (w4) {
w4.__updateProps(props4, extra.fiber, undefined, undefined, sibling);
let pvnode = w4.__owl__.pvnode;
c1.push(pvnode);
} else {
let componentKey3 = \`child\`;
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['child'];
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
w3 = new W3(parent, props3);
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});
const fiber = w3.__owl__.currentFiber;
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
let componentKey4 = \`child\`;
let W4 = context.constructor.components[componentKey4] || QWeb.components[componentKey4]|| context['child'];
if (!W4) {throw new Error('Cannot find the definition of component \\"' + componentKey4 + '\\"')}
w4 = new W4(parent, props4);
parent.__owl__.cmap[templateId4] = w4.__owl__.id;
let def3 = w4.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId4, hook: {insert(vn) { let nvn=w4.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});
const fiber = w4.__owl__.currentFiber;
def3.then(function () {if (w4.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c1.push(pvnode);
w3.__owl__.pvnode = pvnode;
w4.__owl__.pvnode = pvnode;
}
sibling = w3.__owl__.currentFiber || sibling;
sibling = w4.__owl__.currentFiber || sibling;
return vn1;
}"
`;
@@ -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)) {
@@ -1050,34 +960,34 @@ exports[`random stuff/miscellaneous t-on with handler bound to dynamic argument
context.item_index = i1;
context.item = _3[i1];
context.item_value = _4[i1];
const nodeKey5 = context['item'];
//COMPONENT
let key7 = 'key' + context['item'];
let templateId6 = \`__8__\` + key7;
let templateId7 = \`__8__\` + nodeKey5;
let arg9 = context['item'];
let w6 = templateId6 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId6]] : false;
let props6 = {};
if (w6 && w6.__owl__.currentFiber && !w6.__owl__.vnode) {
w6.destroy();
w6 = false;
let w7 = templateId7 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId7]] : false;
let props7 = {};
if (w7 && w7.__owl__.currentFiber && !w7.__owl__.vnode) {
w7.destroy();
w7 = false;
}
if (w6) {
w6.__updateProps(props6, extra.fiber, undefined, undefined, sibling);
let pvnode = w6.__owl__.pvnode;
if (w7) {
w7.__updateProps(props7, extra.fiber, undefined, undefined, sibling);
let pvnode = w7.__owl__.pvnode;
c1.push(pvnode);
} else {
let componentKey6 = \`Child\`;
let W6 = context.constructor.components[componentKey6] || QWeb.components[componentKey6]|| context['Child'];
if (!W6) {throw new Error('Cannot find the definition of component \\"' + componentKey6 + '\\"')}
w6 = new W6(parent, props6);
parent.__owl__.cmap[templateId6] = w6.__owl__.id;
let def5 = w6.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId6, hook: {insert(vn) { let nvn=w6.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w6.destroy();}}});
const fiber = w6.__owl__.currentFiber;
def5.then(function () {if (w6.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {const fn = owner['onEv'];if (fn) { fn.call(owner, arg9, e); } else { owner.onEv; }});}};});
let componentKey7 = \`Child\`;
let W7 = context.constructor.components[componentKey7] || QWeb.components[componentKey7]|| context['Child'];
if (!W7) {throw new Error('Cannot find the definition of component \\"' + componentKey7 + '\\"')}
w7 = new W7(parent, props7);
parent.__owl__.cmap[templateId7] = w7.__owl__.id;
let def6 = w7.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId7, hook: {insert(vn) { let nvn=w7.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w7.destroy();}}});
const fiber = w7.__owl__.currentFiber;
def6.then(function () {if (w7.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', function (e) {const fn = owner['onEv'];if (fn) { fn.call(owner, arg9, e); } else { owner.onEv; }});}};});
c1.push(pvnode);
w6.__owl__.pvnode = pvnode;
w7.__owl__.pvnode = pvnode;
}
sibling = w6.__owl__.currentFiber || sibling;
sibling = w7.__owl__.currentFiber || sibling;
}
return vn1;
}"
@@ -1541,37 +1451,37 @@ exports[`t-slot directive slots are rendered with proper context, part 2 2`] = `
scope.user = context.user;
context.user_value = _5[i1];
scope.user_value = context.user_value;
const nodeKey6 = context['user'].id
let c6 = [], p6 = {key:nodeKey6};
var vn6 = h('li', p6, c6);
c2.push(vn6);
const nodeKey6 = context['user'].id;
let c7 = [], p7 = {key:nodeKey6};
var vn7 = h('li', p7, c7);
c2.push(vn7);
//COMPONENT
let templateId8 = \`__9__\` + nodeKey6;
let w8 = templateId8 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId8]] : false;
let props8 = {to:'/user/'+context['user'].id};
if (w8 && w8.__owl__.currentFiber && !w8.__owl__.vnode) {
w8.destroy();
w8 = false;
let templateId9 = \`__10__\` + nodeKey6;
let w9 = templateId9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId9]] : false;
let props9 = {to:'/user/'+context['user'].id};
if (w9 && w9.__owl__.currentFiber && !w9.__owl__.vnode) {
w9.destroy();
w9 = false;
}
if (w8) {
w8.__updateProps(props8, extra.fiber, Object.assign({}, scope), undefined, sibling);
let pvnode = w8.__owl__.pvnode;
c6.push(pvnode);
if (w9) {
w9.__updateProps(props9, extra.fiber, Object.assign({}, scope), undefined, sibling);
let pvnode = w9.__owl__.pvnode;
c7.push(pvnode);
} else {
let componentKey8 = \`Link\`;
let W8 = context.constructor.components[componentKey8] || QWeb.components[componentKey8]|| context['Link'];
if (!W8) {throw new Error('Cannot find the definition of component \\"' + componentKey8 + '\\"')}
w8 = new W8(parent, props8);
parent.__owl__.cmap[templateId8] = w8.__owl__.id;
w8.__owl__.slotId = 1;
let def7 = w8.__prepare(extra.fiber, Object.assign({}, scope), undefined, sibling);
let pvnode = h('dummy', {key: templateId8, hook: {insert(vn) { let nvn=w8.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w8.destroy();}}});
const fiber = w8.__owl__.currentFiber;
def7.then(function () {if (w8.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c6.push(pvnode);
w8.__owl__.pvnode = pvnode;
let componentKey9 = \`Link\`;
let W9 = context.constructor.components[componentKey9] || QWeb.components[componentKey9]|| context['Link'];
if (!W9) {throw new Error('Cannot find the definition of component \\"' + componentKey9 + '\\"')}
w9 = new W9(parent, props9);
parent.__owl__.cmap[templateId9] = w9.__owl__.id;
w9.__owl__.slotId = 1;
let def8 = w9.__prepare(extra.fiber, Object.assign({}, scope), undefined, sibling);
let pvnode = h('dummy', {key: templateId9, hook: {insert(vn) { let nvn=w9.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w9.destroy();}}});
const fiber = w9.__owl__.currentFiber;
def8.then(function () {if (w9.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c7.push(pvnode);
w9.__owl__.pvnode = pvnode;
}
sibling = w8.__owl__.currentFiber || sibling;
sibling = w9.__owl__.currentFiber || sibling;
}
return vn1;
}"
@@ -1582,12 +1492,12 @@ exports[`t-slot directive slots are rendered with proper context, part 2 3`] = `
) {
let sibling = null;
var h = this.h;
let c6 = extra.parentNode;
let c7 = extra.parentNode;
Object.assign(context, extra.fiber.scope);
c6.push({text: \`User \`});
var _11 = context['user'].name;
if (_11 || _11 === 0) {
c6.push({text: _11});
c7.push({text: \`User \`});
var _12 = context['user'].name;
if (_12 || _12 === 0) {
c7.push({text: _12});
}
}"
`;
@@ -1644,38 +1554,38 @@ exports[`t-slot directive slots are rendered with proper context, part 3 2`] = `
scope.user = context.user;
context.user_value = _5[i1];
scope.user_value = context.user_value;
const nodeKey6 = context['user'].id
let c6 = [], p6 = {key:nodeKey6};
var vn6 = h('li', p6, c6);
c2.push(vn6);
var _7 = 'User '+context['user'].name;
const nodeKey6 = context['user'].id;
let c7 = [], p7 = {key:nodeKey6};
var vn7 = h('li', p7, c7);
c2.push(vn7);
var _8 = 'User '+context['user'].name;
//COMPONENT
let templateId9 = \`__10__\` + nodeKey6;
let w9 = templateId9 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId9]] : false;
let props9 = {to:'/user/'+context['user'].id};
if (w9 && w9.__owl__.currentFiber && !w9.__owl__.vnode) {
w9.destroy();
w9 = false;
let templateId10 = \`__11__\` + nodeKey6;
let w10 = templateId10 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId10]] : false;
let props10 = {to:'/user/'+context['user'].id};
if (w10 && w10.__owl__.currentFiber && !w10.__owl__.vnode) {
w10.destroy();
w10 = false;
}
if (w9) {
w9.__updateProps(props9, extra.fiber, Object.assign({}, scope), {_7}, sibling);
let pvnode = w9.__owl__.pvnode;
c6.push(pvnode);
if (w10) {
w10.__updateProps(props10, extra.fiber, Object.assign({}, scope), {_8}, sibling);
let pvnode = w10.__owl__.pvnode;
c7.push(pvnode);
} else {
let componentKey9 = \`Link\`;
let W9 = context.constructor.components[componentKey9] || QWeb.components[componentKey9]|| context['Link'];
if (!W9) {throw new Error('Cannot find the definition of component \\"' + componentKey9 + '\\"')}
w9 = new W9(parent, props9);
parent.__owl__.cmap[templateId9] = w9.__owl__.id;
w9.__owl__.slotId = 1;
let def8 = w9.__prepare(extra.fiber, Object.assign({}, scope), {_7}, sibling);
let pvnode = h('dummy', {key: templateId9, hook: {insert(vn) { let nvn=w9.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w9.destroy();}}});
const fiber = w9.__owl__.currentFiber;
def8.then(function () {if (w9.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c6.push(pvnode);
w9.__owl__.pvnode = pvnode;
let componentKey10 = \`Link\`;
let W10 = context.constructor.components[componentKey10] || QWeb.components[componentKey10]|| context['Link'];
if (!W10) {throw new Error('Cannot find the definition of component \\"' + componentKey10 + '\\"')}
w10 = new W10(parent, props10);
parent.__owl__.cmap[templateId10] = w10.__owl__.id;
w10.__owl__.slotId = 1;
let def9 = w10.__prepare(extra.fiber, Object.assign({}, scope), {_8}, sibling);
let pvnode = h('dummy', {key: templateId10, hook: {insert(vn) { let nvn=w10.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w10.destroy();}}});
const fiber = w10.__owl__.currentFiber;
def9.then(function () {if (w10.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
c7.push(pvnode);
w10.__owl__.pvnode = pvnode;
}
sibling = w9.__owl__.currentFiber || sibling;
sibling = w10.__owl__.currentFiber || sibling;
}
return vn1;
}"
@@ -1686,11 +1596,11 @@ exports[`t-slot directive slots are rendered with proper context, part 3 3`] = `
) {
let sibling = null;
var h = this.h;
let c6 = extra.parentNode;
let _7 = extra.fiber.vars._7
let c7 = extra.parentNode;
let _8 = extra.fiber.vars._8
Object.assign(context, extra.fiber.scope);
if (_7 || _7 === 0) {
c6.push({text: _7});
if (_8 || _8 === 0) {
c7.push({text: _8});
}
}"
`;
@@ -20,7 +20,6 @@ exports[`props validation props are validated in dev mode (code snapshot) 1`] =
w3 = false;
}
if (w3) {
utils.validateProps(w3.constructor, props3)
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
let pvnode = w3.__owl__.pvnode;
c1.push(pvnode);
File diff suppressed because it is too large Load Diff
+443 -98
View File
@@ -15,6 +15,7 @@ let dev: boolean = false;
beforeEach(() => {
fixture = makeTestFixture();
env = makeTestEnv();
Component.env = env;
dev = QWeb.dev;
QWeb.dev = true;
});
@@ -35,17 +36,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 +69,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 +95,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 +152,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: {
@@ -222,16 +461,44 @@ describe("props validation", () => {
}
}
};
};
}
class Parent extends Component<any, any> {
static template = xml`<div><TestWidget p="p"/></div>`;
static components = { TestWidget };
get p() {
return props.p;
}
}
expect(() => {
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 +516,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
@@ -322,17 +589,95 @@ describe("props validation", () => {
QWeb.utils.validateProps(TestWidget, { message: null });
}).toThrow();
});
test("missing required boolean prop causes an error", async () => {
class TestWidget extends Widget {
static props = ["p"];
static template = xml`<span><t t-if="props.p">hey</t></span>`;
}
class App extends Widget {
static template = xml`<div><TestWidget/></div>`;
static components = { TestWidget };
}
const w = new App(undefined, {});
let error;
try {
await w.mount(fixture);
} catch (e) {
error = e;
}
expect(error).toBeDefined();
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
});
test("props are validated whenever component is updated", async () => {
let error;
class TestWidget extends Component<any, any> {
static props = { p: { type: Number } };
static template = xml`<div><t t-esc="props.p"/></div>`;
async __updateProps() {
try {
await Component.prototype.__updateProps.apply(this, arguments);
} catch (e) {
error = e;
}
}
}
class Parent extends Component<any, any> {
static template = xml`<div><TestWidget p="state.p"/></div>`;
static components = { TestWidget };
state: any = useState({ p: 1 });
}
const w = new Parent();
await w.mount(fixture);
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
w.state.p = undefined;
await nextTick();
expect(error).toBeDefined();
expect(error.message).toBe("Missing props 'p' (component 'TestWidget')");
});
test("default values are applied before validating props at update", async () => {
class TestWidget extends Component<any, any> {
static props = { p: { type: Number } };
static template = xml`<div><t t-esc="props.p"/></div>`;
static defaultProps = { p: 4 };
}
class Parent extends Component<any, any> {
static template = xml`<div><TestWidget p="state.p"/></div>`;
static components = { TestWidget };
state: any = useState({ p: 1 });
}
const w = new Parent();
await w.mount(fixture);
expect(fixture.innerHTML).toBe("<div><div>1</div></div>");
w.state.p = undefined;
await nextTick();
expect(fixture.innerHTML).toBe("<div><div>4</div></div>");
});
});
describe("default props", () => {
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 () => {
@@ -346,7 +691,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>");
@@ -367,7 +712,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 -12
View File
@@ -1,5 +1,5 @@
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 { xml } from "../src/tags";
import { useState } from "../src/hooks";
@@ -11,14 +11,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();
Component.env = makeTestEnv();
});
afterEach(() => {
@@ -37,7 +36,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 +48,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 +67,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 +75,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 +174,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 +205,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 +239,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,12 +283,12 @@ 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>");
testContext.state.key = "y";
testContext.state.y = {n: 2};
testContext.state.y = { n: 2 };
delete testContext.state.x;
await nextTick();
+9 -43
View File
@@ -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);
});
+124 -72
View File
@@ -6,36 +6,9 @@
*/
import * as fs from "fs";
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
// files to be checked
function getFiles(): string[] {
const DOCFILES = fs.readdirSync("doc").map(f => `doc/${f}`);
const MAINREADME = "README.md";
DOCFILES.push("roadmap.md", MAINREADME);
return DOCFILES;
}
test("All markdown links work", () => {
let linkNumber = 0;
let invalidLinkNumber = 0;
const files = getFiles();
const data = readDocData(files);
for (let file of data) {
for (let link of file.links) {
// DEBUG: uncomment next line
// console.warn(`Checking "${link.name}" in "${file.name}"`);
linkNumber++;
if (!isLinkValid(link, file, data)) {
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
invalidLinkNumber++;
}
}
}
expect(invalidLinkNumber).toBe(0);
expect(linkNumber).toBeGreaterThan(10);
});
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
interface MarkDownLink {
name: string;
@@ -49,38 +22,127 @@ interface MarkDownSection {
interface FileData {
name: string;
path: string[];
fullName: string;
links: MarkDownLink[];
sections: MarkDownSection[];
}
function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
const LINK_REGEXP = /\[([^\[]+)\]\(([^\)]+)\)/g;
const HEADING_REGEXP = /\n(#+\s*)(.*)/g;
export function addMardownData(fileData): void {
const sep = fileData.path.length > 0 ? "/" : "";
const fullName = fileData.path.join("/") + sep + fileData.name;
const content = fs.readFileSync(fullName, { encoding: "utf8" });
let m;
// get links info
do {
m = LINK_REGEXP.exec(content);
if (m) {
fileData.links.push({ name: m[0], link: m[2] });
}
} while (m);
// get sections info
do {
m = HEADING_REGEXP.exec(content);
if (m) {
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
}
} while (m);
}
/**
* Returns a list of FileData corresponding to all files that need to be
* validated.
*/
function getFiles(path: string[] = []): FileData[] {
if (path.length === 0) {
const baseFiles: FileData[] = [
{ name: "README.md", path: [], links: [], sections: [], fullName: "README.md" },
{ name: "roadmap.md", path: [], links: [], sections: [], fullName: "roadmap.md" }
];
const rest = getFiles(["doc"]);
const result = baseFiles.concat(rest);
result.forEach(addMardownData);
return result;
}
const files = fs.readdirSync(path.join("/"), { withFileTypes: true }).map(f => {
if (f.isDirectory()) {
return getFiles(path.concat(f.name));
}
const fullName = path.join("/") + (path.length > 0 ? "/" : "") + f.name;
return [
{
name: f.name,
path,
links: [],
sections: [],
fullName
}
];
});
return Array.prototype.concat(...files);
}
const LOCAL_FILES = ["LICENSE"];
export function isLinkValid(link: MarkDownLink, current: FileData, files: FileData[]): boolean {
if (link.link.startsWith("http")) {
// 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)
const parts = link.link.split("#");
const currentParts = current.name.split("/");
const path = currentParts.length > 1 ? currentParts[0] + "/" : "";
const fullName = path + parts[0];
if (parts.length === 1) {
// no # in url
if (parts[0].endsWith(".md")) {
// it is a local md file
if (!files.find(f => f.name === fullName)) {
return false;
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 {
const file = parts[0] === "" ? current : files.find(f => f.name === fullName);
if (!file) {
return false;
}
if (!file.sections.find(s => s.slug === parts[1])) {
// 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;
}
}
return true;
}
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
function slugify(str) {
const a = "àáäâãåăæçèéëêǵḧìíïîḿńǹñòóöôœøṕŕßśșțùúüûǘẃẍÿź·_,:;";
@@ -99,33 +161,23 @@ function slugify(str) {
.replace(/-+$/, ""); // Trim - from end of text
}
function readDocData(files: string[]): FileData[] {
const result: FileData[] = [];
//--------------------------------------------------------------------------
// Test
//--------------------------------------------------------------------------
for (let file of files) {
const fileData: FileData = {
name: file,
links: [],
sections: []
};
const content = fs.readFileSync(file, { encoding: "utf8" });
let m;
// get links info
do {
m = LINK_REGEXP.exec(content);
if (m) {
fileData.links.push({ name: m[0], link: m[2] });
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++;
}
} while (m);
// get sections info
do {
m = HEADING_REGEXP.exec(content);
if (m) {
fileData.sections.push({ name: m[0], slug: slugify(m[2]) });
}
} while (m);
result.push(fileData);
}
}
return result;
}
expect(invalidLinkNumber).toBe(0);
expect(linkNumber).toBeGreaterThan(10);
});
+2 -1
View File
@@ -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";
+43 -42
View File
@@ -28,6 +28,7 @@ let env: Env;
beforeEach(() => {
fixture = makeTestFixture();
env = makeTestEnv();
Component.env = env;
});
afterEach(() => {
@@ -44,7 +45,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 +65,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 +93,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 +104,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 +127,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 +138,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 +158,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 +176,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 +198,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 +227,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 +248,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 +271,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 +305,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 +316,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 +338,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 +378,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 +400,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 +421,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 +436,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 +445,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 +479,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");
+6 -7
View File
@@ -2,7 +2,7 @@ import { AsyncRoot } from "../../src/misc/async_root";
import { useState } from "../../src/hooks";
import { xml } from "../../src/tags";
import { makeDeferred, makeTestFixture, makeTestEnv, nextTick } from "../helpers";
import { Env, Component } from "../../src/component/component";
import { Component } from "../../src/component/component";
//------------------------------------------------------------------------------
// Setup and helpers
@@ -11,14 +11,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();
Component.env = makeTestEnv();
});
afterEach(() => {
@@ -55,7 +54,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 +102,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 +157,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>");
+129 -62
View File
@@ -387,13 +387,13 @@ exports[`foreach iterate on items (on a element node) 1`] = `
context.item_index = i1;
context.item = _3[i1];
context.item_value = _4[i1];
const nodeKey5 = context['item']
let c5 = [], p5 = {key:nodeKey5};
var vn5 = h('span', p5, c5);
c1.push(vn5);
var _6 = context['item'];
if (_6 || _6 === 0) {
c5.push({text: _6});
const nodeKey5 = context['item'];
let c6 = [], p6 = {key:nodeKey5};
var vn6 = h('span', p6, c6);
c1.push(vn6);
var _7 = context['item'];
if (_7 || _7 === 0) {
c6.push({text: _7});
}
}
return vn1;
@@ -1643,14 +1643,14 @@ exports[`t-key can use t-key directive on a node 1`] = `
) {
let sibling = null;
var h = this.h;
const nodeKey1 = context['beer'].id
let c1 = [], p1 = {key:nodeKey1};
var vn1 = h('div', p1, c1);
var _2 = context['beer'].name;
if (_2 || _2 === 0) {
c1.push({text: _2});
const nodeKey1 = context['beer'].id;
let c2 = [], p2 = {key:nodeKey1};
var vn2 = h('div', p2, c2);
var _3 = context['beer'].name;
if (_3 || _3 === 0) {
c2.push({text: _3});
}
return vn1;
return vn2;
}"
`;
@@ -1676,13 +1676,13 @@ exports[`t-key t-key directive in a list 1`] = `
context.beer_index = i1;
context.beer = _3[i1];
context.beer_value = _4[i1];
const nodeKey5 = context['beer'].id
let c5 = [], p5 = {key:nodeKey5};
var vn5 = h('li', p5, c5);
c1.push(vn5);
var _6 = context['beer'].name;
if (_6 || _6 === 0) {
c5.push({text: _6});
const nodeKey5 = context['beer'].id;
let c6 = [], p6 = {key:nodeKey5};
var vn6 = h('li', p6, c6);
c1.push(vn6);
var _7 = context['beer'].name;
if (_7 || _7 === 0) {
c6.push({text: _7});
}
}
return vn1;
@@ -1774,16 +1774,16 @@ exports[`t-on can bind handlers with loop variable as argument 1`] = `
context.action_index = i1;
context.action = _3[i1];
context.action_value = _4[i1];
const nodeKey5 = context['action_index']
let c5 = [], p5 = {key:nodeKey5};
var vn5 = h('li', p5, c5);
c1.push(vn5);
let c6 = [], p6 = {key:6,on:{}};
var vn6 = h('a', p6, c6);
c5.push(vn6);
const handler7 = context['activate'] && context['activate'].bind(owner, context['action']);
p6.on['click'] = function (e) {if (handler7) { handler7(e); } else { context.activate(action); }};
c6.push({text: \`link\`});
const nodeKey5 = context['action_index'];
let c6 = [], p6 = {key:nodeKey5};
var vn6 = h('li', p6, c6);
c1.push(vn6);
let c7 = [], p7 = {key:nodeKey5,on:{}};
var vn7 = h('a', p7, c7);
c6.push(vn7);
const handler8 = context['activate'] && context['activate'].bind(owner, context['action']);
p7.on['click'] = function (e) {if (handler8) { handler8(e); } else { context.activate(action); }};
c7.push({text: \`link\`});
}
return vn1;
}"
@@ -2000,17 +2000,17 @@ exports[`t-on t-on with prevent modifier in t-foreach 1`] = `
context.project_index = i1;
context.project = _3[i1];
context.project_value = _4[i1];
var _5 = '#';
const nodeKey6 = context['project']
let c6 = [], p6 = {key:nodeKey6,attrs:{href: _5},on:{}};
var vn6 = h('a', p6, c6);
c1.push(vn6);
const handler7 = context['onEdit'] && context['onEdit'].bind(owner, context['project'].id);
p6.on['click'] = function (e) {e.preventDefault();if (handler7) { handler7(e); } else { context.onEdit(project.id); }};
c6.push({text: \` Edit \`});
var _8 = context['project'].name;
if (_8 || _8 === 0) {
c6.push({text: _8});
const nodeKey5 = context['project'];
var _6 = '#';
let c7 = [], p7 = {key:nodeKey5,attrs:{href: _6},on:{}};
var vn7 = h('a', p7, c7);
c1.push(vn7);
const handler8 = context['onEdit'] && context['onEdit'].bind(owner, context['project'].id);
p7.on['click'] = function (e) {e.preventDefault();if (handler8) { handler8(e); } else { context.onEdit(project.id); }};
c7.push({text: \` Edit \`});
var _9 = context['project'].name;
if (_9 || _9 === 0) {
c7.push({text: _9});
}
}
return vn1;
@@ -2207,22 +2207,22 @@ exports[`t-ref refs in a loop 1`] = `
context.item_index = i1;
context.item = _3[i1];
context.item_value = _4[i1];
const nodeKey5 = context['item']
let c5 = [], p5 = {key:nodeKey5};
var vn5 = h('div', p5, c5);
c1.push(vn5);
const ref6 = (context['item']);
p5.hook = {
const nodeKey5 = context['item'];
let c6 = [], p6 = {key:nodeKey5};
var vn6 = h('div', p6, c6);
c1.push(vn6);
const ref7 = (context['item']);
p6.hook = {
create: (_, n) => {
context.__owl__.refs[ref6] = n.elm;
context.__owl__.refs[ref7] = n.elm;
},
destroy: () => {
delete context.__owl__.refs[ref6];
delete context.__owl__.refs[ref7];
},
};
var _7 = context['item'];
if (_7 || _7 === 0) {
c5.push({text: _7});
var _8 = context['item'];
if (_8 || _8 === 0) {
c6.push({text: _8});
}
}
return vn1;
@@ -2383,16 +2383,16 @@ exports[`t-set t-set should reuse variable if possible 1`] = `
context.elem_index = i1;
context.elem = _4[i1];
context.elem_value = _5[i1];
const nodeKey6 = context['elem_index']
let c6 = [], p6 = {key:nodeKey6};
var vn6 = h('div', p6, c6);
c1.push(vn6);
let c7 = [], p7 = {key:7};
var vn7 = h('span', p7, c7);
c6.push(vn7);
c7.push({text: \`v\`});
const nodeKey6 = context['elem_index'];
let c7 = [], p7 = {key:nodeKey6};
var vn7 = h('div', p7, c7);
c1.push(vn7);
let c8 = [], p8 = {key:nodeKey6};
var vn8 = h('span', p8, c8);
c7.push(vn8);
c8.push({text: \`v\`});
if (_2 || _2 === 0) {
c7.push({text: _2});
c8.push({text: _2});
}
_2 = context['elem']
}
@@ -2415,6 +2415,73 @@ exports[`t-set value priority 1`] = `
}"
`;
exports[`translation support can translate node content 1`] = `
"function anonymous(context,extra
) {
let sibling = null;
var h = this.h;
let c1 = [], p1 = {key:1};
var vn1 = h('div', p1, c1);
c1.push({text: \`mot\`});
return vn1;
}"
`;
exports[`translation support does not translate node content if disabled 1`] = `
"function anonymous(context,extra
) {
let sibling = null;
var h = this.h;
let c1 = [], p1 = {key:1};
var vn1 = h('div', p1, c1);
let c2 = [], p2 = {key:2};
var vn2 = h('span', p2, c2);
c1.push(vn2);
c2.push({text: \`mot\`});
let c3 = [], p3 = {key:3};
var vn3 = h('span', p3, c3);
c1.push(vn3);
c3.push({text: \`word\`});
return vn1;
}"
`;
exports[`translation support some attributes are translated 1`] = `
"function anonymous(context,extra
) {
let sibling = null;
var h = this.h;
let c1 = [], p1 = {key:1};
var vn1 = h('div', p1, c1);
var _2 = 'mot';
let c3 = [], p3 = {key:3,attrs:{label: _2}};
var vn3 = h('p', p3, c3);
c1.push(vn3);
c3.push({text: \`mot\`});
var _4 = 'mot';
let c5 = [], p5 = {key:5,attrs:{title: _4}};
var vn5 = h('p', p5, c5);
c1.push(vn5);
c5.push({text: \`mot\`});
var _6 = 'mot';
let c7 = [], p7 = {key:7,attrs:{placeholder: _6}};
var vn7 = h('p', p7, c7);
c1.push(vn7);
c7.push({text: \`mot\`});
var _8 = 'mot';
let c9 = [], p9 = {key:9,attrs:{alt: _8}};
var vn9 = h('p', p9, c9);
c1.push(vn9);
c9.push({text: \`mot\`});
var _10 = 'word';
let c11 = [], p11 = {key:11,attrs:{something: _10}};
var vn11 = h('p', p11, c11);
c1.push(vn11);
c11.push({text: \`mot\`});
return vn1;
}"
`;
exports[`whitespace handling consecutives whitespaces are condensed into a single space 1`] = `
"function anonymous(context,extra
) {
+98 -11
View File
@@ -1,5 +1,6 @@
import { QWeb } from "../../src/qweb/index";
import { normalize, renderToDOM, renderToString, trim, nextTick } from "../helpers";
import { nextTick, normalize, renderToDOM, renderToString, trim } from "../helpers";
import { patch } from "../../src/vdom";
//------------------------------------------------------------------------------
// Setup and helpers
@@ -659,7 +660,7 @@ describe("t-call (template calling", () => {
`);
const expected = "<div><span>hey</span></div>";
expect(renderToString(qweb, "recursive")).toBe(expected);
const recursiveFn = Object.values(qweb.recursiveFns)[0];
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
expect(recursiveFn.toString()).toMatchSnapshot();
});
@@ -687,7 +688,7 @@ describe("t-call (template calling", () => {
expect(renderToString(qweb, "Parent", { root }, { fiber: { vars: {}, scope: {} } })).toBe(
expected
);
const recursiveFn = Object.values(qweb.recursiveFns)[0];
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
expect(recursiveFn.toString()).toMatchSnapshot();
});
@@ -714,7 +715,7 @@ describe("t-call (template calling", () => {
const expected =
"<div><div><p>a</p><div><p>b</p><div><p>d</p></div></div><div><p>c</p></div></div></div>";
expect(renderToString(qweb, "Parent", { root }, { fiber: {} })).toBe(expected);
const recursiveFn = Object.values(qweb.recursiveFns)[0];
const recursiveFn = Object.values(qweb.recursiveFns)[0] as any;
expect(recursiveFn.toString()).toMatchSnapshot();
});
@@ -837,6 +838,9 @@ describe("foreach", () => {
);
renderToString(qweb, "test");
expect(console.warn).toHaveBeenCalledTimes(1);
expect(console.warn).toHaveBeenCalledWith(
"Directive t-foreach should always be used with a t-key! (in template: 'test')"
);
console.warn = consoleWarn;
});
});
@@ -1044,8 +1048,8 @@ describe("t-on", () => {
qweb.addTemplate("test", `<button t-on-click="state.counter++">Click</button>`);
let owner = {
state: {
counter: 0,
},
counter: 0
}
};
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
expect(owner.state.counter).toBe(0);
@@ -1058,8 +1062,10 @@ describe("t-on", () => {
let owner = {
state: {
counter: 0,
incrementCounter: (inc) => { owner.state.counter += inc; },
},
incrementCounter: inc => {
owner.state.counter += inc;
}
}
};
const node = renderToDOM(qweb, "test", owner, { handlers: [] });
expect(owner.state.counter).toBe(0);
@@ -1223,7 +1229,7 @@ describe("t-on", () => {
);
const node = renderToDOM(qweb, "test", {}, { handlers: [] });
node.addEventListener('click', (e) => {
node.addEventListener("click", e => {
expect(e.defaultPrevented).toBe(true);
});
@@ -1303,12 +1309,12 @@ describe("t-ref", () => {
describe("loading templates", () => {
test("can initialize qweb with a string", () => {
const data = `
const templates = `
<?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">
<div t-name="hey">jupiler</div>
</templates>`;
const qweb = new QWeb(data);
const qweb = new QWeb({ templates });
expect(renderToString(qweb, "hey")).toBe("<div>jupiler</div>");
});
@@ -1517,3 +1523,84 @@ describe("properly support svg", () => {
);
});
});
describe("translation support", () => {
test("can translate node content", () => {
const translations = {
word: "mot"
};
const translateFn = expr => translations[expr] || expr;
const qweb = new QWeb({ translateFn });
qweb.addTemplate("test", "<div>word</div>");
expect(renderToString(qweb, "test")).toBe("<div>mot</div>");
});
test("does not translate node content if disabled", () => {
const translations = {
word: "mot"
};
const translateFn = expr => translations[expr] || expr;
const qweb = new QWeb({ translateFn });
qweb.addTemplate(
"test",
`
<div>
<span>word</span>
<span t-translation="off">word</span>
</div>`
);
expect(renderToString(qweb, "test")).toBe("<div><span>mot</span><span>word</span></div>");
});
test("some attributes are translated", () => {
const translations = {
word: "mot"
};
const translateFn = expr => translations[expr] || expr;
const qweb = new QWeb({ translateFn });
qweb.addTemplate(
"test",
`
<div>
<p label="word">word</p>
<p title="word">word</p>
<p placeholder="word">word</p>
<p alt="word">word</p>
<p something="word">word</p>
</div>`
);
expect(renderToString(qweb, "test")).toBe(
'<div><p label="mot">mot</p><p title="mot">mot</p><p placeholder="mot">mot</p><p alt="mot">mot</p><p something="word">mot</p></div>'
);
});
});
describe("t-key tests", () => {
test("t-key on t-foreach", async () => {
qweb.addTemplate(
"test",
`
<div>
<t t-foreach="things" t-as="thing" t-key="thing">
<span/>
</t>
</div>`
);
let vnode = qweb.render("test", { things: [1, 2] });
vnode = patch(document.createElement("div"), vnode);
let elm = vnode.elm as HTMLElement;
expect(elm.outerHTML).toBe("<div><span></span><span></span></div>");
const first = elm.querySelectorAll("span")[0];
const second = elm.querySelectorAll("span")[1];
patch(vnode, qweb.render("test", { things: [2, 1] }));
expect(elm.outerHTML).toBe("<div><span></span><span></span></div>");
expect(first).toBe(elm.querySelectorAll("span")[1]);
expect(second).toBe(elm.querySelectorAll("span")[0]);
});
});
@@ -11,35 +11,35 @@ exports[`RouteComponent can render simple cases 1`] = `
let result;
var h = this.h;
if (context['routeComponent']) {
const nodeKey1 = context['env'].router.currentRouteName;
//COMPONENT
let key3 = 'key' + context['env'].router.currentRouteName;
let templateId2 = \`__4__\` + key3;
let w2 = templateId2 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId2]] : false;
let templateId3 = \`__4__\` + nodeKey1;
let w3 = templateId3 in parent.__owl__.cmap ? parent.__owl__.children[parent.__owl__.cmap[templateId3]] : false;
let vn5 = {};
result = vn5;
let props2 = Object.assign({}, context['env'].router.currentParams);
if (w2 && w2.__owl__.currentFiber && !w2.__owl__.vnode) {
w2.destroy();
w2 = false;
let props3 = Object.assign({}, context['env'].router.currentParams);
if (w3 && w3.__owl__.currentFiber && !w3.__owl__.vnode) {
w3.destroy();
w3 = false;
}
if (w2) {
w2.__updateProps(props2, extra.fiber, undefined, undefined, sibling);
let pvnode = w2.__owl__.pvnode;
if (w3) {
w3.__updateProps(props3, extra.fiber, undefined, undefined, sibling);
let pvnode = w3.__owl__.pvnode;
utils.defineProxy(vn5, pvnode);
} else {
let componentKey2 = \`routeComponent\`;
let W2 = context.constructor.components[componentKey2] || QWeb.components[componentKey2]|| context['routeComponent'];
if (!W2) {throw new Error('Cannot find the definition of component \\"' + componentKey2 + '\\"')}
w2 = new W2(parent, props2);
parent.__owl__.cmap[templateId2] = w2.__owl__.id;
let def1 = w2.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId2, hook: {insert(vn) { let nvn=w2.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w2.destroy();}}});
const fiber = w2.__owl__.currentFiber;
def1.then(function () {if (w2.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
let componentKey3 = \`routeComponent\`;
let W3 = context.constructor.components[componentKey3] || QWeb.components[componentKey3]|| context['routeComponent'];
if (!W3) {throw new Error('Cannot find the definition of component \\"' + componentKey3 + '\\"')}
w3 = new W3(parent, props3);
parent.__owl__.cmap[templateId3] = w3.__owl__.id;
let def2 = w3.__prepare(extra.fiber, undefined, undefined, sibling);
let pvnode = h('dummy', {key: templateId3, hook: {insert(vn) { let nvn=w3.__mount(fiber, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w3.destroy();}}});
const fiber = w3.__owl__.currentFiber;
def2.then(function () {if (w3.__owl__.isDestroyed) {return;} const vnode = fiber.vnode; pvnode.sel = vnode.sel; });
utils.defineProxy(vn5, pvnode);
w2.__owl__.pvnode = pvnode;
w3.__owl__.pvnode = pvnode;
}
sibling = w2.__owl__.currentFiber || sibling;
sibling = w3.__owl__.currentFiber || sibling;
}
return result;
}"
+3 -2
View File
@@ -12,6 +12,7 @@ describe("Link component", () => {
beforeEach(() => {
fixture = makeTestFixture();
env = <RouterEnv>makeTestEnv();
Component.env = env;
});
afterEach(() => {
@@ -38,7 +39,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 +70,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");
+4 -3
View File
@@ -12,6 +12,7 @@ describe("RouteComponent", () => {
beforeEach(() => {
fixture = makeTestFixture();
env = <RouterEnv>makeTestEnv();
Component.env = env;
});
afterEach(() => {
@@ -45,7 +46,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 +73,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 +99,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>");
});
+8
View File
@@ -52,6 +52,14 @@ describe("router miscellaneous", () => {
expect(window.location.hash).toBe("#/users/5");
expect(env.qweb.forceUpdate).toHaveBeenCalledTimes(2);
});
test("navigate in hash mode preserve location", async () => {
router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }], { mode: "hash" });
window.history.pushState({}, "title", window.location.origin + "/test.html");
expect(window.location.href).toBe("http://localhost/test.html");
await router.navigate({ to: "users", params: { id: 3 } });
expect(window.location.href).toBe("http://localhost/test.html#/users/3");
});
});
describe("routeToPath", () => {
+25 -22
View File
@@ -12,6 +12,7 @@ describe("connecting a component to store", () => {
beforeEach(() => {
fixture = makeTestFixture();
env = makeTestEnv();
Component.env = env;
});
afterEach(() => {
@@ -37,7 +38,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 +70,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 +102,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 +135,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 +164,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 +199,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 +229,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 +258,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 +295,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 +348,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 +371,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 +402,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 +447,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 +514,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 +589,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 +640,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 +714,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 +788,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 +834,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 +871,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 +902,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 +921,7 @@ describe("various scenarios", () => {
beforeEach(() => {
fixture = makeTestFixture();
env = makeTestEnv();
Component.env = env;
});
afterEach(() => {
@@ -978,7 +980,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();
+2 -4
View File
@@ -15,8 +15,6 @@ class Counter extends owl.Component {
// Message Widget
//------------------------------------------------------------------------------
class Message extends owl.Component {
static components = { Counter };
shouldUpdate(nextProps) {
return nextProps.message !== this.props.message;
}
@@ -26,12 +24,11 @@ class Message extends owl.Component {
});
}
}
Message.components = { Counter };
//------------------------------------------------------------------------------
// Root Widget
//------------------------------------------------------------------------------
class App extends owl.Component {
static components = { Message };
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
mounted() {
@@ -137,6 +134,7 @@ class App extends owl.Component {
this.refs.log.innerHTML = "";
}
}
App.components = { Message };
//------------------------------------------------------------------------------
// Application initialization
+155
View File
@@ -0,0 +1,155 @@
import { buildData, startMeasure, stopMeasure, formatNumber } from "../shared/utils.js";
const { useState, useRef } = owl.hooks;
//------------------------------------------------------------------------------
// Likes Counter Widget
//------------------------------------------------------------------------------
class Counter extends owl.Component {
state = useState({ counter: 0 });
increment() {
this.state.counter++;
}
}
//------------------------------------------------------------------------------
// Message Widget
//------------------------------------------------------------------------------
class Message extends owl.Component {
static components = { Counter };
shouldUpdate(nextProps) {
return nextProps.message !== this.props.message;
}
removeMessage() {
this.trigger("remove-message", {
id: this.props.message.id
});
}
}
//------------------------------------------------------------------------------
// Root Widget
//------------------------------------------------------------------------------
class App extends owl.Component {
static components = { Message };
state = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
logRef = useRef("log");
mounted() {
this.log(`Benchmarking Owl v${owl.__info__.version} (build date: ${owl.__info__.date})`);
}
benchmark(message, fn, callback) {
if (this.state.multipleFlag) {
const N = 20;
let n = N;
let total = 0;
let cb = info => {
let finalize = () => {
n--;
total += info.delta;
if (n === 0) {
const avg = total / N;
this.log(`Average: ${formatNumber(avg)}ms`, true);
if (callback) {
callback();
}
} else {
this._benchmark(message, fn, cb);
}
};
if (this.state.clearAfterFlag) {
this._benchmark(
"clear",
() => {
this.state.messages = [];
},
finalize,
false
);
} else {
finalize();
}
};
this._benchmark(message, fn, cb);
} else {
this._benchmark(message, fn, callback);
}
}
_benchmark(message, fn, cb, log = true) {
setTimeout(() => {
startMeasure(message);
fn();
stopMeasure(info => {
if (log) {
this.log(info.msg);
}
if (cb) {
cb(info);
}
});
}, 10);
}
addMessages(n) {
this.benchmark("add " + n, () => {
const newMessages = buildData(n);
this.state.messages.push.apply(this.state.messages, newMessages);
});
}
clear() {
this._benchmark("clear", () => {
this.state.messages = [];
});
}
updateSomeMessages() {
this.benchmark("update every 10th", () => {
const messages = this.state.messages;
for (let i = 0; i < messages.length; i += 10) {
const msg = Object.assign({}, messages[i]);
msg.author += "!!!";
messages[i] = msg;
}
});
}
removeMessage(event) {
this.benchmark("remove message", () => {
const index = this.state.messages.findIndex(m => m.id === event.detail.id);
this.state.messages.splice(index, 1);
});
}
log(str, isBold) {
const div = document.createElement("div");
if (isBold) {
div.classList.add("bold");
}
div.textContent = `> ${str}`;
this.logRef.el.appendChild(div);
this.logRef.el.scrollTop = this.logRef.el.scrollHeight;
}
clearLog() {
this.logRef.el.innerHTML = "";
}
}
//------------------------------------------------------------------------------
// Application initialization
//------------------------------------------------------------------------------
async function start() {
const templates = await owl.utils.loadFile("templates.xml");
const env = {
qweb: new owl.QWeb(templates)
};
const app = new App(env);
app.mount(document.body);
}
start();
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OWL v0.24.0 Benchmark</title>
<link href="../shared/main.css" rel="stylesheet"/>
<script src='../../owl.js'></script>
</head>
<body>
<script src='app.js' type="module"></script>
</body>
</html>
+50
View File
@@ -0,0 +1,50 @@
<templates>
<div t-name="App" class="main">
<div class="left-thing">
<div class="title">Actions</div>
<div class="panel">
<button t-on-click="addMessages(100)">Add 100 messages</button>
<button t-on-click="addMessages(1000)">Add 1k messages</button>
<button t-on-click="addMessages(10000)">Add 10k messages</button>
<button t-on-click="addMessages(30000)">Add 30k messages</button>
<button t-on-click="updateSomeMessages">Update every 10th messages</button>
<button t-on-click="clear">Clear</button>
</div>
<div class="flags">
<div>
<input type="checkbox" id="multipleflag" t-model="state.multipleFlag"/>
<label for="multipleflag">Do it 20x</label>
</div>
<div>
<input type="checkbox" id="clearFlag" t-model="state.clearAfterFlag" />
<label for="clearFlag">Clear after</label>
</div>
</div>
<div class="info">Number of messages: <t t-esc="state.messages.length"/></div>
<hr/>
<div class="title">Log <span class="clear-log" t-on-click="clearLog">(clear)</span></div>
<div class="log">
<div class="log-content" t-ref="log"/>
</div>
</div>
<div class="right-thing">
<div class="content" t-on-remove-message="removeMessage">
<t t-foreach="state.messages" t-as="message">
<Message t-key="message.id" message="message"/>
</t>
</div>
</div>
</div>
<div t-name="Message" class="message">
<span class="author"><t t-esc="props.message.author"/></span>
<span class="msg"><t t-esc="props.message.msg"/></span>
<button class="remove" t-on-click="removeMessage">Remove</button>
<Counter/>
</div>
<div t-name="Counter">
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
</div>
</templates>
+5 -6
View File
@@ -16,8 +16,6 @@ class Counter extends owl.Component {
// Message Widget
//------------------------------------------------------------------------------
class Message extends owl.Component {
static components = { Counter };
shouldUpdate(nextProps) {
return nextProps.message !== this.props.message;
}
@@ -27,12 +25,12 @@ class Message extends owl.Component {
});
}
}
Message.components = { Counter };
//------------------------------------------------------------------------------
// Root Widget
//------------------------------------------------------------------------------
class App extends owl.Component {
static components = { Message };
state = useState({ messages: [], multipleFlag: false, clearAfterFlag: false });
logRef = useRef("log");
@@ -139,16 +137,17 @@ class App extends owl.Component {
this.logRef.el.innerHTML = "";
}
}
App.components = { Message };
//------------------------------------------------------------------------------
// Application initialization
//------------------------------------------------------------------------------
async function start() {
const templates = await owl.utils.loadFile("templates.xml");
const env = {
qweb: new owl.QWeb(templates)
App.env = {
qweb: new owl.QWeb({ templates })
};
const app = new App(env);
const app = new App();
app.mount(document.body);
}
+12 -10
View File
@@ -44,15 +44,17 @@ export function startMeasure(descr) {
export function stopMeasure(cb) {
let last = lastMeasure;
if (lastMeasure) {
window.setTimeout(function() {
lastMeasure = null;
const stop = performance.now();
const delta = stop - startTime;
const msg = `[${last}] took ${formatNumber(delta)}ms`;
console.log(msg);
if (cb) {
cb({ msg, delta });
}
}, 0);
window.requestAnimationFrame(() => {
window.setTimeout(function() {
lastMeasure = null;
const stop = performance.now();
const delta = stop - startTime;
const msg = `[${last}] took ${formatNumber(delta)}ms`;
console.log(msg);
if (cb) {
cb({ msg, delta });
}
}, 0);
});
}
}
+1
View File
@@ -40,6 +40,7 @@
<li><a href="benchmarks/owl-0.17.0">OWL 0.17.0</a></li>
<li><a href="benchmarks/owl-0.18.0">OWL 0.18.0</a></li>
<li><a href="benchmarks/owl-0.21.0">OWL 0.21.0</a></li>
<li><a href="benchmarks/owl-0.24.0">OWL 0.24.0</a></li>
<li><a href="benchmarks/owl-master">OWL Master</a></li>
</ul>
<ul>
+13 -3
View File
@@ -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.Component.env = { qweb };
}
${js}`;
script.innerHTML = content;
iframe.contentWindow.addEventListener("error", errorHandler);
iframe.contentWindow.addEventListener("unhandledrejection", errorHandler);
@@ -429,12 +436,15 @@ App.components = { TabbedEditor };
//------------------------------------------------------------------------------
async function start() {
document.title = `${document.title} (v${owl.__info__.version})`;
const commit = `https://github.com/odoo/owl/commit/${owl.__info__.hash}`;
console.info(`This application is using Owl built with the following commit:`, commit);
const [templates] = await Promise.all([
owl.utils.loadFile("templates.xml"),
owl.utils.whenReady()
]);
const qweb = new owl.QWeb(templates);
const app = new App({ qweb });
const qweb = new owl.QWeb({ templates });
owl.Component.env = { qweb };
const app = new App();
app.mount(document.body);
}
+27 -42
View File
@@ -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);
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);
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);
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);
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),
themeContext: themeContext,
};
const app = new App(env);
// Add the themeContext the environment to make it available to all components
App.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);
return { qweb, store };
return store;
}
const env = makeEnv();
const app = new TodoApp(env);
TodoApp.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),
};
setupResponsivePlugin(env);
setupResponsivePlugin(App.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);
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);
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);
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);
const windows = [
{
name: "Hello",
@@ -1558,8 +1543,8 @@ const windows = [
}
];
const env = { qweb, windows };
const app = new App(env);
App.env.windows = windows;
const app = new App();
app.mount(document.body);
`;
+1 -1
View File
@@ -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"