mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2701a7d861 | |||
| 3ebe985c3c | |||
| 1c0d4b5832 | |||
| 2840794fa2 | |||
| 710f42d4e4 | |||
| 45a2b0122d | |||
| 4c41f62364 | |||
| c2ab9774fb | |||
| 22e48e3be0 | |||
| 1ff3c32fe4 | |||
| 9a3e1ed99e | |||
| 438e2fbc2e | |||
| b3db085745 | |||
| b948c59c6d | |||
| 6426fe98f9 | |||
| 4dd9de349e | |||
| e1bcea77b5 | |||
| 2a19aeb6a3 | |||
| b53a34b7d1 | |||
| f881640d3d | |||
| 54c3dd76e4 | |||
| 7b887447da | |||
| 438b21df3f | |||
| d1094f647a | |||
| 49baf0de6e | |||
| b14d069ee7 | |||
| e14a4fe338 | |||
| 1f9ec46236 | |||
| 1464a3631b |
+1
-1
@@ -23,4 +23,4 @@ package-lock.json
|
||||
node_modules
|
||||
|
||||
# Extras temp file
|
||||
/extras/owl.js
|
||||
/tools/owl.js
|
||||
@@ -59,8 +59,8 @@ More interesting examples can be found on the [playground](https://odoo.github.i
|
||||
|
||||
If you want to use a simple `<script>` tag, the last release can be downloaded here:
|
||||
|
||||
- [owl-0.13.0.js](https://github.com/odoo/owl/releases/download/v0.13.0/owl.js)
|
||||
- [owl-0.13.0.min.js](https://github.com/odoo/owl/releases/download/v0.13.0/owl.min.js)
|
||||
- [owl-0.14.0.js](https://github.com/odoo/owl/releases/download/v0.14.0/owl.js)
|
||||
- [owl-0.14.0.min.js](https://github.com/odoo/owl/releases/download/v0.14.0/owl.min.js)
|
||||
|
||||
Some npm scripts are available:
|
||||
|
||||
@@ -71,8 +71,8 @@ Some npm scripts are available:
|
||||
| `npm run minify` | minify the prebuilt owl.js file |
|
||||
| `npm run test` | run all tests |
|
||||
| `npm run test:watch` | run all tests, and keep a watcher |
|
||||
| `npm run extras` | build extras applications, start a static server (see [here](extras/readme.md)) |
|
||||
| `npm run extras:watch` | same as `extras`, but with a watcher to rebuild owl |
|
||||
| `npm run tools` | build tools applications, start a static server (see [here](doc/tooling.md)) |
|
||||
| `npm run tools:watch` | same as `tools`, but with a watcher to rebuild owl |
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ keyboard) the button.
|
||||
A more complex situation occurs when we want to transition an element in or out
|
||||
of the page. For example, we may want a fade-in and fade-out effect.
|
||||
|
||||
The `t-transition` directive is here to help us (see [QWeb documentation](qweb.md#t-transition-directive)).
|
||||
The `t-transition` directive is here to help us. It works on html elements and
|
||||
on components, by adding and removing some css classes.
|
||||
|
||||
To perform useful transition effects, whenever an element appears or disappears,
|
||||
it is necessary to add/remove some css style or class at some precise moment in
|
||||
|
||||
+66
-25
@@ -14,7 +14,8 @@
|
||||
- [`t-key` directive](#t-key-directive)
|
||||
- [`t-mounted` directive](#t-mounted-directive)
|
||||
- [Props Validation](#props-validation)
|
||||
- [Keeping References](#keeping-references])
|
||||
- [Keeping References](#keeping-references)
|
||||
- [Slots](#slots)
|
||||
- [Asynchronous rendering](#asynchronous-rendering)
|
||||
|
||||
## Overview
|
||||
@@ -146,11 +147,6 @@ find a template with the component name (or one of its ancestor).
|
||||
if we have a `isMobile` key in the environment, to decide if we want a mobile
|
||||
interface or a destkop one.
|
||||
|
||||
- **`set(target, key, value)`**. This method is necessary in some cases when we
|
||||
need to modify the state of the component in a way that is not visible to the
|
||||
observer (see [observer's technical limitations](observer.md#technical-limitations)).
|
||||
For example, if we need to add a key to the state.
|
||||
|
||||
- **`destroy()`**. As its name suggests, this method will remove the component,
|
||||
and perform all necessary cleanup, such as unmounting the component, its children,
|
||||
removing the parent/children relationship. This method should almost never be
|
||||
@@ -165,13 +161,13 @@ a owl component:
|
||||
|
||||
| Method | Description |
|
||||
| ------------------------------------------------ | ----------------------------------------------------- |
|
||||
| **[constructor](#constructor)** | constructor |
|
||||
| **[willStart](#willStart)** | async, before first rendering |
|
||||
| **[constructor](#constructorparent-props)** | constructor |
|
||||
| **[willStart](#willstart)** | async, before first rendering |
|
||||
| **[mounted](#mounted)** | just after component is rendered and added to the DOM |
|
||||
| **[willUpdateProps](#willupdatepropsnextprops)** | async, before props update |
|
||||
| **[willPatch](#willpatch)** | just before the DOM is patched |
|
||||
| **[patched](#patchedsnapshot)** | just after the DOM is patched |
|
||||
| **[willUnmount](#willUnmount)** | just before removing component from DOM |
|
||||
| **[willUnmount](#willunmount)** | just before removing component from DOM |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -375,11 +371,11 @@ Note that there are some restrictions on prop names: `class`, `style` and any
|
||||
string which starts with `t-` are not allowed.
|
||||
|
||||
The `t-widget` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](#dynamic-attributes-t-att-and-t-attf-directives) directive):
|
||||
(like the [`t-attf-`](qweb.md#dynamic-attributes) directive):
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="ChildWidget#{id}"/>
|
||||
<t t-widget="ChildWidget{{id}}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
@@ -390,14 +386,6 @@ class ParentWidget {
|
||||
}
|
||||
```
|
||||
|
||||
Similarly to `t-attf-`, there is an alternate form of string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-name="ParentWidget">
|
||||
<t t-widget="ChildWidget{{id}}"/>
|
||||
</div>
|
||||
```
|
||||
|
||||
**CSS and style:** there is some specific support to allow the parent to declare
|
||||
additional css classes or style for the sub widget: css declared in `class`, `style`, `t-att-class` or `t-att-style` will be added to the
|
||||
root widget element.
|
||||
@@ -749,23 +737,76 @@ Note: if used on a component, the reference will be set in the `refs`
|
||||
variable between `willPatch` and `patched`.
|
||||
|
||||
The `t-ref` directive also accepts dynamic values with string interpolation
|
||||
(like the [`t-attf-`](#dynamic-attributes-t-att-and-t-attf-directives) and
|
||||
[`t-widget-`](#component-t-widget) directives). For example, if we have
|
||||
(like the [`t-attf-`](qweb.md#dynamic-attributes) and
|
||||
`t-widget` directives). For example, if we have
|
||||
`id` set to 44 in the rendering context,
|
||||
|
||||
```xml
|
||||
<div t-ref="widget_#{id}"/>
|
||||
<div t-ref="widget_{{id}}"/>
|
||||
```
|
||||
|
||||
```js
|
||||
this.refs.widget_44;
|
||||
```
|
||||
|
||||
Similarly to `t-attf-` and `t-widget`, there is an alternate form of string
|
||||
interpolation:
|
||||
### Slots
|
||||
|
||||
To make generic components, it is useful to be able for a parent widget to *inject*
|
||||
some sub template, but still be the owner. For example, a generic dialog widget
|
||||
will need to render some content, some footer, but with the parent as the
|
||||
rendering context.
|
||||
|
||||
This is what *slots* are for.
|
||||
|
||||
```xml
|
||||
<div t-ref="widget_{{id}}"/>
|
||||
<div t-name="Dialog" class="modal">
|
||||
<div class="modal-title"><t t-esc="props.title"/></div>
|
||||
<div class="modal-content">
|
||||
<t t-slot="content"/>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<t t-slot="footer"/>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
Slots are defined by the caller, with the `t-set` directive:
|
||||
|
||||
```xml
|
||||
<div t-name="SomeWidget">
|
||||
<div>some widget</div>
|
||||
<t t-widget="Dialog" title="Some Dialog">
|
||||
<t t-set="content">
|
||||
<div>hey</div>
|
||||
</t>
|
||||
<t t-set="footer">
|
||||
<button t-on-click="doSomething">ok</button>
|
||||
</t>
|
||||
</t>
|
||||
</div>
|
||||
```
|
||||
|
||||
In this example, the widget `Dialog` will render the slots `content` and `footer`
|
||||
with its parent as rendering context. This means that clicking on the button
|
||||
will execute the `doSomething` method on the parent, not on the dialog.
|
||||
|
||||
Warning! Slots have a technical constraint: the result of the slot rendering
|
||||
should have exactly one root node. So,
|
||||
|
||||
```xml
|
||||
<t t-set="content">
|
||||
<div>A</div>
|
||||
<div>B</div>
|
||||
</t>
|
||||
```
|
||||
|
||||
is not allowed. A workaround could be to wrap the content in a div:
|
||||
|
||||
```xml
|
||||
<div t-set="content">
|
||||
<div>A</div>
|
||||
<div>B</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Asynchronous rendering
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# 🦉 Event Bus 🦉
|
||||
|
||||
It is sometimes useful to use a `Bus` to communicate informations between various
|
||||
parts of the code. Owl has a very simple bus class, which manages subscriptions,
|
||||
triggering events, and callbacks.
|
||||
|
||||
```js
|
||||
const bus = new owl.EventBus();
|
||||
|
||||
bus.on("some-event", null, function(...args) {
|
||||
console.log(...args);
|
||||
});
|
||||
|
||||
bus.trigger("some-event", 1, 2, 3);
|
||||
// [1,2,3] will be logged to the console
|
||||
```
|
||||
|
||||
Its API is:
|
||||
|
||||
| Method | Description |
|
||||
| -------------------------------- | --------------------------------- |
|
||||
| `on(eventType, owner, callback)` | add a listener |
|
||||
| `off(eventType, owner)` | remove all listeners for an owner |
|
||||
| `trigger(eventType, ...args)` | trigger an event |
|
||||
| `clear` | remove all subscriptions |
|
||||
|
||||
Note that the [`Store`](store.md) is an example of an `EventBus`.
|
||||
+17
-21
@@ -20,35 +20,31 @@ obj.a.b = 2;
|
||||
## Technical Limitations
|
||||
|
||||
Since the observer uses getters and setters, it is actually unable to react to
|
||||
changes in two situations:
|
||||
changes in three situations:
|
||||
|
||||
- adding a key to an object:
|
||||
- adding a key to an object
|
||||
- deleting a key from an object
|
||||
- modifying an array by setting a new value at a given index
|
||||
|
||||
In those situations, we need a way to tell the observer that something happened.
|
||||
This can be done by using the `set` and `delete` (only for objects) static
|
||||
methods of the `Observer`.
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const obj = { a: 1 };
|
||||
observer.observe(obj);
|
||||
obj.b = 2; // will do nothing
|
||||
obj.b = 2; // won't notify the change
|
||||
owl.Observer.set(obj, "b", 2); // will notify the change
|
||||
|
||||
delete obj.b; // won't notify the change
|
||||
owl.Observer.delete(obj, "b"); // will notify the change
|
||||
```
|
||||
|
||||
In that case, we need a way to tell the observer that something happened.
|
||||
This can be done by using the `set` method:
|
||||
|
||||
```javascript
|
||||
observer.set(obj, "b", 2);
|
||||
```
|
||||
|
||||
- modifying an array by setting a new value at a given index:
|
||||
|
||||
```javascript
|
||||
const observer = new owl.Observer();
|
||||
const obj = { todos: [{ id: 1, text: "todo" }] };
|
||||
observer.observe(obj);
|
||||
obj[0] = { id: 2, text: "othertodo" }; // will do nothing, and obj[0] is not observed
|
||||
```
|
||||
|
||||
In that case, the solution is the same, we can simply use the `set` method:
|
||||
|
||||
```javascript
|
||||
observer.set(obj, 0, { id: 2, text: "othertodo" });
|
||||
const arr = ["a"];
|
||||
observer.observe(arr);
|
||||
arr[0] = "b"; // won't notify the change
|
||||
owl.Observer.set(arr, 0, "b"); // will notify the change
|
||||
```
|
||||
|
||||
+17
-20
@@ -5,7 +5,7 @@
|
||||
- [Overview](#overview)
|
||||
- [Directives](#directives)
|
||||
- [QWeb Engine](#qweb-engine)
|
||||
- [Reference](#qweb-specification)
|
||||
- [Reference](#reference)
|
||||
- [White spaces](#white-spaces)
|
||||
- [Root nodes](#root-nodes)
|
||||
- [Expression evaluation](#expression-evaluation)
|
||||
@@ -72,7 +72,8 @@ needs. Here is a list of all Owl specific directives:
|
||||
| `t-key` | [Defining a key (to help virtual dom reconciliation)](component.md#t-key-directive) |
|
||||
| `t-on-*` | [Event handling](component.md#event-handling) |
|
||||
| `t-transition` | [Defining an animation](animations.md#css-transitions) |
|
||||
| `t-mounted` | [Callback when a node or component is mounted](#component.md#t-mounted-directive) |
|
||||
| `t-mounted` | [Callback when a node or component is mounted](component.md#t-mounted-directive) |
|
||||
| `t-slot` | [Rendering a slot](component.md#slots) |
|
||||
|
||||
## QWeb Engine
|
||||
|
||||
@@ -175,9 +176,15 @@ root nodes.
|
||||
|
||||
### Expression evaluation
|
||||
|
||||
It is useful to explain the various rules that applies on QWeb expressions. These
|
||||
expressions are strings that will be converted to a javascript expression at
|
||||
compile time.
|
||||
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
|
||||
widget). For example, `a + b.c(d)` will be converted into:
|
||||
|
||||
```js
|
||||
context["a"] + context["b"].c(context["d"]);
|
||||
```
|
||||
|
||||
It is useful to explain the various rules that applies on these expressions:
|
||||
|
||||
1. it should be a simple expression which returns a value. It cannot be a statement.
|
||||
|
||||
@@ -191,10 +198,10 @@ compile time.
|
||||
<div><p t-if="console.log(1)">NOT valid</p></div>
|
||||
```
|
||||
|
||||
2. it can use anything in the rendering context:
|
||||
2. it can use anything in the rendering context (typically, the component):
|
||||
|
||||
```xml
|
||||
<p t-if="user.birthday == today()">Happy bithday!</p>
|
||||
<p t-if="user.birthday === today()">Happy bithday!</p>
|
||||
```
|
||||
|
||||
is valid, and will read the `user` object from the context, and call the
|
||||
@@ -357,13 +364,6 @@ If an expression evaluates to a falsy value, it will not be set at all:
|
||||
There is another way to format a string attribute: the `t-attf-` directive. With
|
||||
it, you get string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a #{value1} is #{value2} of #{value3} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
```
|
||||
|
||||
For historical reason, there is an alternate form of string interpolation:
|
||||
|
||||
```xml
|
||||
<div t-attf-foo="a {{value1}} is {{value2}} of {{value3}} ]"/>
|
||||
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
|
||||
@@ -399,9 +399,8 @@ Like conditions, `t-foreach` applies to the element bearing the directive’s at
|
||||
|
||||
is equivalent to the previous example.
|
||||
|
||||
`t-foreach` can iterate on an array (the current item will be the current value),
|
||||
an object (the current item will be the current key) or an integer (equivalent
|
||||
to iterating on an array between 0 inclusive and the provided integer exclusive).
|
||||
`t-foreach` can iterate on an array (the current item will be the current value)
|
||||
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
|
||||
@@ -415,8 +414,6 @@ passed to `t-as`):
|
||||
- `$as_last`: whether the current item is the last of the iteration
|
||||
(equivalent to `$as_index + 1 == $as_size`), requires the iteratee’s size be
|
||||
available
|
||||
- `$as_parity` (deprecated): either "even" or "odd", the parity of the current
|
||||
iteration round
|
||||
|
||||
These extra variables provided and all new variables created into the `t-foreach`
|
||||
are only available in the scope of the `t-foreach`. If the variable exists outside
|
||||
@@ -427,7 +424,7 @@ into the global context.
|
||||
<t t-set="existing_variable" t-value="False"/>
|
||||
<!-- existing_variable now False -->
|
||||
|
||||
<p t-foreach="[1, 2, 3]" t-as="i">
|
||||
<p t-foreach="Array(3)" t-as="i">
|
||||
<t t-set="existing_variable" t-value="True"/>
|
||||
<t t-set="new_variable" t-value="True"/>
|
||||
<!-- existing_variable and new_variable now True -->
|
||||
|
||||
+10
-5
@@ -3,15 +3,20 @@
|
||||
|
||||
## Reference
|
||||
|
||||
- [Animations](animations.md)
|
||||
- [Component](component.md)
|
||||
- [Event Bus](event_bus.md)
|
||||
- [Observer](observer.md)
|
||||
- [QWeb](qweb.md)
|
||||
- [Store](store.md)
|
||||
- [Observer](observer.md)
|
||||
- [Virtual DOM](vdom.md)
|
||||
- [Utils](utils.md)
|
||||
- [Virtual DOM](vdom.md)
|
||||
|
||||
## Learning resources
|
||||
|
||||
- [Quick Start](quick_start.md)
|
||||
|
||||
## Miscellaneous
|
||||
- [Quick Start](quick_start.md)
|
||||
- [Animations](animations.md)
|
||||
- [Tooling](tooling.md)
|
||||
|
||||
- [Comparison with React/Vue](comparison.md)
|
||||
- [Tooling](tooling.md)
|
||||
|
||||
+58
-4
@@ -28,7 +28,7 @@ Note: Owl's store is inspired by React Redux and VueX.
|
||||
|
||||
## Example
|
||||
|
||||
Here is what a simple store look like:
|
||||
Here is what a simple store looks like:
|
||||
|
||||
```js
|
||||
const actions = {
|
||||
@@ -63,12 +63,12 @@ store.dispatch('addTodo', 'fix all bugs');
|
||||
|
||||
## Reference
|
||||
|
||||
The store is a simple `owl.EventBus` that triggers `update` events whenever its
|
||||
The store is a simple [`owl.EventBus`](event_bus.md) that triggers `update` events whenever its
|
||||
state is changed. Note that these events are triggered only after a microtask
|
||||
tick, so only one event will be triggered for any number of state changes in a
|
||||
call stack.
|
||||
|
||||
Also, it is important to mention that the state is observed (with a `owl.Observer`),
|
||||
Also, it is important to mention that the state is observed (with an `owl.Observer`),
|
||||
which is the reason why it is able to know if it was changed. This implies that
|
||||
state changes need to be done carefully in some cases (adding a new key to an
|
||||
object, or modifying an array with the `arr[i] = newValue` syntax). See the
|
||||
@@ -146,4 +146,58 @@ const post = store.getters.getPost(id);
|
||||
|
||||
### Connecting a component
|
||||
|
||||
Todo
|
||||
By default, an Owl `Component` is not connected to any store. The `connect`
|
||||
function is there to create sub Components that are connected versions of
|
||||
Components.
|
||||
|
||||
```javascript
|
||||
const actions = {
|
||||
increment({commit}) {
|
||||
commit('increment', 1);
|
||||
}
|
||||
};
|
||||
const mutations = {
|
||||
increment({state}, val) {
|
||||
state.counter += val;
|
||||
}
|
||||
};
|
||||
const state = {
|
||||
counter: 0,
|
||||
};
|
||||
const store = new owl.Store({state, actions, mutations});
|
||||
|
||||
class Counter extends owl.Component {
|
||||
increment() {
|
||||
this.env.store.dispatch('increment');
|
||||
}
|
||||
}
|
||||
function mapStoreToProps(state) {
|
||||
return {
|
||||
value: state.counter
|
||||
};
|
||||
}
|
||||
const ConnectedCounter = owl.connect(Counter, mapStoreToProps);
|
||||
|
||||
const counter = new ConnectedCounter({ store, qweb });
|
||||
```
|
||||
```xml
|
||||
<button t-name="Counter" t-on-click="increment">
|
||||
Click Me! [<t t-esc="props.value"/>]
|
||||
</button>
|
||||
```
|
||||
|
||||
The arguments of `connect` are:
|
||||
- `Counter`: an owl `Component` to connect
|
||||
- `mapStoreToProps`: a function that extracts the `props` of the Component
|
||||
from the `state` of the `Store` and returns them as a dict
|
||||
- `options`: dictionary of optional parameters that may contain
|
||||
- `getStore`: a function that takes the `env` in arguments and returns an
|
||||
instance of `Store` to connect to (if not given, connects to `env.store`)
|
||||
- `hashFunction`: the function to use to detect changes in the state (if not
|
||||
given, generates a function that uses revision numbers, incremented at
|
||||
each state change)
|
||||
- `deep`: [only useful if no hashFunction is given] if false, only watch
|
||||
for top level state changes (true by default)
|
||||
|
||||
The `connect` function returns a sub class of the given `Component` which is
|
||||
connected to the `store`.
|
||||
|
||||
+43
-6
@@ -1,18 +1,55 @@
|
||||
# 🦉 Tooling 🦉
|
||||
|
||||
## Development mode
|
||||
## Content
|
||||
|
||||
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
|
||||
- [Overview](#overview)
|
||||
- [Development Mode](#development-mode)
|
||||
- [Playground](#playground)
|
||||
- [Benchmarks](#benchmarks)
|
||||
|
||||
## Overview
|
||||
|
||||
To help work with/improve/learn OWL, there are a few extras tools/settings.
|
||||
|
||||
- development mode: enable better error reporting for the developer
|
||||
- a playground application: a space to experiment and learn Owl.
|
||||
- a benchmarks application: allow comparison with a few common frameworks
|
||||
|
||||
The two applications are available in the `tools/` folder, and can be accessed
|
||||
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
|
||||
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';
|
||||
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.
|
||||
So, changing this setting is best done at startup.
|
||||
|
||||
## Playground
|
||||
|
||||
The playground is an important application designed to help learning and
|
||||
experimenting with Owl. The last published version of Owl can be tested [online](https://odoo.github.io/owl/playground/).
|
||||
|
||||
It is an application similar to `jsFiddle`, but specialized for Owl: there are
|
||||
three tabs (`js`, `css` and `xml`), and a simple button `Run` to execute that
|
||||
code in an iframe.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Note: This is more an internal tool, useful for people working on Owl.
|
||||
|
||||
The benchmarks application is a very small application, implemented in different
|
||||
frameworks, and in different versions of Owl. This is a simple internal tool,
|
||||
useful to compare various performance metrics on some tasks.
|
||||
|
||||
+40
-14
@@ -5,35 +5,61 @@ functions are all available in the `owl.utils` namespace.
|
||||
|
||||
## Content
|
||||
|
||||
- [`whenReady`](#whenready)
|
||||
- [`loadJS`](#loadjs)
|
||||
- [`loadTemplates`](#loadtemplates)
|
||||
- [`escape`](#escape)
|
||||
- [`debounce`](#debounce)
|
||||
- [`whenReady`](#whenready): executing code when DOM is ready
|
||||
- [`loadJS`](#loadjs): loading script files
|
||||
- [`loadTemplates`](#loadtemplates): loading xml files
|
||||
- [`escape`](#escape): sanitizing strings
|
||||
- [`debounce`](#debounce): limiting rate of function calls
|
||||
|
||||
## `whenReady`
|
||||
|
||||
The function `whenReady` is useful to register some code that need to be executed
|
||||
as soon as the document (page) is ready:
|
||||
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
|
||||
not ready yet, resolved directly otherwise). If called with a callback as
|
||||
argument, it executes it as soon as the DOM ready (or directly).
|
||||
|
||||
```js
|
||||
owl.utils.whenReady(function () {
|
||||
Promise.all([loadTemplates(), owl.utils.whenReady()]).then(function ([templates]) {
|
||||
const qweb = new owl.QWeb(templates);
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
owl.utils.whenReady(function() {
|
||||
const qweb = new owl.QWeb();
|
||||
const app = new App({ qweb });
|
||||
app.mount(document.body);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## `loadJS`
|
||||
|
||||
`loadJS` takes a url (string) for a javascript resource, and loads it. It returns
|
||||
a promise, so the caller can properly react when it is ready. Also, it is smart:
|
||||
it maintains a list of urls previously loaded (or currently being loaded), and
|
||||
prevent doing twice the work.
|
||||
|
||||
```js
|
||||
class MyComponent extends owl.Component {
|
||||
willStart() {
|
||||
return owl.utils.loadJS('/static/libs/someLib.js');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `loadTemplates`
|
||||
|
||||
```js
|
||||
async function makeEnv() {
|
||||
const templates = await owl.utils.loadTemplates('templates.xml');
|
||||
const qweb = new owl.QWeb(templates);
|
||||
return { qweb };
|
||||
}
|
||||
```
|
||||
|
||||
## `escape`
|
||||
|
||||
|
||||
## `debounce`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+19
-1
@@ -1,3 +1,21 @@
|
||||
# 🦉 VDom 🦉
|
||||
|
||||
Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
|
||||
Owl is a declarative component system: we declare the structure of the component
|
||||
tree, and Owl will translate that to a list of imperative operations. This
|
||||
translation is done by a virtual dom. This is the low level layer of Owl, most
|
||||
developer will not need to call directly the virtual dom functions.
|
||||
|
||||
|
||||
The main idea behind a virtual dom is to keep a in-memory representation of the
|
||||
DOM (called a virtual node), and whenever some change is needed, to regenerate
|
||||
a new representation, compute the difference between the old and the new, then
|
||||
apply the changes.
|
||||
|
||||
`vdom` exports two functions:
|
||||
|
||||
- `h`: create a new virtual node
|
||||
- `patch`: compare two virtual nodes, and apply the difference.
|
||||
|
||||
Note: Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
|
||||
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="message_count">
|
||||
Number of msg: 0
|
||||
</div>
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1000 messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10000 messages</button>
|
||||
<button class="o_btn_msg 50000">Add 50000 messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove" >Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,30 +0,0 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="message_count">
|
||||
Number of msg: 0
|
||||
</div>
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1000 messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10000 messages</button>
|
||||
<button class="o_btn_msg 50000">Add 50000 messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove" >Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,85 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure('remove message');
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,84 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
template = "counter";
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
template = "message";
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
template = "root";
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="root" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,81 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [] };
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.state.messages = [];
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += '!!!';
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,32 +0,0 @@
|
||||
<templates>
|
||||
<div t-name="App" class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: <t t-esc="state.messages.length"/></div>
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button t-on-click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th message</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<t t-foreach="state.messages" t-as="message">
|
||||
<t t-widget="Message" t-key="message.id" message="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -1,221 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
counter: 0
|
||||
};
|
||||
this.increment = this.increment.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
null,
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: this.increment
|
||||
},
|
||||
"Value: ",
|
||||
this.state.counter
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.setState({
|
||||
counter: this.state.counter + 1
|
||||
});
|
||||
}
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "message"
|
||||
},
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "author"
|
||||
},
|
||||
this.props.message.author
|
||||
),
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "msg"
|
||||
},
|
||||
this.props.message.msg
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
className: "remove",
|
||||
onClick: this.removeMessage
|
||||
},
|
||||
"Remove"
|
||||
),
|
||||
React.createElement(Counter, null)
|
||||
);
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.props.removeCB(this.props.message.id);
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Main extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
messages: []
|
||||
};
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
const msgList = this.state.messages.map(m =>
|
||||
React.createElement(Message, {
|
||||
key: m.id,
|
||||
message: m,
|
||||
removeCB: this.removeMessage
|
||||
})
|
||||
);
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "main"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "left-thing"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
null,
|
||||
"Number of msg: ",
|
||||
this.state.messages.length
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(100)
|
||||
},
|
||||
"Add 100 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(1000)
|
||||
},
|
||||
"Add 1000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(10000)
|
||||
},
|
||||
"Add 10000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(50000)
|
||||
},
|
||||
"Add 50000 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.updateSomeMessages()
|
||||
},
|
||||
"Update every 10th messags"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.clear()
|
||||
},
|
||||
"Clear"
|
||||
)
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "right-thing"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "content"
|
||||
},
|
||||
msgList
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = this.state.messages.concat(buildData(n));
|
||||
this.setState({
|
||||
messages: newMessages
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.setState({
|
||||
messages: []
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
this.forceUpdate();
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === id);
|
||||
const messages = this.state.messages.slice();
|
||||
messages.splice(index, 1);
|
||||
this.setState({
|
||||
messages
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
} //-----------------------------
|
||||
// INIT
|
||||
//-----------------------------
|
||||
|
||||
ReactDOM.render(
|
||||
React.createElement(Main, null),
|
||||
document.getElementById("main")
|
||||
);
|
||||
@@ -1,42 +0,0 @@
|
||||
.main {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
}
|
||||
|
||||
.left-thing {
|
||||
background-color: gray;
|
||||
padding: 20px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.left-thing button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.right-thing {
|
||||
padding: 20px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* Message widget */
|
||||
.message .author {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.message {
|
||||
width: 400px;
|
||||
background-color: lightblue;
|
||||
margin: 10px 5px;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.remove {
|
||||
float: right;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("likes-counter", {
|
||||
data: function() {
|
||||
return {
|
||||
counter: 0
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
increment() {
|
||||
this.counter++;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div>
|
||||
<button @click="increment">Value: {{counter}}</button>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("my-message", {
|
||||
props: ["msg"],
|
||||
methods: {
|
||||
removeMessage() {
|
||||
this.$emit("removeMessage", this.msg.id);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="message">
|
||||
<span class="author">{{msg.author}}</span>
|
||||
<span class="msg">{{msg.msg}}</span>
|
||||
<button class="remove" @click="removeMessage">Remove</button>
|
||||
<likes-counter></likes-counter>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
const App = {
|
||||
name: "App",
|
||||
data() {
|
||||
return { messages: [] };
|
||||
},
|
||||
methods: {
|
||||
addMessages(n) {
|
||||
startMeasure("add " + n);
|
||||
const newMessages = buildData(n);
|
||||
this.messages.push.apply(this.messages, newMessages);
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
clear() {
|
||||
startMeasure("clear");
|
||||
this.messages = [];
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
updateSomeMessages() {
|
||||
startMeasure("update every 10th");
|
||||
const messages = this.messages;
|
||||
for (let i = 0; i < this.messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.messages.findIndex(m => m.id === id);
|
||||
this.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="main">
|
||||
<div class="left-thing">
|
||||
<div>Number of msg: {{messages.length}}</div>
|
||||
<button @click="addMessages(100)">Add 100 messages</button>
|
||||
<button @click="addMessages(1000)">Add 1000 messages</button>
|
||||
<button @click="addMessages(10000)">Add 10000 messages</button>
|
||||
<button @click="addMessages(50000)">Add 50000 messages</button>
|
||||
<button @click="updateSomeMessages">Update every 10th message</button>
|
||||
<button @click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<my-message v-for="msg in messages" v-bind:key="msg.id" v-bind:msg="msg" @removeMessage="removeMessage"></my-message>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
new Vue({
|
||||
render: h => h(App)
|
||||
}).$mount(`#main`);
|
||||
@@ -1,21 +0,0 @@
|
||||
# 🦉 Extra Stuff 🦉
|
||||
|
||||
To help work/improve/learn with OWL, we have here:
|
||||
|
||||
- a benchmarks application
|
||||
- a playground application
|
||||
|
||||
Both of them can be accessed 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 extras` (and its version with a watcher: `npm run extras:watch`).
|
||||
|
||||
## Benchmarks
|
||||
|
||||
The benchmarks application is a very small application, implemented in different
|
||||
frameworks, and in different versions of Owl. This is a simple internal tool,
|
||||
useful to compare various performance metrics on some tasks.
|
||||
|
||||
## Playground
|
||||
|
||||
The playground is an important application designed to help learning and
|
||||
experimenting with Owl. It is available [online](https://odoo.github.io/owl/playground/).
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "owl",
|
||||
"version": "0.13.0",
|
||||
"version": "0.14.0",
|
||||
"description": "Odoo Web Library (OWL)",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
@@ -10,10 +10,10 @@
|
||||
"minify": "uglifyjs dist/owl.js -o dist/owl.min.js --compress --mangle",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"extras:serve": "python3 extras/server.py || python extras/server.py",
|
||||
"extras": "npm run build && npm run extras:serve",
|
||||
"preextras:watch": "npm run build",
|
||||
"extras:watch": "npm-run-all --parallel extras:serve \"build:* -- --watch\""
|
||||
"tools:serve": "python3 tools/server.py || python tools/server.py",
|
||||
"tools": "npm run build && npm run tools:serve",
|
||||
"pretools:watch": "npm run build",
|
||||
"tools:watch": "npm-run-all --parallel tools:serve \"build:* -- --watch\""
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -340,14 +340,6 @@ export class Component<T extends Env, Props extends {}, State extends {}> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a key (from the state) to a specific value. This is mostly useful to
|
||||
* work around the limitation in observed value with new keys.
|
||||
*/
|
||||
set(target: any, key: string | number, value: any) {
|
||||
this.__owl__.observer!.set(target, key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a custom event of type 'eventType' with the given 'payload' on the
|
||||
* component's el, if it exists. However, note that the event will only bubble
|
||||
|
||||
+37
-2
@@ -76,6 +76,24 @@ export class Observer {
|
||||
allowMutations: boolean = true;
|
||||
dirty: boolean = false;
|
||||
|
||||
static set(target: any, key: number | string, value: any) {
|
||||
if (!target.__owl__) {
|
||||
throw Error(
|
||||
"`Observer.set()` can only be called with observed Objects or Arrays"
|
||||
);
|
||||
}
|
||||
target.__owl__.observer.set(target, key, value);
|
||||
}
|
||||
|
||||
static delete(target: any, key: number | string) {
|
||||
if (!target.__owl__) {
|
||||
throw Error(
|
||||
"`Observer.delete()` can only be called with observed Objects"
|
||||
);
|
||||
}
|
||||
target.__owl__.observer.delete(target, key);
|
||||
}
|
||||
|
||||
notifyCB() {}
|
||||
notifyChange() {
|
||||
this.dirty = true;
|
||||
@@ -120,8 +138,19 @@ export class Observer {
|
||||
this.notifyChange();
|
||||
}
|
||||
|
||||
delete(target: any, key: number | string) {
|
||||
delete target[key];
|
||||
this._updateRevNumber(target);
|
||||
this.notifyChange();
|
||||
}
|
||||
|
||||
_observeObj<T extends { __owl__?: any }>(obj: T, parent?: any) {
|
||||
obj.__owl__ = { rev: this.rev, deepRev: this.rev, parent };
|
||||
obj.__owl__ = {
|
||||
rev: this.rev,
|
||||
deepRev: this.rev,
|
||||
parent,
|
||||
observer: this
|
||||
};
|
||||
Object.defineProperty(obj, "__owl__", { enumerable: false });
|
||||
for (let key in obj) {
|
||||
this._addProp(obj, key, obj[key]);
|
||||
@@ -129,7 +158,12 @@ export class Observer {
|
||||
}
|
||||
|
||||
_observeArr(arr: Array<any>, parent?: any) {
|
||||
(<any>arr).__owl__ = { rev: this.rev, deepRev: this.rev, parent };
|
||||
(<any>arr).__owl__ = {
|
||||
rev: this.rev,
|
||||
deepRev: this.rev,
|
||||
parent,
|
||||
observer: this
|
||||
};
|
||||
Object.defineProperty(arr, "__owl__", { enumerable: false });
|
||||
(<any>arr).__proto__ = Object.create(ModifiedArrayProto);
|
||||
(<any>arr).__proto__.__observer__ = this;
|
||||
@@ -145,6 +179,7 @@ export class Observer {
|
||||
) {
|
||||
var self = this;
|
||||
Object.defineProperty(obj, key, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() {
|
||||
return value;
|
||||
|
||||
+27
-85
@@ -1,4 +1,5 @@
|
||||
import { VNode, h } from "./vdom";
|
||||
import { QWebVar, compileExpr } from "./qweb_expressions";
|
||||
|
||||
/**
|
||||
* Owl QWeb Engine
|
||||
@@ -56,18 +57,6 @@ export interface Directive {
|
||||
//------------------------------------------------------------------------------
|
||||
// Const/global stuff/helpers
|
||||
//------------------------------------------------------------------------------
|
||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,typeof,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||
","
|
||||
);
|
||||
|
||||
const WORD_REPLACEMENT = {
|
||||
and: "&&",
|
||||
or: "||",
|
||||
gt: ">",
|
||||
gte: ">=",
|
||||
lt: "<",
|
||||
lte: "<="
|
||||
};
|
||||
|
||||
const DISABLED_TAGS = [
|
||||
"input",
|
||||
@@ -151,6 +140,11 @@ export class QWeb {
|
||||
// able to map a qweb instance to a template name.
|
||||
id = nextID++;
|
||||
|
||||
// slots contains sub templates defined with t-set inside t-widget nodes, and
|
||||
// are meant to be used by the t-slot directive.
|
||||
slots = {};
|
||||
nextSlotId = 1;
|
||||
|
||||
constructor(data?: string) {
|
||||
if (data) {
|
||||
this.addTemplates(data);
|
||||
@@ -340,13 +334,15 @@ export class QWeb {
|
||||
}
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
|
||||
} else if (ctx.parentTextNode) {
|
||||
ctx.addLine(`vn${ctx.parentTextNode}.text += \`${text}\`;`);
|
||||
} else {
|
||||
// this is an unusual situation: this text node is the result of the
|
||||
// template rendering.
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.addLine(`var vn${nodeID} = {text: \`${text}\`};`);
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -518,7 +514,8 @@ export class QWeb {
|
||||
// dynamic attributes
|
||||
if (name.startsWith("t-att-")) {
|
||||
let attName = name.slice(6);
|
||||
let formattedValue = ctx.formatExpression(ctx.getValue(value!));
|
||||
const v = ctx.getValue(value);
|
||||
let formattedValue = v.id || ctx.formatExpression(v);
|
||||
if (
|
||||
formattedValue[0] === "{" &&
|
||||
formattedValue[formattedValue.length - 1] === "}"
|
||||
@@ -623,13 +620,14 @@ export class QWeb {
|
||||
//------------------------------------------------------------------------------
|
||||
// Compilation Context
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export class Context {
|
||||
nextID: number = 1;
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: any } = {};
|
||||
definedVariables: { [key: string]: string } = {};
|
||||
variables: { [key: string]: QWebVar } = {};
|
||||
escaping: boolean = false;
|
||||
parentNode: number | null = null;
|
||||
parentTextNode: number | null = null;
|
||||
rootNode: number | null = null;
|
||||
indentLevel: number = 0;
|
||||
rootContext: Context;
|
||||
@@ -654,7 +652,7 @@ export class Context {
|
||||
}
|
||||
|
||||
withParent(node: number): Context {
|
||||
if (this === this.rootContext && this.parentNode) {
|
||||
if (this === this.rootContext && (this.parentNode || this.parentTextNode)) {
|
||||
throw new Error("A template should not have more than one root node");
|
||||
}
|
||||
if (!this.rootContext.rootNode) {
|
||||
@@ -702,66 +700,14 @@ export class Context {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
}
|
||||
|
||||
formatExpression(e: string): string {
|
||||
e = e.trim();
|
||||
if (e[0] === "{" && e[e.length - 1] === "}") {
|
||||
const innerExpr = e
|
||||
.slice(1, -1)
|
||||
.split(",")
|
||||
.map(p => {
|
||||
let [key, val] = p.trim().split(":");
|
||||
if (key === "") {
|
||||
return "";
|
||||
}
|
||||
if (!val) {
|
||||
val = key;
|
||||
}
|
||||
return `${key}: ${this.formatExpression(val)}`;
|
||||
})
|
||||
.join(",");
|
||||
return "{" + innerExpr + "}";
|
||||
}
|
||||
|
||||
// Thanks CHM for this code...
|
||||
const chars = e.split("");
|
||||
let instring = "";
|
||||
let invar = "";
|
||||
let invarPos = 0;
|
||||
let r = "";
|
||||
chars.push(" ");
|
||||
for (let i = 0, ilen = chars.length; i < ilen; i++) {
|
||||
let c = chars[i];
|
||||
if (instring.length) {
|
||||
if (c === instring && chars[i - 1] !== "\\") {
|
||||
instring = "";
|
||||
}
|
||||
} else if (c === '"' || c === "'") {
|
||||
instring = c;
|
||||
} else if (c.match(/[a-zA-Z_\$]/) && !invar.length) {
|
||||
invar = c;
|
||||
invarPos = i;
|
||||
continue;
|
||||
} else if (c.match(/\W/) && invar.length) {
|
||||
// TODO: Should check for possible spaces before dot
|
||||
if (chars[invarPos - 1] !== "." && RESERVED_WORDS.indexOf(invar) < 0) {
|
||||
if (!(invar in this.definedVariables)) {
|
||||
invar =
|
||||
WORD_REPLACEMENT[invar] ||
|
||||
(invar in this.variables &&
|
||||
this.formatExpression(this.variables[invar])) ||
|
||||
"context['" + invar + "']";
|
||||
}
|
||||
}
|
||||
r += invar;
|
||||
invar = "";
|
||||
} else if (invar.length) {
|
||||
invar += c;
|
||||
continue;
|
||||
}
|
||||
r += c;
|
||||
}
|
||||
const result = r.slice(0, -1);
|
||||
return result;
|
||||
/**
|
||||
* Prepare an expression for being consumed at render time. Its main job
|
||||
* is to
|
||||
* - replace unknown variables by a lookup in the context
|
||||
* - replace already defined variables by their internal name
|
||||
*/
|
||||
formatExpression(expr: string): string {
|
||||
return compileExpr(expr, this.variables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -777,15 +723,11 @@ export class Context {
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return `(${this.formatExpression(s.slice(2, -2))})`;
|
||||
}
|
||||
matches = s.match(/\#\{.*?\}/g);
|
||||
if (matches && matches[0].length === s.length) {
|
||||
return `(${this.formatExpression(s.slice(2, -1))})`;
|
||||
}
|
||||
|
||||
let formatter = expr => "${" + this.formatExpression(expr) + "}";
|
||||
let r = s
|
||||
.replace(/\{\{.*?\}\}/g, s => formatter(s.slice(2, -2)))
|
||||
.replace(/\#\{.*?\}/g, s => formatter(s.slice(2, -1)));
|
||||
let r = s.replace(
|
||||
/\{\{.*?\}\}/g,
|
||||
s => "${" + this.formatExpression(s.slice(2, -2)) + "}"
|
||||
);
|
||||
return "`" + r + "`";
|
||||
}
|
||||
}
|
||||
|
||||
+67
-62
@@ -1,4 +1,5 @@
|
||||
import { Context, QWeb, UTILS } from "./qweb_core";
|
||||
import { QWebExprVar } from "./qweb_expressions";
|
||||
|
||||
/**
|
||||
* Owl QWeb Directives
|
||||
@@ -14,7 +15,6 @@ import { Context, QWeb, UTILS } from "./qweb_core";
|
||||
* - t-log
|
||||
*/
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-esc and t-raw
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -30,42 +30,49 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
let exprID = value;
|
||||
if (!(value in ctx.definedVariables)) {
|
||||
exprID = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
||||
}
|
||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
||||
if (!ctx.parentNode) {
|
||||
throw new Error("Should not have a text node without a parent");
|
||||
}
|
||||
if (ctx.escaping) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: ${exprID}});`);
|
||||
} else {
|
||||
let fragID = ctx.generateID();
|
||||
ctx.addLine(`var frag${fragID} = this.utils.getFragment(${exprID})`);
|
||||
let tempNodeID = ctx.generateID();
|
||||
ctx.addLine(`var p${tempNodeID} = {hook: {`);
|
||||
ctx.addLine(
|
||||
` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`
|
||||
);
|
||||
ctx.addLine(`}};`);
|
||||
ctx.addLine(`var vn${tempNodeID} = h('div', p${tempNodeID})`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
|
||||
}
|
||||
if (node.childNodes.length) {
|
||||
ctx.addElse();
|
||||
qweb._compileChildren(node, ctx);
|
||||
}
|
||||
ctx.closeIf();
|
||||
return;
|
||||
}
|
||||
if (value instanceof NodeList) {
|
||||
for (let node of Array.from(value)) {
|
||||
if (value.xml instanceof NodeList) {
|
||||
for (let node of Array.from(value.xml)) {
|
||||
qweb._compileNode(<ChildNode>node, ctx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let exprID: string;
|
||||
if (typeof value === "string") {
|
||||
exprID = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
||||
} else {
|
||||
exprID = value.id;
|
||||
}
|
||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
||||
if (ctx.escaping) {
|
||||
if (ctx.parentTextNode) {
|
||||
ctx.addLine(`vn${ctx.parentTextNode}.text += ${exprID};`);
|
||||
} else if (ctx.parentNode) {
|
||||
ctx.addLine(`c${ctx.parentNode}.push({text: ${exprID}});`);
|
||||
} else {
|
||||
let nodeID = ctx.generateID();
|
||||
ctx.rootContext.rootNode = nodeID;
|
||||
ctx.rootContext.parentTextNode = nodeID;
|
||||
ctx.addLine(`var vn${nodeID} = {text: ${exprID}};`);
|
||||
}
|
||||
} else {
|
||||
let fragID = ctx.generateID();
|
||||
ctx.addLine(`var frag${fragID} = this.utils.getFragment(${exprID})`);
|
||||
let tempNodeID = ctx.generateID();
|
||||
ctx.addLine(`var p${tempNodeID} = {hook: {`);
|
||||
ctx.addLine(
|
||||
` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`
|
||||
);
|
||||
ctx.addLine(`}};`);
|
||||
ctx.addLine(`var vn${tempNodeID} = h('div', p${tempNodeID})`);
|
||||
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
|
||||
}
|
||||
if (node.childNodes.length) {
|
||||
ctx.addElse();
|
||||
qweb._compileChildren(node, ctx);
|
||||
}
|
||||
|
||||
ctx.closeIf();
|
||||
}
|
||||
|
||||
QWeb.addDirective({
|
||||
@@ -109,15 +116,21 @@ QWeb.addDirective({
|
||||
if (value) {
|
||||
const formattedValue = ctx.formatExpression(value);
|
||||
if (ctx.variables.hasOwnProperty(variable)) {
|
||||
ctx.addLine(`${ctx.variables[variable]} = ${formattedValue}`);
|
||||
ctx.addLine(
|
||||
`${(<QWebExprVar>ctx.variables[variable]).id} = ${formattedValue}`
|
||||
);
|
||||
} else {
|
||||
const varName = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
||||
ctx.definedVariables[varName] = formattedValue;
|
||||
ctx.variables[variable] = varName;
|
||||
ctx.variables[variable] = {
|
||||
id: varName,
|
||||
expr: formattedValue
|
||||
};
|
||||
}
|
||||
} else {
|
||||
ctx.variables[variable] = node.childNodes;
|
||||
ctx.variables[variable] = {
|
||||
xml: node.childNodes
|
||||
};
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -189,30 +202,27 @@ QWeb.addDirective({
|
||||
tempCtx.nextID = ctx.rootContext.nextID;
|
||||
qweb._compileNode(nodeCopy, tempCtx);
|
||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
||||
var definedVariables = Object.assign(
|
||||
{},
|
||||
ctx.definedVariables,
|
||||
tempCtx.definedVariables
|
||||
);
|
||||
ctx.rootContext.nextID = tempCtx.nextID;
|
||||
|
||||
// open new scope, if necessary
|
||||
const hasNewVariables = Object.keys(definedVariables).length > 0;
|
||||
const hasNewVariables = Object.keys(tempCtx.variables).length > 0;
|
||||
if (hasNewVariables) {
|
||||
ctx.addLine("{");
|
||||
ctx.indent();
|
||||
}
|
||||
|
||||
// add new variables, if any
|
||||
for (let key in definedVariables) {
|
||||
ctx.addLine(`let ${key} = ${definedVariables[key]}`);
|
||||
// add new variables, if any
|
||||
for (let key in tempCtx.variables) {
|
||||
const v = tempCtx.variables[key];
|
||||
if ((<QWebExprVar>v).expr) {
|
||||
ctx.addLine(`let ${(<QWebExprVar>v).id} = ${(<QWebExprVar>v).expr};`);
|
||||
}
|
||||
// todo: handle XML variables...
|
||||
}
|
||||
}
|
||||
|
||||
// compile sub template
|
||||
const subCtx = ctx
|
||||
.subContext("caller", nodeCopy)
|
||||
.subContext("variables", Object.create(vars))
|
||||
.subContext("definedVariables", Object.create(definedVariables));
|
||||
.subContext("variables", Object.create(vars));
|
||||
|
||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
||||
|
||||
@@ -243,23 +253,18 @@ QWeb.addDirective({
|
||||
ctx.addLine(
|
||||
`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`
|
||||
);
|
||||
ctx.addLine(
|
||||
`if (typeof _${arrayID} === 'number') { _${arrayID} = Array.from(Array(_${arrayID}).keys())}`
|
||||
);
|
||||
let keysID = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`var _${keysID} = _${arrayID} instanceof Array ? _${arrayID} : Object.keys(_${arrayID});`
|
||||
);
|
||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
||||
let valuesID = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`var _${valuesID} = _${arrayID} instanceof Array ? _${arrayID} : Object.values(_${arrayID});`
|
||||
);
|
||||
ctx.addLine(`var _${keysID} = _${valuesID} = _${arrayID};`);
|
||||
ctx.addIf(`!(_${arrayID} instanceof Array)`);
|
||||
ctx.addLine(`_${keysID} = Object.keys(_${arrayID});`);
|
||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
||||
ctx.closeIf();
|
||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
||||
ctx.addLine(`for (let i = 0; i < _length${keysID}; i++) {`);
|
||||
ctx.indent();
|
||||
ctx.addLine(`context.${name}_first = i === 0;`);
|
||||
ctx.addLine(`context.${name}_last = i === _length${keysID} - 1;`);
|
||||
ctx.addLine(`context.${name}_parity = i % 2 === 0 ? 'even' : 'odd';`);
|
||||
ctx.addLine(`context.${name}_index = i;`);
|
||||
ctx.addLine(`context.${name} = _${keysID}[i];`);
|
||||
ctx.addLine(`context.${name}_value = _${valuesID}[i];`);
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Owl QWeb Expression Parser
|
||||
*
|
||||
* Owl needs in various contexts to be able to understand the structure of a
|
||||
* string representing a javascript expression. The usual goal is to be able
|
||||
* to rewrite some variables. For example, if a template has
|
||||
*
|
||||
* ```xml
|
||||
* <t t-if="computeSomething({val: state.val})">...</t>
|
||||
* ```
|
||||
*
|
||||
* this needs to be translated in something like this:
|
||||
*
|
||||
* ```js
|
||||
* if (context["computeSomething"]({val: context["state"].val})) { ... }
|
||||
* ```
|
||||
*
|
||||
* This file contains the implementation of an extremely naive tokenizer/parser
|
||||
* and evaluator for javascript expressions. The supported grammar is basically
|
||||
* only expressive enough to understand the shape of objects, of arrays, and
|
||||
* various operators.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Misc types, constants and helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,typeof,eval,void,Math,RegExp,Array,Object,Date".split(
|
||||
","
|
||||
);
|
||||
|
||||
const WORD_REPLACEMENT = {
|
||||
and: "&&",
|
||||
or: "||",
|
||||
gt: ">",
|
||||
gte: ">=",
|
||||
lt: "<",
|
||||
lte: "<="
|
||||
};
|
||||
|
||||
export interface QWebExprVar {
|
||||
id: string;
|
||||
expr: string;
|
||||
}
|
||||
|
||||
export interface QWebXMLVar {
|
||||
xml: NodeList;
|
||||
}
|
||||
|
||||
export type QWebVar = QWebExprVar | QWebXMLVar;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Tokenizer
|
||||
//------------------------------------------------------------------------------
|
||||
type TKind =
|
||||
| "LEFT_BRACE"
|
||||
| "RIGHT_BRACE"
|
||||
| "LEFT_BRACKET"
|
||||
| "RIGHT_BRACKET"
|
||||
| "LEFT_PAREN"
|
||||
| "RIGHT_PAREN"
|
||||
| "COMMA"
|
||||
| "VALUE"
|
||||
| "SYMBOL"
|
||||
| "OPERATOR"
|
||||
| "COLON";
|
||||
|
||||
interface Token {
|
||||
type: TKind;
|
||||
value: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
const STATIC_TOKEN_MAP: { [key: string]: TKind } = {
|
||||
"{": "LEFT_BRACE",
|
||||
"}": "RIGHT_BRACE",
|
||||
"[": "LEFT_BRACKET",
|
||||
"]": "RIGHT_BRACKET",
|
||||
":": "COLON",
|
||||
",": "COMMA",
|
||||
"(": "LEFT_PAREN",
|
||||
")": "RIGHT_PAREN"
|
||||
};
|
||||
|
||||
const OPERATORS = ".,===,==,+,!,||,&&,>=,>,<=,<,?,-,*,/,%".split(',');
|
||||
|
||||
type Tokenizer = (expr: string) => Token | false;
|
||||
|
||||
let tokenizeString: Tokenizer = function(expr) {
|
||||
let s = expr[0];
|
||||
let start = s;
|
||||
if (s !== "'" && s !== '"') {
|
||||
return false;
|
||||
}
|
||||
let i = 1;
|
||||
let cur;
|
||||
while (expr[i] && expr[i] !== start) {
|
||||
cur = expr[i];
|
||||
s += cur;
|
||||
if (cur === "\\") {
|
||||
i++;
|
||||
cur = expr[i];
|
||||
if (!cur) {
|
||||
throw new Error("Invalid expression");
|
||||
}
|
||||
s += cur;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (expr[i] !== start) {
|
||||
throw new Error("Invalid expression");
|
||||
}
|
||||
s += start;
|
||||
return { type: "VALUE", value: s };
|
||||
};
|
||||
|
||||
let tokenizeNumber: Tokenizer = function(expr) {
|
||||
let s = expr[0];
|
||||
if (s && s.match(/[0-9]/)) {
|
||||
let i = 1;
|
||||
while (expr[i] && expr[i].match(/[0-9]|\./)) {
|
||||
s += expr[i];
|
||||
i++;
|
||||
}
|
||||
return { type: "VALUE", value: s };
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let tokenizeSymbol: Tokenizer = function(expr) {
|
||||
let s = expr[0];
|
||||
if (s && s.match(/[a-zA-Z_\$]/)) {
|
||||
let i = 1;
|
||||
while (expr[i] && expr[i].match(/\w/)) {
|
||||
s += expr[i];
|
||||
i++;
|
||||
}
|
||||
if (s in WORD_REPLACEMENT) {
|
||||
return { type: "OPERATOR", value: WORD_REPLACEMENT[s], size: s.length };
|
||||
}
|
||||
return { type: "SYMBOL", value: s };
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const tokenizeStatic: Tokenizer = function(expr) {
|
||||
const char = expr[0];
|
||||
if (char && char in STATIC_TOKEN_MAP) {
|
||||
return { type: STATIC_TOKEN_MAP[char], value: char };
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const tokenizeOperator: Tokenizer = function(expr) {
|
||||
for (let op of OPERATORS) {
|
||||
if (expr.startsWith(op)) {
|
||||
return { type: "OPERATOR", value: op };
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const TOKENIZERS = [
|
||||
tokenizeString,
|
||||
tokenizeNumber,
|
||||
tokenizeSymbol,
|
||||
tokenizeStatic,
|
||||
tokenizeOperator
|
||||
];
|
||||
|
||||
/**
|
||||
* Convert a javascript expression (as a string) into a list of tokens. For
|
||||
* example: `tokenize("1 + b")` will return:
|
||||
* ```js
|
||||
* [
|
||||
* {type: "VALUE", value: "1"},
|
||||
* {type: "OPERATOR", value: "+"},
|
||||
* {type: "SYMBOL", value: "b"}
|
||||
* ]
|
||||
* ```
|
||||
*/
|
||||
export function tokenize(expr: string): Token[] {
|
||||
const result: Token[] = [];
|
||||
let token: boolean | Token = true;
|
||||
|
||||
while (token) {
|
||||
expr = expr.trim();
|
||||
if (expr) {
|
||||
for (let tokenizer of TOKENIZERS) {
|
||||
token = tokenizer(expr);
|
||||
if (token) {
|
||||
result.push(token);
|
||||
expr = expr.slice(token.size || token.value.length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
token = false;
|
||||
}
|
||||
}
|
||||
if (expr.length) {
|
||||
throw new Error(`Tokenizer error: could not tokenize "${expr}"`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Expression "evaluator"
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* This is the main function exported by this file. This is the code that will
|
||||
* process an expression (given as a string) and returns another expression with
|
||||
* proper lookups in the context.
|
||||
*
|
||||
* Usually, this kind of code would be very simple to do if we had an AST (so,
|
||||
* if we had a javascript parser), since then, we would only need to find the
|
||||
* variables and replace them. However, a parser is more complicated, and there
|
||||
* are no standard builtin parser API.
|
||||
*
|
||||
* Since this method is applied to simple javasript expressions, and the work to
|
||||
* be done is actually quite simple, we actually can get away with not using a
|
||||
* parser, which helps with the code size.
|
||||
*
|
||||
* Here is the heuristic used by this method to determine if a token is a
|
||||
* variable:
|
||||
* - by default, all symbols are considered a variable
|
||||
* - unless the previous token is a dot (in that case, this is a property: `a.b`)
|
||||
* - or if the previous token is a left brace or a comma, and the next token is
|
||||
* a colon (in that case, this is an object key: `{a: b}`)
|
||||
*/
|
||||
export function compileExpr(
|
||||
expr: string,
|
||||
vars: { [key: string]: QWebVar }
|
||||
): string {
|
||||
const tokens = tokenize(expr);
|
||||
let result = "";
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
let token = tokens[i];
|
||||
if (token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value)) {
|
||||
// we need to find if it is a variable
|
||||
let isVar = true;
|
||||
let prevToken = tokens[i - 1];
|
||||
if (prevToken) {
|
||||
if (prevToken.type === "OPERATOR" && prevToken.value === ".") {
|
||||
isVar = false;
|
||||
} else if (
|
||||
prevToken.type === "LEFT_BRACE" ||
|
||||
prevToken.type === "COMMA"
|
||||
) {
|
||||
let nextToken = tokens[i + 1];
|
||||
if (nextToken && nextToken.type === "COLON") {
|
||||
isVar = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isVar) {
|
||||
if (token.value in vars && "id" in vars[token.value]) {
|
||||
token.value = (<QWebExprVar>vars[token.value]).id;
|
||||
} else {
|
||||
token.value = `context['${token.value}']`;
|
||||
}
|
||||
}
|
||||
}
|
||||
result += token.value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
+59
-15
@@ -1,4 +1,5 @@
|
||||
import { QWeb, UTILS } from "./qweb_core";
|
||||
import { VNode } from "./vdom";
|
||||
|
||||
/**
|
||||
* Owl QWeb Extensions
|
||||
@@ -11,6 +12,7 @@ import { QWeb, UTILS } from "./qweb_core";
|
||||
* - t-transition
|
||||
* - t-widget/t-keepalive
|
||||
* - t-mounted
|
||||
* - t-slot
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -94,7 +96,17 @@ UTILS.nextFrame = function(cb: () => void) {
|
||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
||||
};
|
||||
|
||||
UTILS.transitionInsert = function(elm: HTMLElement, name: string) {
|
||||
UTILS.transitionInsert = function(vn: VNode, name: string) {
|
||||
const elm = <HTMLElement>vn.elm;
|
||||
// remove potential duplicated vnode that is currently being removed, to
|
||||
// prevent from having twice the same node in the DOM during an animation
|
||||
const dup =
|
||||
elm.parentElement &&
|
||||
elm.parentElement!.querySelector(`*[data-owl-key='${vn.key}']`);
|
||||
if (dup) {
|
||||
dup.remove();
|
||||
}
|
||||
|
||||
elm.classList.add(name + "-enter");
|
||||
elm.classList.add(name + "-enter-active");
|
||||
const finalize = () => {
|
||||
@@ -108,11 +120,10 @@ UTILS.transitionInsert = function(elm: HTMLElement, name: string) {
|
||||
});
|
||||
};
|
||||
|
||||
UTILS.transitionRemove = function(
|
||||
elm: HTMLElement,
|
||||
name: string,
|
||||
rm: () => void
|
||||
) {
|
||||
UTILS.transitionRemove = function(vn: VNode, name: string, rm: () => void) {
|
||||
const elm = <HTMLElement>vn.elm;
|
||||
elm.setAttribute("data-owl-key", vn.key!);
|
||||
|
||||
elm.classList.add(name + "-leave");
|
||||
elm.classList.add(name + "-leave-active");
|
||||
const finalize = () => {
|
||||
@@ -169,8 +180,8 @@ QWeb.addDirective({
|
||||
atNodeCreation({ value, addNodeHook }) {
|
||||
let name = value;
|
||||
const hooks = {
|
||||
insert: `this.utils.transitionInsert(vn.elm, '${name}');`,
|
||||
remove: `this.utils.transitionRemove(vn.elm, '${name}', rm);`
|
||||
insert: `this.utils.transitionInsert(vn, '${name}');`,
|
||||
remove: `this.utils.transitionRemove(vn, '${name}', rm);`
|
||||
};
|
||||
for (let hookName in hooks) {
|
||||
addNodeHook(hookName, hooks[hookName]);
|
||||
@@ -296,7 +307,7 @@ const T_WIDGET_MODS_CODE = Object.assign({}, MODS_CODE, {
|
||||
* let nvn = w4._mount(vnode, vn.elm);
|
||||
* pvnode.elm = nvn.elm;
|
||||
* // what follows is only present if there are animations on the widget
|
||||
* utils.transitionInsert(vn.elm, "fade");
|
||||
* utils.transitionInsert(vn, "fade");
|
||||
* },
|
||||
* remove() {
|
||||
* // override with empty function to prevent from removing the node
|
||||
@@ -309,7 +320,7 @@ const T_WIDGET_MODS_CODE = Object.assign({}, MODS_CODE, {
|
||||
* let finalize = () => {
|
||||
* w4.destroy();
|
||||
* };
|
||||
* utils.transitionRemove(vn.elm, "fade", finalize);
|
||||
* utils.transitionRemove(vn, "fade", finalize);
|
||||
* }
|
||||
* };
|
||||
* // the pvnode is inserted at the correct position in the div's children
|
||||
@@ -351,7 +362,7 @@ QWeb.addDirective({
|
||||
name: "widget",
|
||||
extraNames: ["props", "keepalive"],
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node }): boolean {
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
ctx.addLine("//WIDGET");
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
ctx.rootContext.shouldDefineQWeb = true;
|
||||
@@ -421,19 +432,19 @@ QWeb.addDirective({
|
||||
}
|
||||
let transitionsInsertCode = "";
|
||||
if (transition) {
|
||||
transitionsInsertCode = `utils.transitionInsert(vn.elm, '${transition}');`;
|
||||
transitionsInsertCode = `utils.transitionInsert(vn, '${transition}');`;
|
||||
}
|
||||
let finalizeWidgetCode = `w${widgetID}.${
|
||||
keepAlive ? "unmount" : "destroy"
|
||||
}();`;
|
||||
if (ref) {
|
||||
finalizeWidgetCode += `delete context.refs[${refKey}];`; // FIXME: shouldn't we keep ref if keepAlive is true?
|
||||
if (ref && !keepAlive) {
|
||||
finalizeWidgetCode += `delete context.refs[${refKey}];`;
|
||||
}
|
||||
if (transition) {
|
||||
finalizeWidgetCode = `let finalize = () => {
|
||||
${finalizeWidgetCode}
|
||||
};
|
||||
utils.transitionRemove(vn.elm, '${transition}', finalize);`;
|
||||
utils.transitionRemove(vn, '${transition}', finalize);`;
|
||||
}
|
||||
|
||||
let createHook = "";
|
||||
@@ -523,6 +534,21 @@ QWeb.addDirective({
|
||||
ctx.addLine(
|
||||
`context.__owl__.cmap[${templateID}] = w${widgetID}.__owl__.id;`
|
||||
);
|
||||
|
||||
// SLOTS
|
||||
const slotNodes = node.querySelectorAll("[t-set]");
|
||||
if (slotNodes.length) {
|
||||
const slotId = qweb.nextSlotId++;
|
||||
for (let i = 0, length = slotNodes.length; i < length; i++) {
|
||||
const slotNode = slotNodes[i];
|
||||
const key = slotNode.getAttribute("t-set")!;
|
||||
slotNode.removeAttribute("t-set");
|
||||
const slotFn = qweb._compile(`slot_${key}_template`, slotNode);
|
||||
qweb.slots[`${slotId}_${key}`] = slotFn.bind(qweb);
|
||||
}
|
||||
ctx.addLine(`w${widgetID}.__owl__.slotId = ${slotId};`);
|
||||
}
|
||||
|
||||
ctx.addLine(`def${defID} = w${widgetID}._prepare();`);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
// FIXME: click to re-add widget during remove transition -> leak
|
||||
@@ -602,3 +628,21 @@ QWeb.addDirective({
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// t-slot
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.addDirective({
|
||||
name: "slot",
|
||||
priority: 80,
|
||||
atNodeEncounter({ ctx, value }): boolean {
|
||||
const slotKey = ctx.generateID();
|
||||
ctx.addLine(
|
||||
`const slot${slotKey} = this.slots[context.__owl__.slotId + '_' + '${value}'];`
|
||||
);
|
||||
ctx.addLine(
|
||||
`c${ctx.parentNode}.push(slot${slotKey}(context.__owl__.parent, extra));`
|
||||
);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
+98
-96
@@ -21,7 +21,7 @@ import { Observer } from "./observer";
|
||||
// Store Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
type Mutation = ({ state, commit, set, getters }, payload: any) => void;
|
||||
type Mutation = ({ state, commit, getters }, payload: any) => void;
|
||||
type Action = ({ commit, state, dispatch, env, getters }, payload: any) => void;
|
||||
type Getter = ({ state, getters }, payload) => any;
|
||||
|
||||
@@ -46,7 +46,6 @@ export class Store extends EventBus {
|
||||
debug: boolean;
|
||||
env: any;
|
||||
observer: Observer;
|
||||
set: any;
|
||||
getters: { [name: string]: (payload?) => any };
|
||||
|
||||
constructor(config: StoreConfig, options: StoreOption = {}) {
|
||||
@@ -65,7 +64,6 @@ export class Store extends EventBus {
|
||||
if (this.debug) {
|
||||
this.history.push({ state: this.state });
|
||||
}
|
||||
this.set = this.observer.set.bind(this.observer);
|
||||
|
||||
for (let entry of Object.entries(config.getters || {})) {
|
||||
const name: string = entry[0];
|
||||
@@ -110,7 +108,6 @@ export class Store extends EventBus {
|
||||
{
|
||||
commit: this.commit.bind(this),
|
||||
state: this.state,
|
||||
set: this.set,
|
||||
getters: this.getters
|
||||
},
|
||||
payload
|
||||
@@ -153,11 +150,22 @@ type Constructor<T> = new (...args: any[]) => T;
|
||||
interface EnvWithStore extends Env {
|
||||
store: Store;
|
||||
}
|
||||
type HashFunction = (a: any, b: any) => number;
|
||||
interface StoreOptions {
|
||||
getStore?(Env): Store;
|
||||
hashFunction?: HashFunction;
|
||||
deep?: boolean;
|
||||
}
|
||||
|
||||
let nextID = 1;
|
||||
|
||||
export function connect(mapStateToProps, options: any = {}) {
|
||||
export function connect<E extends EnvWithStore, P, S>(
|
||||
Comp: Constructor<Component<E, P, S>>,
|
||||
mapStoreToProps,
|
||||
options: StoreOptions = <StoreOptions>{}
|
||||
) {
|
||||
let hashFunction = options.hashFunction || null;
|
||||
const getStore = options.getStore || (env => env.store);
|
||||
|
||||
if (!hashFunction) {
|
||||
let deep = "deep" in options ? options.deep : true;
|
||||
@@ -183,101 +191,95 @@ export function connect(mapStateToProps, options: any = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
return function<E extends EnvWithStore, P, S>(
|
||||
Comp: Constructor<Component<E, P, S>>
|
||||
) {
|
||||
const Result = class extends Comp {
|
||||
constructor(parent, props?: any) {
|
||||
const env = parent instanceof Component ? parent.env : parent;
|
||||
const ownProps = Object.assign({}, props || {});
|
||||
const storeProps = mapStateToProps(
|
||||
env.store.state,
|
||||
ownProps,
|
||||
env.store.getters
|
||||
);
|
||||
const mergedProps = Object.assign({}, props || {}, storeProps);
|
||||
super(parent, mergedProps);
|
||||
(<any>this.__owl__).ownProps = ownProps;
|
||||
const Result = class extends Comp {
|
||||
constructor(parent, props?: any) {
|
||||
const env = parent instanceof Component ? parent.env : parent;
|
||||
const store = getStore(env);
|
||||
const ownProps = Object.assign({}, props || {});
|
||||
const storeProps = mapStoreToProps(store.state, ownProps, store.getters);
|
||||
const mergedProps = Object.assign({}, props || {}, storeProps);
|
||||
super(parent, mergedProps);
|
||||
(<any>this.__owl__).ownProps = ownProps;
|
||||
(<any>this.__owl__).currentStoreProps = storeProps;
|
||||
(<any>this.__owl__).store = store;
|
||||
(<any>this.__owl__).storeHash = (<HashFunction>hashFunction)(
|
||||
{
|
||||
state: store.state,
|
||||
storeProps: storeProps,
|
||||
revNumber,
|
||||
deepRevNumber
|
||||
},
|
||||
{
|
||||
currentStoreProps: storeProps
|
||||
}
|
||||
);
|
||||
}
|
||||
/**
|
||||
* We do not use the mounted hook here for a subtle reason: we want the
|
||||
* updates to be called for the parents before the children. However,
|
||||
* if we use the mounted hook, this will be done in the reverse order.
|
||||
*/
|
||||
_callMounted() {
|
||||
(<any>this.__owl__).store.on("update", this, this._checkUpdate);
|
||||
super._callMounted();
|
||||
}
|
||||
willUnmount() {
|
||||
(<any>this.__owl__).store.off("update", this);
|
||||
super.willUnmount();
|
||||
}
|
||||
|
||||
_checkUpdate() {
|
||||
const ownProps = (<any>this.__owl__).ownProps;
|
||||
const storeProps = mapStoreToProps(
|
||||
(<any>this.__owl__).store.state,
|
||||
ownProps,
|
||||
(<any>this.__owl__).store.getters
|
||||
);
|
||||
const options: any = {
|
||||
currentStoreProps: (<any>this.__owl__).currentStoreProps
|
||||
};
|
||||
const storeHash = (<HashFunction>hashFunction)(
|
||||
{
|
||||
state: (<any>this.__owl__).store.state,
|
||||
storeProps: storeProps,
|
||||
revNumber,
|
||||
deepRevNumber
|
||||
},
|
||||
options
|
||||
);
|
||||
let didChange = options.didChange;
|
||||
if (storeHash !== (<any>this.__owl__).storeHash) {
|
||||
didChange = true;
|
||||
(<any>this.__owl__).storeHash = storeHash;
|
||||
}
|
||||
if (didChange) {
|
||||
(<any>this.__owl__).currentStoreProps = storeProps;
|
||||
(<any>this.__owl__).storeHash = hashFunction(
|
||||
{
|
||||
state: env.store.state,
|
||||
storeProps: storeProps,
|
||||
revNumber,
|
||||
deepRevNumber
|
||||
},
|
||||
{
|
||||
currentStoreProps: storeProps
|
||||
}
|
||||
);
|
||||
this._updateProps(ownProps, false);
|
||||
}
|
||||
/**
|
||||
* We do not use the mounted hook here for a subtle reason: we want the
|
||||
* updates to be called for the parents before the children. However,
|
||||
* if we use the mounted hook, this will be done in the reverse order.
|
||||
*/
|
||||
_callMounted() {
|
||||
this.env.store.on("update", this, this._checkUpdate);
|
||||
super._callMounted();
|
||||
}
|
||||
willUnmount() {
|
||||
this.env.store.off("update", this);
|
||||
super.willUnmount();
|
||||
}
|
||||
|
||||
_checkUpdate() {
|
||||
const ownProps = (<any>this.__owl__).ownProps;
|
||||
const storeProps = mapStateToProps(
|
||||
this.env.store.state,
|
||||
ownProps,
|
||||
this.env.store.getters
|
||||
);
|
||||
const options: any = {
|
||||
currentStoreProps: (<any>this.__owl__).currentStoreProps
|
||||
};
|
||||
const storeHash = hashFunction(
|
||||
{
|
||||
state: this.env.store.state,
|
||||
storeProps: storeProps,
|
||||
revNumber,
|
||||
deepRevNumber
|
||||
},
|
||||
options
|
||||
);
|
||||
let didChange = options.didChange;
|
||||
if (storeHash !== (<any>this.__owl__).storeHash) {
|
||||
didChange = true;
|
||||
(<any>this.__owl__).storeHash = storeHash;
|
||||
}
|
||||
if (didChange) {
|
||||
(<any>this.__owl__).currentStoreProps = storeProps;
|
||||
this._updateProps(ownProps, false);
|
||||
}
|
||||
}
|
||||
_updateProps(nextProps, forceUpdate, patchQueue?: any[]) {
|
||||
if ((<any>this.__owl__).ownProps !== nextProps) {
|
||||
(<any>this.__owl__).currentStoreProps = mapStateToProps(
|
||||
this.env.store.state,
|
||||
nextProps,
|
||||
this.env.store.getters
|
||||
);
|
||||
}
|
||||
(<any>this.__owl__).ownProps = nextProps;
|
||||
const mergedProps = Object.assign(
|
||||
{},
|
||||
}
|
||||
_updateProps(nextProps, forceUpdate, patchQueue?: any[]) {
|
||||
if ((<any>this.__owl__).ownProps !== nextProps) {
|
||||
(<any>this.__owl__).currentStoreProps = mapStoreToProps(
|
||||
(<any>this.__owl__).store.state,
|
||||
nextProps,
|
||||
(<any>this.__owl__).currentStoreProps
|
||||
(<any>this.__owl__).store.getters
|
||||
);
|
||||
return super._updateProps(mergedProps, forceUpdate, patchQueue);
|
||||
}
|
||||
};
|
||||
|
||||
// we assign here a unique name to the resulting anonymous class.
|
||||
// this is necessary for Owl to be able to properly deduce templates.
|
||||
// Otherwise, all connected components would have the same name, and then
|
||||
// each component after the first will necessarily have the same template.
|
||||
let name = `ConnectedComponent${nextID++}`;
|
||||
Object.defineProperty(Result, "name", { value: name });
|
||||
return Result;
|
||||
(<any>this.__owl__).ownProps = nextProps;
|
||||
const mergedProps = Object.assign(
|
||||
{},
|
||||
nextProps,
|
||||
(<any>this.__owl__).currentStoreProps
|
||||
);
|
||||
return super._updateProps(mergedProps, forceUpdate, patchQueue);
|
||||
}
|
||||
};
|
||||
|
||||
// we assign here a unique name to the resulting anonymous class.
|
||||
// this is necessary for Owl to be able to properly deduce templates.
|
||||
// Otherwise, all connected components would have the same name, and then
|
||||
// each component after the first will necessarily have the same template.
|
||||
let name = `ConnectedComponent${nextID++}`;
|
||||
Object.defineProperty(Result, "name", { value: name });
|
||||
return Result;
|
||||
}
|
||||
|
||||
+7
-5
@@ -11,11 +11,13 @@
|
||||
*/
|
||||
|
||||
export function whenReady(fn) {
|
||||
if (document.readyState === "complete") {
|
||||
fn();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", fn, false);
|
||||
}
|
||||
return new Promise(function(resolve) {
|
||||
if (document.readyState !== "loading") {
|
||||
resolve();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", resolve, false);
|
||||
}
|
||||
}).then(fn || function () {});
|
||||
}
|
||||
|
||||
const loadedScripts: { [key: string]: Promise<void> } = {};
|
||||
|
||||
+1
-8
@@ -59,14 +59,7 @@ function vnode(
|
||||
elm: Element | Text | undefined
|
||||
): VNode {
|
||||
let key = data === undefined ? undefined : data.key;
|
||||
return {
|
||||
sel: sel,
|
||||
data: data,
|
||||
children: children,
|
||||
text: text,
|
||||
elm: elm,
|
||||
key: key
|
||||
};
|
||||
return {sel, data, children, text, elm, key};
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
@@ -30,10 +30,10 @@ exports[`animations t-transition combined with t-widget 1`] = `
|
||||
w4 = new W4(owner, props4);
|
||||
context.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4._prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn.elm, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w4.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn.elm, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4._updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
@@ -74,10 +74,10 @@ exports[`animations t-transition combined with t-widget and t-if 1`] = `
|
||||
w4 = new W4(owner, props4);
|
||||
context.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4._prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn.elm, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;utils.transitionInsert(vn, 'chimay');},remove() {},destroy(vn) {let finalize = () => {
|
||||
w4.destroy();
|
||||
};
|
||||
utils.transitionRemove(vn.elm, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
utils.transitionRemove(vn, 'chimay', finalize);}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4._updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
@@ -96,10 +96,10 @@ exports[`animations t-transition with no delay/duration 1`] = `
|
||||
var vn1 = h('span', p1, c1);
|
||||
p1.hook = {
|
||||
insert: vn => {
|
||||
this.utils.transitionInsert(vn.elm, 'jupiler');
|
||||
this.utils.transitionInsert(vn, 'jupiler');
|
||||
},
|
||||
remove: (vn, rm) => {
|
||||
this.utils.transitionRemove(vn.elm, 'jupiler', rm);
|
||||
this.utils.transitionRemove(vn, 'jupiler', rm);
|
||||
},
|
||||
};
|
||||
c1.push({text: \`blue\`});
|
||||
@@ -115,10 +115,10 @@ exports[`animations t-transition, on a simple node (insert) 1`] = `
|
||||
var vn1 = h('span', p1, c1);
|
||||
p1.hook = {
|
||||
insert: vn => {
|
||||
this.utils.transitionInsert(vn.elm, 'chimay');
|
||||
this.utils.transitionInsert(vn, 'chimay');
|
||||
},
|
||||
remove: (vn, rm) => {
|
||||
this.utils.transitionRemove(vn.elm, 'chimay', rm);
|
||||
this.utils.transitionRemove(vn, 'chimay', rm);
|
||||
},
|
||||
};
|
||||
c1.push({text: \`blue\`});
|
||||
|
||||
@@ -54,7 +54,7 @@ exports[`class and style attributes with t-widget t-att-class is properly added/
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let def3;
|
||||
const _5 = {a: context['state'].a,b: context['state'].b};
|
||||
const _5 = {a:context['state'].a,b:context['state'].b};
|
||||
let w4 = 4 in context.__owl__.cmap ? context.__owl__.children[context.__owl__.cmap[4]] : false;
|
||||
let props4 = {};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
@@ -98,14 +98,15 @@ exports[`composition sub widgets with some state rendered in a loop 1`] = `
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['state'].numbers;
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.number_first = i === 0;
|
||||
context.number_last = i === _length3 - 1;
|
||||
context.number_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.number_index = i;
|
||||
context.number = _3[i];
|
||||
context.number_value = _4[i];
|
||||
@@ -372,7 +373,7 @@ exports[`other directives with t-widget t-on with handler bound to object 1`] =
|
||||
w4 = new W4(owner, props4);
|
||||
context.__owl__.cmap[4] = w4.__owl__.id;
|
||||
def3 = w4._prepare();
|
||||
def3 = def3.then(vnode=>{vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', owner['onEv'].bind(owner, {val: 3}));}};let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
def3 = def3.then(vnode=>{vnode.data.hook = {create(_, vn){vn.elm.addEventListener('ev', owner['onEv'].bind(owner, {val:3}));}};let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4._updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
@@ -582,3 +583,64 @@ exports[`random stuff/miscellaneous snapshotting compiled code 1`] = `
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`t-slot directive can define and call slots 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
let utils = this.utils;
|
||||
let QWeb = this.constructor;
|
||||
let owner = context;
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
//WIDGET
|
||||
let _2_index = c1.length;
|
||||
c1.push(null);
|
||||
let def3;
|
||||
let w4 = 4 in context.__owl__.cmap ? context.__owl__.children[context.__owl__.cmap[4]] : false;
|
||||
let props4 = {};
|
||||
if (w4 && w4.__owl__.renderPromise && !w4.__owl__.vnode) {
|
||||
if (utils.shallowEqual(props4, w4.__owl__.renderProps)) {
|
||||
def3 = w4.__owl__.renderPromise;
|
||||
} else {
|
||||
w4.destroy();
|
||||
w4 = false;
|
||||
}
|
||||
}
|
||||
if (!w4) {
|
||||
let widgetKey4 = \`Dialog\`;
|
||||
let W4 = context.widgets && context.widgets[widgetKey4] || QWeb.widgets[widgetKey4];
|
||||
if (!W4) {throw new Error('Cannot find the definition of widget \\"' + widgetKey4 + '\\"')}
|
||||
w4 = new W4(owner, props4);
|
||||
context.__owl__.cmap[4] = w4.__owl__.id;
|
||||
w4.__owl__.slotId = 1;
|
||||
def3 = w4._prepare();
|
||||
def3 = def3.then(vnode=>{let pvnode=h(vnode.sel, {key: 4, hook: {insert(vn) {let nvn=w4._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;},remove() {},destroy(vn) {w4.destroy();}}});c1[_2_index]=pvnode;w4.__owl__.pvnode = pvnode;});
|
||||
} else {
|
||||
def3 = def3 || w4._updateProps(props4, extra.forceUpdate, extra.patchQueue);
|
||||
def3 = def3.then(()=>{if (w4.__owl__.isDestroyed) {return};let pvnode=w4.__owl__.pvnode;c1[_2_index]=pvnode;});
|
||||
}
|
||||
extra.promises.push(def3);
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`t-slot directive can define and call slots 2`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
let c2 = [], p2 = {key:2};
|
||||
var vn2 = h('div', p2, c2);
|
||||
c1.push(vn2);
|
||||
const slot3 = this.slots[context.__owl__.slotId + '_' + 'header'];
|
||||
c2.push(slot3(context.__owl__.parent, extra));
|
||||
let c4 = [], p4 = {key:4};
|
||||
var vn4 = h('div', p4, c4);
|
||||
c1.push(vn4);
|
||||
const slot5 = this.slots[context.__owl__.slotId + '_' + 'footer'];
|
||||
c4.push(slot5(context.__owl__.parent, extra));
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
@@ -4,7 +4,7 @@ exports[`attributes class and t-attf-class with ternary operation 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = 'hello ' + (context['value'] ? 'world' : '');
|
||||
var _1 = 'hello ' + (context['value']?'world':'');
|
||||
let c2 = [], p2 = {key:2,attrs:{class: _1}};
|
||||
var vn2 = h('div', p2, c2);
|
||||
return vn2;
|
||||
@@ -70,7 +70,7 @@ exports[`attributes format expression 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = (context['value'] + 37);
|
||||
var _1 = (context['value']+37);
|
||||
let c2 = [], p2 = {key:2,attrs:{foo: _1}};
|
||||
var vn2 = h('div', p2, c2);
|
||||
return vn2;
|
||||
@@ -81,7 +81,7 @@ exports[`attributes format expression, other format 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = (context['value'] + 37);
|
||||
var _1 = (context['value']+37);
|
||||
let c2 = [], p2 = {key:2,attrs:{foo: _1}};
|
||||
var vn2 = h('div', p2, c2);
|
||||
return vn2;
|
||||
@@ -127,7 +127,7 @@ exports[`attributes from object variables set previously 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = {a: 'b'};
|
||||
var _2 = {a:'b'};
|
||||
var _3 = _2.a;
|
||||
let c4 = [], p4 = {key:4,attrs:{class: _3}};
|
||||
var vn4 = h('span', p4, c4);
|
||||
@@ -223,7 +223,7 @@ exports[`attributes t-att-class with object 1`] = `
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = 'static';
|
||||
var _3 = this.utils.objectToAttrString({a: context['b'],c: context['d'],e: context['f']});
|
||||
var _3 = this.utils.objectToAttrString({a:context['b'],c:context['d'],e:context['f']});
|
||||
var _2 = 'static' + (_3 ? ' ' + _3 : '');
|
||||
let c4 = [], p4 = {key:4,attrs:{class: _2}};
|
||||
var vn4 = h('div', p4, c4);
|
||||
@@ -246,7 +246,7 @@ exports[`attributes tuple literal 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = ['foo', 'bar'];
|
||||
var _1 = ['foo','bar'];
|
||||
let c2 = [], p2 = {key:2,attrs:{}};
|
||||
if (_1 instanceof Array) {
|
||||
p2.attrs[_1[0]] = _1[1];
|
||||
@@ -303,7 +303,7 @@ exports[`debugging t-log 1`] = `
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = 42;
|
||||
console.log(_2 + 3)
|
||||
console.log(_2+3)
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
@@ -317,14 +317,15 @@ exports[`foreach does not pollute the rendering context 1`] = `
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = [1];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -344,16 +345,17 @@ exports[`foreach iterate on items (on a element node) 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = [1, 2];
|
||||
var _2 = [1,2];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -376,16 +378,17 @@ exports[`foreach iterate on items 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = [3, 2, 1];
|
||||
var _2 = [3,2,1];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -419,60 +422,15 @@ exports[`foreach iterate, dict param 1`] = `
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['value'];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
c1.push({text: \` [\`});
|
||||
var _5 = context['item_index'];
|
||||
if (_5 || _5 === 0) {
|
||||
c1.push({text: _5});
|
||||
}
|
||||
c1.push({text: \`: \`});
|
||||
var _6 = context['item'];
|
||||
if (_6 || _6 === 0) {
|
||||
c1.push({text: _6});
|
||||
}
|
||||
c1.push({text: \` \`});
|
||||
var _7 = context['item_value'];
|
||||
if (_7 || _7 === 0) {
|
||||
c1.push({text: _7});
|
||||
}
|
||||
c1.push({text: \` - \`});
|
||||
var _8 = context['item_parity'];
|
||||
if (_8 || _8 === 0) {
|
||||
c1.push({text: _8});
|
||||
}
|
||||
c1.push({text: \`] \`});
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`foreach iterate, integer param 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
context = Object.create(context);
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = 3;
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -504,16 +462,17 @@ exports[`foreach iterate, position 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = 5;
|
||||
var _2 = Array(5);
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.elem_first = i === 0;
|
||||
context.elem_last = i === _length3 - 1;
|
||||
context.elem_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.elem_index = i;
|
||||
context.elem = _3[i];
|
||||
context.elem_value = _4[i];
|
||||
@@ -525,7 +484,7 @@ exports[`foreach iterate, position 1`] = `
|
||||
c1.push({text: \` last\`});
|
||||
}
|
||||
c1.push({text: \` (\`});
|
||||
var _5 = context['elem_parity'];
|
||||
var _5 = context['elem_index'];
|
||||
if (_5 || _5 === 0) {
|
||||
c1.push({text: _5});
|
||||
}
|
||||
@@ -542,16 +501,17 @@ exports[`foreach warn if no key in some case 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = [1, 2];
|
||||
var _2 = [1,2];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -605,14 +565,15 @@ exports[`misc global 1`] = `
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = [4,5,6];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.value_first = i === 0;
|
||||
context.value_last = i === _length3 - 1;
|
||||
context.value_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.value_index = i;
|
||||
context.value = _3[i];
|
||||
context.value_value = _4[i];
|
||||
@@ -624,13 +585,13 @@ exports[`misc global 1`] = `
|
||||
c5.push({text: _6});
|
||||
}
|
||||
{
|
||||
let _11 = 'bbb'
|
||||
let _11 = 'bbb';
|
||||
var _13 = 'agüero';
|
||||
let c14 = [], p14 = {key:14,attrs:{\\"falló\\": _13},on:{}};
|
||||
var vn14 = h('Año', p14, c14);
|
||||
c1.push(vn14);
|
||||
{
|
||||
let _15 = 'aaa'
|
||||
let _15 = 'aaa';
|
||||
let c16 = [], p16 = {key:16,on:{}};
|
||||
var vn16 = h('span', p16, c16);
|
||||
c14.push(vn16);
|
||||
@@ -650,16 +611,13 @@ exports[`misc global 1`] = `
|
||||
c17.push({text: \`foo default\`});
|
||||
}
|
||||
var _19 = 'bbb';
|
||||
{
|
||||
let _19 = 'bbb'
|
||||
let c20 = [], p20 = {key:20,on:{}};
|
||||
var vn20 = h('span', p20, c20);
|
||||
c14.push(vn20);
|
||||
if (_19 || _19 === 0) {
|
||||
c20.push({text: _19});
|
||||
} else {
|
||||
c20.push({text: \`foo default\`});
|
||||
}
|
||||
let c20 = [], p20 = {key:20,on:{}};
|
||||
var vn20 = h('span', p20, c20);
|
||||
c14.push(vn20);
|
||||
if (_19 || _19 === 0) {
|
||||
c20.push({text: _19});
|
||||
} else {
|
||||
c20.push({text: \`foo default\`});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -768,6 +726,18 @@ exports[`static templates empty div 1`] = `
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`static templates simple dynamic value 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var _1 = context['text'];
|
||||
if (_1 || _1 === 0) {
|
||||
var vn2 = {text: _1};
|
||||
}
|
||||
return vn2;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`static templates simple string 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
@@ -777,6 +747,19 @@ exports[`static templates simple string 1`] = `
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`static templates simple string, with some dynamic value 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
var vn1 = {text: \`hello \`};
|
||||
var _2 = context['text'];
|
||||
if (_2 || _2 === 0) {
|
||||
vn1.text += _2;
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`t-call (template calling basic caller 1`] = `
|
||||
"function anonymous(context,extra
|
||||
) {
|
||||
@@ -795,11 +778,8 @@ exports[`t-call (template calling inherit context 1`] = `
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = 1;
|
||||
{
|
||||
let _2 = 1
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
return vn1;
|
||||
}"
|
||||
@@ -812,7 +792,7 @@ exports[`t-call (template calling scoped parameters 1`] = `
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
{
|
||||
let _2 = 42
|
||||
let _2 = 42;
|
||||
c1.push({text: \`ok\`});
|
||||
}
|
||||
var _3 = context['foo'];
|
||||
@@ -839,7 +819,7 @@ exports[`t-call (template calling with unused setbody 1`] = `
|
||||
) {
|
||||
var h = this.utils.h;
|
||||
{
|
||||
let _1 = 3
|
||||
let _1 = 3;
|
||||
let c2 = [], p2 = {key:2};
|
||||
var vn2 = h('div', p2, c2);
|
||||
c2.push({text: \`ok\`});
|
||||
@@ -866,7 +846,7 @@ exports[`t-call (template calling with used set body 1`] = `
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('span', p1, c1);
|
||||
{
|
||||
let _2 = 'ok'
|
||||
let _2 = 'ok';
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
@@ -955,13 +935,13 @@ exports[`t-if boolean value condition elif 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['color'] == 'black') {
|
||||
if (context['color']=='black') {
|
||||
c1.push({text: \`black pearl\`});
|
||||
}
|
||||
else if (context['color'] == 'yellow') {
|
||||
else if (context['color']=='yellow') {
|
||||
c1.push({text: \`yellow submarine\`});
|
||||
}
|
||||
else if (context['color'] == 'red') {
|
||||
else if (context['color']=='red') {
|
||||
c1.push({text: \`red is dead\`});
|
||||
}
|
||||
else {
|
||||
@@ -1064,28 +1044,28 @@ exports[`t-if can use some boolean operators in expressions 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
if (context['cond1'] && context['cond2']) {
|
||||
if (context['cond1']&&context['cond2']) {
|
||||
c1.push({text: \`and\`});
|
||||
}
|
||||
if (context['cond1'] && context['cond3']) {
|
||||
if (context['cond1']&&context['cond3']) {
|
||||
c1.push({text: \`nope\`});
|
||||
}
|
||||
if (context['cond1'] || context['cond3']) {
|
||||
if (context['cond1']||context['cond3']) {
|
||||
c1.push({text: \`or\`});
|
||||
}
|
||||
if (context['cond3'] || context['cond4']) {
|
||||
if (context['cond3']||context['cond4']) {
|
||||
c1.push({text: \`nope\`});
|
||||
}
|
||||
if (context['m'] > 3) {
|
||||
if (context['m']>3) {
|
||||
c1.push({text: \`mgt\`});
|
||||
}
|
||||
if (context['n'] > 3) {
|
||||
if (context['n']>3) {
|
||||
c1.push({text: \`ngt\`});
|
||||
}
|
||||
if (context['m'] < 3) {
|
||||
if (context['m']<3) {
|
||||
c1.push({text: \`mlt\`});
|
||||
}
|
||||
if (context['n'] < 3) {
|
||||
if (context['n']<3) {
|
||||
c1.push({text: \`nlt\`});
|
||||
}
|
||||
return vn1;
|
||||
@@ -1115,14 +1095,15 @@ exports[`t-key t-key directive in a list 1`] = `
|
||||
var vn1 = h('ul', p1, c1);
|
||||
var _2 = context['beers'];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.beer_first = i === 0;
|
||||
context.beer_last = i === _length3 - 1;
|
||||
context.beer_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.beer_index = i;
|
||||
context.beer = _3[i];
|
||||
context.beer_value = _4[i];
|
||||
@@ -1215,14 +1196,15 @@ exports[`t-on can bind handlers with loop variable as argument 1`] = `
|
||||
var vn1 = h('ul', p1, c1);
|
||||
var _2 = ['someval'];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.action_first = i === 0;
|
||||
context.action_last = i === _length3 - 1;
|
||||
context.action_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.action_index = i;
|
||||
context.action = _3[i];
|
||||
context.action_value = _4[i];
|
||||
@@ -1252,7 +1234,7 @@ exports[`t-on can bind handlers with object arguments 1`] = `
|
||||
if (!context['add']) {
|
||||
throw new Error('Missing handler \\\\'' + 'add' + \`\\\\' when evaluating template 'test'\`)
|
||||
}
|
||||
p1.on['click'] = context['add'].bind(owner, {val: 5});
|
||||
p1.on['click'] = context['add'].bind(owner, {val:5});
|
||||
c1.push({text: \`Click\`});
|
||||
return vn1;
|
||||
}"
|
||||
@@ -1543,14 +1525,15 @@ exports[`t-ref refs in a loop 1`] = `
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['items'];
|
||||
if (!_2) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _2 === 'number') { _2 = Array.from(Array(_2).keys())}
|
||||
var _3 = _2 instanceof Array ? _2 : Object.keys(_2);
|
||||
var _3 = _4 = _2;
|
||||
if (!(_2 instanceof Array)) {
|
||||
_3 = Object.keys(_2);
|
||||
_4 = Object.values(_2);
|
||||
}
|
||||
var _length3 = _3.length;
|
||||
var _4 = _2 instanceof Array ? _2 : Object.values(_2);
|
||||
for (let i = 0; i < _length3; i++) {
|
||||
context.item_first = i === 0;
|
||||
context.item_last = i === _length3 - 1;
|
||||
context.item_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.item_index = i;
|
||||
context.item = _3[i];
|
||||
context.item_value = _4[i];
|
||||
@@ -1578,7 +1561,7 @@ exports[`t-set evaluate value expression 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = 1 + 2;
|
||||
var _2 = 1+2;
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
@@ -1592,7 +1575,7 @@ exports[`t-set evaluate value expression, part 2 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['somevariable'] + 2;
|
||||
var _2 = context['somevariable']+2;
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
@@ -1668,7 +1651,7 @@ exports[`t-set t-set and t-if 1`] = `
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['value'];
|
||||
if (_2 === 'ok') {
|
||||
if (_2==='ok') {
|
||||
c1.push({text: \`grimbergen\`});
|
||||
}
|
||||
return vn1;
|
||||
@@ -1681,7 +1664,7 @@ exports[`t-set t-set evaluates an expression only once 1`] = `
|
||||
var h = this.utils.h;
|
||||
let c1 = [], p1 = {key:1};
|
||||
var vn1 = h('div', p1, c1);
|
||||
var _2 = context['value'] + ' artois';
|
||||
var _2 = context['value']+' artois';
|
||||
if (_2 || _2 === 0) {
|
||||
c1.push({text: _2});
|
||||
}
|
||||
@@ -1702,14 +1685,15 @@ exports[`t-set t-set should reuse variable if possible 1`] = `
|
||||
var _2 = 1;
|
||||
var _3 = context['list'];
|
||||
if (!_3) { throw new Error('QWeb error: Invalid loop expression')}
|
||||
if (typeof _3 === 'number') { _3 = Array.from(Array(_3).keys())}
|
||||
var _4 = _3 instanceof Array ? _3 : Object.keys(_3);
|
||||
var _4 = _5 = _3;
|
||||
if (!(_3 instanceof Array)) {
|
||||
_4 = Object.keys(_3);
|
||||
_5 = Object.values(_3);
|
||||
}
|
||||
var _length4 = _4.length;
|
||||
var _5 = _3 instanceof Array ? _3 : Object.values(_3);
|
||||
for (let i = 0; i < _length4; i++) {
|
||||
context.elem_first = i === 0;
|
||||
context.elem_last = i === _length4 - 1;
|
||||
context.elem_parity = i % 2 === 0 ? 'even' : 'odd';
|
||||
context.elem_index = i;
|
||||
context.elem = _4[i];
|
||||
context.elem_value = _5[i];
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`connecting a component to store connecting a component to a local store 1`] = `"<div></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component to a local store 2`] = `"<div><span>hello</span></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component works 1`] = `"<div></div>"`;
|
||||
|
||||
exports[`connecting a component to store connecting a component works 2`] = `"<div><span>hello</span></div>"`;
|
||||
|
||||
+131
-2
@@ -253,11 +253,11 @@ describe("animations", () => {
|
||||
widget.state.display = false;
|
||||
patchNextFrame(cb => {
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave chimay-leave-active">blue</span></div>'
|
||||
'<div><span class="chimay-leave chimay-leave-active" data-owl-key="4">blue</span></div>'
|
||||
);
|
||||
cb();
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="chimay-leave-active chimay-leave-to">blue</span></div>'
|
||||
'<div><span class="chimay-leave-active chimay-leave-to" data-owl-key="4">blue</span></div>'
|
||||
);
|
||||
def.resolve();
|
||||
});
|
||||
@@ -287,4 +287,133 @@ describe("animations", () => {
|
||||
expect(widget.f).toHaveBeenCalledTimes(1);
|
||||
unpatchNextFrame();
|
||||
});
|
||||
|
||||
test("t-transition, remove and re-add before transitionend", async () => {
|
||||
expect.assertions(11);
|
||||
|
||||
env.qweb.addTemplates(
|
||||
`<templates>
|
||||
<div t-name="Parent">
|
||||
<button t-on-click="toggle">Toggle</button>
|
||||
<span t-if="state.flag" t-transition="chimay">blue</span>
|
||||
</div>
|
||||
</templates>`
|
||||
);
|
||||
class Parent extends Widget {
|
||||
constructor(parent) {
|
||||
super(parent);
|
||||
this.state = { flag: false };
|
||||
}
|
||||
toggle() {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new Parent(env);
|
||||
await widget.mount(fixture);
|
||||
let button = widget.el!.querySelector("button");
|
||||
|
||||
let def = makeDeferred();
|
||||
let phase = "enter";
|
||||
patchNextFrame(cb => {
|
||||
let spans = fixture.querySelectorAll("span");
|
||||
expect(spans.length).toBe(1);
|
||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||
cb();
|
||||
expect(spans[0].className).toBe(
|
||||
`chimay-${phase}-active chimay-${phase}-to`
|
||||
);
|
||||
def.resolve();
|
||||
});
|
||||
|
||||
// click display the span
|
||||
button!.click();
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><button>Toggle</button><span class="">blue</span></div>'
|
||||
);
|
||||
|
||||
// click to remove the span, and click again to re-add it before transitionend
|
||||
def = makeDeferred();
|
||||
phase = "leave";
|
||||
button!.click();
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
def = makeDeferred();
|
||||
phase = "enter";
|
||||
button!.click();
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><button>Toggle</button><span class="">blue</span></div>'
|
||||
);
|
||||
});
|
||||
|
||||
test("t-transition combined with t-widget, remove and re-add before transitionend", async () => {
|
||||
expect.assertions(11);
|
||||
|
||||
env.qweb.addTemplates(
|
||||
`<templates>
|
||||
<div t-name="Parent">
|
||||
<button t-on-click="toggle">Toggle</button>
|
||||
<t t-if="state.flag" t-widget="Child" t-transition="chimay"/>
|
||||
</div>
|
||||
<span t-name="Child">blue</span>
|
||||
</templates>`
|
||||
);
|
||||
class Child extends Widget {}
|
||||
class Parent extends Widget {
|
||||
widgets = { Child };
|
||||
constructor(parent) {
|
||||
super(parent);
|
||||
this.state = { flag: false };
|
||||
}
|
||||
toggle() {
|
||||
this.state.flag = !this.state.flag;
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new Parent(env);
|
||||
await widget.mount(fixture);
|
||||
let button = widget.el!.querySelector("button");
|
||||
|
||||
let def = makeDeferred();
|
||||
let phase = "enter";
|
||||
patchNextFrame(cb => {
|
||||
let spans = fixture.querySelectorAll("span");
|
||||
expect(spans.length).toBe(1);
|
||||
expect(spans[0].className).toBe(`chimay-${phase} chimay-${phase}-active`);
|
||||
cb();
|
||||
expect(spans[0].className).toBe(
|
||||
`chimay-${phase}-active chimay-${phase}-to`
|
||||
);
|
||||
def.resolve();
|
||||
});
|
||||
|
||||
// click display the span
|
||||
button!.click();
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><button>Toggle</button><span class="">blue</span></div>'
|
||||
);
|
||||
|
||||
// click to remove the span, and click again to re-add it before transitionend
|
||||
def = makeDeferred();
|
||||
phase = "leave";
|
||||
button!.click();
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
def = makeDeferred();
|
||||
phase = "enter";
|
||||
button!.click();
|
||||
|
||||
await def; // wait for the mocked repaint to be done
|
||||
widget.el!.querySelector("span")!.dispatchEvent(new Event("transitionend")); // mock end of css transition
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><button>Toggle</button><span class="">blue</span></div>'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+135
-19
@@ -1144,6 +1144,39 @@ describe("composition", () => {
|
||||
expect(input2.value).toBe("test");
|
||||
});
|
||||
|
||||
test("sub widget with t-ref and t-keepalive", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="ParentWidget">
|
||||
<t t-if="state.ok"><t t-widget="ChildWidget" t-ref="child" t-keepalive="1"/></t>
|
||||
</div>
|
||||
<span t-name="ChildWidget">Hello</span>
|
||||
</templates>`);
|
||||
class ParentWidget extends Widget {
|
||||
state = { ok: true };
|
||||
widgets = { ChildWidget };
|
||||
}
|
||||
class ChildWidget extends Widget {}
|
||||
const widget = new ParentWidget(env);
|
||||
await widget.mount(fixture);
|
||||
let child = children(widget)[0];
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><span>Hello</span></div>");
|
||||
expect(widget.refs.child).toEqual(child);
|
||||
|
||||
widget.state.ok = false;
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div></div>");
|
||||
expect(widget.refs.child).toEqual(child);
|
||||
|
||||
widget.state.ok = true;
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div><span>Hello</span></div>");
|
||||
expect(widget.refs.child).toEqual(child);
|
||||
});
|
||||
|
||||
test("sub widgets rendered in a loop", async () => {
|
||||
env.qweb.addTemplate("ChildWidget", `<span><t t-esc="props.n"/></span>`);
|
||||
class ChildWidget extends Widget {}
|
||||
@@ -1815,7 +1848,7 @@ describe("random stuff/miscellaneous", () => {
|
||||
// directive as a key
|
||||
env.qweb.addTemplate(
|
||||
"Test",
|
||||
`<div><t t-foreach="2">txt</t><t t-widget="widget"/></div>`
|
||||
`<div><t t-foreach="Array(2)">txt</t><t t-widget="widget"/></div>`
|
||||
);
|
||||
class Test extends Widget {
|
||||
widgets = { widget: Widget };
|
||||
@@ -2465,24 +2498,6 @@ describe("widget and observable state", () => {
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("widget can add observed keys to its state", async () => {
|
||||
env.qweb.addTemplate(
|
||||
"TestWidget",
|
||||
`<div><t t-esc="state.a"/><t t-esc="state.b"/></div>`
|
||||
);
|
||||
class TestWidget extends Widget {
|
||||
state: any = { a: 1 };
|
||||
}
|
||||
const widget = new TestWidget(env);
|
||||
await widget.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe("<div>1</div>");
|
||||
|
||||
widget.set(widget.state, "b", 2);
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toBe("<div>12</div>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("t-mounted directive", () => {
|
||||
@@ -2598,3 +2613,104 @@ describe("can deduce template from name", () => {
|
||||
expect(fixture.innerHTML).toBe("<span>Rochefort 10</span>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("t-slot directive", () => {
|
||||
test("can define and call slots", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="Parent">
|
||||
<t t-widget="Dialog">
|
||||
<t t-set="header"><span>header</span></t>
|
||||
<t t-set="footer"><span>footer</span></t>
|
||||
</t>
|
||||
</div>
|
||||
<div t-name="Dialog">
|
||||
<div><t t-slot="header"/></div>
|
||||
<div><t t-slot="footer"/></div>
|
||||
</div>
|
||||
</templates>
|
||||
`);
|
||||
class Dialog extends Widget {}
|
||||
class Parent extends Widget {
|
||||
widgets = { Dialog };
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe(
|
||||
"<div><div><div><span>header</span></div><div><span>footer</span></div></div></div>"
|
||||
);
|
||||
expect(env.qweb.templates.Parent.fn.toString()).toMatchSnapshot();
|
||||
expect(env.qweb.templates.Dialog.fn.toString()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("slots are rendered with proper context", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="Parent">
|
||||
<span class="counter"><t t-esc="state.val"/></span>
|
||||
<t t-widget="Dialog">
|
||||
<t t-set="footer"><button t-on-click="doSomething">do something</button></t>
|
||||
</t>
|
||||
</div>
|
||||
<span t-name="Dialog"><t t-slot="footer"/></span>
|
||||
</templates>
|
||||
`);
|
||||
class Dialog extends Widget {}
|
||||
class Parent extends Widget {
|
||||
widgets = { Dialog };
|
||||
state = { val: 0 };
|
||||
doSomething() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="counter">0</span><span><button>do something</button></span></div>'
|
||||
);
|
||||
|
||||
fixture.querySelector("button")!.click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="counter">1</span><span><button>do something</button></span></div>'
|
||||
);
|
||||
});
|
||||
|
||||
test("refs are properly bound in slots", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="Parent">
|
||||
<span class="counter"><t t-esc="state.val"/></span>
|
||||
<t t-widget="Dialog">
|
||||
<t t-set="footer"><button t-ref="myButton" t-on-click="doSomething">do something</button></t>
|
||||
</t>
|
||||
</div>
|
||||
<span t-name="Dialog"><t t-slot="footer"/></span>
|
||||
</templates>
|
||||
`);
|
||||
class Dialog extends Widget {}
|
||||
class Parent extends Widget {
|
||||
widgets = { Dialog };
|
||||
state = { val: 0 };
|
||||
doSomething() {
|
||||
this.state.val++;
|
||||
}
|
||||
}
|
||||
const parent = new Parent(env);
|
||||
await parent.mount(fixture);
|
||||
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="counter">0</span><span><button>do something</button></span></div>'
|
||||
);
|
||||
|
||||
(<any>parent.refs.myButton).click();
|
||||
await nextTick();
|
||||
|
||||
expect(fixture.innerHTML).toBe(
|
||||
'<div><span class="counter">1</span><span><button>do something</button></span></div>'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Doc Link Checker
|
||||
*
|
||||
* We define here a test to make sure that there are no dead link in the Owl
|
||||
* documentation.
|
||||
*/
|
||||
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";
|
||||
return DOCFILES.concat(MAINREADME);
|
||||
}
|
||||
|
||||
test("All markdown links work", () => {
|
||||
let linkNumber = 0;
|
||||
let invalidLinkNumber = 0;
|
||||
const files = getFiles();
|
||||
const data = readDocData(files);
|
||||
for (let file of data) {
|
||||
for (let link of file.links) {
|
||||
// DEBUG: uncomment next line
|
||||
// console.warn(`Checking "${link.name}" in "${file.name}"`);
|
||||
linkNumber++;
|
||||
if (!isLinkValid(link, file, data)) {
|
||||
console.warn(`Invalid Link: "${link.name}" in "${file.name}"`);
|
||||
invalidLinkNumber++;
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(invalidLinkNumber).toBe(0);
|
||||
expect(linkNumber).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
interface MarkDownLink {
|
||||
name: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
interface MarkDownSection {
|
||||
name: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
interface FileData {
|
||||
name: string;
|
||||
links: MarkDownLink[];
|
||||
sections: MarkDownSection[];
|
||||
}
|
||||
|
||||
function isLinkValid(
|
||||
link: MarkDownLink,
|
||||
current: FileData,
|
||||
files: FileData[]
|
||||
): boolean {
|
||||
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;
|
||||
}
|
||||
}
|
||||
} 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])) {
|
||||
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 = "àáäâãåăæçèéëêǵḧìíïîḿńǹñòóöôœøṕŕßśșțùúüûǘẃẍÿź·_,:;";
|
||||
const b = "aaaaaaaaceeeeghiiiimnnnooooooprssstuuuuuwxyz-----";
|
||||
const p = new RegExp(a.split("").join("|"), "g");
|
||||
return str
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.replace(/\//g, "") // remove /
|
||||
.replace(/\s+/g, "-") // Replace spaces with -
|
||||
.replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
|
||||
.replace(/&/g, "-and-") // Replace & with ‘and’
|
||||
.replace(/[^\w\-]+/g, "") // Remove all non-word characters
|
||||
.replace(/\-\-+/g, "-") // Replace multiple - with single -
|
||||
.replace(/^-+/, "") // Trim - from start of text
|
||||
.replace(/-+$/, ""); // Trim - from end of text
|
||||
}
|
||||
|
||||
function readDocData(files: string[]): FileData[] {
|
||||
const result: FileData[] = [];
|
||||
|
||||
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] });
|
||||
}
|
||||
} 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;
|
||||
}
|
||||
@@ -134,6 +134,57 @@ describe("observer", () => {
|
||||
expect(arr[0].__owl__.rev).toBe(3);
|
||||
});
|
||||
|
||||
test("set new property on observed object", async () => {
|
||||
const observer = new Observer();
|
||||
observer.notifyCB = jest.fn();
|
||||
const state: any = { a: 1 };
|
||||
observer.observe(state);
|
||||
expect(state.__owl__.rev).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||
|
||||
Observer.set(state, "b", 8);
|
||||
await nextMicroTick();
|
||||
expect(state.__owl__.rev).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||
expect(state.b).toBe(8);
|
||||
});
|
||||
|
||||
test("delete property from observed object", async () => {
|
||||
const observer = new Observer();
|
||||
observer.notifyCB = jest.fn();
|
||||
const state: any = { a: 1, b: 8 };
|
||||
observer.observe(state);
|
||||
expect(state.__owl__.rev).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||
|
||||
Observer.delete(state, "b");
|
||||
await nextMicroTick();
|
||||
expect(state.__owl__.rev).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||
expect(state).toEqual({ a: 1 });
|
||||
});
|
||||
|
||||
test("set element in observed array", async () => {
|
||||
const observer = new Observer();
|
||||
observer.notifyCB = jest.fn();
|
||||
const state: any = ["a"];
|
||||
observer.observe(state);
|
||||
expect(state.__owl__.rev).toBe(1);
|
||||
expect(observer.rev).toBe(1);
|
||||
expect(observer.notifyCB).toBeCalledTimes(0);
|
||||
|
||||
Observer.set(state, 1, "b");
|
||||
await nextMicroTick();
|
||||
expect(state.__owl__.rev).toBe(2);
|
||||
expect(observer.rev).toBe(2);
|
||||
expect(observer.notifyCB).toBeCalledTimes(1);
|
||||
expect(state).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("properly observe arrays in object", () => {
|
||||
const observer = new Observer();
|
||||
const state: any = { arr: [] };
|
||||
|
||||
+21
-37
@@ -24,6 +24,16 @@ describe("static templates", () => {
|
||||
expect(renderToString(qweb, "test")).toBe("hello vdom");
|
||||
});
|
||||
|
||||
test("simple dynamic value", () => {
|
||||
qweb.addTemplate("test", "<t><t t-esc=\"text\"/></t>");
|
||||
expect(renderToString(qweb, "test", {text: "hello vdom"})).toBe("hello vdom");
|
||||
});
|
||||
|
||||
test("simple string, with some dynamic value", () => {
|
||||
qweb.addTemplate("test", "<t>hello <t t-esc=\"text\"/></t>");
|
||||
expect(renderToString(qweb, "test", {text: "vdom"})).toBe("hello vdom");
|
||||
});
|
||||
|
||||
test("empty div", () => {
|
||||
qweb.addTemplate("test", "<div></div>");
|
||||
expect(renderToString(qweb, "test")).toBe("<div></div>");
|
||||
@@ -84,23 +94,6 @@ describe("error handling", () => {
|
||||
).toThrow("Missing event name with t-on directive");
|
||||
});
|
||||
|
||||
test("error when compiled code is invalid", () => {
|
||||
const consoleWarn = console.warn;
|
||||
const consoleGroupCollapsed = console.groupCollapsed;
|
||||
console.warn = jest.fn();
|
||||
console.groupCollapsed = jest.fn();
|
||||
qweb.addTemplate(
|
||||
"templatename",
|
||||
`<div t-att-hey="}/^function invalid{{>'"></div>`
|
||||
);
|
||||
expect(() => qweb.render("templatename")).toThrow(
|
||||
"Invalid generated code while compiling template 'templatename': Unexpected token }"
|
||||
);
|
||||
expect(console.warn).toBeCalledTimes(1);
|
||||
console.warn = consoleWarn;
|
||||
console.groupCollapsed = consoleGroupCollapsed;
|
||||
});
|
||||
|
||||
test("error when unknown directive", () => {
|
||||
qweb.addTemplate(
|
||||
"templatename",
|
||||
@@ -184,7 +177,7 @@ describe("t-set", () => {
|
||||
test("t-set and t-if", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div >
|
||||
`<div>
|
||||
<t t-set="v" t-value="value"/>
|
||||
<t t-if="v === 'ok'">grimbergen</t>
|
||||
</div>`
|
||||
@@ -485,7 +478,7 @@ describe("attributes", () => {
|
||||
});
|
||||
|
||||
test("format expression, other format", () => {
|
||||
qweb.addTemplate("test", `<div t-attf-foo="#{value + 37}"/>`);
|
||||
qweb.addTemplate("test", `<div t-attf-foo="{{value + 37}}"/>`);
|
||||
const result = renderToString(qweb, "test", { value: 5 });
|
||||
expect(result).toBe(`<div foo="42"></div>`);
|
||||
});
|
||||
@@ -530,7 +523,10 @@ describe("attributes", () => {
|
||||
});
|
||||
|
||||
test("class and t-attf-class with ternary operation", () => {
|
||||
qweb.addTemplate("test", `<div class="hello" t-attf-class="#{value ? 'world' : ''}"/>`);
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div class="hello" t-attf-class="{{value ? 'world' : ''}}"/>`
|
||||
);
|
||||
const result = renderToString(qweb, "test", { value: true });
|
||||
expect(result).toBe(`<div class="hello world"></div>`);
|
||||
});
|
||||
@@ -657,25 +653,13 @@ describe("foreach", () => {
|
||||
"test",
|
||||
`
|
||||
<div>
|
||||
<t t-foreach="5" t-as="elem">
|
||||
-<t t-if="elem_first"> first</t><t t-if="elem_last"> last</t> (<t t-esc="elem_parity"/>)
|
||||
<t t-foreach="Array(5)" t-as="elem">
|
||||
-<t t-if="elem_first"> first</t><t t-if="elem_last"> last</t> (<t t-esc="elem_index"/>)
|
||||
</t>
|
||||
</div>`
|
||||
);
|
||||
const result = trim(renderToString(qweb, "test"));
|
||||
const expected = `<div>-first(even)-(odd)-(even)-(odd)-last(even)</div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
test("iterate, integer param", () => {
|
||||
qweb.addTemplate(
|
||||
"test",
|
||||
`<div><t t-foreach="3" t-as="item">
|
||||
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
|
||||
</t></div>`
|
||||
);
|
||||
const result = trim(renderToString(qweb, "test"));
|
||||
const expected = `<div>[0:00][1:11][2:22]</div>`;
|
||||
const expected = `<div>-first(0)-(1)-(2)-(3)-last(4)</div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
@@ -685,14 +669,14 @@ describe("foreach", () => {
|
||||
`
|
||||
<div>
|
||||
<t t-foreach="value" t-as="item">
|
||||
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/> - <t t-esc="item_parity"/>]
|
||||
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
|
||||
</t>
|
||||
</div>`
|
||||
);
|
||||
const result = trim(
|
||||
renderToString(qweb, "test", { value: { a: 1, b: 2, c: 3 } })
|
||||
);
|
||||
const expected = `<div>[0:a1-even][1:b2-odd][2:c3-even]</div>`;
|
||||
const expected = `<div>[0:a1][1:b2][2:c3]</div>`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { compileExpr, tokenize } from "../src/qweb_expressions";
|
||||
|
||||
describe("tokenizer", () => {
|
||||
test("simple tokens", () => {
|
||||
expect(tokenize("1.3")).toEqual([
|
||||
{ type: "VALUE", value: "1.3" }
|
||||
]);
|
||||
|
||||
expect(tokenize("{}")).toEqual([
|
||||
{ type: "LEFT_BRACE", value: "{" },
|
||||
{ type: "RIGHT_BRACE", value: "}" }
|
||||
]);
|
||||
expect(tokenize("{ }}")).toEqual([
|
||||
{ type: "LEFT_BRACE", value: "{" },
|
||||
{ type: "RIGHT_BRACE", value: "}" },
|
||||
{ type: "RIGHT_BRACE", value: "}" }
|
||||
]);
|
||||
expect(tokenize("a")).toEqual([{ type: "SYMBOL", value: "a" }]);
|
||||
expect(tokenize("true")).toEqual([{ type: "SYMBOL", value: "true" }]);
|
||||
expect(tokenize("abcde")).toEqual([{ type: "SYMBOL", value: "abcde" }]);
|
||||
expect(tokenize("_ab2")).toEqual([{ type: "SYMBOL", value: "_ab2" }]);
|
||||
expect(tokenize("$ab2")).toEqual([{ type: "SYMBOL", value: "$ab2" }]);
|
||||
expect(tokenize("ABC")).toEqual([{ type: "SYMBOL", value: "ABC" }]);
|
||||
|
||||
expect(tokenize("{a: 2}")).toEqual([
|
||||
{ type: "LEFT_BRACE", value: "{" },
|
||||
{ type: "SYMBOL", value: "a" },
|
||||
{ type: "COLON", value: ":" },
|
||||
{ type: "VALUE", value: "2" },
|
||||
{ type: "RIGHT_BRACE", value: "}" }
|
||||
]);
|
||||
expect(tokenize("a,")).toEqual([
|
||||
{ type: "SYMBOL", value: "a" },
|
||||
{ type: "COMMA", value: "," }
|
||||
]);
|
||||
expect(tokenize("][")).toEqual([
|
||||
{ type: "RIGHT_BRACKET", value: "]" },
|
||||
{ type: "LEFT_BRACKET", value: "[" }
|
||||
]);
|
||||
});
|
||||
|
||||
test("various operators", () => {
|
||||
expect(tokenize(">= <= < >")).toEqual([
|
||||
{ type: "OPERATOR", value: ">=" },
|
||||
{ type: "OPERATOR", value: "<=" },
|
||||
{ type: "OPERATOR", value: "<" },
|
||||
{ type: "OPERATOR", value: ">" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("strings", () => {
|
||||
expect(() => tokenize("'")).toThrow("Invalid expression");
|
||||
expect(() => tokenize("'\\")).toThrow("Invalid expression");
|
||||
expect(() => tokenize("'\\'")).toThrow("Invalid expression");
|
||||
expect(tokenize("'hello ged'")).toEqual([
|
||||
{ type: "VALUE", value: "'hello ged'" }
|
||||
]);
|
||||
expect(tokenize("'hello \\'ged\\''")).toEqual([
|
||||
{ type: "VALUE", value: "'hello \\'ged\\''" }
|
||||
]);
|
||||
|
||||
expect(() => tokenize('"')).toThrow("Invalid expression");
|
||||
expect(() => tokenize('"\\"')).toThrow("Invalid expression");
|
||||
expect(tokenize('"hello ged"')).toEqual([
|
||||
{ type: "VALUE", value: '"hello ged"' }
|
||||
]);
|
||||
expect(tokenize('"hello ged"}')).toEqual([
|
||||
{ type: "VALUE", value: '"hello ged"' },
|
||||
{ type: "RIGHT_BRACE", value: "}" }
|
||||
]);
|
||||
expect(tokenize('"hello \\"ged\\""')).toEqual([
|
||||
{ type: "VALUE", value: '"hello \\"ged\\""' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expression evaluation", () => {
|
||||
test("simple static values", () => {
|
||||
expect(compileExpr("1", {})).toBe("1");
|
||||
expect(compileExpr("1 ", {})).toBe("1");
|
||||
expect(compileExpr("'some string#/, {' ", {})).toBe("'some string#/, {'");
|
||||
expect(compileExpr("{ } ", {})).toBe("{}");
|
||||
expect(compileExpr("{a: 1} ", {})).toBe("{a:1}");
|
||||
expect(compileExpr("{a: 1, b: 2 } ", {})).toBe("{a:1,b:2}");
|
||||
expect(compileExpr("[] ", {})).toBe("[]");
|
||||
expect(compileExpr("[1] ", {})).toBe("[1]");
|
||||
expect(compileExpr("['1', '2'] ", {})).toBe("['1','2']");
|
||||
expect(compileExpr("['1', \"2\"] ", {})).toBe("['1',\"2\"]");
|
||||
});
|
||||
|
||||
test("various types of 'words'", () => {
|
||||
expect(compileExpr("true", {})).toBe("true");
|
||||
expect(compileExpr("false", {})).toBe("false");
|
||||
expect(compileExpr("debugger", {})).toBe("debugger");
|
||||
});
|
||||
|
||||
test("parenthesis", () => {
|
||||
expect(compileExpr("(1)", {})).toBe("(1)");
|
||||
expect(compileExpr("a*(1 +3)", {})).toBe("context['a']*(1+3)");
|
||||
});
|
||||
|
||||
test("objects and sub objects", () => {
|
||||
expect(compileExpr("{a:{b:1}} ", {})).toBe("{a:{b:1}}");
|
||||
});
|
||||
|
||||
test("replacing variables", () => {
|
||||
expect(compileExpr("a", {})).toBe("context['a']");
|
||||
expect(compileExpr("a", { a: { id: "_3", expr: "" } })).toBe("_3");
|
||||
});
|
||||
|
||||
test("arrays and objects", () => {
|
||||
expect(compileExpr("[{b:1}] ", {})).toBe("[{b:1}]");
|
||||
expect(compileExpr("{a: []} ", {})).toBe("{a:[]}");
|
||||
expect(compileExpr("[{b:1, c: [1, {d: {e: 3}} ]}] ", {})).toBe(
|
||||
"[{b:1,c:[1,{d:{e:3}}]}]"
|
||||
);
|
||||
});
|
||||
|
||||
test("dot operator", () => {
|
||||
expect(compileExpr("a.b", {})).toBe("context['a'].b");
|
||||
expect(compileExpr("a.b.c", {})).toBe("context['a'].b.c");
|
||||
});
|
||||
|
||||
test("various unary operators", () => {
|
||||
expect(compileExpr("!flag", {})).toBe("!context['flag']");
|
||||
expect(compileExpr("-3", {})).toBe("-3");
|
||||
expect(compileExpr("-a", {})).toBe("-context['a']");
|
||||
});
|
||||
|
||||
test("various binary operators", () => {
|
||||
expect(compileExpr("color == 'black'", {})).toBe(
|
||||
"context['color']=='black'"
|
||||
);
|
||||
expect(compileExpr("a || b", {})).toBe("context['a']||context['b']");
|
||||
expect(compileExpr("color === 'black'", {})).toBe(
|
||||
"context['color']==='black'"
|
||||
);
|
||||
expect(compileExpr("'li_'+item", {})).toBe("'li_'+context['item']");
|
||||
expect(compileExpr("state.val > 1", {})).toBe("context['state'].val>1");
|
||||
});
|
||||
|
||||
test("boolean operations", () => {
|
||||
expect(compileExpr("a && b", {})).toBe("context['a']&&context['b']");
|
||||
});
|
||||
|
||||
test("ternary operators", () => {
|
||||
expect(compileExpr("a ? b: '2'", {})).toBe("context['a']?context['b']:'2'");
|
||||
expect(compileExpr("a ? b: (c or '2') ", {})).toBe(
|
||||
"context['a']?context['b']:(context['c']||'2')"
|
||||
);
|
||||
expect(compileExpr("a ? {test:c}: [1,u]", {})).toBe(
|
||||
"context['a']?{test:context['c']}:[1,context['u']]"
|
||||
);
|
||||
});
|
||||
|
||||
test("word replacement", () => {
|
||||
expect(compileExpr("a or b", {})).toBe("context['a']||context['b']");
|
||||
expect(compileExpr("a and b", {})).toBe("context['a']&&context['b']");
|
||||
});
|
||||
|
||||
test("function calls", () => {
|
||||
expect(compileExpr("a()", {})).toBe("context['a']()");
|
||||
expect(compileExpr("a(1)", {})).toBe("context['a'](1)");
|
||||
expect(compileExpr("a(1,2)", {})).toBe("context['a'](1,2)");
|
||||
expect(compileExpr("a(1,2,{a:[a]})", {})).toBe(
|
||||
"context['a'](1,2,{a:[context['a']]})"
|
||||
);
|
||||
expect(compileExpr("'x'.toUpperCase()", {})).toBe("'x'.toUpperCase()");
|
||||
expect(compileExpr("'x'.toUpperCase({a: 3})", {})).toBe(
|
||||
"'x'.toUpperCase({a:3})"
|
||||
);
|
||||
expect(
|
||||
compileExpr("'x'.toUpperCase(a)", { a: { id: "_v5", expr: "" } })
|
||||
).toBe("'x'.toUpperCase(_v5)");
|
||||
expect(
|
||||
compileExpr("'x'.toUpperCase({b: a})", { a: { id: "_v5", expr: "" } })
|
||||
).toBe("'x'.toUpperCase({b:_v5})");
|
||||
});
|
||||
});
|
||||
+139
-71
@@ -152,24 +152,6 @@ describe("basic use", () => {
|
||||
store.dispatch("someaction");
|
||||
});
|
||||
|
||||
test("set function is given to mutations", async () => {
|
||||
let updateCounter = 0;
|
||||
const state = { bertinchamps: "brune" };
|
||||
const mutations = {
|
||||
addInfo({ state, set }) {
|
||||
set(state, "chouffe", "blonde");
|
||||
}
|
||||
};
|
||||
const store = new Store({ state, mutations, actions: {} });
|
||||
store.on("update", null, () => updateCounter++);
|
||||
|
||||
expect(updateCounter).toBe(0);
|
||||
store.commit("addInfo");
|
||||
await nextMicroTick();
|
||||
expect(updateCounter).toBe(1);
|
||||
expect(store.state).toEqual({ bertinchamps: "brune", chouffe: "blonde" });
|
||||
});
|
||||
|
||||
test("can have getters from store", async () => {
|
||||
const state = {
|
||||
beers: {
|
||||
@@ -429,10 +411,13 @@ describe("connecting a component to store", () => {
|
||||
state.todos.push({ msg });
|
||||
}
|
||||
};
|
||||
function mapStateToProps(s) {
|
||||
function mapStoreToProps(s) {
|
||||
return { todos: s.todos };
|
||||
}
|
||||
const TodoApp = connect(mapStateToProps)(App);
|
||||
const TodoApp = connect(
|
||||
App,
|
||||
mapStoreToProps
|
||||
);
|
||||
const store = new Store({ state, mutations });
|
||||
(<any>env).store = store;
|
||||
const app = new TodoApp(env);
|
||||
@@ -452,7 +437,7 @@ describe("connecting a component to store", () => {
|
||||
state.todos[0].title = title;
|
||||
}
|
||||
};
|
||||
function mapStateToProps(s) {
|
||||
function mapStoreToProps(s) {
|
||||
return { todos: s.todos };
|
||||
}
|
||||
const store = new Store({ state, mutations });
|
||||
@@ -469,13 +454,15 @@ describe("connecting a component to store", () => {
|
||||
class App extends Component<any, any, any> {}
|
||||
|
||||
const DeepTodoApp = connect(
|
||||
mapStateToProps,
|
||||
App,
|
||||
mapStoreToProps,
|
||||
{ deep: true }
|
||||
)(App);
|
||||
);
|
||||
const ShallowTodoApp = connect(
|
||||
mapStateToProps,
|
||||
App,
|
||||
mapStoreToProps,
|
||||
{ deep: false }
|
||||
)(App);
|
||||
);
|
||||
(<any>env).store = store;
|
||||
const deepTodoApp = new DeepTodoApp(env);
|
||||
const shallowTodoApp = new ShallowTodoApp(env);
|
||||
@@ -494,6 +481,51 @@ describe("connecting a component to store", () => {
|
||||
expect(shallowFix.innerHTML).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("connecting a component to a local store", async () => {
|
||||
env.qweb.addTemplates(`
|
||||
<templates>
|
||||
<div t-name="App">
|
||||
<t t-foreach="props.todos" t-as="todo" t-key="todo">
|
||||
<t t-widget="Todo" msg="todo.msg"/>
|
||||
</t>
|
||||
</div>
|
||||
<span t-name="Todo"><t t-esc="props.msg"/></span>
|
||||
</templates>
|
||||
`);
|
||||
class App extends Component<any, any, any> {
|
||||
widgets = { Todo };
|
||||
}
|
||||
class Todo extends Component<any, any, any> {}
|
||||
|
||||
(<any>env).store = new Store({});
|
||||
const store = new Store({
|
||||
state: { todos: [] },
|
||||
mutations: {
|
||||
addTodo({ state }, msg) {
|
||||
state.todos.push({ msg });
|
||||
}
|
||||
}
|
||||
});
|
||||
function mapStoreToProps(s) {
|
||||
return { todos: s.todos };
|
||||
}
|
||||
const TodoApp = connect(
|
||||
App,
|
||||
mapStoreToProps,
|
||||
{
|
||||
getStore: () => store
|
||||
}
|
||||
);
|
||||
const app = new TodoApp(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
|
||||
(<any>app.__owl__).store.commit("addTodo", "hello");
|
||||
await nextTick();
|
||||
expect(fixture.innerHTML).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("connected child components with custom hooks", async () => {
|
||||
let steps: any = [];
|
||||
env.qweb.addTemplate("Child", `<div/>`);
|
||||
@@ -506,7 +538,10 @@ describe("connecting a component to store", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const ConnectedChild = connect(s => s)(Child);
|
||||
const ConnectedChild = connect(
|
||||
Child,
|
||||
s => s
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"Parent",
|
||||
@@ -548,10 +583,13 @@ describe("connecting a component to store", () => {
|
||||
|
||||
env.qweb.addTemplate("TodoItem", `<span><t t-esc="props.text"/></span>`);
|
||||
class TodoItem extends Component<any, any, any> {}
|
||||
const ConnectedTodo = connect((state, props) => {
|
||||
const todo = state.todos.find(t => t.id === props.id);
|
||||
return todo;
|
||||
})(TodoItem);
|
||||
const ConnectedTodo = connect(
|
||||
TodoItem,
|
||||
(state, props) => {
|
||||
const todo = state.todos.find(t => t.id === props.id);
|
||||
return todo;
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"TodoList",
|
||||
@@ -565,10 +603,13 @@ describe("connecting a component to store", () => {
|
||||
widgets = { ConnectedTodo };
|
||||
}
|
||||
|
||||
function mapStateToProps(state) {
|
||||
function mapStoreToProps(state) {
|
||||
return { todos: state.todos };
|
||||
}
|
||||
const ConnectedTodoList = connect(mapStateToProps)(TodoList);
|
||||
const ConnectedTodoList = connect(
|
||||
TodoList,
|
||||
mapStoreToProps
|
||||
);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new ConnectedTodoList(env);
|
||||
@@ -606,13 +647,16 @@ describe("connecting a component to store", () => {
|
||||
</div>`
|
||||
);
|
||||
class TodoItem extends Component<any, any, any> {}
|
||||
const ConnectedTodo = connect((state, props, getters) => {
|
||||
const todo = state.todos.find(t => t.id === props.id);
|
||||
return {
|
||||
activeTodoText: getters.text(todo.id),
|
||||
importantTodoText: getters.importantTodoText()
|
||||
};
|
||||
})(TodoItem);
|
||||
const ConnectedTodo = connect(
|
||||
TodoItem,
|
||||
(state, props, getters) => {
|
||||
const todo = state.todos.find(t => t.id === props.id);
|
||||
return {
|
||||
activeTodoText: getters.text(todo.id),
|
||||
importantTodoText: getters.importantTodoText()
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"TodoList",
|
||||
@@ -626,10 +670,13 @@ describe("connecting a component to store", () => {
|
||||
widgets = { ConnectedTodo };
|
||||
}
|
||||
|
||||
function mapStateToProps(state) {
|
||||
function mapStoreToProps(state) {
|
||||
return { todos: state.todos };
|
||||
}
|
||||
const ConnectedTodoList = connect(mapStateToProps)(TodoList);
|
||||
const ConnectedTodoList = connect(
|
||||
TodoList,
|
||||
mapStoreToProps
|
||||
);
|
||||
|
||||
(<any>env).store = store;
|
||||
const app = new ConnectedTodoList(env);
|
||||
@@ -643,9 +690,12 @@ describe("connecting a component to store", () => {
|
||||
test("connected component is updated when props are updated", async () => {
|
||||
env.qweb.addTemplate("Beer", `<span><t t-esc="props.name"/></span>`);
|
||||
class Beer extends Component<any, any, any> {}
|
||||
const ConnectedBeer = connect((state, props) => {
|
||||
return state.beers[props.id];
|
||||
})(Beer);
|
||||
const ConnectedBeer = connect(
|
||||
Beer,
|
||||
(state, props) => {
|
||||
return state.beers[props.id];
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"App",
|
||||
@@ -691,10 +741,13 @@ describe("connecting a component to store", () => {
|
||||
const store = new Store({ state, mutations });
|
||||
(<any>env).store = store;
|
||||
|
||||
function mapStateToProps(state) {
|
||||
function mapStoreToProps(state) {
|
||||
return { beers: state.beers, otherKey: 1 };
|
||||
}
|
||||
const ConnectedApp = connect(mapStateToProps)(App);
|
||||
const ConnectedApp = connect(
|
||||
App,
|
||||
mapStoreToProps
|
||||
);
|
||||
const app = new ConnectedApp(env);
|
||||
|
||||
await app.mount(fixture);
|
||||
@@ -717,13 +770,16 @@ describe("connecting a component to store", () => {
|
||||
</div>`
|
||||
);
|
||||
class Beer extends Component<any, any, any> {}
|
||||
const ConnectedBeer = connect((state, props) => {
|
||||
return {
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
};
|
||||
})(Beer);
|
||||
const ConnectedBeer = connect(
|
||||
Beer,
|
||||
(state, props) => {
|
||||
return {
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"App",
|
||||
@@ -786,13 +842,16 @@ describe("connecting a component to store", () => {
|
||||
</div>`
|
||||
);
|
||||
class Beer extends Component<any, any, any> {}
|
||||
const ConnectedBeer = connect((state, props) => {
|
||||
return {
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
};
|
||||
})(Beer);
|
||||
const ConnectedBeer = connect(
|
||||
Beer,
|
||||
(state, props) => {
|
||||
return {
|
||||
selected: state.beers[props.id],
|
||||
consumed: state.beers[state.consumedID] || null,
|
||||
taster: state.taster
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate(
|
||||
"App",
|
||||
@@ -883,18 +942,24 @@ describe("connecting a component to store", () => {
|
||||
class Parent extends Component<any, any, any> {
|
||||
widgets = { Child: ConnectedChild };
|
||||
}
|
||||
const ConnectedParent = connect(function(s) {
|
||||
steps.push("parent");
|
||||
return { current: s.current, isvisible: s.isvisible };
|
||||
})(Parent);
|
||||
const ConnectedParent = connect(
|
||||
Parent,
|
||||
function(s) {
|
||||
steps.push("parent");
|
||||
return { current: s.current, isvisible: s.isvisible };
|
||||
}
|
||||
);
|
||||
|
||||
env.qweb.addTemplate("Child", `<span><t t-esc="props.msg"/></span>`);
|
||||
class Child extends Component<any, any, any> {}
|
||||
|
||||
const ConnectedChild = connect(function(s, props) {
|
||||
steps.push("child");
|
||||
return { msg: s.msg[props.key] };
|
||||
})(Child);
|
||||
const ConnectedChild = connect(
|
||||
Child,
|
||||
function(s, props) {
|
||||
steps.push("child");
|
||||
return { msg: s.msg[props.key] };
|
||||
}
|
||||
);
|
||||
|
||||
const state = { current: "a", msg: { a: "a", b: "b" } };
|
||||
const mutations = {
|
||||
@@ -927,9 +992,12 @@ describe("connecting a component to store", () => {
|
||||
steps.push("patched");
|
||||
}
|
||||
}
|
||||
const ConnectedApp = connect(function(s) {
|
||||
return { msg: s.msg };
|
||||
})(App);
|
||||
const ConnectedApp = connect(
|
||||
App,
|
||||
function(s) {
|
||||
return { msg: s.msg };
|
||||
}
|
||||
);
|
||||
|
||||
const state = { msg: "a" };
|
||||
const mutations = {
|
||||
|
||||
+118
-35
@@ -1,4 +1,9 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
odoo.define("app", function(require) {
|
||||
const Widget = require("web.Widget");
|
||||
@@ -97,14 +102,23 @@ odoo.define("app", function(require) {
|
||||
"click .o_btn_msg.10000": function() {
|
||||
this.addMessages(10000);
|
||||
},
|
||||
"click .o_btn_msg.50000": function() {
|
||||
this.addMessages(50000);
|
||||
"click .o_btn_msg.30000": function() {
|
||||
this.addMessages(30000);
|
||||
},
|
||||
"click .updateSomeMessages": function() {
|
||||
this.updateSomeMessages();
|
||||
},
|
||||
"click .clear": function() {
|
||||
this.clear();
|
||||
},
|
||||
"click .o_multiple": function() {
|
||||
this.multipleFlag = !this.multipleFlag;
|
||||
},
|
||||
"click .o_clear": function() {
|
||||
this.clearFlag = !this.clearFlag;
|
||||
},
|
||||
"click .clear-log": function() {
|
||||
this.$log[0].innerHTML = "";
|
||||
}
|
||||
},
|
||||
custom_events: {
|
||||
@@ -116,11 +130,15 @@ odoo.define("app", function(require) {
|
||||
this.widgets = {};
|
||||
this.isInDom = false;
|
||||
this.messageCount = 0;
|
||||
this.multipleFlag = false;
|
||||
this.clearFlag = false;
|
||||
},
|
||||
|
||||
start: function() {
|
||||
this.$content = this.$(".content");
|
||||
this.$msgCount = this.$(".message_count");
|
||||
this.$log = this.$(".log-content");
|
||||
this.log("Benchmarking odoo widgets, 12.0");
|
||||
},
|
||||
on_attach_callback: function() {
|
||||
this.isInDom = true;
|
||||
@@ -144,34 +162,41 @@ odoo.define("app", function(require) {
|
||||
},
|
||||
|
||||
addMessages: function(n) {
|
||||
var self = this;
|
||||
startMeasure("add " + n);
|
||||
const defs = [];
|
||||
const messages = buildData(n);
|
||||
for (let message of messages) {
|
||||
const widget = new Message(this, message);
|
||||
this.widgets[message.id] = widget;
|
||||
defs.push(widget.appendTo("<div>"));
|
||||
}
|
||||
$.when
|
||||
.apply($, defs)
|
||||
.then(function() {
|
||||
for (let message of messages) {
|
||||
let widget = self.widgets[message.id];
|
||||
dom.append(self.$content, widget.$el, {
|
||||
in_DOM: this.isInDom,
|
||||
callbacks: [{ widget: widget }]
|
||||
});
|
||||
}
|
||||
})
|
||||
.then(function() {
|
||||
self.messageCount += n;
|
||||
self.updateMessageCount();
|
||||
stopMeasure();
|
||||
});
|
||||
const self = this;
|
||||
this.benchmark("add " + n, () => {
|
||||
const defs = [];
|
||||
const messages = buildData(n);
|
||||
for (let message of messages) {
|
||||
const widget = new Message(this, message);
|
||||
this.widgets[message.id] = widget;
|
||||
defs.push(widget.appendTo("<div>"));
|
||||
}
|
||||
return $.when
|
||||
.apply($, defs)
|
||||
.then(function() {
|
||||
for (let message of messages) {
|
||||
let widget = self.widgets[message.id];
|
||||
dom.append(self.$content, widget.$el, {
|
||||
in_DOM: this.isInDom,
|
||||
callbacks: [{ widget: widget }]
|
||||
});
|
||||
}
|
||||
})
|
||||
.then(function() {
|
||||
self.messageCount += n;
|
||||
self.updateMessageCount();
|
||||
});
|
||||
});
|
||||
},
|
||||
clear: function() {
|
||||
startMeasure("clear");
|
||||
this._clear();
|
||||
stopMeasure(info => {
|
||||
this.log(info.msg);
|
||||
});
|
||||
},
|
||||
|
||||
_clear: function() {
|
||||
this.$content.empty();
|
||||
for (let key in this.widgets) {
|
||||
this.widgets[key].destroy();
|
||||
@@ -179,15 +204,14 @@ odoo.define("app", function(require) {
|
||||
}
|
||||
this.messageCount = 0;
|
||||
this.updateMessageCount();
|
||||
stopMeasure();
|
||||
},
|
||||
updateSomeMessages: function() {
|
||||
startMeasure("update every 10th");
|
||||
const widgets = Object.values(this.widgets);
|
||||
for (let i = 0; i < widgets.length; i += 10) {
|
||||
widgets[i].update();
|
||||
}
|
||||
stopMeasure();
|
||||
this.benchmark("update every 10th", () => {
|
||||
const widgets = Object.values(this.widgets);
|
||||
for (let i = 0; i < widgets.length; i += 10) {
|
||||
widgets[i].update();
|
||||
}
|
||||
});
|
||||
},
|
||||
_onRemoveMessage: function(ev) {
|
||||
startMeasure("remove message");
|
||||
@@ -196,6 +220,65 @@ odoo.define("app", function(require) {
|
||||
this.messageCount--;
|
||||
this.updateMessageCount();
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
benchmark: function(message, fn, callback) {
|
||||
if (this.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.clearFlag) {
|
||||
this._benchmark("clear", this._clear.bind(this), finalize, false);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
},
|
||||
|
||||
_benchmark: function(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
const benchmark = fn();
|
||||
(benchmark && benchmark.then ? benchmark : $.when()).then(() => {
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
});
|
||||
},
|
||||
|
||||
log: function(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.$log[0].appendChild(div);
|
||||
this.$log[0].scrollTop = this.$log[0].scrollHeight;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1k messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10k messages</button>
|
||||
<button class="o_btn_msg 30000">Add 30k messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" class="o_multiple" id="multipleflag" />
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" class="o_clear" id="clearFlag" />
|
||||
<label for="clearFlag">Clear after</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info message_count">
|
||||
Number of messages: 0
|
||||
</div>
|
||||
<div class="title">Log <span class="clear-log">(clear)</span></div>
|
||||
<div class="log">
|
||||
<div class="log-content"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove">Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
+118
-35
@@ -1,4 +1,9 @@
|
||||
import { buildData, startMeasure, stopMeasure } from "../shared/utils.js";
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
odoo.define("app", function(require) {
|
||||
const Widget = require("web.Widget");
|
||||
@@ -97,14 +102,23 @@ odoo.define("app", function(require) {
|
||||
"click .o_btn_msg.10000": function() {
|
||||
this.addMessages(10000);
|
||||
},
|
||||
"click .o_btn_msg.50000": function() {
|
||||
this.addMessages(50000);
|
||||
"click .o_btn_msg.30000": function() {
|
||||
this.addMessages(30000);
|
||||
},
|
||||
"click .updateSomeMessages": function() {
|
||||
this.updateSomeMessages();
|
||||
},
|
||||
"click .clear": function() {
|
||||
this.clear();
|
||||
},
|
||||
"click .o_multiple": function() {
|
||||
this.multipleFlag = !this.multipleFlag;
|
||||
},
|
||||
"click .o_clear": function() {
|
||||
this.clearFlag = !this.clearFlag;
|
||||
},
|
||||
"click .clear-log": function() {
|
||||
this.$log[0].innerHTML = "";
|
||||
}
|
||||
},
|
||||
custom_events: {
|
||||
@@ -116,11 +130,15 @@ odoo.define("app", function(require) {
|
||||
this.widgets = {};
|
||||
this.isInDom = false;
|
||||
this.messageCount = 0;
|
||||
this.multipleFlag = false;
|
||||
this.clearFlag = false;
|
||||
},
|
||||
|
||||
start: function() {
|
||||
this.$content = this.$(".content");
|
||||
this.$msgCount = this.$(".message_count");
|
||||
this.$log = this.$(".log-content");
|
||||
this.log("Benchmarking odoo widgets, 12.3");
|
||||
},
|
||||
on_attach_callback: function() {
|
||||
this.isInDom = true;
|
||||
@@ -144,34 +162,41 @@ odoo.define("app", function(require) {
|
||||
},
|
||||
|
||||
addMessages: function(n) {
|
||||
var self = this;
|
||||
startMeasure("add " + n);
|
||||
const defs = [];
|
||||
const messages = buildData(n);
|
||||
for (let message of messages) {
|
||||
const widget = new Message(this, message);
|
||||
this.widgets[message.id] = widget;
|
||||
defs.push(widget.appendTo("<div>"));
|
||||
}
|
||||
$.when
|
||||
.apply($, defs)
|
||||
.then(function() {
|
||||
for (let message of messages) {
|
||||
let widget = self.widgets[message.id];
|
||||
dom.append(self.$content, widget.$el, {
|
||||
in_DOM: this.isInDom,
|
||||
callbacks: [{ widget: widget }]
|
||||
});
|
||||
}
|
||||
})
|
||||
.then(function() {
|
||||
self.messageCount += n;
|
||||
self.updateMessageCount();
|
||||
stopMeasure();
|
||||
});
|
||||
const self = this;
|
||||
this.benchmark("add " + n, () => {
|
||||
const defs = [];
|
||||
const messages = buildData(n);
|
||||
for (let message of messages) {
|
||||
const widget = new Message(this, message);
|
||||
this.widgets[message.id] = widget;
|
||||
defs.push(widget.appendTo("<div>"));
|
||||
}
|
||||
return $.when
|
||||
.apply($, defs)
|
||||
.then(function() {
|
||||
for (let message of messages) {
|
||||
let widget = self.widgets[message.id];
|
||||
dom.append(self.$content, widget.$el, {
|
||||
in_DOM: this.isInDom,
|
||||
callbacks: [{ widget: widget }]
|
||||
});
|
||||
}
|
||||
})
|
||||
.then(function() {
|
||||
self.messageCount += n;
|
||||
self.updateMessageCount();
|
||||
});
|
||||
});
|
||||
},
|
||||
clear: function() {
|
||||
startMeasure("clear");
|
||||
this._clear();
|
||||
stopMeasure(info => {
|
||||
this.log(info.msg);
|
||||
});
|
||||
},
|
||||
|
||||
_clear: function() {
|
||||
this.$content.empty();
|
||||
for (let key in this.widgets) {
|
||||
this.widgets[key].destroy();
|
||||
@@ -179,15 +204,14 @@ odoo.define("app", function(require) {
|
||||
}
|
||||
this.messageCount = 0;
|
||||
this.updateMessageCount();
|
||||
stopMeasure();
|
||||
},
|
||||
updateSomeMessages: function() {
|
||||
startMeasure("update every 10th");
|
||||
const widgets = Object.values(this.widgets);
|
||||
for (let i = 0; i < widgets.length; i += 10) {
|
||||
widgets[i].update();
|
||||
}
|
||||
stopMeasure();
|
||||
this.benchmark("update every 10th", () => {
|
||||
const widgets = Object.values(this.widgets);
|
||||
for (let i = 0; i < widgets.length; i += 10) {
|
||||
widgets[i].update();
|
||||
}
|
||||
});
|
||||
},
|
||||
_onRemoveMessage: function(ev) {
|
||||
startMeasure("remove message");
|
||||
@@ -196,6 +220,65 @@ odoo.define("app", function(require) {
|
||||
this.messageCount--;
|
||||
this.updateMessageCount();
|
||||
stopMeasure();
|
||||
},
|
||||
|
||||
benchmark: function(message, fn, callback) {
|
||||
if (this.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.clearFlag) {
|
||||
this._benchmark("clear", this._clear.bind(this), finalize, false);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
},
|
||||
|
||||
_benchmark: function(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
const benchmark = fn();
|
||||
(benchmark && benchmark.then ? benchmark : $.when()).then(() => {
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
});
|
||||
},
|
||||
|
||||
log: function(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.$log[0].appendChild(div);
|
||||
this.$log[0].scrollTop = this.$log[0].scrollHeight;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<templates>
|
||||
<div class="main" t-name="root">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button class="o_btn_msg 100">Add 100 messages</button>
|
||||
<button class="o_btn_msg 1000">Add 1k messages</button>
|
||||
<button class="o_btn_msg 10000">Add 10k messages</button>
|
||||
<button class="o_btn_msg 30000">Add 30k messages</button>
|
||||
<button class="updateSomeMessages">Update every 10th message</button>
|
||||
<button class="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" class="o_multiple" id="multipleflag" />
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" class="o_clear" id="clearFlag" />
|
||||
<label for="clearFlag">Clear after</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info message_count">
|
||||
Number of messages: 0
|
||||
</div>
|
||||
<div class="title">Log <span class="clear-log">(clear)</span></div>
|
||||
<div class="log">
|
||||
<div class="log-content"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="message" class="message">
|
||||
<span class="author"><t t-esc="widget.author"/></span>
|
||||
<span class="msg"><t t-esc="widget.msg"/></span>
|
||||
<button class="remove">Remove</button>
|
||||
</div>
|
||||
|
||||
<div t-name="counter">
|
||||
<button class="o_increment"></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
template = "Counter";
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
template = "Message";
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
template = "App";
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl._version} (build date: ${
|
||||
owl._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 < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl._version} (build date: ${
|
||||
owl._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 < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl.__info__.version} (build date: ${
|
||||
owl.__info__.date
|
||||
})`
|
||||
);
|
||||
}
|
||||
|
||||
benchmark(message, fn, callback) {
|
||||
if (this.state.multipleFlag) {
|
||||
const N = 20;
|
||||
let n = N;
|
||||
let total = 0;
|
||||
let cb = info => {
|
||||
let finalize = () => {
|
||||
n--;
|
||||
total += info.delta;
|
||||
if (n === 0) {
|
||||
const avg = total / N;
|
||||
this.log(`Average: ${formatNumber(avg)}ms`, true);
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
this._benchmark(message, fn, cb);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.state.clearAfterFlag) {
|
||||
this._benchmark(
|
||||
"clear",
|
||||
() => {
|
||||
this.state.messages = [];
|
||||
},
|
||||
finalize,
|
||||
false
|
||||
);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
}
|
||||
|
||||
_benchmark(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
fn();
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
});
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.benchmark("clear", () => {
|
||||
this.state.messages = [];
|
||||
});
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { 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 {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl.__info__.version} (build date: ${
|
||||
owl.__info__.date
|
||||
})`
|
||||
);
|
||||
}
|
||||
|
||||
benchmark(message, fn, callback) {
|
||||
if (this.state.multipleFlag) {
|
||||
const N = 20;
|
||||
let n = N;
|
||||
let total = 0;
|
||||
let cb = info => {
|
||||
let finalize = () => {
|
||||
n--;
|
||||
total += info.delta;
|
||||
if (n === 0) {
|
||||
const avg = total / N;
|
||||
this.log(`Average: ${formatNumber(avg)}ms`, true);
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
this._benchmark(message, fn, cb);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.state.clearAfterFlag) {
|
||||
this._benchmark(
|
||||
"clear",
|
||||
() => {
|
||||
this.state.messages = [];
|
||||
},
|
||||
finalize,
|
||||
false
|
||||
);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
}
|
||||
|
||||
_benchmark(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
fn();
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
});
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._benchmark("clear", () => {
|
||||
this.state.messages = [];
|
||||
});
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(event) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === event.detail.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>OWL 0.13.0 Benchmark</title>
|
||||
<link href="../shared/main.css" rel="stylesheet"/>
|
||||
<script src='owl.js'></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id='main'></div>
|
||||
<script src='app.js' type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
<templates>
|
||||
<div t-name="App" class="main">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1k messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10k messages</button>
|
||||
<button t-on-click="addMessages(30000)">Add 30k messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th messages</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" id="multipleflag" t-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="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>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
template = "Counter";
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
template = "Message";
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
template = "App";
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl._version} (build date: ${
|
||||
owl._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 < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
template = "Counter";
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
template = "Message";
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
template = "App";
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl._version} (build date: ${
|
||||
owl._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 < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
template = "Counter";
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { Counter };
|
||||
template = "Message";
|
||||
|
||||
shouldUpdate(nextProps) {
|
||||
return nextProps !== this.props;
|
||||
}
|
||||
removeMessage() {
|
||||
this.trigger("remove_message", {
|
||||
id: this.props.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class App extends owl.Component {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
template = "App";
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl._version} (build date: ${
|
||||
owl._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 < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
this.set(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(data) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === data.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,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-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="Message" t-key="message.id" t-props="message" t-on-remove_message="removeMessage"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div t-name="Message" class="message">
|
||||
<span class="author"><t t-esc="props.author"/></span>
|
||||
<span class="msg"><t t-esc="props.msg"/></span>
|
||||
<button class="remove" t-on-click="removeMessage">Remove</button>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Likes Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends owl.Component {
|
||||
state = { counter: 0 };
|
||||
|
||||
increment() {
|
||||
this.state.counter++;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends owl.Component {
|
||||
widgets = { 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 {
|
||||
widgets = { Message };
|
||||
state = { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
|
||||
mounted() {
|
||||
this.log(
|
||||
`Benchmarking Owl v${owl.__info__.version} (build date: ${
|
||||
owl.__info__.date
|
||||
})`
|
||||
);
|
||||
}
|
||||
|
||||
benchmark(message, fn, callback) {
|
||||
if (this.state.multipleFlag) {
|
||||
const N = 20;
|
||||
let n = N;
|
||||
let total = 0;
|
||||
let cb = info => {
|
||||
let finalize = () => {
|
||||
n--;
|
||||
total += info.delta;
|
||||
if (n === 0) {
|
||||
const avg = total / N;
|
||||
this.log(`Average: ${formatNumber(avg)}ms`, true);
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
this._benchmark(message, fn, cb);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.state.clearAfterFlag) {
|
||||
this._benchmark(
|
||||
"clear",
|
||||
() => {
|
||||
this.state.messages = [];
|
||||
},
|
||||
finalize,
|
||||
false
|
||||
);
|
||||
} else {
|
||||
finalize();
|
||||
}
|
||||
};
|
||||
this._benchmark(message, fn, cb);
|
||||
} else {
|
||||
this._benchmark(message, fn, callback);
|
||||
}
|
||||
}
|
||||
|
||||
_benchmark(message, fn, cb, log = true) {
|
||||
setTimeout(() => {
|
||||
startMeasure(message);
|
||||
fn();
|
||||
stopMeasure(info => {
|
||||
if (log) {
|
||||
this.log(info.msg);
|
||||
}
|
||||
if (cb) {
|
||||
cb(info);
|
||||
}
|
||||
});
|
||||
}, 10);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = buildData(n);
|
||||
this.state.messages.push.apply(this.state.messages, newMessages);
|
||||
});
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._benchmark("clear", () => {
|
||||
this.state.messages = [];
|
||||
});
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const setState = owl.Observer.set;
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < this.state.messages.length; i += 10) {
|
||||
const msg = Object.assign({}, messages[i]);
|
||||
msg.author += "!!!";
|
||||
setState(messages, i, msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(event) {
|
||||
this.benchmark("remove message", () => {
|
||||
const index = this.state.messages.findIndex(m => m.id === event.detail.id);
|
||||
this.state.messages.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.log.appendChild(div);
|
||||
this.refs.log.scrollTop = this.refs.log.scrollHeight;
|
||||
}
|
||||
|
||||
clearLog() {
|
||||
this.refs.log.innerHTML = "";
|
||||
}
|
||||
|
||||
toggleMultiple() {
|
||||
this.state.multipleFlag = !this.state.multipleFlag;
|
||||
}
|
||||
|
||||
toggleClear() {
|
||||
this.state.clearAfterFlag = !this.state.clearAfterFlag;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
async function start() {
|
||||
const templates = await owl.utils.loadTemplates("templates.xml");
|
||||
const env = {
|
||||
qweb: new owl.QWeb(templates)
|
||||
};
|
||||
const app = new App(env);
|
||||
app.mount(document.body);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -7,7 +7,6 @@
|
||||
<script src='../../owl.js'></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id='main'></div>
|
||||
<script src='app.js' type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
<templates>
|
||||
<div t-name="App" class="main">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button t-on-click="addMessages(100)">Add 100 messages</button>
|
||||
<button t-on-click="addMessages(1000)">Add 1k messages</button>
|
||||
<button t-on-click="addMessages(10000)">Add 10k messages</button>
|
||||
<button t-on-click="addMessages(30000)">Add 30k messages</button>
|
||||
<button t-on-click="updateSomeMessages">Update every 10th messages</button>
|
||||
<button t-on-click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" id="multipleflag" t-on-change="toggleMultiple" t-att-checked="state.multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" t-on-change="toggleClear" t-att-checked="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">
|
||||
<t t-widget="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>
|
||||
<t t-widget="Counter"/>
|
||||
</div>
|
||||
|
||||
<div t-name="Counter">
|
||||
<button t-on-click="increment">Value: <t t-esc="state.counter"/></button>
|
||||
</div>
|
||||
|
||||
</templates>
|
||||
@@ -0,0 +1,345 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Counter extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
counter: 0
|
||||
};
|
||||
this.increment = this.increment.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
null,
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: this.increment
|
||||
},
|
||||
"Value: ",
|
||||
this.state.counter
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.setState({
|
||||
counter: this.state.counter + 1
|
||||
});
|
||||
}
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Message extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "message"
|
||||
},
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "author"
|
||||
},
|
||||
this.props.message.author
|
||||
),
|
||||
React.createElement(
|
||||
"span",
|
||||
{
|
||||
className: "msg"
|
||||
},
|
||||
this.props.message.msg
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
className: "remove",
|
||||
onClick: this.removeMessage
|
||||
},
|
||||
"Remove"
|
||||
),
|
||||
React.createElement(Counter, null)
|
||||
);
|
||||
}
|
||||
|
||||
removeMessage() {
|
||||
this.props.removeCB(this.props.message.id);
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
class Main extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
messages: [],
|
||||
multipleFlag: false,
|
||||
clearAfterFlag: false
|
||||
};
|
||||
this.removeMessage = this.removeMessage.bind(this);
|
||||
this.toggleMultipleFlag = this.toggleMultipleFlag.bind(this);
|
||||
this.toggleClearAfterFlag = this.toggleClearAfterFlag.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.log(`Benchmarking React v${React.version}`);
|
||||
}
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.refs.logref.appendChild(div);
|
||||
this.refs.logref.scrollTop = this.refs.logref.scrollHeight;
|
||||
}
|
||||
|
||||
toggleMultipleFlag() {
|
||||
this.setState({ multipleFlag: !this.state.multipleFlag });
|
||||
}
|
||||
toggleClearAfterFlag() {
|
||||
this.setState({ clearAfterFlag: !this.state.clearAfterFlag });
|
||||
}
|
||||
|
||||
render() {
|
||||
const msgList = this.state.messages.map(m =>
|
||||
React.createElement(Message, {
|
||||
key: m.id,
|
||||
message: m,
|
||||
removeCB: this.removeMessage
|
||||
})
|
||||
);
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "main"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "left-thing"
|
||||
},
|
||||
React.createElement("div", { className: "title" }, "Actions"),
|
||||
React.createElement(
|
||||
"div",
|
||||
{ className: "panel" },
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(100)
|
||||
},
|
||||
"Add 100 messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(1000)
|
||||
},
|
||||
"Add 1k messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(10000)
|
||||
},
|
||||
"Add 10k messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.addMessages(30000)
|
||||
},
|
||||
"Add 30k messages"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.updateSomeMessages()
|
||||
},
|
||||
"Update every 10th message"
|
||||
),
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
onClick: _ => this.clear()
|
||||
},
|
||||
"Clear"
|
||||
)
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{ className: "flags" },
|
||||
React.createElement(
|
||||
"div",
|
||||
null,
|
||||
React.createElement("input", {
|
||||
type: "checkbox",
|
||||
id: "multipleFlag",
|
||||
value: this.state.multipleFlag,
|
||||
onChange: this.toggleMultipleFlag
|
||||
}),
|
||||
React.createElement("label", { for: "multipleFlag" }, " Do it 20x")
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
null,
|
||||
React.createElement("input", {
|
||||
type: "checkbox",
|
||||
id: "clearFlag",
|
||||
value: this.state.clearAfterFlag,
|
||||
onChange: this.toggleClearAfterFlag
|
||||
}),
|
||||
React.createElement("label", { for: "clearFlag" }, " Clear after")
|
||||
)
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{ className: "info" },
|
||||
"Number of messages: ",
|
||||
this.state.messages.length
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{ className: "title" },
|
||||
"Log ",
|
||||
React.createElement("span", { className: "clear-log" }, "(clear)")
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{ className: "log" },
|
||||
React.createElement("div", {
|
||||
className: "log-content",
|
||||
ref: "logref"
|
||||
})
|
||||
)
|
||||
),
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "right-thing"
|
||||
},
|
||||
React.createElement(
|
||||
"div",
|
||||
{
|
||||
className: "content"
|
||||
},
|
||||
msgList
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = this.state.messages.concat(buildData(n));
|
||||
this.setState({
|
||||
messages: newMessages
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._benchmark("clear", () => {
|
||||
this.setState({
|
||||
messages: []
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const messages = this.state.messages;
|
||||
for (let i = 0; i < messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
this.forceUpdate();
|
||||
});
|
||||
}
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.state.messages.findIndex(m => m.id === id);
|
||||
const messages = this.state.messages.slice();
|
||||
messages.splice(index, 1);
|
||||
this.setState({
|
||||
messages
|
||||
});
|
||||
stopMeasure();
|
||||
}
|
||||
|
||||
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.setState({ 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);
|
||||
}
|
||||
} //-----------------------------
|
||||
// INIT
|
||||
//-----------------------------
|
||||
|
||||
ReactDOM.render(React.createElement(Main, null), document.body);
|
||||
Vendored
Executable
+107
@@ -0,0 +1,107 @@
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
|
||||
Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", Arial,
|
||||
sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
.main {
|
||||
height: 100%;
|
||||
|
||||
font-size: 14px;
|
||||
display: grid;
|
||||
grid-template-columns: 640px 1fr;
|
||||
}
|
||||
|
||||
.left-thing {
|
||||
background-color: gray;
|
||||
color: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.left-thing hr {
|
||||
width: 100%;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.title {
|
||||
padding: 10px;
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.panel button {
|
||||
flex: 0 0 32%;
|
||||
height: 32px;
|
||||
margin-top: 4px;
|
||||
margin-bottom: 4px;
|
||||
font-size: 14px;
|
||||
margin-left: 3px;
|
||||
margin-right: 3px;
|
||||
}
|
||||
|
||||
.info {
|
||||
padding: 10px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.flags {
|
||||
padding: 10px;
|
||||
}
|
||||
.log {
|
||||
flex: 1 1 auto;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.log-content {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.bold {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.clear-log {
|
||||
font-size: 14px;
|
||||
color: #eeeeee;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.right-thing {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* Message widget */
|
||||
.message .author {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.message {
|
||||
width: 400px;
|
||||
background-color: lightblue;
|
||||
margin: 10px 5px;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.remove {
|
||||
float: right;
|
||||
}
|
||||
@@ -31,19 +31,28 @@ export function buildData(n = 1000) {
|
||||
//------------------------------------------------------------------------------
|
||||
// Measuring helpers
|
||||
//------------------------------------------------------------------------------
|
||||
export function formatNumber(n) {
|
||||
return Number(n).toFixed();
|
||||
}
|
||||
|
||||
let startTime;
|
||||
let lastMeasure;
|
||||
export function startMeasure(descr) {
|
||||
startTime = performance.now();
|
||||
lastMeasure = descr;
|
||||
}
|
||||
export function stopMeasure() {
|
||||
export function stopMeasure(cb) {
|
||||
let last = lastMeasure;
|
||||
if (lastMeasure) {
|
||||
window.setTimeout(function() {
|
||||
lastMeasure = null;
|
||||
const stop = performance.now();
|
||||
console.log(`[${last}] took ${Number(stop - startTime).toFixed()}ms`);
|
||||
const delta = stop - startTime;
|
||||
const msg = `[${last}] took ${formatNumber(delta)}ms`;
|
||||
console.log(msg);
|
||||
if (cb) {
|
||||
cb({msg, delta});
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import {
|
||||
buildData,
|
||||
startMeasure,
|
||||
stopMeasure,
|
||||
formatNumber
|
||||
} from "../shared/utils.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Counter Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("likes-counter", {
|
||||
data: function() {
|
||||
return {
|
||||
counter: 0
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
increment() {
|
||||
this.counter++;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div>
|
||||
<button @click="increment">Value: {{counter}}</button>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Message Widget
|
||||
//------------------------------------------------------------------------------
|
||||
Vue.component("my-message", {
|
||||
props: ["msg"],
|
||||
methods: {
|
||||
removeMessage() {
|
||||
this.$emit("removeMessage", this.msg.id);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="message">
|
||||
<span class="author">{{msg.author}}</span>
|
||||
<span class="msg">{{msg.msg}}</span>
|
||||
<button class="remove" @click="removeMessage">Remove</button>
|
||||
<likes-counter></likes-counter>
|
||||
</div>`
|
||||
});
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Root Widget
|
||||
//------------------------------------------------------------------------------
|
||||
const App = {
|
||||
name: "App",
|
||||
data() {
|
||||
return { messages: [], multipleFlag: false, clearAfterFlag: false };
|
||||
},
|
||||
mounted() {
|
||||
this.log(`Benchmarking Vue v${Vue.version}`);
|
||||
},
|
||||
methods: {
|
||||
addMessages(n) {
|
||||
this.benchmark("add " + n, () => {
|
||||
const newMessages = buildData(n);
|
||||
this.messages.push.apply(this.messages, newMessages);
|
||||
});
|
||||
},
|
||||
|
||||
clear() {
|
||||
this._benchmark("clear", () => {
|
||||
this.messages = [];
|
||||
});
|
||||
},
|
||||
|
||||
clearLog() {
|
||||
this.$refs.log.innerHTML = "";
|
||||
},
|
||||
|
||||
updateSomeMessages() {
|
||||
this.benchmark("update every 10th", () => {
|
||||
const messages = this.messages;
|
||||
for (let i = 0; i < this.messages.length; i += 10) {
|
||||
messages[i].author += "!!!";
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
removeMessage(id) {
|
||||
startMeasure("remove message");
|
||||
const index = this.messages.findIndex(m => m.id === id);
|
||||
this.messages.splice(index, 1);
|
||||
stopMeasure();
|
||||
},
|
||||
log(str, isBold) {
|
||||
const div = document.createElement("div");
|
||||
if (isBold) {
|
||||
div.classList.add("bold");
|
||||
}
|
||||
div.textContent = `> ${str}`;
|
||||
this.$refs.log.appendChild(div);
|
||||
this.$refs.log.scrollTop = this.$refs.log.scrollHeight;
|
||||
},
|
||||
benchmark(message, fn, callback) {
|
||||
if (this.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.clearAfterFlag) {
|
||||
this._benchmark(
|
||||
"clear",
|
||||
() => {
|
||||
this.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);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="main">
|
||||
<div class="left-thing">
|
||||
<div class="title">Actions</div>
|
||||
<div class="panel">
|
||||
<button @click="addMessages(100)">Add 100 messages</button>
|
||||
<button @click="addMessages(1000)">Add 1k messages</button>
|
||||
<button @click="addMessages(10000)">Add 10k messages</button>
|
||||
<button @click="addMessages(30000)">Add 30k messages</button>
|
||||
<button @click="updateSomeMessages">Update every 10th message</button>
|
||||
<button @click="clear">Clear</button>
|
||||
</div>
|
||||
<div class="flags">
|
||||
<div>
|
||||
<input type="checkbox" id="multipleflag" v-model="multipleFlag"/>
|
||||
<label for="multipleflag">Do it 20x</label>
|
||||
</div>
|
||||
<div>
|
||||
<input type="checkbox" id="clearFlag" v-model="clearAfterFlag"/>
|
||||
<label for="clearFlag">Clear after</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info">Number of messages: {{messages.length}}</div>
|
||||
<hr/>
|
||||
<div class="title">Log <span class="clear-log" @click="clearLog">(clear)</span></div>
|
||||
<div class="log">
|
||||
<div class="log-content" ref="log"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-thing">
|
||||
<div class="content">
|
||||
<my-message v-for="msg in messages" v-bind:key="msg.id" v-bind:msg="msg" @removeMessage="removeMessage"></my-message>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Application initialization
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
new Vue({
|
||||
render: h => h(App)
|
||||
}).$mount(`#main`);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user