Compare commits

..

2 Commits

Author SHA1 Message Date
Géry Debongnie 3ae81e9bee wip 2023-02-21 15:12:19 +01:00
Géry Debongnie 56cfc6403d wip 2023-02-20 17:04:49 +01:00
317 changed files with 11624 additions and 46824 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
strategy: strategy:
matrix: matrix:
node-version: [20.x, 22.x] node-version: [12.x, 14.x, 16.x]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
+5 -9
View File
@@ -15,21 +15,17 @@ yarn-debug.log*
yarn-error.log* yarn-error.log*
#ide's #ide's
**/.vscode/* .vscode
.idea .idea
node_modules node_modules
# Extras temp file
/tools/owl.js
release-notes.md release-notes.md
.rpt2_cache .rpt2_cache
# useful in some cases # useful in some cases
/temp /temp
# owl-vision
*/owl-vision/out/
*/owl-vision/.vs/
**/*.vsix
!*/owl-vision/.vscode/launch.json
!*/owl-vision/.vscode/tasks.json
+1 -22
View File
@@ -113,7 +113,6 @@ Are you new to Owl? This is the place to start!
- [Why did Odoo build Owl?](doc/miscellaneous/why_owl.md) - [Why did Odoo build Owl?](doc/miscellaneous/why_owl.md)
- [Changelog (from owl 1.x to 2.x)](CHANGELOG.md) - [Changelog (from owl 1.x to 2.x)](CHANGELOG.md)
- [Notes on compiled templates](doc/miscellaneous/compiled_template.md) - [Notes on compiled templates](doc/miscellaneous/compiled_template.md)
- [Owl devtools extension](doc/tools/devtools.md)
## Installing Owl ## Installing Owl
@@ -122,28 +121,8 @@ Owl is available on `npm` and can be installed with the following command:
``` ```
npm install @odoo/owl npm install @odoo/owl
``` ```
If you want to use a simple `<script>` tag, the last release can be downloaded here: If you want to use a simple `<script>` tag, the last release can be downloaded here:
- [owl](https://github.com/odoo/owl/releases/latest) - [owl](https://github.com/odoo/owl/releases/latest)
## Installing Owl devtools
The Owl devtools browser extension is also available in the [release](https://github.com/odoo/owl/releases/latest):
Unzip the owl-devtools.zip file and follow the instructions depending on your browser:
### Chrome
Go to your chrome extensions admin panel, activate developer mode and click on `Load unpacked`.
Select the devtools-chrome folder and that's it, your extension is active!
There is a convenient refresh button on the extension card (still on the same admin page) to update your code.
Do note that if you got some problems, you may need to completly remove and reload the extension to completly refresh the extension.
### Firefox
Go to the address about:debugging#/runtime/this-firefox and click on `Load temporary Add-on...`.
Select any file in the devtools-firefox folder and that's it, your extension is active!
Here, you can use the reload button to refresh the extension.
Note that you may have to open another window or reload your tab to see the extension working.
Also note that the extension will only be active on pages that have a sufficient version of owl.
-1
View File
@@ -47,4 +47,3 @@ Utility/helpers:
- [`status`](reference/component.md#status-helper): utility function to get the status of a component (new, mounted or destroyed) - [`status`](reference/component.md#status-helper): utility function to get the status of a component (new, mounted or destroyed)
- [`validate`](reference/utils.md#validate): validates if an object satisfies a specified schema - [`validate`](reference/utils.md#validate): validates if an object satisfies a specified schema
- [`whenReady`](reference/utils.md#whenready): utility function to execute code when DOM is ready - [`whenReady`](reference/utils.md#whenready): utility function to execute code when DOM is ready
- [`batched`](reference/utils.md#batched): utility function to batch function calls
-33
View File
@@ -6,7 +6,6 @@
- [API](#api) - [API](#api)
- [Configuration](#configuration) - [Configuration](#configuration)
- [`mount` helper](#mount-helper) - [`mount` helper](#mount-helper)
- [Roots](#roots)
- [Loading templates](#loading-templates) - [Loading templates](#loading-templates)
## Overview ## Overview
@@ -62,13 +61,8 @@ The `config` object is an object with some of the following keys:
templates (see [translations](translations.md)) templates (see [translations](translations.md))
- **`templates (string | xml document)`**: all the templates that will be used by - **`templates (string | xml document)`**: all the templates that will be used by
the components created by the application. the components created by the application.
- **`getTemplate ((s: string) => Element | Function | string | void)`**: a function that will be called by owl when it
needs a template. If undefined is returned, owl looks into the app templates.
- **`warnIfNoStaticProps (boolean, default=false)`**: if true, Owl will log a warning - **`warnIfNoStaticProps (boolean, default=false)`**: if true, Owl will log a warning
whenever it encounters a component that does not provide a [static props description](props.md#props-validation). whenever it encounters a component that does not provide a [static props description](props.md#props-validation).
- **`customDirectives (object)`**: if given, the corresponding function on the object will be called
on the template custom directives: `t-custom-*` (see [Custom Directives](templates.md#custom-directives)).
- **`globalValues (object)`**: Global object of elements available at compilations.
## `mount` helper ## `mount` helper
@@ -96,33 +90,6 @@ Most of the time, the `mount` helper is more convenient, but whenever one needs
a reference to the actual Owl App, then using the `App` class directly is a reference to the actual Owl App, then using the `App` class directly is
possible. possible.
## Roots
An application can have multiple roots. It is sometimes useful to instantiate
sub components in places that are not managed by Owl, such as an html editor
with dynamic content (the Knowledge application in Odoo).
To create a root, one can use the `createRoot` method, which takes two arguments:
- **`Component`**: a component class (Root component of the app)
- **`config (optional)`**: a config object that may contain a `props` object or a
`env` object.
The `createRoot` method returns an object with a `mount` method (same API as
the `App.mount` method), and a `destroy` method.
```js
const root = app.createRoot(MyComponent, { props: { someProps: true } });
await root.mount(targetElement);
// later
root.destroy();
```
Note that, like with owl `App`, it is the responsibility of the code that created
the root to properly destroy it (before it has been removed from the DOM!). Owl
has no way of doing it itself.
## Loading templates ## Loading templates
Most applications will need to load templates whenever they start. Here is Most applications will need to load templates whenever they start. Here is
+1 -2
View File
@@ -357,7 +357,7 @@ cleaning operation, since the component may be destroyed before it has even been
mounted. The `willDestroy` hook is useful in that situation, since it is always mounted. The `willDestroy` hook is useful in that situation, since it is always
called. called.
The `onWillDestroy` hook is used to register a function that will be executed at The `onWillUnmount` hook is used to register a function that will be executed at
this moment: this moment:
```javascript ```javascript
@@ -451,6 +451,5 @@ console.log(status(component));
// logs either: // logs either:
// - 'new', if the component is new and has not been mounted yet // - 'new', if the component is new and has not been mounted yet
// - 'mounted', if the component is currently mounted // - 'mounted', if the component is currently mounted
// - 'cancelled', if the component has not been mounted yet but will be destroyed soon
// - 'destroyed' if the component is currently destroyed // - 'destroyed' if the component is currently destroyed
``` ```
+2 -2
View File
@@ -51,8 +51,8 @@ that render its content, and a fallback if an error happened.
```js ```js
class ErrorBoundary extends Component { class ErrorBoundary extends Component {
static template = xml` static template = xml`
<t t-if="state.error" t-slot="fallback">An error occurred</t> <t t-if="error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="default"/>`; <t t-else="" t-slot="content"`;
setup() { setup() {
this.state = useState({ error: false }); this.state = useState({ error: false });
+10 -10
View File
@@ -112,16 +112,17 @@ of a component, rendered by Owl. It only work on a html element tagged by the
```xml ```xml
<div> <div>
<input t-ref="someInput"/> <input t-ref="someDiv"/>
<span>hello</span> <span>hello</span>
</div> </div>
``` ```
In this example, the component will be able to access the `input` with the `useRef` hook: In this example, the component will be able to access the `div` and the component
`SubComponent` with the `useRef` hook:
```js ```js
class Parent extends Component { class Parent extends Component {
inputRef = useRef("someInput"); inputRef = useRef("someComponent");
someMethod() { someMethod() {
// here, if component is mounted, refs are active: // here, if component is mounted, refs are active:
@@ -138,18 +139,18 @@ The `t-ref` directive also accepts dynamic values with string interpolation
`t-component` directives). For example, `t-component` directives). For example,
```xml ```xml
<div t-ref="div_{{someCondition ? '1' : '2'}}"/> <div t-ref="component_{{someCondition ? '1' : '2'}}"/>
``` ```
Here, the references need to be set like this: Here, the references need to be set like this:
```js ```js
this.ref1 = useRef("div_1"); this.ref1 = useRef("component_1");
this.ref2 = useRef("div_2"); this.ref2 = useRef("component_2");
``` ```
References are only guaranteed to be active while the parent component is mounted. References are only guaranteed to be active while the parent component is mounted.
If this is not the case, accessing `el` on it will return `null`. If this is not the case, accessing `el` or `comp` on it will return `null`.
### `useSubEnv` and `useChildSubEnv` ### `useSubEnv` and `useChildSubEnv`
@@ -190,13 +191,12 @@ will then be updated accordingly.
### `useExternalListener` ### `useExternalListener`
The `useExternalListener` hook helps solve a very common problem: adding and removing The `useExternalListener` hook helps solve a very common problem: adding and removing
a listener on some target whenever a component is mounted/unmounted. It takes a target a listener on some target whenever a component is mounted/unmounted. For example,
as its first argument, forwards the other arguments to `addEventListener`. For example,
a dropdown menu (or its parent) may need to listen to a `click` event on `window` a dropdown menu (or its parent) may need to listen to a `click` event on `window`
to be closed: to be closed:
```js ```js
useExternalListener(window, "click", this.closeMenu, { capture: true }); useExternalListener(window, "click", this.closeMenu);
``` ```
### `useComponent` ### `useComponent`
+2 -97
View File
@@ -4,7 +4,6 @@
- [Overview](#overview) - [Overview](#overview)
- [Definition](#definition) - [Definition](#definition)
- [Props comparison](#props-comparison)
- [Binding function props](#binding-function-props) - [Binding function props](#binding-function-props)
- [Dynamic Props](#dynamic-props) - [Dynamic Props](#dynamic-props)
- [Default Props](#default-props) - [Default Props](#default-props)
@@ -57,47 +56,6 @@ the `props` object contains the following keys:
- for `ComponentA`: `a` and `b`, - for `ComponentA`: `a` and `b`,
- for `ComponentB`: `model`, - for `ComponentB`: `model`,
## Props comparison
Whenever Owl encounters a subcomponent in a template, it performs a shallow
comparison of all props. If they are all referentially equal, then the subcomponent
will not even be updated. Otherwise, if at least one props has changed, then
Owl will update it.
However, in some cases, we know that two values are different, but they have the
same effect, and should not be considered different by Owl. For example, anonymous
functions in a template are always different, but most of them should not be
considered different:
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<Todo todo="todo" onDelete="() => deleteTodo(todo.id)" />
</t>
```
In that case, one can use the `.alike` suffix:
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<Todo todo="todo" onDelete.alike="() => deleteTodo(todo.id)" />
</t>
```
This tells Owl that this specific prop should always be considered equivalent
(or, in other words, should be removed from the list of comparable props).
Note that even if most anonymous functions should probably be considered `alike`,
it is not necessarily true in all cases. It depends on what values are captured
by the anonymous function. The following example shows a case where it is probably
wrong to use `.alike`.
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<!-- Probably wrong! todo.isCompleted may change -->
<Todo todo="todo" toggle.alike="() => toggleTodo(todo.isCompleted)" />
</t>
```
## Binding function props ## Binding function props
It is common to have the need to pass a callback as a prop. Since Owl components It is common to have the need to pass a callback as a prop. Since Owl components
@@ -137,31 +95,6 @@ class SomeComponent extends Component {
} }
``` ```
The `.bind` suffix also implies `.alike`, so these props will not cause additional
renderings.
## Translatable props
When you need to pass a user-facing string to a subcomponent, you likely want it
to be translated. Unfortunately, because props are arbitrary expressions, it wouldn't
be practical for Owl to find out which parts of the expression are strings and translate
them, and it also makes it difficult for tooling to extract these strings to generate
terms to translate. While you can work around this issue by doing the translation in
JavaScript, or by using `t-set` with a body (the body of `t-set` is translated),
and passing the variable as a prop, this is a sufficiently common use case that Owl
provides a suffix for this purpose: `.translate`.
```xml
<t t-name="ParentComponent">
<Child someProp.translate="some message"/>
</t>
```
Note that the content of this attribute is _NOT_ treated as a JavaScript expression:
it is treated as a string, as if it was an attribute on an HTML element, and translated
before being passed to the component. If you need to interpolate some data into the
string, you will still have to do this in JavaScript.
## Dynamic Props ## Dynamic Props
The `t-props` directive can be used to specify totally dynamic props: The `t-props` directive can be used to specify totally dynamic props:
@@ -234,7 +167,6 @@ For each key, a `prop` definition is either a boolean, a constructor, a list of
- `type`: the main type of the prop being validated - `type`: the main type of the prop being validated
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. If it is not set, then we only validate the array, not its elements, - `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. If it is not set, then we only validate the array, not its elements,
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. If it is not set, then we only validate the object, not its elements, - `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. If it is not set, then we only validate the object, not its elements,
- `values`: if the type was `Object`, then the `values` key describes the interface of values in the object, this allows validating objects that are used as mappings, where keys are not known in advance but the shape of the values is.
- `validate`: this is a function which should return a boolean to determine if - `validate`: this is a function which should return a boolean to determine if
the value is valid or not. Useful for custom validation logic. the value is valid or not. Useful for custom validation logic.
- `optional`: if true, the prop is not mandatory - `optional`: if true, the prop is not mandatory
@@ -260,7 +192,7 @@ class ComponentB extends owl.Component {
count: {type: Number}, count: {type: Number},
messages: { messages: {
type: Array, type: Array,
element: {type: Object, shape: {id: Boolean, text: String }} element: {type: Object, shape: {id: Boolean, text: String }
}, },
date: Date, date: Date,
combinedVal: [Number, Boolean], combinedVal: [Number, Boolean],
@@ -298,12 +230,7 @@ class ComponentB extends owl.Component {
id: Number, id: Number,
name: {type: String, optional: true}, name: {type: String, optional: true},
url: String url: String
} ]}, // object, with keys id (number), name (string, optional) and url (string)
}, // object, with keys id (number), name (string, optional) and url (string)
someObj3: {
type: Object,
values: { type: Array, element: String },
}, // object with arbitary keys where values are arrays of strings
someFlag: Boolean, // a boolean, mandatory (even if `false`) someFlag: Boolean, // a boolean, mandatory (even if `false`)
someVal: [Boolean, Date], // either a boolean or a date someVal: [Boolean, Date], // either a boolean or a date
otherValue: true, // indicates that it is a prop otherValue: true, // indicates that it is a prop
@@ -320,28 +247,6 @@ class ComponentB extends owl.Component {
Note: the props validation code is done by using the [validate utility function](utils.md#validate). Note: the props validation code is done by using the [validate utility function](utils.md#validate).
### `slots` prop
If a component that uses [slots](slots.md) also lists or validates its props, then
you will have to explicitely allow the `slots` prop (with an `Object` type), or
allow extra props using the `*` notation mentioned above. This is because slots
are provided to a component [as props](slots.md#slots-and-props).
For example:
```js
class MyComponent extends Component {
static props = [someProp, slots?];
}
class MyComponentWithValidation extends Component {
static props = {
someProp: {type: Number, optional: true},
slots : {type: Object, optional: true},
}
}
```
## Good Practices ## Good Practices
A `props` object is a collection of values that come from the parent. As such, A `props` object is a collection of values that come from the parent. As such,
+2 -2
View File
@@ -152,7 +152,7 @@ This may seem counter-intuitive, but it makes perfect sense in the context of co
```js ```js
class DoubleCounter extends Component { class DoubleCounter extends Component {
static template = xml` static template = xml`
<t t-esc="'selected: ' + state.selected + ', value: ' + state[state.selected]"/> <t t-esc="state.selected + ': ' + state[state.selected].value"/>
<button t-on-click="() => this.state.count1++">increment count 1</button> <button t-on-click="() => this.state.count1++">increment count 1</button>
<button t-on-click="() => this.state.count2++">increment count 2</button> <button t-on-click="() => this.state.count2++">increment count 2</button>
<button t-on-click="changeCounter">Switch counter</button> <button t-on-click="changeCounter">Switch counter</button>
@@ -193,7 +193,7 @@ to be able to opt out of creating them in the first place. This is the purpose o
### `markRaw` ### `markRaw`
Marks an object so that it is ignored by the reactivity system, meaning that if this object is ever Marks an object so that it is ignored by the reactivity system, meaning that if this object is ever
part of a reactive object, it will be returned as is, and no keys in that object will be part of a of a reactive object, it will be returned as is, and no keys in that object will be
observed. observed.
```js ```js
+5 -6
View File
@@ -133,7 +133,7 @@ Slots can define a default content, in case the parent did not define them:
## Dynamic Slots ## Dynamic Slots
The `t-slot` directive is actually able to use any expressions, using string The `t-slot` directive is actually able to use any expressions, using string
interpolation: interplolation:
```xml ```xml
<t t-slot="{{current}}" /> <t t-slot="{{current}}" />
@@ -175,7 +175,7 @@ class Notebook extends Component {
<div class="notebook"> <div class="notebook">
<div class="tabs"> <div class="tabs">
<t t-foreach="tabNames" t-as="tab" t-key="tab_index"> <t t-foreach="tabNames" t-as="tab" t-key="tab_index">
<span t-att-class="{active:tab_index === activeTab}" t-on-click="() => state.activeTab=tab_index"> <span t-att-class="{active:tab_index === activeTab}" t-on-click="() => state.activeTab=tab">
<t t-esc="props.slots[tab].title"/> <t t-esc="props.slots[tab].title"/>
</span> </span>
</t> </t>
@@ -201,17 +201,16 @@ use this `Notebook` component:
```xml ```xml
<Notebook> <Notebook>
<t t-set-slot="page1" title.translate="Page 1"> <t t-set-slot="page1" title="'Page 1'">
<div>this is in the page 1</div> <div>this is in the page 1</div>
</t> </t>
<t t-set-slot="page2" title.translate="Page 2" hidden="somevalue"> <t t-set-slot="page2" title="'Page 2'" hidden="somevalue">
<div>this is in the page 2</div> <div>this is in the page 2</div>
</t> </t>
</Notebook> </Notebook>
``` ```
Slot params works like normal props, so one can use suffixes like `.translate` Slot params works like normal props, so one can use the `.bind` suffix to
when a prop is a user facing string and should be translated, or `.bind` to
bind a function if needed. bind a function if needed.
## Slot scopes ## Slot scopes
+19 -62
View File
@@ -18,7 +18,6 @@
- [Sub Templates](#sub-templates) - [Sub Templates](#sub-templates)
- [Dynamic Sub Templates](#dynamic-sub-templates) - [Dynamic Sub Templates](#dynamic-sub-templates)
- [Debugging](#debugging) - [Debugging](#debugging)
- [Custom Directives](#custom-directives)
- [Fragments](#fragments) - [Fragments](#fragments)
- [Inline templates](#inline-templates) - [Inline templates](#inline-templates)
- [Rendering svg](#rendering-svg) - [Rendering svg](#rendering-svg)
@@ -56,19 +55,17 @@ extensions.
For reference, here is a list of all standard QWeb directives: For reference, here is a list of all standard QWeb directives:
| Name | Description | | Name | Description |
| ------------------------------ | ----------------------------------------------------------------------- | | ------------------------------ | --------------------------------------------------------------- |
| `t-esc` | [Outputting safely a value](#outputting-data) | | `t-esc` | [Outputting safely a value](#outputting-data) |
| `t-out` | [Outputting value, possibly without escaping](#outputting-data) | | `t-out` | [Outputting value, possibly without escaping](#outputting-data) |
| `t-set`, `t-value` | [Setting variables](#setting-variables) | | `t-set`, `t-value` | [Setting variables](#setting-variables) |
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) | | `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
| `t-foreach`, `t-as` | [Loops](#loops) | | `t-foreach`, `t-as` | [Loops](#loops) |
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) | | `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
| `t-call` | [Rendering sub templates](#sub-templates) | | `t-call` | [Rendering sub templates](#sub-templates) |
| `t-debug`, `t-log` | [Debugging](#debugging) | | `t-debug`, `t-log` | [Debugging](#debugging) |
| `t-translation` | [Disabling the translation of a node](translations.md) | | `t-translation` | [Disabling the translation of a node](translations.md) |
| `t-translation-context` | [Context of translations within a node](translations.md) |
| `t-translation-context-*` | [Context of translation for a specific node attribute](translations.md) |
The component system in Owl requires additional directives, to express various The component system in Owl requires additional directives, to express various
needs. Here is a list of all Owl specific directives: needs. Here is a list of all Owl specific directives:
@@ -83,7 +80,6 @@ needs. Here is a list of all Owl specific directives:
| `t-slot`, `t-set-slot`, `t-slot-scope` | [Rendering a slot](slots.md) | | `t-slot`, `t-set-slot`, `t-slot-scope` | [Rendering a slot](slots.md) |
| `t-model` | [Form input bindings](input_bindings.md) | | `t-model` | [Form input bindings](input_bindings.md) |
| `t-tag` | [Rendering nodes with dynamic tag name](#dynamic-tag-names) | | `t-tag` | [Rendering nodes with dynamic tag name](#dynamic-tag-names) |
| `t-custom-*` | [Rendering nodes with custom directives](#custom-directives) |
## QWeb Template Reference ## QWeb Template Reference
@@ -193,15 +189,6 @@ The first `t-out` will act as a `t-esc` directive, which means that the content
of `value1` will be escaped. However, since `value2` has been tagged as a markup, of `value1` will be escaped. However, since `value2` has been tagged as a markup,
this will be injected as html. this will be injected as html.
`markup` can also be used as a tag function, allowing the interpolated values to
be safely escaped:
```js
const maliciousInput = "<script>alert('💥💥')</script>";
// <b>&lt;script&gt;alert(&#x27;💥💥&#x27;)&lt;/script&gt;</b>
const value = markup`<b>${maliciousInput}</b>`;
```
### Setting Variables ### Setting Variables
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ... QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
@@ -389,16 +376,15 @@ An important difference should be made with the usual `QWeb` behaviour: Owl
requires the presence of a `t-key` directive, to be able to properly reconcile requires the presence of a `t-key` directive, to be able to properly reconcile
renderings. renderings.
`t-foreach` can iterate on any iterable, and also has special support for objects `t-foreach` can iterate on an array (the current item will be the current value)
and maps, it will expose the key of the current iteration as the contents of the or an object (the current item will be the current key).
`t-as`, and the corresponding value with the same name and the suffix `_value`.
In addition to the name passed via t-as, `t-foreach` provides a few other useful In addition to the name passed via t-as, `t-foreach` provides a few other
variables (note: `$as` will be replaced with the name passed to `t-as`): variables for various data points (note: `$as` will be replaced with the name
passed to `t-as`):
- `$as_value`: the current iteration value, identical to `$as` for arrays and - `$as_value`: the current iteration value, identical to `$as` for lists and
other iterables, but for objects and maps, it provides the value (where `$as` integers, but for objects, it provides the value (where `$as` provides the key)
provides the key)
- `$as_index`: the current iteration index (the first item of the iteration has index 0) - `$as_index`: the current iteration index (the first item of the iteration has index 0)
- `$as_first`: whether the current item is the first of the iteration - `$as_first`: whether the current item is the first of the iteration
(equivalent to `$as_index == 0`) (equivalent to `$as_index == 0`)
@@ -491,7 +477,7 @@ not work with other iterables, such as `Set`. However, it is only a matter of
using the `...` javascript operator. For example: using the `...` javascript operator. For example:
```xml ```xml
<t t-foreach="[...items]" t-as="item">...</t> <t t-foreach="...items" t-as="item">...</t>
``` ```
The `...` operator will convert the `Set` (or any other iterables) into a list, The `...` operator will convert the `Set` (or any other iterables) into a list,
@@ -601,35 +587,6 @@ will stop execution if the browser dev tools are open.
will print 42 to the console. will print 42 to the console.
### Custom Directives
Owl 2 supports the declaration of custom directives. To use them, an Object of functions needs to be configured on the owl APP:
```js
new App(..., {
customDirectives: {
test_directive: function (el, value) {
el.setAttribute("t-on-click", value);
}
}
});
```
The functions will be called when a custom directive with the name of the
function is found. The original element will be replaced with the one
modified by the function.
This :
```xml
<div t-custom-test_directive="click" />
```
will be replaced by :
```xml
<div t-on-click="value"/>
```
## Fragments ## Fragments
Owl 2 supports templates with an arbitrary number of root elements, or even just Owl 2 supports templates with an arbitrary number of root elements, or even just
+5 -37
View File
@@ -1,28 +1,17 @@
# 🦉 Translations 🦉 # 🦉 Translations 🦉
If properly setup, Owl can translate all rendered templates. To do If properly setup, Owl can translate all rendered templates. To do
so, it needs a translate function, which takes so, it needs a translate function, which takes a string and returns a string.
- a string (the term to translate)
- a string (the translation context of the term)
and returns a string.
For example: For example:
```js ```js
const translations = { const translations = {
fr: { hello: "bonjour",
hello: "bonjour", yes: "oui",
yes: "oui", no: "non",
no: "non",
},
pt: {
hello: "bom dia",
yes: "sim",
no: "não",
},
}; };
const translateFn = (str, ctx) => translations[ctx]?.[str] || str; const translateFn = (str) => translations[str] || str;
const app = new App(Root, { templates, tranaslateFn }); const app = new App(Root, { templates, tranaslateFn });
// ... // ...
@@ -38,11 +27,6 @@ Once setup, all rendered templates will be translated using `translateFn`:
`placeholder`, `label` and `alt`, `placeholder`, `label` and `alt`,
- translating text nodes can be disabled with the special attribute `t-translation`, - translating text nodes can be disabled with the special attribute `t-translation`,
if its value is `off`. if its value is `off`.
- the translate function receives as second parameter a context that can be used
to contextualized the translation. That context can be set globally on a node
and its children by using `t-translation-context`. If a specific node
attribute `x` needs another context, that context can be specified with a
special directive `t-translation-context-x`.
So, with the above `translateFn`, the following templates: So, with the above `translateFn`, the following templates:
@@ -62,22 +46,6 @@ will be rendered as:
<input placeholder="bonjour" other="yes"/> <input placeholder="bonjour" other="yes"/>
``` ```
and the following template:
```xml
<div t-translation-context="fr" title="hello">hello</div>
<div>Are you sure?</div>
<input t-translation-context-placeholder="pt" placeholder="hello" other="yes"/>
```
will be rendered as:
```xml
<div title="bonjour">bonjour</div>
<div>Are you sure?</div>
<input placeholder="bom dia" other="yes"/>
```
Note that the translation is done during the compilation of the template, not Note that the translation is done during the compilation of the template, not
when it is rendered. when it is rendered.
-20
View File
@@ -9,7 +9,6 @@ functions are all available in the `owl.utils` namespace.
- [`loadFile`](#loadfile): loading a file (useful for templates) - [`loadFile`](#loadfile): loading a file (useful for templates)
- [`EventBus`](#eventbus): a simple EventBus - [`EventBus`](#eventbus): a simple EventBus
- [`validate`](#validate): a validation function - [`validate`](#validate): a validation function
- [`batched`](#batched): batch function calls
## `whenReady` ## `whenReady`
@@ -79,22 +78,3 @@ validate(
// - 'id' is missing (should be a number), // - 'id' is missing (should be a number),
// - 'url' is missing (should be a boolean or list of numbers), // - 'url' is missing (should be a boolean or list of numbers),
``` ```
## `batched`
The `batched` function creates a batched version of a callback so that multiple calls to it within the same microtick will only result in a single invocation of the original callback.
```js
function hello() {
console.log("hello");
}
const batchedHello = batched(hello);
batchedHello();
// Nothing is logged
batchedHello();
// Still not logged
await Promise.resolve(); // Await the next microtick
// "hello" is logged only once
```
-56
View File
@@ -1,56 +0,0 @@
# Owl Devtools Browser extension
The owl devtools browser extension is an extension available on chrome or firefox which adds an owl tab
to the browser devtools in order to inspect all owl apps that are present on any web page, their components
and allows to interract with their data to a certain extend. There is also a profiler available to visualize
the components' lifecycle and be able to trace their origin.
See the [`devtools doc`](devtools_guide.md) for more information.
## Install the extension manually (for devs)
In the owl root folder:
```bash
npm install
```
For chrome:
```bash
npm run build:devtools-chrome
```
For firefox:
```bash
npm run build:devtools-firefox
```
You can also run:
```bash
npm run dev:devtools-chrome
```
or
```bash
npm run dev:devtools-firefox
```
to avoid recompiling owl and gain time if it has already been done.
To run the extension:
In google chrome: go to your chrome extensions admin panel, activate developer mode and click on `Load unpacked`.
Select the output folder (dist/devtools) and that's it, your extension is active!
There is a convenient refresh button on the extension card (still on the same admin page) to update your code.
Do note that if you got some problems, you may need to completly remove and reload the extension to completly refresh the extension.
In firefox: go to the address about:debugging#/runtime/this-firefox and click on `Load temporary Add-on...`.
Select any file of the output folder (dist/devtools) and that's it, your extension is active!
Here, you can use the reload button to refresh the extension.
Note that you may have to open another window or reload your tab to see the extension working.
Also note that the extension will only be active on pages that have a sufficient version of owl.
-171
View File
@@ -1,171 +0,0 @@
# Owl Devtools Guide
## Information popup
After having installed the extension, a new icon will be added to your extension bar.
If you don't see it, you can pin the extension using the extensions popup.
<img src="screenshots/extensions.png"/>
Clicking on the owl icon will open the information popup. This popup is useful
to know in advance whether owl is loaded in the tab or not. This is also indicated
by the icon itself: if it is flipped upside-down, it means that owl is not loaded in the
active tab. Do note that old versions of owl are not supported by the extension and will
therefore be indicated either as obsolete or absent by the extension popup.
<img src="screenshots/popup.png"/>
## First steps
When you are on a page where owl is detected, you can open your devtools either with
right-click -> Inspect or using F12. In the devtools menu, you can search for the Owl
tab which is added by the extension. It will be present by default at the end of the list but
you can drag and drop it at the position you want for easier navigation in the future.
<img src="screenshots/find_owl_tab.png"/>
When you open the tab, you arrive on the Components view by default which is one of the
two available tabs at the top. Here is an example of the devtools on the Odoo CRM app:
<img src="screenshots/crm.png"/>
## Components tab
The components tab is separated into two sub windows: the components tree in the left and
the component details in the right. The components tree will display all the different
components that are present in the tab in the form of a tree. The root of this tree is
actually the app which is not a component but can still be inspected by the devtools like
one. There can also be multiple apps loaded in the page like in website:
<img src="screenshots/multi_apps.png"/>
There is a convenient search bar at the top of the components tree which will help finding
the components tou want in the tree and also, an element picker can be used to directly select
the component you want to focus on in the page which is especially useful when 1trying to find
what you want. Just click on the elements picker icon and click on the element you want to focus
on in the page and it will be selected in the devtools accordingly. Hovering any element in the
page in this mode will highlight it and the same happens anytime in the components tree.
<img src="screenshots/picker.png"/>
In the tree itself, the navigation is quite simple and is similar to the one in the Elements tab
of the browser's devtools. It is possible to navigate with the keyboard using the arrow keys and
multiple shortcuts are available in a custom menu when right-clicking on a component. This menu
allows to expand/fold all the children nodes of a component, fold its direct children only, inspect
the source code of the component, send it as a global variable in the console, go to the Elements tab
and focus on its content, force a rerender of the component, send its observed states to the console
as a global variable, inspect its compiled template in the Sources tab or send its raw template
to the console.
<img src="screenshots/menu.png"/>
The component details window in the right will show the component that is currently selected as well
as its env, props, observed states and all the other variables that are present on its instance.
While the props and the env are already present on the actual instance of the component and are
pretty explicit by themselves, the observed state value is a bit more complicated to grasp.
The observed state is actually information about which variables are being observed by the component:
when any property of a reactive object is being read by the component, the component will subscribe
to this property which means it will listen to any change that can occur on the property and render
when such a change occurs. This can be visualized easily within the devtools inside of the observed
state section: observed properties of the reactive object(s) are displayed in bold while the others
are greyed out. Do keep in mind that a greyed out property in the observed state of one component
may be observed by another and the other way around is also possible. Here is an example for some
user Field component:
<img src="screenshots/states.png"/>
Navigation inside the properties is also similar to the one in console variables: properties have
their prototype displayed and getters will get their value when clicked on (...). It is also possible to
send any property to the console using the right-click context menu on it and functions can be inspected
in the sources tab as well.
<img src="screenshots/function_menu.png"/>
Using the right-click context menu on a property also allows to observe variables. Observed variables will
be sent to a dedicated section of the details window and their value will be refreshed every 200ms. These
variables are only shown when they are found and their access path will be kept in memory inside the
browser so that it will always persist until the user decides to stop observing the variable. As in the
browser's devtools, observed objects are displayed in reduced form and cannot be interacted with. It is
still possible to send them to the console or remove them from the list using right-click.
<img src="screenshots/observe_variables.png"/>
The last section of the details window is filled with the component's lifecycle hooks. Using right click on
them allows to place breakpoints inside the hook (either on its instance or class, hooks like mounted and
willStart cannot have instance-based breakpoints because they will never trigger). Conditions in conditional
breakpoints will be evaluated in the context of the component's definition.
<img src="screenshots/hooks.png"/>
There are several icons available to perform several of the actions described before in the components
tree context menu and all these actions are also available by opening the menu by right-clicking on the
component's name. Using the left click on the component's name will focus it in the components tree.
It is also possible to edit any of the leaf node properties. To do so, you must double click on the
property's value and modify it using the freshly created input then press enter to apply the changes.
Do note that the modified values should be written in JSON format in order to be valid (examples:
89, "yes", undefined, null, \["hello", 15\], {"a": 1}, true, ...). Editing any value will produce a
manual render of the component (or the root component of the application in the case of env values).
Whether the edition has an impact on the component or not and whether it produces an error is the
responsability of the user.
<img src="screenshots/edit.png"/>
## Profiler
The profiler tab is the other tab of the owl devtools. It consists in an actions bar at the top and
a tree/list of events related to the owl components' renders. Here is an example of the events launched
when entering the Odoo Crm app.
<img src="screenshots/profiler.png"/>
In the initial state, no event is displayed. You need to activate the recording of events before they
are intercepted by the devtools using the record button.
<img src="screenshots/record.png"/>
The second button is used to clear all the events that have been recorded. The select can be used to
switch between the tree view (which shows the causality between renders) and the events log view which
simply displays the events in the exact order they were triggered. In this view, you can expand the create,
update and destroy events which reveals the component that initiated the event. Also, a transition line will
appear each time a new animation frame has been loaded between events.
<img src="screenshots/events_log.png"/>
The third button is only visible in tree view and allows to fold all the render events that were recorded.
Some actions are also available when using the right-click on any event of the tree view for navigation
purpose in a similar fashion as in the components tree.
<img src="screenshots/tree_actions.png"/>
There is also the Trace Renderings and Trace Subscriptions features. These features are independant of the
recording of events and have no effect on the profiler tab. The Trace Renderings option is used to log in
the console all the render events and allows to show their traceback information. Similarly, the Trace
Subscriptions option logs all the properties that caused a render event and also allows to see the traceback
of the modification.
<img src="screenshots/trace_rendering.png"/>
<img src="screenshots/trace_subscriptions.png"/>
The Owl Devtools also allow to inspect iframes coded in Owl: when an Owl iframe is detected in the page,
the iframe selector will appear next to the tabs. This allows to switch from an iframe to another easily.
Be aware that switching iframes will clear all record events from the profiler tab. Iframes detection is
currently not working in the firefox version, we are aware of this issue and will try to address it in the
future.
<img src="screenshots/iframes.png"/>
## Options
The owl devtools extension has a dark mode feature which defaults to your general devtools settings and can
be toggled using the sun/moon icon at the top-right corner of the tab. There is also a refresh button to
completely reset the owl devtools.
<img src="screenshots/darkmode.png"/>
## Troubleshooting
If the feedback from the page to the devtools seems to be cut, you can first try to use the refresh
button mentioned above but if it still doesn't seem to work, just close the devtools and refresh the page.
This will eventually happen any time a tab stays opened for too long without being refreshed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 346 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

File diff suppressed because one or more lines are too long
-72
View File
@@ -1,72 +0,0 @@
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Tomorrow Comment */
.hljs-comment,
.hljs-quote {
color: #8e908c;
}
/* Tomorrow Red */
.hljs-variable,
.hljs-template-variable,
.hljs-tag,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class,
.hljs-regexp,
.hljs-deletion {
color: #c82829;
}
/* Tomorrow Orange */
.hljs-number,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params,
.hljs-meta,
.hljs-link {
color: #f5871f;
}
/* Tomorrow Yellow */
.hljs-attribute {
color: #eab700;
}
/* Tomorrow Green */
.hljs-string,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: #718c00;
}
/* Tomorrow Blue */
.hljs-title,
.hljs-section {
color: #4271ae;
}
/* Tomorrow Purple */
.hljs-keyword,
.hljs-selector-tag {
color: #8959a8;
}
.hljs {
display: block;
overflow-x: auto;
background: white;
color: #4d4d4c;
padding: 0.5em;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
-116
View File
@@ -1,116 +0,0 @@
html, body {
background-color: #fefefe;
font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
height: 100%;
margin: 0;
text-rendering: optimizeLegibility;
}
body {
display: grid;
grid-gap: 3rem;
grid-template-areas: "header" "nav" "main" "footer";
grid-template-columns: 1fr;
height: 100%;
grid-template-rows: 1fr 3rem 1fr 3rem;
}
@media screen and (max-width: 800px) {
body {
grid-template-rows: 1fr 3rem 1fr 5rem;
}
}
a {
color: #00A09D;
text-decoration: none;
}
a:hover, a:active, a:visited {
text-decoration: underline;
}
header {
grid-area: header;
display: flex;
align-items: center;
flex-direction: column;
justify-content: flex-end;
text-align: center;
padding-top: 3rem !important;
}
hgroup > p {
margin-bottom: auto;
}
nav {
grid-area: nav;
}
main {
grid-area: main;
/*justify-self: center;*/
grid-column: 1 / -1;
/*max-width: 80rem !important;*/
/*margin: 3rem 0;*/
}
footer {
grid-area: footer;
padding-bottom: 3rem !important;
}
header, nav, footer {
text-align: center;
}
article {
padding: 3rem 0;
}
article h3 {
font-size: 2rem;
font-weight: 700;
}
article.brand {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
article.design {
background-color: #875A7B;
color: #f0eeee;
}
header .homepage-logo {
margin-bottom: 2rem;
}
@media (min-width: 40rem) {
.row {
flex-direction: column;
margin-left: initial;
width: 100%;
}
.row .column {
margin-bottom: initial;
padding: initial;
}
}
@media (min-width: 60rem) {
.row {
flex-direction: row;
margin-left: -1.0rem;
width: calc(100% + 2.0rem);
}
.row .column {
margin-bottom: inherit;
padding: 0 1.0rem;
}
}
-602
View File
@@ -1,602 +0,0 @@
/*!
* Milligram v1.3.0
* https://milligram.github.io
*
* Copyright (c) 2017 CJ Patoilo
* Licensed under the MIT license
*/
*,
*:after,
*:before {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 62.5%;
}
body {
color: #606c76;
font-family: 'Roboto', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
font-size: 1.6em;
font-weight: 300;
letter-spacing: .01em;
line-height: 1.6;
}
blockquote {
border-left: 0.3rem solid #d1d1d1;
margin-left: 0;
margin-right: 0;
padding: 1rem 1.5rem;
}
blockquote *:last-child {
margin-bottom: 0;
}
.button,
button,
input[type='button'],
input[type='reset'],
input[type='submit'] {
background-color: #9b4dca;
border: 0.1rem solid #9b4dca;
border-radius: .4rem;
color: #fff;
cursor: pointer;
display: inline-block;
font-size: 1.1rem;
font-weight: 700;
height: 3.8rem;
letter-spacing: .1rem;
line-height: 3.8rem;
padding: 0 3.0rem;
text-align: center;
text-decoration: none;
text-transform: uppercase;
white-space: nowrap;
}
.button:focus, .button:hover,
button:focus,
button:hover,
input[type='button']:focus,
input[type='button']:hover,
input[type='reset']:focus,
input[type='reset']:hover,
input[type='submit']:focus,
input[type='submit']:hover {
background-color: #606c76;
border-color: #606c76;
color: #fff;
outline: 0;
}
.button[disabled],
button[disabled],
input[type='button'][disabled],
input[type='reset'][disabled],
input[type='submit'][disabled] {
cursor: default;
opacity: .5;
}
.button[disabled]:focus, .button[disabled]:hover,
button[disabled]:focus,
button[disabled]:hover,
input[type='button'][disabled]:focus,
input[type='button'][disabled]:hover,
input[type='reset'][disabled]:focus,
input[type='reset'][disabled]:hover,
input[type='submit'][disabled]:focus,
input[type='submit'][disabled]:hover {
background-color: #9b4dca;
border-color: #9b4dca;
}
.button.button-outline,
button.button-outline,
input[type='button'].button-outline,
input[type='reset'].button-outline,
input[type='submit'].button-outline {
background-color: transparent;
color: #9b4dca;
}
.button.button-outline:focus, .button.button-outline:hover,
button.button-outline:focus,
button.button-outline:hover,
input[type='button'].button-outline:focus,
input[type='button'].button-outline:hover,
input[type='reset'].button-outline:focus,
input[type='reset'].button-outline:hover,
input[type='submit'].button-outline:focus,
input[type='submit'].button-outline:hover {
background-color: transparent;
border-color: #606c76;
color: #606c76;
}
.button.button-outline[disabled]:focus, .button.button-outline[disabled]:hover,
button.button-outline[disabled]:focus,
button.button-outline[disabled]:hover,
input[type='button'].button-outline[disabled]:focus,
input[type='button'].button-outline[disabled]:hover,
input[type='reset'].button-outline[disabled]:focus,
input[type='reset'].button-outline[disabled]:hover,
input[type='submit'].button-outline[disabled]:focus,
input[type='submit'].button-outline[disabled]:hover {
border-color: inherit;
color: #9b4dca;
}
.button.button-clear,
button.button-clear,
input[type='button'].button-clear,
input[type='reset'].button-clear,
input[type='submit'].button-clear {
background-color: transparent;
border-color: transparent;
color: #9b4dca;
}
.button.button-clear:focus, .button.button-clear:hover,
button.button-clear:focus,
button.button-clear:hover,
input[type='button'].button-clear:focus,
input[type='button'].button-clear:hover,
input[type='reset'].button-clear:focus,
input[type='reset'].button-clear:hover,
input[type='submit'].button-clear:focus,
input[type='submit'].button-clear:hover {
background-color: transparent;
border-color: transparent;
color: #606c76;
}
.button.button-clear[disabled]:focus, .button.button-clear[disabled]:hover,
button.button-clear[disabled]:focus,
button.button-clear[disabled]:hover,
input[type='button'].button-clear[disabled]:focus,
input[type='button'].button-clear[disabled]:hover,
input[type='reset'].button-clear[disabled]:focus,
input[type='reset'].button-clear[disabled]:hover,
input[type='submit'].button-clear[disabled]:focus,
input[type='submit'].button-clear[disabled]:hover {
color: #9b4dca;
}
code {
background: #f4f5f6;
border-radius: .4rem;
font-size: 86%;
margin: 0 .2rem;
padding: .2rem .5rem;
white-space: nowrap;
}
pre {
background: #f4f5f6;
border-left: 0.3rem solid #9b4dca;
overflow-y: hidden;
}
pre > code {
border-radius: 0;
display: block;
padding: 1rem 1.5rem;
white-space: pre;
}
hr {
border: 0;
border-top: 0.1rem solid #f4f5f6;
margin: 3.0rem 0;
}
input[type='email'],
input[type='number'],
input[type='password'],
input[type='search'],
input[type='tel'],
input[type='text'],
input[type='url'],
textarea,
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: transparent;
border: 0.1rem solid #d1d1d1;
border-radius: .4rem;
box-shadow: none;
box-sizing: inherit;
height: 3.8rem;
padding: .6rem 1.0rem;
width: 100%;
}
input[type='email']:focus,
input[type='number']:focus,
input[type='password']:focus,
input[type='search']:focus,
input[type='tel']:focus,
input[type='text']:focus,
input[type='url']:focus,
textarea:focus,
select:focus {
border-color: #9b4dca;
outline: 0;
}
select {
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="14" viewBox="0 0 29 14" width="29"><path fill="#d1d1d1" d="M9.37727 3.625l5.08154 6.93523L19.54036 3.625"/></svg>') center right no-repeat;
padding-right: 3.0rem;
}
select:focus {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="14" viewBox="0 0 29 14" width="29"><path fill="#9b4dca" d="M9.37727 3.625l5.08154 6.93523L19.54036 3.625"/></svg>');
}
textarea {
min-height: 6.5rem;
}
label,
legend {
display: block;
font-size: 1.6rem;
font-weight: 700;
margin-bottom: .5rem;
}
fieldset {
border-width: 0;
padding: 0;
}
input[type='checkbox'],
input[type='radio'] {
display: inline;
}
.label-inline {
display: inline-block;
font-weight: normal;
margin-left: .5rem;
}
.container {
margin: 0 auto;
max-width: 112.0rem;
padding: 0 2.0rem;
position: relative;
width: 100%;
}
.row {
display: flex;
flex-direction: column;
padding: 0;
width: 100%;
}
.row.row-no-padding {
padding: 0;
}
.row.row-no-padding > .column {
padding: 0;
}
.row.row-wrap {
flex-wrap: wrap;
}
.row.row-top {
align-items: flex-start;
}
.row.row-bottom {
align-items: flex-end;
}
.row.row-center {
align-items: center;
}
.row.row-stretch {
align-items: stretch;
}
.row.row-baseline {
align-items: baseline;
}
.row .column {
display: block;
flex: 1 1 auto;
margin-left: 0;
max-width: 100%;
width: 100%;
}
.row .column.column-offset-10 {
margin-left: 10%;
}
.row .column.column-offset-20 {
margin-left: 20%;
}
.row .column.column-offset-25 {
margin-left: 25%;
}
.row .column.column-offset-33, .row .column.column-offset-34 {
margin-left: 33.3333%;
}
.row .column.column-offset-50 {
margin-left: 50%;
}
.row .column.column-offset-66, .row .column.column-offset-67 {
margin-left: 66.6666%;
}
.row .column.column-offset-75 {
margin-left: 75%;
}
.row .column.column-offset-80 {
margin-left: 80%;
}
.row .column.column-offset-90 {
margin-left: 90%;
}
.row .column.column-10 {
flex: 0 0 10%;
max-width: 10%;
}
.row .column.column-20 {
flex: 0 0 20%;
max-width: 20%;
}
.row .column.column-25 {
flex: 0 0 25%;
max-width: 25%;
}
.row .column.column-33, .row .column.column-34 {
flex: 0 0 33.3333%;
max-width: 33.3333%;
}
.row .column.column-40 {
flex: 0 0 40%;
max-width: 40%;
}
.row .column.column-50 {
flex: 0 0 50%;
max-width: 50%;
}
.row .column.column-60 {
flex: 0 0 60%;
max-width: 60%;
}
.row .column.column-66, .row .column.column-67 {
flex: 0 0 66.6666%;
max-width: 66.6666%;
}
.row .column.column-75 {
flex: 0 0 75%;
max-width: 75%;
}
.row .column.column-80 {
flex: 0 0 80%;
max-width: 80%;
}
.row .column.column-90 {
flex: 0 0 90%;
max-width: 90%;
}
.row .column .column-top {
align-self: flex-start;
}
.row .column .column-bottom {
align-self: flex-end;
}
.row .column .column-center {
-ms-grid-row-align: center;
align-self: center;
}
@media (min-width: 40rem) {
.row {
flex-direction: row;
margin-left: -1.0rem;
width: calc(100% + 2.0rem);
}
.row .column {
margin-bottom: inherit;
padding: 0 1.0rem;
}
}
a {
color: #9b4dca;
text-decoration: none;
}
a:focus, a:hover {
color: #606c76;
}
dl,
ol,
ul {
list-style: none;
margin-top: 0;
padding-left: 0;
}
dl dl,
dl ol,
dl ul,
ol dl,
ol ol,
ol ul,
ul dl,
ul ol,
ul ul {
font-size: 90%;
margin: 1.5rem 0 1.5rem 3.0rem;
}
ol {
list-style: decimal inside;
}
ul {
list-style: circle inside;
}
.button,
button,
dd,
dt,
li {
margin-bottom: 1.0rem;
}
fieldset,
input,
select,
textarea {
margin-bottom: 1.5rem;
}
blockquote,
dl,
figure,
form,
ol,
p,
pre,
table,
ul {
margin-bottom: 2.5rem;
}
table {
border-spacing: 0;
width: 100%;
}
td,
th {
border-bottom: 0.1rem solid #e1e1e1;
padding: 1.2rem 1.5rem;
text-align: left;
}
td:first-child,
th:first-child {
padding-left: 0;
}
td:last-child,
th:last-child {
padding-right: 0;
}
b,
strong {
font-weight: bold;
}
p {
margin-top: 0;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: 300;
letter-spacing: -.1rem;
margin-bottom: 2.0rem;
margin-top: 0;
}
h1 {
font-size: 4.6rem;
line-height: 1.2;
}
h2 {
font-size: 3.6rem;
line-height: 1.25;
}
h3 {
font-size: 2.8rem;
line-height: 1.3;
}
h4 {
font-size: 2.2rem;
letter-spacing: -.08rem;
line-height: 1.35;
}
h5 {
font-size: 1.8rem;
letter-spacing: -.05rem;
line-height: 1.5;
}
h6 {
font-size: 1.6rem;
letter-spacing: 0;
line-height: 1.4;
}
img {
max-width: 100%;
}
.clearfix:after {
clear: both;
content: ' ';
display: table;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
/*# sourceMappingURL=milligram.css.map */
-349
View File
@@ -1,349 +0,0 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

-15
View File
@@ -1,15 +0,0 @@
import { mount, Component, useState, loadFile } from "@odoo/owl";
class Counter extends Component {
static template = "Counter";
setup() {
this.state = useState({ value: 0 });
}
increment() {
this.state.value++;
}
}
const templates = await loadFile("./counter.xml");
mount(Counter, document.getElementById("app-container"), { templates });
-7
View File
@@ -1,7 +0,0 @@
<templates>
<t t-name="Counter">
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>
</t>
</templates>
-9
View File
@@ -1,9 +0,0 @@
import { loadFile } from "@odoo/owl";
for (const [className, type] of [["xml", "xml"], ["javascript", "js"]]) {
loadFile(`./counter.${type}`).then(code => {
const el = document.querySelector(`code.${className}`);
el.textContent = code;
hljs.highlightBlock(el);
})
}
-74
View File
@@ -1,74 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OWL Framework</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
<link rel="stylesheet" href="assets/normalize.css">
<link rel="stylesheet" href="assets/milligram.css">
<link rel="stylesheet" href="assets/highlight.tomorrow.css">
<link rel="stylesheet" href="assets/main.css">
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
</head>
<body>
<header class="container">
<img class="homepage-logo" src="assets/owl_1f989.png" alt="OWL Logo">
<hgroup>
<h1>OWL Framework</h1>
<p>Mysterious OWL: A web framework for structured, dynamic and maintainable applications</p>
</hgroup>
</header>
<nav class="container">
<p>
<a href="https://github.com/odoo/owl" title="https://github.com/odoo/owl">Github</a>
&bull;
<a href="https://github.com/odoo/owl/blob/master/doc/readme.md">Documentation</a>
&bull;
<a href="playground/">Playground</a>
</p>
</nav>
<main>
<article class="design">
<div class="container">
<h2>Why OWL?</h2>
<div class="row">
<section class="column">
<h3>XML based</h3>
<p>Templates are based on the XML format, which allows interesting applications. For example, they could be stored in a database and modified dynamically with <tt>xpaths</tt>.</p>
</section>
<section class="column">
<h3>Templates compiled in the browser</h3>
<p>This may not be a good fit for all applications, but if you need to generate dynamically user interfaces in the browser, this is very powerful. For example, a generic form view component could generate a specific form user interface for each various models, from a XML view.</p>
</section>
<section class="column">
<h3>No toolchain required</h3>
<p>This is extremely useful for some applications, if, for various reasons (security/deployment/dynamic modules/specific assets tools), it is not ok to use standard web tools based on <tt>npm</tt>.</p>
</section>
</div>
</div>
</article>
<article class="example">
<div class="container">
<h2>Example</h2>
<div class="row">
<section class="column">
<pre><code class="javascript"></code></pre>
</section>
<section class="column">
<pre><code class="xml"></code></pre>
<div id="app-container"></div>
</section>
</div>
</div>
</article>
</main>
<footer>
<p><a href=".">OWL</a> is licensed under LGPLv3.<br>Logo from <a href="https://github.com/googlefonts/noto-emoji">Google Noto Emoji Font</a>, licensed under Apache License 2.0</p>
</footer>
<script src="assets/highlight.pack.js"></script>
<script type="module" src="display_code.js"></script>
<script type="module" src="counter.js"></script>
</body>
</html>
-6289
View File
File diff suppressed because it is too large Load Diff
-18
View File
@@ -1,18 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OWL Playground</title>
<link rel="icon" href="data:,">
<script src="libs/ace.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/solid.css" integrity="sha384-QokYePQSOwpBDuhlHOsX0ymF6R/vLk/UQVz3WHa6wygxI5oGTmDTv8wahFOSspdm" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/fontawesome.css" integrity="sha384-vd1e11sR28tEK9YANUtpIOdjGW14pS87bUBuOIoBILVWLFnS+MCX9T6MMf0VdPGq" crossorigin="anonymous">
<!-- Application JS/CSS -->
<link rel="stylesheet" href="playground.css">
<script type="module" src="playground.js"></script>
</head>
<body>
</body>
</html>
@@ -1,11 +0,0 @@
tr.danger {
font-weight: bold;
}
.remove:hover {
font-weight: bold;
}
.remove {
cursor: pointer;
}
@@ -1,124 +0,0 @@
import { Component, mount, useState, onPatched} from "@odoo/owl";
// -----------------------------------------------------------------------------
// Data generation
// -----------------------------------------------------------------------------
let idCounter = 1;
const adjectives = [
"pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain",
"quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd",
"unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
function _random (max) { return Math.round(Math.random() * 1000) % max; };
function buildData(count) {
const data = new Array(count);
for (let i = 0; i < count; i++) {
const label = `${adjectives[_random(adjectives.length)]} ${colours[_random(colours.length)]} ${nouns[_random(nouns.length)]}`;
data[i] = {
id: idCounter++,
label,
};
}
return data;
}
// -----------------------------------------------------------------------------
// Components
// -----------------------------------------------------------------------------
class Button extends Component {
static template = "Button";
}
class Row extends Component {
static template = "Row";
}
class Root extends Component {
static template = "Root";
static components = { Button, Row };
setup() {
this.state = useState({
rows: [],
selectedRowId: null
});
this.benchmarking = false;
onPatched(() => {
if (this.benchmarking) {
this.stop();
}
});
}
start(descr) {
this.benchmarking = `[${descr}]`;
console.time(this.benchmarking);
}
stop() {
console.timeEnd(this.benchmarking);
this.benchmarking = false;
}
run() {
this.start('add1000');
this.state.rows = buildData(1000);
this.state.selectedRowId = null;
}
runLots() {
this.start('add10_000');
this.state.rows = buildData(10_000);
this.state.selectedRowId = null;
}
add() {
this.start('append1000');
this.state.rows = this.state.rows.concat(buildData(1000));
}
update() {
this.start('update1/10th');
let index = 0;
const rows = this.state.rows;
while (index < rows.length) {
rows[index].label = rows[index].label + " !!!";
index += 10;
}
}
clear() {
this.start('clear');
this.state.rows = [];
this.state.selectedRowId = null;
}
swapRows() {
this.start('swap');
const rows = this.state.rows;
if (rows.length > 998) {
let tmp = rows[1];
rows[1] = rows[998];
rows[998] = tmp;
}
}
selectRow(id) {
this.start('select');
this.state.selectedRowId = id;
}
removeRow(id) {
this.start('remove1');
const rows = this.state.rows;
rows.splice(rows.findIndex(row => row.id === id), 1);
}
}
// dev=false for benchmarking. we don't want to benchmark dev code!
mount(Root, document.body, { templates: TEMPLATES, dev: false });
@@ -1,52 +0,0 @@
<templates>
<t t-name="Button">
<div class='col-sm-6 smallpad'>
<button t-att-id="props.id" class='btn btn-primary btn-block' type='button' t-on-click="props.onClick">
<t t-esc="props.text"/>
</button>
</div>
</t>
<t t-name="Row">
<tr t-att-class="props.isSelected ? 'danger' : ''">
<td class="col-md-1" t-esc="props.row.id" />
<td class="col-md-4">
<a t-on-click="() => props.onSelect(props.row.id)" t-esc="props.row.label" />
</td>
<td class="col-md-1">
<a t-on-click="() => props.onRemove(props.row.id)" class="remove">[x]
<span class='glyphicon glyphicon-remove' aria-hidden="true" />
</a>
</td>
<td class='col-md-6'/>
</tr>
</t>
<t t-name="Root">
<div class='container'>
<div class='jumbotron'>
<div class='row'>
<div class='col-md-6'>
<h1>Owl Keyed</h1>
</div>
<div class='col-md-6'>
<div class='row'>
<Button id="'run'" onClick.bind="run" text="'Create 1,000 rows'" />
<Button id="'runlots'" onClick.bind="runLots" text="'Create 10,000 rows'" />
<Button id="'add'" onClick.bind="add" text="'Append 1,000 rows'" />
<Button id="'update'" onClick.bind="update" text="'Update every 10th row'" />
<Button id="'clear'" onClick.bind="clear" text="'Clear'" />
<Button id="'swaprows'" onClick.bind="swapRows" text="'Swap Rows'" />
</div>
</div>
</div>
</div>
<table class='table table-hover table-striped test-data'>
<tbody>
<t t-foreach="state.rows" t-as="row" t-key="row.id">
<Row row="row" isSelected="row.id === state.selectedRowId" onSelect.bind="selectRow" onRemove.bind="removeRow"/>
</t>
</tbody>
</table>
<span class='preloadicon glyphicon glyphicon-remove' aria-hidden="true" />
</div>
</t>
</templates>
@@ -1,10 +0,0 @@
.greeter {
font-size: 20px;
width: 300px;
height: 100px;
margin: 5px;
text-align: center;
line-height: 100px;
background-color: #eeeeee;
user-select: none;
}
@@ -1,26 +0,0 @@
// In this example, we show how components can be defined and created.
import { Component, useState, mount } from "@odoo/owl";
class Greeter extends Component {
static template = "Greeter";
setup() {
this.state = useState({ word: 'Hello' });
}
toggle() {
this.state.word = this.state.word === 'Hi' ? 'Hello' : 'Hi';
}
}
// Main root component
class Root extends Component {
static components = { Greeter };
static template = "Root"
setup() {
this.state = useState({ name: 'World'});
}
}
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -1,9 +0,0 @@
<templates>
<div t-name="Greeter" class="greeter" t-on-click="toggle">
<t t-esc="state.word"/>, <t t-esc="props.name"/>
</div>
<t t-name="Root">
<Greeter name="state.name"/>
</t>
</templates>
@@ -1,6 +0,0 @@
button {
width: 120px;
height: 35px;
font-size: 16px;
}
@@ -1,40 +0,0 @@
// In this example, we show how hooks can be used or defined.
import { Component, mount, useState, onWillDestroy } from "@odoo/owl";
// We define here a custom behaviour: this hook tracks the state of the mouse
// position
function useMouse() {
const position = useState({x:0, y: 0});
function update(e) {
position.x = e.clientX;
position.y = e.clientY;
}
window.addEventListener('mousemove', update);
onWillDestroy(() => {
window.removeEventListener('mousemove', update);
});
return position;
}
// Main root component
class Root extends Component {
static template = "Root";
setup() {
// simple state hook (reactive object)
this.counter = useState({ value: 0 });
// this hooks is bound to the 'mouse' property.
this.mouse = useMouse();
}
increment() {
this.counter.value++;
}
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -1,7 +0,0 @@
<templates>
<div t-name="Root">
<button t-on-click="increment">Click! <t t-esc="counter.value"/></button>
<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>
</div>
</templates>
-22
View File
@@ -1,22 +0,0 @@
// This example illustrate how the t-model directive can be used to synchronize
// data between html inputs (and select/textareas) and the state of a component.
// Note that there are two controls with t-model="color": they are totally
// synchronized.
import { Component, useState, mount } from "@odoo/owl";
class Form extends Component {
static template = "Form";
setup() {
this.state = useState({
text: "",
othertext: "",
number: 11,
color: "",
bool: false
});
}
}
// Application setup
mount(Form, document.body, { templates: TEMPLATES, dev: true });
-37
View File
@@ -1,37 +0,0 @@
<templates>
<div t-name="Form">
<h1>Form</h1>
<div>
Text (immediate): <input t-model="state.text"/>
</div>
<div>
Other text (lazy): <input t-model.lazy="state.othertext"/>
</div>
<div>
Number: <input t-model.number="state.number"/>
</div>
<div>
Boolean: <input type="checkbox" t-model="state.bool"/>
</div>
<div>
Color, with a select:
<select t-model="state.color">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<div>
Color, with radio buttons:
<span><input type="radio" name="color" id="red" value="red" t-model="state.color"/><label for="red">Red</label></span>
<span><input type="radio" name="color" id="blue" value="blue" t-model="state.color"/><label for="blue">Blue</label></span>
</div>
<hr/>
<h1>State</h1>
<div>Text: <t t-esc="state.text"/></div>
<div>Other Text: <t t-esc="state.othertext"/></div>
<div>Number: <t t-esc="state.number"/></div>
<div>Boolean: <t t-if="state.bool">True</t><t t-else="">False</t></div>
<div>Color: <t t-esc="state.color"/></div>
</div>
</templates>
-7
View File
@@ -1,7 +0,0 @@
{
"compilerOptions": {
"paths": {
"owl": ["../../../src/index.ts"],
},
}
}
@@ -1,11 +0,0 @@
button {
font-size: 18px;
margin: 5px;
}
.demo {
margin: 10px;
padding: 10px;
background-color: #dddddd;
width: 250px;
}
@@ -1,68 +0,0 @@
// This example shows all the possible lifecycle hooks
//
// The root component controls a sub component (DemoComponent). It logs all its lifecycle
// methods in the console. Try modifying its state by clicking on it, or by
// clicking on the two main buttons, and look into the console to see what
// happens.
import {
Component,
useState,
mount,
useComponent,
onWillStart,
onMounted,
onWillUnmount,
onWillUpdateProps,
onPatched,
onWillPatch,
onWillRender,
onRendered,
onWillDestroy,
} from "@odoo/owl";
function useLogLifecycle() {
const component = useComponent();
const name = component.constructor.name;
onWillStart(() => console.log(`${name}:willStart`));
onMounted(() => console.log(`${name}:mounted`));
onWillUpdateProps(() => console.log(`${name}:willUpdateProps`));
onWillRender(() => console.log(`${name}:willRender`));
onRendered(() => console.log(`${name}:rendered`));
onWillPatch(() => console.log(`${name}:willPatch`));
onPatched(() => console.log(`${name}:patched`));
onWillUnmount(() => console.log(`${name}:willUnmount`));
onWillDestroy(() => console.log(`${name}:willDestroy`));
}
class DemoComponent extends Component {
static template = "DemoComponent";
setup() {
useLogLifecycle();
this.state = useState({ n: 0 });
}
increment() {
this.state.n++;
}
}
class Root extends Component {
static template = "Root";
static components = { DemoComponent };
setup() {
useLogLifecycle();
this.state = useState({ n: 0, flag: true });
}
increment() {
this.state.n++;
}
toggleSubComponent() {
this.state.flag = !this.state.flag;
}
}
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -1,15 +0,0 @@
<templates>
<div t-name="DemoComponent" t-on-click="increment" class="demo">
<div>Demo Sub Component</div>
<div>(click on me to update me)</div>
<div>Props: <t t-esc="props.n"/>, State: <t t-esc="state.n"/>. </div>
</div>
<div t-name="Root">
<button t-on-click="increment">Increment Parent State</button>
<button t-on-click="toggleSubComponent">Toggle SubComponent</button>
<div t-if="state.flag">
<DemoComponent n="state.n"/>
</div>
</div>
</templates>
@@ -1,56 +0,0 @@
body {
margin: 0;
}
.app {
height: 100%;
flex-direction: column;
}
.app.desktop {
display: flex;
}
.navbar {
flex: 0 0 30px;
height: 30px;
background-color: cadetblue;
color: white;
line-height: 30px;
}
.controlpanel {
flex: 0 0 100px;
height: 100px;
background-color: #dddddd;
padding: 8px;
}
.content-wrapper {
flex: 1 1 auto;
position: relative;
}
.content {
display: flex;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.formview {
overflow-y: auto;
flex: 1 1 60%;
min-height: 200px;
padding: 8px;
}
.chatter {
overflow-y: auto;
flex: 1 1 40%;
background-color: #eeeeee;
color: #333333;
padding: 8px;
}
@@ -1,118 +0,0 @@
// In this example, we show how one can design an application that is responsive:
// its UI is different in mobile mode or in desktop mode.
//
// The main idea is to have a "isMobile" key in the environment, then listen
// to resize events and update the env if needed. Then, the whole interface
// will be updated, creating and destroying components as needed.
//
// To see this in action, try resizing the window. The application will switch
// to mobile mode whenever it has less than 768px.
import { Component, useState, mount, reactive, useEnv } from "@odoo/owl";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
function debounce(func, wait, immediate) {
let timeout;
return function () {
const context = this;
const args = arguments;
function later() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
}
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
//------------------------------------------------------------------------------
// Responsive hook
//------------------------------------------------------------------------------
function createUI() {
const getIsMobile = () => window.innerWidth <= 768;
const ui = reactive({ isMobile: getIsMobile() });
const updateEnv = debounce(() => {
const isMobile = getIsMobile();
if (ui.isMobile !== isMobile) {
ui.isMobile = isMobile;
}
}, 15);
window.addEventListener("resize", updateEnv);
return ui;
}
function useUI() {
const env = useEnv();
return useState(env.ui);
}
//------------------------------------------------------------------------------
// Components
//------------------------------------------------------------------------------
class Navbar extends Component {
static template = "Navbar";
}
class MobileSearchView extends Component {
static template = "MobileSearchView";
}
class ControlPanel extends Component {
static template = "ControlPanel";
static components = { MobileSearchView };
setup() {
this.ui = useUI();
}
}
class AdvancedComponent extends Component {
static template = "AdvancedComponent";
}
class FormView extends Component {
static template = "FormView";
static components = { AdvancedComponent };
setup() {
this.ui = useUI();
}
}
class Chatter extends Component {
static template = "Chatter";
setup() {
this.messages = Array.from(Array(100).keys());
}
}
class Root extends Component {
static template = "Root";
static components = { Navbar, ControlPanel, FormView, Chatter };
setup() {
this.ui = useUI();
}
}
//------------------------------------------------------------------------------
// Application Startup
//------------------------------------------------------------------------------
const env = {
ui: createUI()
};
mount(Root, document.body, { templates: TEMPLATES, env, dev: true });
@@ -1,42 +0,0 @@
<templates>
<div t-name="Navbar" class="navbar">Navbar</div>
<div t-name="ControlPanel" class="controlpanel">
<h2>Control Panel</h2>
<MobileSearchView t-if="ui.isMobile" />
</div>
<div t-name="FormView" class="formview">
<h2>Form View</h2>
<AdvancedComponent t-if="!ui.isMobile" />
</div>
<div t-name="Chatter" class="chatter">
<h2>Chatter</h2>
<t t-foreach="messages" t-as="item" t-key="item"><div>Message <t t-esc="item"/></div></t>
</div>
<div t-name="MobileSearchView">Mobile searchview</div>
<div t-name="AdvancedComponent">
This component is only created in desktop mode.
<button>Button!</button>
</div>
<t t-name="maincontent">
<FormView />
<Chatter />
</t>
<div t-name="Root" class="app" t-att-class="{mobile: ui.isMobile, desktop: !ui.isMobile}">
<Navbar/>
<ControlPanel/>
<div class="content-wrapper" t-if="!ui.isMobile">
<div class="content">
<t t-call="maincontent"/>
</div>
</div>
<t t-else="">
<t t-call="maincontent"/>
</t>
</div>
</templates>
@@ -1,28 +0,0 @@
// This example illustrates how one can write Owl components with
// inline templates.
import { Component, useState, xml, mount } from "@odoo/owl";
// Counter component
class Counter extends Component {
static template = xml`
<button t-on-click="() => state.value++">
Click! [<t t-esc="state.value"/>]
</button>`;
state = useState({ value: 0 })
}
// Root
class Root extends Component {
static template = xml`
<div>
<Counter/>
<Counter/>
</div>`;
static components = { Counter };
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true});
-43
View File
@@ -1,43 +0,0 @@
.main {
display: flex;
}
.card {
display: flex;
flex-direction: column;
background-color: #eeeeee;
width: 200px;
height: 100px;
margin: 10px;
border: 1px solid gray;
}
.card.full {
height: 100px;
}
.card.small {
height: 25px;
}
.card-title {
flex: 0 0 25px;
font-weight: bold;
background-color: darkcyan;
color: white;
padding: 2px;
}
.card-title button {
float: right;
}
.card-content {
flex: 1 1 auto;
padding: 5px;
border-top: 1px solid white;
}
.card-footer {
border-top: 1px solid white;
}
-49
View File
@@ -1,49 +0,0 @@
// We show here how slots can be used to create generic components.
// In this example, the Card component is basically only a container. It is not
// aware of its content. It just knows where it should be (with t-slot).
// The parent component define the content with t-set-slot.
//
// Note that the t-on-click event, defined in the Root template, is executed in
// the context of the Root component, even though it is inside the Card component
import { Component, useState, mount } from "@odoo/owl";
class Card extends Component {
static template = "Card";
setup() {
this.state = useState({ showContent: true });
}
toggleDisplay() {
this.state.showContent = !this.state.showContent;
}
}
class Counter extends Component {
static template = "Counter";
setup() {
this.state = useState({val: 1});
}
inc() {
this.state.val++;
}
}
// Main root component
class Root extends Component {
static template = "Root"
static components = { Card, Counter };
setup() {
this.state = useState({a: 1, b: 3});
}
inc(key, delta) {
this.state[key] += delta;
}
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true});
-33
View File
@@ -1,33 +0,0 @@
<templates>
<div t-name="Card" class="card" t-att-class="state.showContent ? 'full' : 'small'">
<div class="card-title">
<t t-esc="props.title"/><button t-on-click="toggleDisplay">Toggle</button>
</div>
<t t-if="state.showContent">
<div class="card-content" >
<t t-slot="content"/>
</div>
<div class="card-footer">
<t t-slot="footer"/>
</div>
</t>
</div>
<div t-name="Counter">
<t t-esc="state.val"/><button t-on-click="inc">Inc</button>
</div>
<div t-name="Root" class="main">
<Card title="'Title card A'">
<t t-set-slot="content">Content of card 1... [<t t-esc="state.a"/>]</t>
<t t-set-slot="footer"><button t-on-click="() => this.inc('a', 1)">Increment A</button></t>
</Card>
<Card title="'Title card B'">
<t t-set-slot="content">
<div>Card 2... [<t t-esc="state.b"/>]</div>
<Counter />
</t>
<t t-set-slot="footer"><button t-on-click="() => this.inc('b', -1)">Decrement B</button></t>
</Card>
</div>
</templates>
@@ -1,379 +0,0 @@
html,body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #4d4d4d;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 300;
}
:focus {
outline: 0;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp h1 {
position: absolute;
top: -155px;
width: 100%;
font-size: 100px;
font-weight: 100;
text-align: center;
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
.toggle-all {
width: 1px;
height: 1px;
border: none; /* Mobile Safari */
opacity: 0;
position: absolute;
right: 100%;
bottom: 100%;
}
.toggle-all + label {
width: 60px;
height: 34px;
font-size: 0;
position: absolute;
top: -52px;
left: -13px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}
.toggle-all + label:before {
content: "";
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked + label:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: calc(100% - 43px);
padding: 12px 16px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle {
opacity: 0;
}
.todo-list li .toggle + label {
/*
Firefox requires \`#\` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
IE and Edge requires *everything* to be escaped to render, so we do that instead of just the \`#\` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
*/
background-image: url("data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: center left;
}
.todo-list li .toggle:checked + label {
background-image: url("data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E");
}
.todo-list li label {
word-break: break-all;
padding: 15px 15px 15px 60px;
display: block;
line-height: 1.2;
transition: color 0.4s;
}
.todo-list li.completed label {
color: #d9d9d9;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: "×";
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 10px 15px;
height: 20px;
text-align: center;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: "";
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
.filters a {
cursor: pointer;
}
@@ -1,178 +0,0 @@
// This example is an implementation of the TodoList application, from the
// www.todomvc.com project. This is a non trivial application with some
// interesting user interactions. It uses the local storage for persistence.
//
// In this implementation, we use the owl reactivity mechanism.
import { Component, useState, mount, useRef, reactive, useEnv, useEffect } from "@odoo/owl";
//------------------------------------------------------------------------------
// Constants, helpers
//------------------------------------------------------------------------------
const ENTER_KEY = 13;
const ESC_KEY = 27;
function useAutofocus(name) {
let ref = useRef(name);
useEffect(el => el && el.focus(), () => [ref.el]);
}
function useStore() {
const env = useEnv();
return useState(env.store);
}
//------------------------------------------------------------------------------
// Task store
//------------------------------------------------------------------------------
class TaskList {
constructor(tasks) {
this.tasks = tasks || [];
const taskIds = this.tasks.map((t) => t.id);
this.nextId = taskIds.length ? Math.max(...taskIds) + 1 : 1;
}
addTask(text) {
text = text.trim();
if (text) {
const task = {
id: this.nextId++,
text: text,
isCompleted: false,
};
this.tasks.push(task);
}
}
toggleTask(id) {
const task = this.tasks.find(t => t.id === id);
task.isCompleted = !task.isCompleted;
}
toggleAll(value) {
for (let task of this.tasks) {
task.isCompleted = value;
}
}
clearCompleted() {
const tasks = this.tasks.filter(t => t.isCompleted);
for (let task of tasks) {
this.deleteTask(task.id);
}
}
deleteTask(id) {
const index = this.tasks.findIndex((t) => t.id === id);
this.tasks.splice(index, 1);
}
updateTask(id, text) {
const value = text.trim();
if (!value) {
this.deleteTask(id);
} else {
const task = this.tasks.find(t => t.id === id);
task.text = value;
}
}
}
function createTaskStore() {
const saveTasks = () => localStorage.setItem("todoapp", JSON.stringify(taskStore.tasks));
const initialTasks = JSON.parse(localStorage.getItem("todoapp") || "[]");
const taskStore = reactive(new TaskList(initialTasks), saveTasks);
saveTasks();
return taskStore;
}
//------------------------------------------------------------------------------
// Todo
//------------------------------------------------------------------------------
class Todo extends Component {
static template = "Todo";
setup() {
useAutofocus("input");
this.store = useStore();
this.state = useState({
isEditing: false
});
}
handleKeyup(ev) {
if (ev.keyCode === ENTER_KEY) {
this.updateText(ev.target.value);
}
if (ev.keyCode === ESC_KEY) {
ev.target.value = this.props.text;
this.state.isEditing = false;
}
}
handleBlur(ev) {
this.updateText(ev.target.value);
}
updateText(text) {
this.store.updateTask(this.props.id, text);
this.state.isEditing = false;
}
}
//------------------------------------------------------------------------------
// TodoList
//------------------------------------------------------------------------------
class TodoList extends Component {
static template = "TodoList";
static components = { Todo };
setup() {
this.store = useStore();
this.state = useState({ filter: "all" });
}
get displayedTasks() {
const tasks = this.store.tasks;
switch (this.state.filter) {
case "active":
return tasks.filter((t) => !t.isCompleted);
case "completed":
return tasks.filter((t) => t.isCompleted);
case "all":
return tasks;
}
}
get allChecked() {
return this.store.tasks.every(todo => todo.isCompleted);
}
get remaining() {
return this.store.tasks.filter(todo => !todo.isCompleted).length;
}
get remainingText() {
const items = this.remaining < 2 ? "item" : "items";
return ` ${items} left`;
}
addTodo(ev) {
if (ev.keyCode === ENTER_KEY) {
const text = ev.target.value;
if (text.trim()) {
this.store.addTask(text);
}
ev.target.value = "";
}
}
setFilter(filter) {
this.state.filter = filter;
}
}
//------------------------------------------------------------------------------
// App Initialization
//------------------------------------------------------------------------------
const env = { store: createTaskStore() };
mount(TodoList, document.body, { env, templates: TEMPLATES, dev: true });
@@ -1,50 +0,0 @@
<templates>
<section t-name="TodoList" class="todoapp">
<header class="header">
<h1>todos</h1>
<input class="new-todo" autofocus="true" autocomplete="off" placeholder="What needs to be done?" t-on-keyup="addTodo"/>
</header>
<section class="main" t-if="store.tasks.length">
<input class="toggle-all" id="toggle-all" type="checkbox" t-att-checked="allChecked" t-on-click="() => store.toggleAll(!allChecked)"/>
<label for="toggle-all"></label>
<ul class="todo-list">
<t t-foreach="displayedTasks" t-as="todo" t-key="todo.id">
<Todo id="todo.id" isCompleted="todo.isCompleted" text="todo.text"/>
</t>
</ul>
</section>
<footer class="footer" t-if="store.tasks.length">
<span class="todo-count">
<strong>
<t t-esc="remaining"/>
</strong>
<t t-esc="remainingText"/>
</span>
<ul class="filters">
<li>
<a t-on-click="() => this.setFilter('all')" t-att-class="{selected: state.filter === 'all'}">All</a>
</li>
<li>
<a t-on-click="() => this.setFilter('active')" t-att-class="{selected: state.filter === 'active'}">Active</a>
</li>
<li>
<a t-on-click="() => this.setFilter('completed')" t-att-class="{selected: state.filter === 'completed'}">Completed</a>
</li>
</ul>
<button class="clear-completed" t-if="store.tasks.length gt remaining" t-on-click="() => store.clearCompleted()">
Clear completed
</button>
</footer>
</section>
<li t-name="Todo" class="todo" t-att-class="{completed: props.isCompleted, editing: state.isEditing}">
<div class="view">
<input class="toggle" type="checkbox" t-on-change="() => store.toggleTask(props.id)" t-att-checked="props.completed"/>
<label t-on-dblclick="() => state.isEditing = true">
<t t-esc="props.text"/>
</label>
<button class="destroy" t-on-click="() => store.deleteTask(props.id)"></button>
</div>
<input class="edit" t-ref="input" t-if="state.isEditing" t-att-value="props.text" t-on-keyup="handleKeyup" t-on-blur="handleBlur"/>
</li>
</templates>
@@ -1,70 +0,0 @@
body {
margin: 0;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: auto 50px;
}
.window-manager {
position: relative;
width: 100%;
height: 100%;
background-color: #eeeeee;
overflow: hidden;
}
.menubar {
background-color: #875a7b;
color: white;
}
.menubar button {
height: 40px;
font-size: 18px;
margin: 5px;
}
.window {
display: grid;
grid-template-rows: 30px auto;
border: 1px solid gray;
background-color: white;
position: absolute;
box-shadow: 1px 1px 2px 1px grey;
}
.window.dragging {
opacity: 0.75;
}
.window .header {
background-color: #875a7b;
display: grid;
grid-template-columns: auto 24px;
color: white;
line-height: 30px;
padding-left: 5px;
cursor: default;
user-select: none;
}
.window .header .close {
cursor: pointer;
font-size: 22px;
padding-left: 4px;
padding-right: 4px;
font-weight: bold;
}
.counter {
font-size: 20px;
}
.counter button {
width: 80px;
height:40px;
font-size: 20px;
}
@@ -1,192 +0,0 @@
// This example is slightly more complex than usual. We demonstrate
// here a way to manage sub windows in Owl, declaratively. This is still just a
// demonstration. Managing windows can be as complex as we want. For example,
// we could implement the following features:
// - resizing windows
// - minimizing windows
// - configuration options for windows to make a window non resizeable
// - minimal width/height
// - better heuristic for initial window position
// - ...
import { Component, useState, mount, useRef, reactive, useEnv, onMounted } from "@odoo/owl";
// -----------------------------------------------------------------------------
// Window manager code
// -----------------------------------------------------------------------------
class WindowManager {
// contains all components with metadata
static Windows = {};
windows = {}; // mapping id => info
nextId = 1;
add(type) {
const Comp = WindowManager.Windows[type];
const left = 50 + Math.round(Math.random()*(window.innerWidth - 50 - Comp.defaultWidth));
const top = 50 + Math.round(Math.random()*(window.innerHeight - 100 - Comp.defaultHeight));
const id = this.nextId++;
this.windows[id] = {
id,
title: Comp.defaultTitle,
width: Comp.defaultWidth,
height: Comp.defaultHeight,
left,
top,
Component: Comp,
};
}
close(id) {
delete this.windows[id];
}
updatePosition(id, left, top) {
const w = this.windows[id];
w.left = left;
w.top = top;
}
getWindows() {
return Object.values(this.windows);
}
}
function createWindowService() {
return reactive(new WindowManager());
}
function useWindowService() {
const env = useEnv();
return useState(env.windowService);
}
// -----------------------------------------------------------------------------
// Generic Window Component
// -----------------------------------------------------------------------------
class Window extends Component {
static template = "Window";
static nextZIndex = 1;
zIndex = 0;
setup() {
this.windowService = useWindowService();
this.root = useRef('root');
onMounted(this.updateZIndex);
}
get style() {
let { width, height, top, left } = this.props.info;
return `width: ${width}px;height: ${height}px;top:${top}px;left:${left}px;z-index:${this.zIndex}`;
}
close() {
this.windowService.close(this.props.info.id);
}
startDragAndDrop(ev) {
this.updateZIndex();
const self = this;
const root = this.root;
const el = root.el;
el.classList.add('dragging');
const current = this.props.info;
const offsetX = current.left - ev.pageX;
const offsetY = current.top - ev.pageY;
let left, top;
window.addEventListener("mousemove", moveWindow);
window.addEventListener("mouseup", stopDnD, { once: true });
function moveWindow(ev) {
left = Math.max(offsetX + ev.pageX, 0);
top = Math.max(offsetY + ev.pageY, 0);
el.style.left = `${left}px`;
el.style.top = `${top}px`;
}
function stopDnD() {
window.removeEventListener("mousemove", moveWindow);
el.classList.remove('dragging');
if (top !== undefined && left !== undefined) {
self.windowService.updatePosition(current.id, left, top);
}
}
}
updateZIndex() {
this.zIndex = Window.nextZIndex++;
this.root.el.style['z-index'] = this.zIndex;
}
}
// -----------------------------------------------------------------------------
// Two concrete Window type implementations
// -----------------------------------------------------------------------------
class HelloWorld extends Component {
static template = "HelloWorld";
static defaultTitle = "Hello Owl!";
static defaultWidth = 200;
static defaultHeight = 100;
}
class Counter extends Component {
static template = "Counter";
static defaultTitle = "Click Counter";
static defaultWidth = 300;
static defaultHeight = 120;
state = useState({ value: 0 });
inc() {
this.state.value++;
}
}
// register window components
WindowManager.Windows.Hello = HelloWorld;
WindowManager.Windows.Counter = Counter;
// -----------------------------------------------------------------------------
// Window Container
// -----------------------------------------------------------------------------
class WindowContainer extends Component {
static template = "WindowContainer";
static components = { Window };
setup() {
this.windowService = useWindowService();
}
}
// -----------------------------------------------------------------------------
// Root Component
// -----------------------------------------------------------------------------
class Root extends Component {
static template = "Root";
static components = { WindowContainer };
setup() {
this.windowService = useWindowService();
}
addWindow(type) {
this.windowService.add(type);
}
}
// -----------------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------------
const env = {
windowService: createWindowService(),
};
mount(Root, document.body, { templates: TEMPLATES, env, dev: true });
@@ -1,32 +0,0 @@
<templates>
<div t-name="Window" class="window" t-att-style="style" t-on-click="updateZIndex" t-ref="root">
<div class="header">
<span t-on-mousedown="startDragAndDrop"><t t-esc="props.info.title"/></span>
<span class="close" t-on-click.stop="close">×</span>
</div>
<t t-slot="default"/>
</div>
<div t-name="WindowContainer" class="window-manager">
<Window t-foreach="windowService.getWindows()" t-as="w" t-key="w.id" info="w">
<t t-component="w.Component"/>
</Window>
</div>
<div t-name="Root" class="app">
<WindowContainer/>
<div class="menubar">
<button t-on-click="() => this.addWindow('Hello')">Say Hello</button>
<button t-on-click="() => this.addWindow('Counter')">Counter</button>
</div>
</div>
<div t-name="HelloWorld">
Some content here...
</div>
<div t-name="Counter" class="counter">
<button t-on-click="inc">Click</button>
<span><t t-esc="state.value"/></span>
</div>
</templates>
-28
View File
@@ -1,28 +0,0 @@
#!/usr/bin/env python3
import threading
import time
from http.server import SimpleHTTPRequestHandler, HTTPServer
httpd = None
def start_server():
global httpd
SimpleHTTPRequestHandler.extensions_map['.js'] = 'application/javascript'
httpd = HTTPServer(('0.0.0.0', 3600), SimpleHTTPRequestHandler)
httpd.serve_forever()
url = 'http://127.0.0.1:3600'
if __name__ == "__main__":
print("Owl Application")
print("---------------")
print("Server running on: {}".format(url))
threading.Thread(target=start_server, daemon=True).start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
httpd.server_close()
quit(0)
-22
View File
@@ -1,22 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OWL App</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="app.css">
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
<script type="module" src="app.js"></script>
</head>
<body>
<pre>
This app requires a web server, simply opening the html file using your browser will not work.
You can run a simple web server with one of the following:
- if you have python3 installed, run app.py with python3 or run 'python3 -m http.server' in the app folder
- if you have node/npm installed, run 'npx serve' in the app folder
- if you have php installed, run 'php -S localhost:8080 -t .' in the app folder
</pre>
<script>if (window.location.protocol !== "file:") document.querySelector("pre").remove()</script>
</body>
</html>
-5
View File
@@ -1,5 +0,0 @@
# Github page and playground
This folder contains the code for owl's [github page](https://odoo.github.io/owl)
and the owl [playground](https://odoo.github.io/owl/playground/). If you're
looking for the owl documentation, click [here](/doc)
+3329 -7098
View File
File diff suppressed because it is too large Load Diff
+8 -23
View File
@@ -1,6 +1,6 @@
{ {
"name": "@odoo/owl", "name": "@odoo/owl",
"version": "2.8.1", "version": "2.0.7",
"description": "Odoo Web Library (OWL)", "description": "Odoo Web Library (OWL)",
"main": "dist/owl.cjs.js", "main": "dist/owl.cjs.js",
"module": "dist/owl.es.js", "module": "dist/owl.es.js",
@@ -9,33 +9,26 @@
"dist" "dist"
], ],
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=12.18.3"
}, },
"scripts": { "scripts": {
"build:bundle": "rollup -c --failAfterWarnings", "build:bundle": "rollup -c --failAfterWarnings",
"build:runtime": "rollup -c --failAfterWarnings runtime", "build:runtime": "rollup -c --failAfterWarnings runtime",
"build:compiler": "rollup -c --failAfterWarnings compiler", "build:compiler": "rollup -c --failAfterWarnings compiler",
"build": "npm run build:bundle", "build": "npm run build:bundle",
"build:devtools": "rollup -c ./tools/devtools/rollup.config.js",
"dev:devtools-chrome": "npm run build:devtools -- --config-browser=chrome",
"dev:devtools-firefox": "npm run build:devtools -- --config-browser=firefox",
"build:devtools-chrome": "npm run dev:devtools-chrome -- --config-env=production",
"build:devtools-firefox": "npm run dev:devtools-firefox -- --config-env=production",
"test": "jest", "test": "jest",
"test:debug": "node node_modules/.bin/jest --runInBand --watch --testTimeout=5000000", "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand --watch --testTimeout=5000000",
"test:watch": "jest --watch", "test:watch": "jest --watch",
"playground:serve": "python3 tools/playground_server.py || python tools/playground_server.py", "playground:serve": "python3 tools/server.py || python tools/server.py",
"playground": "npm run build && npm run playground:serve", "playground": "npm run build && npm run playground:serve",
"preplayground:watch": "npm run build", "preplayground:watch": "npm run build",
"playground:watch": "npm-run-all --parallel playground:serve \"build:* -- --watch\"", "playground:watch": "npm-run-all --parallel playground:serve \"build:* -- --watch\"",
"prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md,tools/devtools/**/*.js} --write", "prettier": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --write",
"check-formatting": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md,tools/devtools/**/*.js} --check", "check-formatting": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md} --check",
"lint": "eslint src/**/*.ts tests/**/*.ts", "lint": "eslint src/**/*.ts tests/**/*.ts",
"publish": "npm run build && npm publish",
"release": "node tools/release.js", "release": "node tools/release.js",
"compile_templates": "node tools/compile_owl_templates.mjs" "compile_templates": "node tools/compile_xml.js"
},
"bin": {
"compile_owl_templates": "tools/compile_owl_templates.mjs"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -49,7 +42,6 @@
"homepage": "https://github.com/odoo/owl#readme", "homepage": "https://github.com/odoo/owl#readme",
"devDependencies": { "devDependencies": {
"@types/jest": "^27.0.1", "@types/jest": "^27.0.1",
"@types/jsdom": "^21.1.7",
"@types/node": "^14.11.8", "@types/node": "^14.11.8",
"@typescript-eslint/eslint-plugin": "5.48.1", "@typescript-eslint/eslint-plugin": "5.48.1",
"@typescript-eslint/parser": "5.48.1", "@typescript-eslint/parser": "5.48.1",
@@ -64,11 +56,7 @@
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"prettier": "2.4.1", "prettier": "2.4.1",
"rollup": "^2.56.3", "rollup": "^2.56.3",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-delete": "^2.0.0",
"rollup-plugin-dts": "^4.2.2", "rollup-plugin-dts": "^4.2.2",
"rollup-plugin-execute": "^1.1.1",
"rollup-plugin-string": "^3.0.0",
"rollup-plugin-terser": "^7.0.2", "rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.31.1", "rollup-plugin-typescript2": "^0.31.1",
"source-map-support": "^0.5.10", "source-map-support": "^0.5.10",
@@ -101,8 +89,5 @@
"prettier": { "prettier": {
"printWidth": 100, "printWidth": 100,
"endOfLine": "auto" "endOfLine": "auto"
},
"dependencies": {
"jsdom": "^25.0.1"
} }
} }
+26 -33
View File
@@ -1,6 +1,6 @@
import pkg from "./package.json"; import pkg from "./package.json";
import git from "git-rev-sync"; import git from "git-rev-sync";
import typescript from "rollup-plugin-typescript2"; import typescript from 'rollup-plugin-typescript2';
import { terser } from "rollup-plugin-terser"; import { terser } from "rollup-plugin-terser";
import dts from "rollup-plugin-dts"; import dts from "rollup-plugin-dts";
@@ -12,46 +12,49 @@ const ES_FILENAME = "dist/owl.es.js";
if (pkg.module !== ES_FILENAME || pkg.main !== CJS_FILENAME) { if (pkg.module !== ES_FILENAME || pkg.main !== CJS_FILENAME) {
throw new Error("package.json has been modified. Build script should be updated accordingly"); throw new Error("package.json has been modified. Build script should be updated accordingly");
} }
const outro = ` const outro = `
__info__.version = '${pkg.version}';
__info__.date = '${new Date().toISOString()}'; __info__.date = '${new Date().toISOString()}';
__info__.hash = '${git.short()}'; __info__.hash = '${git.short()}';
__info__.url = 'https://github.com/odoo/owl'; __info__.url = 'https://github.com/odoo/owl';
`; `;
switch (process.argv[4]) { switch (process.argv[4]) {
case "compiler": case "compiler":
(input = "src/compiler/index.ts"), input = "src/compiler/index.ts",
(output = [getConfigForFormat("cjs", "dist/compiler.js", "")]); output = [
getConfigForFormat('cjs', 'dist/compiler.js', ''),
]
break; break;
case "runtime": case "runtime":
input = "src/runtime/index.ts"; input = "src/runtime/index.ts";
output = [ output = [
getConfigForFormat("esm", addSuffix(ES_FILENAME, "runtime"), outro), getConfigForFormat('esm', addSuffix(ES_FILENAME, 'runtime'), outro),
getConfigForFormat("cjs", addSuffix(CJS_FILENAME, "runtime"), outro), getConfigForFormat('cjs', addSuffix(CJS_FILENAME, 'runtime'), outro),
getConfigForFormat("iife", addSuffix(IIFE_FILENAME, "runtime"), outro), getConfigForFormat('iife', addSuffix(IIFE_FILENAME, 'runtime'), outro),
getConfigForFormat("iife", addSuffix(IIFE_FILENAME, "runtime"), outro, true), getConfigForFormat('iife', addSuffix(IIFE_FILENAME, 'runtime'), outro, true),
]; ]
break; break;
default: default:
(input = "src/index.ts"), input = "src/index.ts",
(output = [ output = [
getConfigForFormat("esm", ES_FILENAME, outro), getConfigForFormat('esm', ES_FILENAME, outro),
getConfigForFormat("cjs", CJS_FILENAME, outro), getConfigForFormat('cjs', CJS_FILENAME, outro),
getConfigForFormat("iife", IIFE_FILENAME, outro), getConfigForFormat('iife', IIFE_FILENAME, outro),
getConfigForFormat("iife", IIFE_FILENAME, outro, true), getConfigForFormat('iife', IIFE_FILENAME, outro, true),
]); ]
} }
/** /**
* Generate from a string depicting a path a new path for the minified version. * Generate from a string depicting a path a new path for the minified version.
* @param {string} pkgFileName file name * @param {string} pkgFileName file name
*/ */
function addSuffix(pkgFileName, suffix) { function addSuffix(pkgFileName, suffix) {
const parts = pkgFileName.split("."); const parts = pkgFileName.split('.');
parts.splice(parts.length - 1, 0, suffix); parts.splice(parts.length - 1, 0, suffix);
return parts.join("."); return parts.join('.');
} }
/** /**
@@ -69,7 +72,7 @@ function getConfigForFormat(format, generatedFileName, outro, minified = false)
outro: outro, outro: outro,
freeze: false, freeze: false,
plugins: minified ? [terser()] : [], plugins: minified ? [terser()] : [],
indent: " ", // indent with 4 spaces indent: ' ', // indent with 4 spaces
}; };
} }
@@ -79,19 +82,9 @@ export default [
output, output,
plugins: [ plugins: [
typescript({ typescript({
useTsconfigDeclarationDir: true, useTsconfigDeclarationDir: true
}), }),
], ]
},
{
input: "src/compiler/standalone/index.ts",
output: [{ file: "dist/compile_templates.mjs", format: "es" }],
external: ["fs", "fs/promises", "path", "jsdom"],
plugins: [
typescript({
useTsconfigDeclarationDir: true,
}),
],
}, },
{ {
input: "dist/types/index.d.ts", input: "dist/types/index.d.ts",
-18
View File
@@ -1,18 +0,0 @@
# encountered issues
## dropdown issue
- there was a problem that writing in a state while the effect was updated.
- the tracking of signal being written were dropped because we cleared it
after re-running the effect that made a write.
- solution: clear the tracked signal before re-executing the effects
- reading signal A while also writing signal A makes an infinite loop
- current solution: use toRaw in order to not track the read
- possible better solution to explore: do not track read if there is a write in a effect.
## website issue
- a rpc request was made on onWillStart, onWillStart was tracking reads. (see WebsiteBuilderClientAction)
- The read subsequently made a write, that re-triggered the onWillStart.
- A similar situation happened with onWillUpdateProps (see Transition)
- solution: prevent tracking reads in onWillStart and onWillUpdateProps
# future
- worker for computation?
- cap'n web
-4
View File
@@ -1,4 +0,0 @@
// Custom error class that wraps error that happen in the owl lifecycle
export class OwlError extends Error {
cause?: any;
}
-28
View File
@@ -1,28 +0,0 @@
export type ExecutionContext = {
onReadAtom: (atom: Atom) => void;
unsubcribe?: (scheduledContexts: Set<ExecutionContext>) => void;
update?: Function;
atoms?: Set<Atom>;
meta?: any;
// getParent: () => ExecutionContext | undefined;
// getChildren: () => ExecutionContext[];
// schedule: () => void;
};
export type customDirectives = Record<
string,
(node: Element, value: string, modifier: string[]) => void
>;
export type Atom = {
executionContexts: Set<ExecutionContext>;
dependents: Set<DerivedAtom>;
getValue: () => any;
};
export type OldValue = any;
export type DerivedAtom = Atom & {
dependencies: Map<Atom, OldValue>;
computed: boolean;
};
-38
View File
@@ -1,38 +0,0 @@
import { OwlError } from "./owl_error";
/**
* Parses an XML string into an XML document, throwing errors on parser errors
* instead of returning an XML document containing the parseerror.
*
* @param xml the string to parse
* @returns an XML document corresponding to the content of the string
*/
export function parseXML(xml: string): XMLDocument {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
if (doc.getElementsByTagName("parsererror").length) {
let msg = "Invalid XML in template.";
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
if (parsererrorText) {
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
const re = /\d+/g;
const firstMatch = re.exec(parsererrorText);
if (firstMatch) {
const lineNumber = Number(firstMatch[0]);
const line = xml.split("\n")[lineNumber - 1];
const secondMatch = re.exec(parsererrorText);
if (line && secondMatch) {
const columnIndex = Number(secondMatch[0]) - 1;
if (line[columnIndex]) {
msg +=
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
`${line}\n${"-".repeat(columnIndex - 1)}^`;
}
}
}
}
throw new OwlError(msg);
}
return doc;
}
+189 -251
View File
@@ -1,3 +1,4 @@
import { isProp } from "../runtime/blockdom/attributes";
import { import {
compileExpr, compileExpr,
compileExprToArray, compileExprToArray,
@@ -14,6 +15,7 @@ import {
ASTLog, ASTLog,
ASTMulti, ASTMulti,
ASTSlot, ASTSlot,
ASTSlotDefinition,
ASTTCall, ASTTCall,
ASTTCallBlock, ASTTCallBlock,
ASTTEsc, ASTTEsc,
@@ -24,19 +26,17 @@ import {
ASTTOut, ASTTOut,
ASTTPortal, ASTTPortal,
ASTTranslation, ASTTranslation,
ASTTranslationContext,
ASTTSet, ASTTSet,
ASTType, ASTType,
Attrs, Attrs,
EventHandlers, EventHandlers,
} from "./parser"; } from "./parser";
import { OwlError } from "../common/owl_error"; import { OwlError } from "../runtime/error_handling";
type BlockType = "block" | "text" | "multi" | "list" | "html" | "comment"; type BlockType = "block" | "text" | "multi" | "list" | "html" | "comment";
const whitespaceRE = /\s+/g;
export interface Config { export interface Config {
translateFn?: (s: string, translationCtx: string) => string; translateFn?: (s: string) => string;
translatableAttributes?: string[]; translatableAttributes?: string[];
dev?: boolean; dev?: boolean;
} }
@@ -44,7 +44,6 @@ export interface Config {
export interface CodeGenOptions extends Config { export interface CodeGenOptions extends Config {
hasSafeContext?: boolean; hasSafeContext?: boolean;
name?: string; name?: string;
hasGlobalValues: boolean;
} }
// using a non-html document so that <inner/outer>HTML serializes as XML instead // using a non-html document so that <inner/outer>HTML serializes as XML instead
@@ -60,38 +59,6 @@ function generateId(prefix: string = "") {
return prefix + nextDataIds[prefix]; return prefix + nextDataIds[prefix];
} }
function isProp(tag: string, key: string): boolean {
switch (tag) {
case "input":
return (
key === "checked" ||
key === "indeterminate" ||
key === "value" ||
key === "readonly" ||
key === "readOnly" ||
key === "disabled"
);
case "option":
return key === "selected" || key === "disabled";
case "textarea":
return key === "value" || key === "readonly" || key === "readOnly" || key === "disabled";
case "select":
return key === "value" || key === "disabled";
case "button":
case "optgroup":
return key === "disabled";
}
return false;
}
/**
* Returns a template literal that evaluates to str. You can add interpolation
* sigils into the string if required
*/
function toStringExpression(str: string) {
return `\`${str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${")}\``;
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// BlockDescription // BlockDescription
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -170,14 +137,15 @@ interface Context {
block: BlockDescription | null; block: BlockDescription | null;
index: number | string; index: number | string;
forceNewBlock: boolean; forceNewBlock: boolean;
preventRoot?: boolean;
ignoreRoot?: boolean;
isLast?: boolean; isLast?: boolean;
translate: boolean; translate: boolean;
translationCtx: string;
tKeyExpr: string | null; tKeyExpr: string | null;
nameSpace?: string; nameSpace?: string;
tModelSelectedExpr?: string; tModelSelectedExpr?: string;
ctxVar?: string; ctxVar?: string;
inPreTag?: boolean; slotVar?: string;
} }
function createContext(parentCtx: Context, params?: Partial<Context>): Context { function createContext(parentCtx: Context, params?: Partial<Context>): Context {
@@ -187,10 +155,10 @@ function createContext(parentCtx: Context, params?: Partial<Context>): Context {
index: 0, index: 0,
forceNewBlock: true, forceNewBlock: true,
translate: parentCtx.translate, translate: parentCtx.translate,
translationCtx: parentCtx.translationCtx,
tKeyExpr: null, tKeyExpr: null,
nameSpace: parentCtx.nameSpace, nameSpace: parentCtx.nameSpace,
tModelSelectedExpr: parentCtx.tModelSelectedExpr, tModelSelectedExpr: parentCtx.tModelSelectedExpr,
slotVar: parentCtx.slotVar
}, },
params params
); );
@@ -203,9 +171,11 @@ class CodeTarget {
code: string[] = []; code: string[] = [];
hasRoot = false; hasRoot = false;
hasCache = false; hasCache = false;
hasRef: boolean = false;
// maps ref name to [id, expr]
refInfo: { [name: string]: [string, string] } = {};
shouldProtectScope: boolean = false; shouldProtectScope: boolean = false;
on: EventHandlers | null; on: EventHandlers | null;
hasRefWrapper: boolean = false;
constructor(name: string, on?: EventHandlers | null) { constructor(name: string, on?: EventHandlers | null) {
this.name = name; this.name = name;
@@ -224,13 +194,17 @@ class CodeTarget {
generateCode(): string { generateCode(): string {
let result: string[] = []; let result: string[] = [];
result.push(`function ${this.name}(ctx, node, key = "") {`); result.push(`function ${this.name}(ctx, node, key = "") {`);
if (this.hasRef) {
result.push(` const refs = this.__owl__.refs;`);
for (let name in this.refInfo) {
const [id, expr] = this.refInfo[name];
result.push(` const ${id} = ${expr};`);
}
}
if (this.shouldProtectScope) { if (this.shouldProtectScope) {
result.push(` ctx = Object.create(ctx);`); result.push(` ctx = Object.create(ctx);`);
result.push(` ctx[isBoundary] = 1`); result.push(` ctx[isBoundary] = 1`);
} }
if (this.hasRefWrapper) {
result.push(` let refWrapper = makeRefWrapper(this.__owl__);`);
}
if (this.hasCache) { if (this.hasCache) {
result.push(` let cache = ctx.cache || {};`); result.push(` let cache = ctx.cache || {};`);
result.push(` let nextCache = ctx.cache = {};`); result.push(` let nextCache = ctx.cache = {};`);
@@ -254,16 +228,7 @@ class CodeTarget {
} }
} }
const TRANSLATABLE_ATTRS = [ const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
"alt",
"aria-label",
"aria-placeholder",
"aria-roledescription",
"aria-valuetext",
"label",
"placeholder",
"title",
];
const translationRE = /^(\s*)([\s\S]+?)(\s*)$/; const translationRE = /^(\s*)([\s\S]+?)(\s*)$/;
export class CodeGenerator { export class CodeGenerator {
@@ -275,7 +240,7 @@ export class CodeGenerator {
target = new CodeTarget("template"); target = new CodeTarget("template");
templateName?: string; templateName?: string;
dev: boolean; dev: boolean;
translateFn: (s: string, translationCtx: string) => string; translateFn: (s: string) => string;
translatableAttributes: string[] = TRANSLATABLE_ATTRS; translatableAttributes: string[] = TRANSLATABLE_ATTRS;
ast: AST; ast: AST;
staticDefs: { id: string; expr: string }[] = []; staticDefs: { id: string; expr: string }[] = [];
@@ -299,9 +264,6 @@ export class CodeGenerator {
this.dev = options.dev || false; this.dev = options.dev || false;
this.ast = ast; this.ast = ast;
this.templateName = options.name; this.templateName = options.name;
if (options.hasGlobalValues) {
this.helpers.add("__globals__");
}
} }
generateCode(): string { generateCode(): string {
@@ -315,7 +277,6 @@ export class CodeGenerator {
forceNewBlock: false, forceNewBlock: false,
isLast: true, isLast: true,
translate: true, translate: true,
translationCtx: "",
tKeyExpr: null, tKeyExpr: null,
}); });
// define blocks and utility functions // define blocks and utility functions
@@ -336,13 +297,14 @@ export class CodeGenerator {
mainCode.push(``); mainCode.push(``);
for (let block of this.blocks) { for (let block of this.blocks) {
if (block.dom) { if (block.dom) {
let xmlString = toStringExpression(block.asXmlString()); let xmlString = block.asXmlString();
xmlString = xmlString.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
if (block.dynamicTagName) { if (block.dynamicTagName) {
xmlString = xmlString.replace(/^`<\w+/, `\`<\${tag || '${block.dom.nodeName}'}`); xmlString = xmlString.replace(/^<\w+/, `<\${tag || '${block.dom.nodeName}'}`);
xmlString = xmlString.replace(/\w+>`$/, `\${tag || '${block.dom.nodeName}'}>\``); xmlString = xmlString.replace(/\w+>$/, `\${tag || '${block.dom.nodeName}'}>`);
mainCode.push(`let ${block.blockName} = tag => createBlock(${xmlString});`); mainCode.push(`let ${block.blockName} = tag => createBlock(\`${xmlString}\`);`);
} else { } else {
mainCode.push(`let ${block.blockName} = createBlock(${xmlString});`); mainCode.push(`let ${block.blockName} = createBlock(\`${xmlString}\`);`);
} }
} }
} }
@@ -400,7 +362,7 @@ export class CodeGenerator {
): BlockDescription { ): BlockDescription {
const hasRoot = this.target.hasRoot; const hasRoot = this.target.hasRoot;
const block = new BlockDescription(this.target, type); const block = new BlockDescription(this.target, type);
if (!hasRoot) { if (!hasRoot && !ctx.preventRoot && !ctx.ignoreRoot) {
this.target.hasRoot = true; this.target.hasRoot = true;
block.isRoot = true; block.isRoot = true;
} }
@@ -426,7 +388,10 @@ export class CodeGenerator {
blockExpr = `toggler(${ctx.tKeyExpr}, ${blockExpr})`; blockExpr = `toggler(${ctx.tKeyExpr}, ${blockExpr})`;
} }
if (block.isRoot) { if (ctx.ignoreRoot) {
return;
}
if (block.isRoot && !ctx.preventRoot) {
if (this.target.on) { if (this.target.on) {
blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on); blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on);
} }
@@ -470,11 +435,6 @@ export class CodeGenerator {
.join(""); .join("");
} }
translate(str: string, translationCtx: string): string {
const match = translationRE.exec(str) as any;
return match[1] + this.translateFn(match[2], translationCtx) + match[3];
}
/** /**
* @returns the newly created block name, if any * @returns the newly created block name, if any
*/ */
@@ -512,10 +472,10 @@ export class CodeGenerator {
return this.compileLog(ast, ctx); return this.compileLog(ast, ctx);
case ASTType.TSlot: case ASTType.TSlot:
return this.compileTSlot(ast, ctx); return this.compileTSlot(ast, ctx);
case ASTType.TSetSlot:
return this.compileTSetSlot(ast, ctx);
case ASTType.TTranslation: case ASTType.TTranslation:
return this.compileTTranslation(ast, ctx); return this.compileTTranslation(ast, ctx);
case ASTType.TTranslationContext:
return this.compileTTranslationContext(ast, ctx);
case ASTType.TPortal: case ASTType.TPortal:
return this.compileTPortal(ast, ctx); return this.compileTPortal(ast, ctx);
} }
@@ -541,7 +501,7 @@ export class CodeGenerator {
const isNewBlock = !block || forceNewBlock; const isNewBlock = !block || forceNewBlock;
if (isNewBlock) { if (isNewBlock) {
block = this.createBlock(block, "comment", ctx); block = this.createBlock(block, "comment", ctx);
this.insertBlock(`comment(${toStringExpression(ast.value)})`, block, { this.insertBlock(`comment(\`${ast.value}\`)`, block, {
...ctx, ...ctx,
forceNewBlock: forceNewBlock && !block, forceNewBlock: forceNewBlock && !block,
}); });
@@ -557,15 +517,13 @@ export class CodeGenerator {
let value = ast.value; let value = ast.value;
if (value && ctx.translate !== false) { if (value && ctx.translate !== false) {
value = this.translate(value, ctx.translationCtx); const match = translationRE.exec(value) as any;
} value = match[1] + this.translateFn(match[2]) + match[3];
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
} }
if (!block || forceNewBlock) { if (!block || forceNewBlock) {
block = this.createBlock(block, "text", ctx); block = this.createBlock(block, "text", ctx);
this.insertBlock(`text(${toStringExpression(value)})`, block, { this.insertBlock(`text(\`${value}\`)`, block, {
...ctx, ...ctx,
forceNewBlock: forceNewBlock && !block, forceNewBlock: forceNewBlock && !block,
}); });
@@ -611,6 +569,11 @@ export class CodeGenerator {
} }
// attributes // attributes
const attrs: Attrs = {}; const attrs: Attrs = {};
const nameSpace = ast.ns || ctx.nameSpace;
if (nameSpace && isNewBlock) {
// specific namespace uri
attrs["block-ns"] = nameSpace;
}
for (let key in ast.attrs) { for (let key in ast.attrs) {
let expr, attrName; let expr, attrName;
@@ -624,30 +587,22 @@ export class CodeGenerator {
attrName = key === "t-att" ? null : key.slice(6); attrName = key === "t-att" ? null : key.slice(6);
expr = compileExpr(ast.attrs[key]); expr = compileExpr(ast.attrs[key]);
if (attrName && isProp(ast.tag, attrName)) { if (attrName && isProp(ast.tag, attrName)) {
if (attrName === "readonly") {
// the property has a different name than the attribute
attrName = "readOnly";
}
// we force a new string or new boolean to bypass the equality check in blockdom when patching same value // we force a new string or new boolean to bypass the equality check in blockdom when patching same value
if (attrName === "value") { if (attrName === "value") {
// When the expression is falsy (except 0), fall back to an empty string // When the expression is falsy, fall back to an empty string
expr = `new String((${expr}) === 0 ? 0 : ((${expr}) || ""))`; expr = `new String((${expr}) || "")`;
} else { } else {
expr = `new Boolean(${expr})`; expr = `new Boolean(${expr})`;
} }
const idx = block!.insertData(expr, "prop"); }
attrs[`block-property-${idx}`] = attrName!; const idx = block!.insertData(expr, "attr");
if (key === "t-att") {
attrs[`block-attributes`] = String(idx);
} else { } else {
const idx = block!.insertData(expr, "attr"); attrs[`block-attribute-${idx}`] = attrName!;
if (key === "t-att") {
attrs[`block-attributes`] = String(idx);
} else {
attrs[`block-attribute-${idx}`] = attrName!;
}
} }
} else if (this.translatableAttributes.includes(key)) { } else if (this.translatableAttributes.includes(key)) {
const attrTranslationCtx = ast.attrsTranslationCtx?.[key] || ctx.translationCtx; attrs[key] = this.translateFn(ast.attrs[key]);
attrs[key] = this.translateFn(ast.attrs[key], attrTranslationCtx);
} else { } else {
expr = `"${ast.attrs[key]}"`; expr = `"${ast.attrs[key]}"`;
attrName = key; attrName = key;
@@ -694,15 +649,15 @@ export class CodeGenerator {
targetExpr = compileExpr(dynamicTgExpr); targetExpr = compileExpr(dynamicTgExpr);
} }
} }
idx = block!.insertData(`${fullExpression} === ${targetExpr}`, "prop"); idx = block!.insertData(`${fullExpression} === ${targetExpr}`, "attr");
attrs[`block-property-${idx}`] = specialInitTargetAttr; attrs[`block-attribute-${idx}`] = specialInitTargetAttr;
} else if (hasDynamicChildren) { } else if (hasDynamicChildren) {
const bValueId = generateId("bValue"); const bValueId = generateId("bValue");
tModelSelectedExpr = `${bValueId}`; tModelSelectedExpr = `${bValueId}`;
this.define(tModelSelectedExpr, fullExpression); this.define(tModelSelectedExpr, fullExpression);
} else { } else {
idx = block!.insertData(`${fullExpression}`, "prop"); idx = block!.insertData(`${fullExpression}`, "attr");
attrs[`block-property-${idx}`] = targetAttr; attrs[`block-attribute-${idx}`] = targetAttr;
} }
this.helpers.add("toNumber"); this.helpers.add("toNumber");
let valueCode = `ev.target.${targetAttr}`; let valueCode = `ev.target.${targetAttr}`;
@@ -723,27 +678,33 @@ export class CodeGenerator {
// t-ref // t-ref
if (ast.ref) { if (ast.ref) {
if (this.dev) { this.target.hasRef = true;
this.helpers.add("makeRefWrapper");
this.target.hasRefWrapper = true;
}
const isDynamic = INTERP_REGEXP.test(ast.ref); const isDynamic = INTERP_REGEXP.test(ast.ref);
let name = `\`${ast.ref}\``;
if (isDynamic) { if (isDynamic) {
name = replaceDynamicParts(ast.ref, (expr) => this.captureExpression(expr, true)); this.helpers.add("singleRefSetter");
const str = replaceDynamicParts(ast.ref, (expr) => this.captureExpression(expr, true));
const idx = block!.insertData(`singleRefSetter(refs, ${str})`, "ref");
attrs["block-ref"] = String(idx);
} else {
let name = ast.ref;
if (name in this.target.refInfo) {
// ref has already been defined
this.helpers.add("multiRefSetter");
const info = this.target.refInfo[name];
const index = block!.data.push(info[0]) - 1;
attrs["block-ref"] = String(index);
info[1] = `multiRefSetter(refs, \`${name}\`)`;
} else {
let id = generateId("ref");
this.helpers.add("singleRefSetter");
this.target.refInfo[name] = [id, `singleRefSetter(refs, \`${name}\`)`];
const index = block!.data.push(id) - 1;
attrs["block-ref"] = String(index);
}
} }
let setRefStr = `(el) => this.__owl__.setRef((${name}), el)`;
if (this.dev) {
setRefStr = `refWrapper(${name}, ${setRefStr})`;
}
const idx = block!.insertData(setRefStr, "ref");
attrs["block-ref"] = String(idx);
} }
const nameSpace = ast.ns || ctx.nameSpace; const dom = xmlDoc.createElement(ast.tag);
const dom = nameSpace
? xmlDoc.createElementNS(nameSpace, ast.tag)
: xmlDoc.createElement(ast.tag);
for (const [attr, val] of Object.entries(attrs)) { for (const [attr, val] of Object.entries(attrs)) {
if (!(attr === "class" && val === "")) { if (!(attr === "class" && val === "")) {
dom.setAttribute(attr, val); dom.setAttribute(attr, val);
@@ -764,7 +725,6 @@ export class CodeGenerator {
tKeyExpr: ctx.tKeyExpr, tKeyExpr: ctx.tKeyExpr,
nameSpace, nameSpace,
tModelSelectedExpr, tModelSelectedExpr,
inPreTag: ctx.inPreTag || ast.tag === "pre",
}); });
this.compileAST(child, subCtx); this.compileAST(child, subCtx);
} }
@@ -785,7 +745,7 @@ export class CodeGenerator {
if (!current) break; if (!current) break;
} }
} }
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx); this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
} }
} }
return block!.varName; return block!.varName;
@@ -801,8 +761,7 @@ export class CodeGenerator {
expr = compileExpr(ast.expr); expr = compileExpr(ast.expr);
if (ast.defaultValue) { if (ast.defaultValue) {
this.helpers.add("withDefault"); this.helpers.add("withDefault");
// FIXME: defaultValue is not translated expr = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
expr = `withDefault(${expr}, ${toStringExpression(ast.defaultValue)})`;
} }
} }
if (!block || forceNewBlock) { if (!block || forceNewBlock) {
@@ -888,7 +847,7 @@ export class CodeGenerator {
if (!current) break; if (!current) break;
} }
} }
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx); this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
} }
// note: this part is duplicated from end of compilemulti: // note: this part is duplicated from end of compilemulti:
@@ -919,18 +878,18 @@ export class CodeGenerator {
} }
this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`); this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
this.target.indentLevel++; this.target.indentLevel++;
this.addLine(`ctx[\`${ast.elem}\`] = ${keys}[${loopVar}];`); this.addLine(`ctx[\`${ast.elem}\`] = ${vals}[${loopVar}];`);
if (!ast.hasNoFirst) { if (!ast.hasNoFirst) {
this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`); this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`);
} }
if (!ast.hasNoLast) { if (!ast.hasNoLast) {
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${keys}.length - 1;`); this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${vals}.length - 1;`);
} }
if (!ast.hasNoIndex) { if (!ast.hasNoIndex) {
this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`); this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`);
} }
if (!ast.hasNoValue) { if (!ast.hasNoValue) {
this.addLine(`ctx[\`${ast.elem}_value\`] = ${vals}[${loopVar}];`); this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
} }
this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar); this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar);
if (this.dev) { if (this.dev) {
@@ -995,7 +954,7 @@ export class CodeGenerator {
const isNewBlock = !block || forceNewBlock; const isNewBlock = !block || forceNewBlock;
let codeIdx = this.target.code.length; let codeIdx = this.target.code.length;
if (isNewBlock) { if (isNewBlock) {
const n = ast.content.filter((c) => !c.hasNoRepresentation).length; const n = ast.content.filter((c) => c.type !== ASTType.TSet).length;
let result: string | null = null; let result: string | null = null;
if (n <= 1) { if (n <= 1) {
for (let child of ast.content) { for (let child of ast.content) {
@@ -1009,31 +968,34 @@ export class CodeGenerator {
let index = 0; let index = 0;
for (let i = 0, l = ast.content.length; i < l; i++) { for (let i = 0, l = ast.content.length; i < l; i++) {
const child = ast.content[i]; const child = ast.content[i];
const forceNewBlock = !child.hasNoRepresentation; const isTSet = child.type === ASTType.TSet;
const subCtx = createContext(ctx, { const subCtx = createContext(ctx, {
block, block,
index, index,
forceNewBlock, forceNewBlock: !isTSet,
preventRoot: ctx.preventRoot,
isLast: ctx.isLast && i === l - 1, isLast: ctx.isLast && i === l - 1,
}); });
this.compileAST(child, subCtx); this.compileAST(child, subCtx);
if (forceNewBlock) { if (!isTSet) {
index++; index++;
} }
} }
if (isNewBlock) { if (isNewBlock) {
if (block!.hasDynamicChildren && block!.children.length) { if (block!.hasDynamicChildren) {
const code = this.target.code; if (block!.children.length) {
const children = block!.children.slice(); const code = this.target.code;
let current = children.shift(); const children = block!.children.slice();
for (let i = codeIdx; i < code.length; i++) { let current = children.shift();
if (code[i].trimStart().startsWith(`const ${current!.varName} `)) { for (let i = codeIdx; i < code.length; i++) {
code[i] = code[i].replace(`const ${current!.varName}`, current!.varName); if (code[i].trimStart().startsWith(`const ${current!.varName} `)) {
current = children.shift(); code[i] = code[i].replace(`const ${current!.varName}`, current!.varName);
if (!current) break; current = children.shift();
if (!current) break;
}
} }
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
} }
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
} }
const args = block!.children.map((c) => c.varName).join(", "); const args = block!.children.map((c) => c.varName).join(", ");
@@ -1049,31 +1011,32 @@ export class CodeGenerator {
ctxVar = generateId("ctx"); ctxVar = generateId("ctx");
this.addLine(`let ${ctxVar} = ${compileExpr(ast.context)};`); this.addLine(`let ${ctxVar} = ${compileExpr(ast.context)};`);
} }
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block && !forceNewBlock) {
this.insertAnchor(block);
}
block = this.createBlock(block, "multi", ctx);
if (ast.body) { if (ast.body) {
this.addLine(`${ctxVar} = Object.create(${ctxVar});`); this.addLine(`${ctxVar} = Object.create(${ctxVar});`);
this.addLine(`${ctxVar}[isBoundary] = 1;`); this.addLine(`${ctxVar}[isBoundary] = 1;`);
this.helpers.add("isBoundary"); this.helpers.add("isBoundary");
const subCtx = createContext(ctx, { ctxVar }); const subCtx = createContext(ctx, { preventRoot: true, ctxVar });
const bl = this.compileMulti({ type: ASTType.Multi, content: ast.body }, subCtx); const bl = this.compileMulti({ type: ASTType.Multi, content: ast.body }, subCtx);
if (bl) { if (bl) {
this.helpers.add("zero"); this.helpers.add("zero");
this.addLine(`${ctxVar}[zero] = ${bl};`); this.addLine(`${ctxVar}[zero] = ${bl};`);
} }
} }
const isDynamic = INTERP_REGEXP.test(ast.name);
const key = this.generateComponentKey(); const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block) {
if (!forceNewBlock) {
this.insertAnchor(block);
}
}
const key = `key + \`${this.generateComponentKey()}\``;
if (isDynamic) { if (isDynamic) {
const templateVar = generateId("template"); const templateVar = generateId("template");
if (!this.staticDefs.find((d) => d.id === "call")) { if (!this.staticDefs.find((d) => d.id === "call")) {
this.staticDefs.push({ id: "call", expr: `app.callTemplate.bind(app)` }); this.staticDefs.push({ id: "call", expr: `app.callTemplate.bind(app)` });
} }
this.define(templateVar, subTemplate); this.define(templateVar, subTemplate);
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`call(this, ${templateVar}, ${ctxVar}, node, ${key})`, block!, { this.insertBlock(`call(this, ${templateVar}, ${ctxVar}, node, ${key})`, block!, {
...ctx, ...ctx,
forceNewBlock: !block, forceNewBlock: !block,
@@ -1081,6 +1044,7 @@ export class CodeGenerator {
} else { } else {
const id = generateId(`callTemplate_`); const id = generateId(`callTemplate_`);
this.staticDefs.push({ id, expr: `app.getTemplate(${subTemplate})` }); this.staticDefs.push({ id, expr: `app.getTemplate(${subTemplate})` });
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`${id}.call(this, ${ctxVar}, node, ${key})`, block!, { this.insertBlock(`${id}.call(this, ${ctxVar}, node, ${key})`, block!, {
...ctx, ...ctx,
forceNewBlock: !block, forceNewBlock: !block,
@@ -1119,13 +1083,10 @@ export class CodeGenerator {
} else { } else {
let value: string; let value: string;
if (ast.defaultValue) { if (ast.defaultValue) {
const defaultValue = toStringExpression(
ctx.translate ? this.translate(ast.defaultValue, ctx.translationCtx) : ast.defaultValue
);
if (ast.value) { if (ast.value) {
value = `withDefault(${expr}, ${defaultValue})`; value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
} else { } else {
value = defaultValue; value = `\`${ast.defaultValue}\``;
} }
} else { } else {
value = expr; value = expr;
@@ -1136,12 +1097,12 @@ export class CodeGenerator {
return null; return null;
} }
generateComponentKey(currentKey: string = "key") { generateComponentKey() {
const parts = [generateId("__")]; const parts = [generateId("__")];
for (let i = 0; i < this.target.loopLevel; i++) { for (let i = 0; i < this.target.loopLevel; i++) {
parts.push(`\${key${i + 1}}`); parts.push(`\${key${i + 1}}`);
} }
return `${currentKey} + \`${parts.join("__")}\``; return parts.join("__");
} }
/** /**
@@ -1155,44 +1116,24 @@ export class CodeGenerator {
* "some-prop" "state" "'some-prop': ctx['state']" * "some-prop" "state" "'some-prop': ctx['state']"
* "onClick.bind" "onClick" "onClick: bind(ctx, ctx['onClick'])" * "onClick.bind" "onClick" "onClick: bind(ctx, ctx['onClick'])"
*/ */
formatProp( formatProp(name: string, value: string): string {
name: string, value = this.captureExpression(value);
value: string,
attrsTranslationCtx: { [name: string]: string } | null,
translationCtx: string
): string {
if (name.endsWith(".translate")) {
const attrTranslationCtx = attrsTranslationCtx?.[name] || translationCtx;
value = toStringExpression(this.translateFn(value, attrTranslationCtx));
} else {
value = this.captureExpression(value);
}
if (name.includes(".")) { if (name.includes(".")) {
let [_name, suffix] = name.split("."); let [_name, suffix] = name.split(".");
name = _name; if (suffix === "bind") {
switch (suffix) { this.helpers.add("bind");
case "bind": name = _name;
value = `(${value}).bind(this)`; value = `bind(this, ${value || undefined})`;
break; } else {
case "alike": throw new OwlError("Invalid prop suffix");
case "translate":
break;
default:
throw new OwlError(`Invalid prop suffix: ${suffix}`);
} }
} }
name = /^[a-z_]+$/i.test(name) ? name : `'${name}'`; name = /^[a-z_]+$/i.test(name) ? name : `'${name}'`;
return `${name}: ${value || undefined}`; return `${name}: ${value || undefined}`;
} }
formatPropObject( formatPropObject(obj: { [prop: string]: any }): string[] {
obj: { [prop: string]: any }, return Object.entries(obj).map(([k, v]) => this.formatProp(k, v));
attrsTranslationCtx: { [name: string]: string } | null,
translationCtx: string
): string[] {
return Object.entries(obj).map(([k, v]) =>
this.formatProp(k, v, attrsTranslationCtx, translationCtx)
);
} }
getPropString(props: string[], dynProps: string | null): string { getPropString(props: string[], dynProps: string | null): string {
@@ -1209,66 +1150,45 @@ export class CodeGenerator {
let { block } = ctx; let { block } = ctx;
// props // props
const hasSlotsProp = "slots" in (ast.props || {}); const hasSlotsProp = "slots" in (ast.props || {});
const props: string[] = ast.props const props: string[] = ast.props ? this.formatPropObject(ast.props) : [];
? this.formatPropObject(ast.props, ast.propsTranslationCtx, ctx.translationCtx)
: [];
// slots // slots
let slotDef: string = ""; let slotVar: string = "";
if (ast.slots) { if (ast.body) {
let ctxStr = "ctx"; slotVar = generateId("slots");
if (this.target.loopLevel || !this.hasSafeContext) { this.helpers.add("markRaw");
ctxStr = generateId("ctx"); if (ast.body.type === ASTType.TSetSlot) {
this.helpers.add("capture"); const subCtx = createContext(ctx, { slotVar: undefined, ignoreRoot: true });
this.define(ctxStr, `capture(ctx)`); const slotInfo = this.compileAST(ast.body, subCtx);
this.target.addLine(`let ${slotVar} = markRaw({'${ast.body.name}': ${slotInfo}});`);
} else {
this.target.addLine(`let ${slotVar} = markRaw({});`);
const subCtx = createContext(ctx, { slotVar, ignoreRoot: true });
this.compileAST(ast.body, subCtx);
} }
let slotStr: string[] = [];
for (let slotName in ast.slots) {
const slotAst = ast.slots[slotName];
const params = [];
if (slotAst.content) {
const name = this.compileInNewTarget("slot", slotAst.content, ctx, slotAst.on);
params.push(`__render: ${name}.bind(this), __ctx: ${ctxStr}`);
}
const scope = ast.slots[slotName].scope;
if (scope) {
params.push(`__scope: "${scope}"`);
}
if (ast.slots[slotName].attrs) {
params.push(
...this.formatPropObject(
ast.slots[slotName].attrs!,
ast.slots[slotName].attrsTranslationCtx,
ctx.translationCtx
)
);
}
const slotInfo = `{${params.join(", ")}}`;
slotStr.push(`'${slotName}': ${slotInfo}`);
}
slotDef = `{${slotStr.join(", ")}}`;
} }
if (slotDef && !(ast.dynamicProps || hasSlotsProp)) { if (slotVar && !(ast.dynamicProps || hasSlotsProp)) {
this.helpers.add("markRaw"); props.push(`slots: ${slotVar}`);
props.push(`slots: markRaw(${slotDef})`);
} }
let propString = this.getPropString(props, ast.dynamicProps); let propString = this.getPropString(props, ast.dynamicProps);
let propVar: string; let propVar: string;
if ((slotDef && (ast.dynamicProps || hasSlotsProp)) || this.dev) { if ((slotVar && (ast.dynamicProps || hasSlotsProp)) || this.dev) {
propVar = generateId("props"); propVar = generateId("props");
this.define(propVar!, propString); this.define(propVar!, propString);
propString = propVar!; propString = propVar!;
} }
if (slotDef && (ast.dynamicProps || hasSlotsProp)) { if (slotVar && (ast.dynamicProps || hasSlotsProp)) {
this.helpers.add("markRaw"); this.helpers.add("markRaw");
this.addLine(`${propVar!}.slots = markRaw(Object.assign(${slotDef}, ${propVar!}.slots))`); this.addLine(`${propVar!}.slots = markRaw(Object.assign(${slotVar}, ${propVar!}.slots))`);
} }
// cmap key // cmap key
const key = this.generateComponentKey();
let expr: string; let expr: string;
if (ast.isDynamic) { if (ast.isDynamic) {
expr = generateId("Comp"); expr = generateId("Comp");
@@ -1286,23 +1206,18 @@ export class CodeGenerator {
this.insertAnchor(block); this.insertAnchor(block);
} }
let keyArg = this.generateComponentKey(); let keyArg = `key + \`${key}\``;
if (ctx.tKeyExpr) { if (ctx.tKeyExpr) {
keyArg = `${ctx.tKeyExpr} + ${keyArg}`; keyArg = `${ctx.tKeyExpr} + ${keyArg}`;
} }
let id = generateId("comp"); let id = generateId("comp");
const propList: string[] = [];
for (let p in ast.props || {}) {
let [name, suffix] = p.split(".");
if (!suffix) {
propList.push(`"${name}"`);
}
}
this.staticDefs.push({ this.staticDefs.push({
id, id,
expr: `app.createComponent(${ expr: `app.createComponent(${
ast.isDynamic ? null : expr ast.isDynamic ? null : expr
}, ${!ast.isDynamic}, ${!!ast.slots}, ${!!ast.dynamicProps}, [${propList}])`, }, ${!ast.isDynamic}, ${!!ast.body}, ${!!ast.dynamicProps}, ${
!ast.props && !ast.dynamicProps
})`,
}); });
if (ast.isDynamic) { if (ast.isDynamic) {
@@ -1343,6 +1258,39 @@ export class CodeGenerator {
return `${name}(${expr}, [${handlers.join(",")}])`; return `${name}(${expr}, [${handlers.join(",")}])`;
} }
compileTSetSlot(ast: ASTSlotDefinition, ctx: Context): string {
let ctxStr = "ctx";
if (this.target.loopLevel || !this.hasSafeContext) {
ctxStr = generateId("ctx");
this.helpers.add("capture");
this.define(ctxStr, `capture(ctx)`);
}
// let slotStr: string[] = [];
// for (let slotName in ast.slots) {
// const slotAst = ast.slots[slotName];
const params = [];
if (ast.content) {
const name = this.compileInNewTarget("slot", ast.content, ctx, ast.on);
params.push(`__render: ${name}.bind(this), __ctx: ${ctxStr}`);
}
// ast.scope
// const scope = ast.slots[slotName].scope;
if (ast.scope) {
params.push(`__scope: "${ast.scope}"`);
}
if (ast.attrs) {
params.push(...this.formatPropObject(ast.attrs!));
}
const slotInfo = `{${params.join(", ")}}`;
if (ctx.slotVar) {
this.target.addLine(`${ctx.slotVar}['${ast.name}'] = ${slotInfo};`)
}
// slotStr.push(`'${slotName}': ${slotInfo}`);
// }
// slotDef = `{${slotStr.join(", ")}}`;
return slotInfo;
}
compileTSlot(ast: ASTSlot, ctx: Context): string { compileTSlot(ast: ASTSlot, ctx: Context): string {
this.helpers.add("callSlot"); this.helpers.add("callSlot");
let { block } = ctx; let { block } = ctx;
@@ -1359,17 +1307,16 @@ export class CodeGenerator {
isMultiple = isMultiple || this.slotNames.has(ast.name); isMultiple = isMultiple || this.slotNames.has(ast.name);
this.slotNames.add(ast.name); this.slotNames.add(ast.name);
} }
const attrs = { ...ast.attrs }; const dynProps = ast.attrs ? ast.attrs["t-props"] : null;
const dynProps = attrs["t-props"]; if (ast.attrs) {
delete attrs["t-props"]; delete ast.attrs["t-props"];
}
let key = this.target.loopLevel ? `key${this.target.loopLevel}` : "key"; let key = this.target.loopLevel ? `key${this.target.loopLevel}` : "key";
if (isMultiple) { if (isMultiple) {
key = this.generateComponentKey(key); key = `${key} + \`${this.generateComponentKey()}\``;
} }
const props = ast.attrs const props = ast.attrs ? this.formatPropObject(ast.attrs) : [];
? this.formatPropObject(attrs, ast.attrsTranslationCtx, ctx.translationCtx)
: [];
const scope = this.getPropString(props, dynProps); const scope = this.getPropString(props, dynProps);
if (ast.defaultContent) { if (ast.defaultContent) {
const name = this.compileInNewTarget("defaultContent", ast.defaultContent, ctx); const name = this.compileInNewTarget("defaultContent", ast.defaultContent, ctx);
@@ -1402,15 +1349,6 @@ export class CodeGenerator {
} }
return null; return null;
} }
compileTTranslationContext(ast: ASTTranslationContext, ctx: Context): string | null {
if (ast.content) {
return this.compileAST(
ast.content,
Object.assign({}, ctx, { translationCtx: ast.translationCtx })
);
}
return null;
}
compileTPortal(ast: ASTTPortal, ctx: Context): string { compileTPortal(ast: ASTTPortal, ctx: Context): string {
if (!this.staticDefs.find((d) => d.id === "Portal")) { if (!this.staticDefs.find((d) => d.id === "Portal")) {
this.staticDefs.push({ id: "Portal", expr: `app.Portal` }); this.staticDefs.push({ id: "Portal", expr: `app.Portal` });
@@ -1418,6 +1356,7 @@ export class CodeGenerator {
let { block } = ctx; let { block } = ctx;
const name = this.compileInNewTarget("slot", ast.content, ctx); const name = this.compileInNewTarget("slot", ast.content, ctx);
const key = this.generateComponentKey();
let ctxStr = "ctx"; let ctxStr = "ctx";
if (this.target.loopLevel || !this.hasSafeContext) { if (this.target.loopLevel || !this.hasSafeContext) {
ctxStr = generateId("ctx"); ctxStr = generateId("ctx");
@@ -1431,8 +1370,7 @@ export class CodeGenerator {
}); });
const target = compileExpr(ast.target); const target = compileExpr(ast.target);
const key = this.generateComponentKey(); const blockString = `${id}({target: ${target},slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, key + \`${key}\`, node, ctx, Portal)`;
const blockString = `${id}({target: ${target},slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, ${key}, node, ctx, Portal)`;
if (block) { if (block) {
this.insertAnchor(block); this.insertAnchor(block);
} }
+3 -19
View File
@@ -1,9 +1,7 @@
import type { customDirectives } from "../common/types";
import type { TemplateSet } from "../runtime/template_set"; import type { TemplateSet } from "../runtime/template_set";
import type { BDom } from "../runtime/blockdom"; import type { BDom } from "../runtime/blockdom";
import { CodeGenerator, Config } from "./code_generator"; import { CodeGenerator, Config } from "./code_generator";
import { parse } from "./parser"; import { parse } from "./parser";
import { OwlError } from "../common/owl_error";
export type Template = (context: any, vnode: any, key?: string) => BDom; export type Template = (context: any, vnode: any, key?: string) => BDom;
@@ -11,17 +9,13 @@ export type TemplateFunction = (app: TemplateSet, bdom: any, helpers: any) => Te
interface CompileOptions extends Config { interface CompileOptions extends Config {
name?: string; name?: string;
customDirectives?: customDirectives;
hasGlobalValues: boolean;
} }
export function compile( export function compile(
template: string | Element, template: string | Element,
options: CompileOptions = { options: CompileOptions = {}
hasGlobalValues: false,
}
): TemplateFunction { ): TemplateFunction {
// parsing // parsing
const ast = parse(template, options.customDirectives); const ast = parse(template);
// some work // some work
const hasSafeContext = const hasSafeContext =
@@ -33,15 +27,5 @@ export function compile(
const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext }); const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
const code = codeGenerator.generateCode(); const code = codeGenerator.generateCode();
// template function // template function
try { return new Function("app, bdom, helpers", code) as TemplateFunction;
return new Function("app, bdom, helpers", code) as TemplateFunction;
} catch (originalError: any) {
const { name } = options;
const nameStr = name ? `template "${name}"` : "anonymous template";
const err = new OwlError(
`Failed to compile ${nameStr}: ${originalError.message}\n\ngenerated code:\nfunction(app, bdom, helpers) {\n${code}\n}`
);
err.cause = originalError;
throw err;
}
} }
+3 -5
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../common/owl_error"; import { OwlError } from "../runtime/error_handling";
/** /**
* Owl QWeb Expression Parser * Owl QWeb Expression Parser
@@ -28,7 +28,7 @@ import { OwlError } from "../common/owl_error";
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const RESERVED_WORDS = const RESERVED_WORDS =
"true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,eval,void,Math,RegExp,Array,Object,Date,__globals__".split( "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,eval,void,Math,RegExp,Array,Object,Date".split(
"," ","
); );
@@ -268,7 +268,7 @@ export function compileExprToArray(expr: string): Token[] {
const localVars = new Set<string>(); const localVars = new Set<string>();
const tokens = tokenize(expr); const tokens = tokenize(expr);
let i = 0; let i = 0;
let stack = []; // to track last opening (, [ or { let stack = []; // to track last opening [ or {
while (i < tokens.length) { while (i < tokens.length) {
let token = tokens[i]; let token = tokens[i];
@@ -279,12 +279,10 @@ export function compileExprToArray(expr: string): Token[] {
switch (token.type) { switch (token.type) {
case "LEFT_BRACE": case "LEFT_BRACE":
case "LEFT_BRACKET": case "LEFT_BRACKET":
case "LEFT_PAREN":
stack.push(token.type); stack.push(token.type);
break; break;
case "RIGHT_BRACE": case "RIGHT_BRACE":
case "RIGHT_BRACKET": case "RIGHT_BRACKET":
case "RIGHT_PAREN":
stack.pop(); stack.pop();
} }
+200 -311
View File
@@ -1,6 +1,4 @@
import { OwlError } from "../common/owl_error"; import { OwlError } from "../runtime/error_handling";
import type { customDirectives } from "../common/types";
import { parseXML } from "../common/utils";
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// AST Type definition // AST Type definition
@@ -25,23 +23,18 @@ export const enum ASTType {
TDebug, TDebug,
TLog, TLog,
TSlot, TSlot,
TSetSlot,
TCallBlock, TCallBlock,
TTranslation, TTranslation,
TTranslationContext,
TPortal, TPortal,
} }
export interface BaseAST { export interface ASTText {
type: ASTType;
hasNoRepresentation?: true;
}
export interface ASTText extends BaseAST {
type: ASTType.Text; type: ASTType.Text;
value: string; value: string;
} }
export interface ASTComment extends BaseAST { export interface ASTComment {
type: ASTType.Comment; type: ASTType.Comment;
value: string; value: string;
} }
@@ -57,12 +50,11 @@ interface TModelInfo {
specialInitTargetAttr: string | null; specialInitTargetAttr: string | null;
} }
export interface ASTDomNode extends BaseAST { export interface ASTDomNode {
type: ASTType.DomNode; type: ASTType.DomNode;
tag: string; tag: string;
content: AST[]; content: AST[];
attrs: Attrs | null; attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
ref: string | null; ref: string | null;
on: EventHandlers | null; on: EventHandlers | null;
model: TModelInfo | null; model: TModelInfo | null;
@@ -70,24 +62,24 @@ export interface ASTDomNode extends BaseAST {
ns: string | null; ns: string | null;
} }
export interface ASTMulti extends BaseAST { export interface ASTMulti {
type: ASTType.Multi; type: ASTType.Multi;
content: AST[]; content: AST[];
} }
export interface ASTTEsc extends BaseAST { export interface ASTTEsc {
type: ASTType.TEsc; type: ASTType.TEsc;
expr: string; expr: string;
defaultValue: string; defaultValue: string;
} }
export interface ASTTOut extends BaseAST { export interface ASTTOut {
type: ASTType.TOut; type: ASTType.TOut;
expr: string; expr: string;
body: AST[] | null; body: AST[] | null;
} }
export interface ASTTif extends BaseAST { export interface ASTTif {
type: ASTType.TIf; type: ASTType.TIf;
condition: string; condition: string;
content: AST; content: AST;
@@ -95,16 +87,15 @@ export interface ASTTif extends BaseAST {
tElse: AST | null; tElse: AST | null;
} }
export interface ASTTSet extends BaseAST { export interface ASTTSet {
type: ASTType.TSet; type: ASTType.TSet;
name: string; name: string;
value: string | null; // value defined in attribute value: string | null; // value defined in attribute
defaultValue: string | null; // value defined in body, if text defaultValue: string | null; // value defined in body, if text
body: AST[] | null; // content of body if not text body: AST[] | null; // content of body if not text
hasNoRepresentation: true;
} }
export interface ASTTForEach extends BaseAST { export interface ASTTForEach {
type: ASTType.TForEach; type: ASTType.TForEach;
collection: string; collection: string;
elem: string; elem: string;
@@ -117,75 +108,69 @@ export interface ASTTForEach extends BaseAST {
key: string | null; key: string | null;
} }
export interface ASTTKey extends BaseAST { export interface ASTTKey {
type: ASTType.TKey; type: ASTType.TKey;
expr: string; expr: string;
content: AST; content: AST;
} }
export interface ASTTCall extends BaseAST { export interface ASTTCall {
type: ASTType.TCall; type: ASTType.TCall;
name: string; name: string;
body: AST[] | null; body: AST[] | null;
context: string | null; context: string | null;
} }
interface SlotDefinition { export interface ASTSlotDefinition {
type: ASTType.TSetSlot;
name: string;
content: AST | null; content: AST | null;
scope: string | null; scope: string | null;
on: EventHandlers | null; on: EventHandlers | null;
attrs: Attrs | null; attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
} }
export interface ASTComponent extends BaseAST { export interface ASTComponent {
type: ASTType.TComponent; type: ASTType.TComponent;
name: string; name: string;
isDynamic: boolean; isDynamic: boolean;
dynamicProps: string | null; dynamicProps: string | null;
on: EventHandlers | null; on: EventHandlers | null;
props: { [name: string]: string } | null; props: { [name: string]: string } | null;
propsTranslationCtx: { [name: string]: string } | null; body: AST | null;
slots: { [name: string]: SlotDefinition } | null; // slots: { [name: string]: ASTSlotDefinition } | null;
} }
export interface ASTSlot extends BaseAST { export interface ASTSlot {
type: ASTType.TSlot; type: ASTType.TSlot;
name: string; name: string;
attrs: Attrs | null; attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
on: EventHandlers | null; on: EventHandlers | null;
defaultContent: AST | null; defaultContent: AST | null;
} }
export interface ASTTCallBlock extends BaseAST { export interface ASTTCallBlock {
type: ASTType.TCallBlock; type: ASTType.TCallBlock;
name: string; name: string;
} }
export interface ASTDebug extends BaseAST { export interface ASTDebug {
type: ASTType.TDebug; type: ASTType.TDebug;
content: AST | null; content: AST | null;
} }
export interface ASTLog extends BaseAST { export interface ASTLog {
type: ASTType.TLog; type: ASTType.TLog;
expr: string; expr: string;
content: AST | null; content: AST | null;
} }
export interface ASTTranslation extends BaseAST { export interface ASTTranslation {
type: ASTType.TTranslation; type: ASTType.TTranslation;
content: AST | null; content: AST | null;
} }
export interface ASTTranslationContext extends BaseAST { export interface ASTTPortal {
type: ASTType.TTranslationContext;
content: AST | null;
translationCtx: string;
}
export interface ASTTPortal extends BaseAST {
type: ASTType.TPortal; type: ASTType.TPortal;
target: string; target: string;
content: AST; content: AST;
@@ -205,11 +190,11 @@ export type AST =
| ASTTKey | ASTTKey
| ASTComponent | ASTComponent
| ASTSlot | ASTSlot
| ASTSlotDefinition
| ASTTCallBlock | ASTTCallBlock
| ASTLog | ASTLog
| ASTDebug | ASTDebug
| ASTTranslation | ASTTranslation
| ASTTranslationContext
| ASTTPortal; | ASTTPortal;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -217,34 +202,30 @@ export type AST =
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
const cache: WeakMap<Element, AST> = new WeakMap(); const cache: WeakMap<Element, AST> = new WeakMap();
export function parse(xml: string | Element, customDir?: customDirectives): AST { export function parse(xml: string | Element): AST {
const ctx = {
inPreTag: false,
customDirectives: customDir,
};
if (typeof xml === "string") { if (typeof xml === "string") {
const elem = parseXML(`<t>${xml}</t>`).firstChild as Element; const elem = parseXML(`<t>${xml}</t>`).firstChild as Element;
return _parse(elem, ctx); return _parse(elem);
} }
let ast = cache.get(xml); let ast = cache.get(xml);
if (!ast) { if (!ast) {
// we clone here the xml to prevent modifying it in place // we clone here the xml to prevent modifying it in place
ast = _parse(xml.cloneNode(true) as Element, ctx); ast = _parse(xml.cloneNode(true) as Element);
cache.set(xml, ast); cache.set(xml, ast);
} }
return ast; return ast;
} }
function _parse(xml: Element, ctx: ParsingContext): AST { function _parse(xml: Element): AST {
normalizeXML(xml); normalizeXML(xml);
const ctx = { inPreTag: false, inSVG: false };
return parseNode(xml, ctx) || { type: ASTType.Text, value: "" }; return parseNode(xml, ctx) || { type: ASTType.Text, value: "" };
} }
interface ParsingContext { interface ParsingContext {
tModelInfo?: TModelInfo | null; tModelInfo?: TModelInfo | null;
nameSpace?: string;
inPreTag: boolean; inPreTag: boolean;
customDirectives?: customDirectives; inSVG: boolean;
} }
function parseNode(node: Node, ctx: ParsingContext): AST | null { function parseNode(node: Node, ctx: ParsingContext): AST | null {
@@ -252,19 +233,18 @@ function parseNode(node: Node, ctx: ParsingContext): AST | null {
return parseTextCommentNode(node, ctx); return parseTextCommentNode(node, ctx);
} }
return ( return (
parseTCustom(node, ctx) ||
parseTDebugLog(node, ctx) || parseTDebugLog(node, ctx) ||
parseTForEach(node, ctx) || parseTForEach(node, ctx) ||
parseTIf(node, ctx) || parseTIf(node, ctx) ||
parseTPortal(node, ctx) || parseTPortal(node, ctx) ||
parseTCall(node, ctx) || parseTCall(node, ctx) ||
parseTCallBlock(node, ctx) || parseTCallBlock(node, ctx) ||
parseTTranslation(node, ctx) ||
parseTTranslationContext(node, ctx) ||
parseTKey(node, ctx) ||
parseTEscNode(node, ctx) || parseTEscNode(node, ctx) ||
parseTOutNode(node, ctx) || parseTKey(node, ctx) ||
parseTTranslation(node, ctx) ||
parseTSlot(node, ctx) || parseTSlot(node, ctx) ||
parseTSetSlot(node, ctx) ||
parseTOutNode(node, ctx) ||
parseComponent(node, ctx) || parseComponent(node, ctx) ||
parseDOMNode(node, ctx) || parseDOMNode(node, ctx) ||
parseTSetNode(node, ctx) || parseTSetNode(node, ctx) ||
@@ -287,12 +267,16 @@ function parseTNode(node: Element, ctx: ParsingContext): AST | null {
// Text and Comment Nodes // Text and Comment Nodes
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
const lineBreakRE = /[\r\n]/; const lineBreakRE = /[\r\n]/;
const whitespaceRE = /\s+/g;
function parseTextCommentNode(node: Node, ctx: ParsingContext): AST | null { function parseTextCommentNode(node: Node, ctx: ParsingContext): AST | null {
if (node.nodeType === Node.TEXT_NODE) { if (node.nodeType === Node.TEXT_NODE) {
let value = node.textContent || ""; let value = node.textContent || "";
if (!ctx.inPreTag && lineBreakRE.test(value) && !value.trim()) { if (!ctx.inPreTag) {
return null; if (lineBreakRE.test(value) && !value.trim()) {
return null;
}
value = value.replace(whitespaceRE, " ");
} }
return { type: ASTType.Text, value }; return { type: ASTType.Text, value };
@@ -302,37 +286,6 @@ function parseTextCommentNode(node: Node, ctx: ParsingContext): AST | null {
return null; return null;
} }
function parseTCustom(node: Element, ctx: ParsingContext): AST | null {
if (!ctx.customDirectives) {
return null;
}
const nodeAttrsNames = node.getAttributeNames();
for (let attr of nodeAttrsNames) {
if (attr === "t-custom" || attr === "t-custom-") {
throw new OwlError("Missing custom directive name with t-custom directive");
}
if (attr.startsWith("t-custom-")) {
const directiveName = attr.split(".")[0].slice(9);
const customDirective = ctx.customDirectives[directiveName];
if (!customDirective) {
throw new OwlError(`Custom directive "${directiveName}" is not defined`);
}
const value = node.getAttribute(attr)!;
const modifiers = attr.split(".").slice(1);
node.removeAttribute(attr);
try {
customDirective(node, value, modifiers);
} catch (error) {
throw new OwlError(
`Custom directive "${directiveName}" throw the following error: ${error}`
);
}
return parseNode(node, ctx);
}
}
return null;
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// debugging // debugging
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -340,30 +293,20 @@ function parseTCustom(node: Element, ctx: ParsingContext): AST | null {
function parseTDebugLog(node: Element, ctx: ParsingContext): AST | null { function parseTDebugLog(node: Element, ctx: ParsingContext): AST | null {
if (node.hasAttribute("t-debug")) { if (node.hasAttribute("t-debug")) {
node.removeAttribute("t-debug"); node.removeAttribute("t-debug");
const content = parseNode(node, ctx); return {
const ast: ASTDebug = {
type: ASTType.TDebug, type: ASTType.TDebug,
content, content: parseNode(node, ctx),
}; };
if (content?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
} }
if (node.hasAttribute("t-log")) { if (node.hasAttribute("t-log")) {
const expr = node.getAttribute("t-log")!; const expr = node.getAttribute("t-log")!;
node.removeAttribute("t-log"); node.removeAttribute("t-log");
const content = parseNode(node, ctx); return {
const ast: ASTLog = {
type: ASTType.TLog, type: ASTType.TLog,
expr, expr,
content, content: parseNode(node, ctx),
}; };
if (content?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
} }
return null; return null;
} }
@@ -390,23 +333,23 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
if (tagName === "pre") { if (tagName === "pre") {
ctx.inPreTag = true; ctx.inPreTag = true;
} }
const shouldAddSVGNS = ROOT_SVG_TAGS.has(tagName) && !ctx.inSVG;
let ns = !ctx.nameSpace && ROOT_SVG_TAGS.has(tagName) ? "http://www.w3.org/2000/svg" : null; ctx.inSVG = ctx.inSVG || shouldAddSVGNS;
const ns = shouldAddSVGNS ? "http://www.w3.org/2000/svg" : null;
const ref = node.getAttribute("t-ref"); const ref = node.getAttribute("t-ref");
node.removeAttribute("t-ref"); node.removeAttribute("t-ref");
const nodeAttrsNames = node.getAttributeNames(); const nodeAttrsNames = node.getAttributeNames();
let attrs: ASTDomNode["attrs"] = null; let attrs: ASTDomNode["attrs"] = null;
let attrsTranslationCtx: ASTDomNode["attrsTranslationCtx"] = null;
let on: EventHandlers | null = null; let on: EventHandlers | null = null;
let model: TModelInfo | null = null; let model: TModelInfo | null = null;
for (let attr of nodeAttrsNames) { for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr)!; const value = node.getAttribute(attr)!;
if (attr === "t-on" || attr === "t-on-") { if (attr.startsWith("t-on")) {
throw new OwlError("Missing event name with t-on directive"); if (attr === "t-on") {
} throw new OwlError("Missing event name with t-on directive");
if (attr.startsWith("t-on-")) { }
on = on || {}; on = on || {};
on[attr.slice(5)] = value; on[attr.slice(5)] = value;
} else if (attr.startsWith("t-model")) { } else if (attr.startsWith("t-model")) {
@@ -432,11 +375,13 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
const typeAttr = node.getAttribute("type"); const typeAttr = node.getAttribute("type");
const isInput = tagName === "input"; const isInput = tagName === "input";
const isSelect = tagName === "select"; const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox"; const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio"; const isRadioInput = isInput && typeAttr === "radio";
const hasTrimMod = attr.includes(".trim"); const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = hasTrimMod || attr.includes(".lazy"); const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number"); const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
const eventType = isRadioInput ? "click" : isSelect || hasLazyMod ? "change" : "input"; const eventType = isRadioInput ? "click" : isSelect || hasLazyMod ? "change" : "input";
model = { model = {
@@ -446,8 +391,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
specialInitTargetAttr: isRadioInput ? "checked" : null, specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType, eventType,
hasDynamicChildren: false, hasDynamicChildren: false,
shouldTrim: hasTrimMod, shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod, shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
}; };
if (isSelect) { if (isSelect) {
// don't pollute the original ctx // don't pollute the original ctx
@@ -456,12 +401,6 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
} }
} else if (attr.startsWith("block-")) { } else if (attr.startsWith("block-")) {
throw new OwlError(`Invalid attribute: '${attr}'`); throw new OwlError(`Invalid attribute: '${attr}'`);
} else if (attr === "xmlns") {
ns = value;
} else if (attr.startsWith("t-translation-context-")) {
const attrName = attr.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else if (attr !== "t-name") { } else if (attr !== "t-name") {
if (attr.startsWith("t-") && !attr.startsWith("t-att")) { if (attr.startsWith("t-") && !attr.startsWith("t-att")) {
throw new OwlError(`Unknown QWeb directive: '${attr}'`); throw new OwlError(`Unknown QWeb directive: '${attr}'`);
@@ -474,9 +413,6 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
attrs[attr] = value; attrs[attr] = value;
} }
} }
if (ns) {
ctx.nameSpace = ns;
}
const children = parseChildren(node, ctx); const children = parseChildren(node, ctx);
return { return {
@@ -484,7 +420,6 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
tag: tagName, tag: tagName,
dynamicTag, dynamicTag,
attrs, attrs,
attrsTranslationCtx,
on, on,
ref, ref,
content: children, content: children,
@@ -521,6 +456,9 @@ function parseTEscNode(node: Element, ctx: ParsingContext): AST | null {
content: [tesc], content: [tesc],
}; };
} }
if (ast.type === ASTType.TComponent) {
throw new OwlError("t-esc is not supported on Component nodes");
}
return tesc; return tesc;
} }
@@ -614,19 +552,11 @@ function parseTKey(node: Element, ctx: ParsingContext): AST | null {
} }
const key = node.getAttribute("t-key")!; const key = node.getAttribute("t-key")!;
node.removeAttribute("t-key"); node.removeAttribute("t-key");
const content = parseNode(node, ctx); const body = parseNode(node, ctx);
if (!content) { if (!body) {
return null; return null;
} }
const ast: ASTTKey = { return { type: ASTType.TKey, expr: key, content: body };
type: ASTType.TKey,
expr: key,
content,
};
if (content.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -649,20 +579,12 @@ function parseTCall(node: Element, ctx: ParsingContext): AST | null {
ast.content = [tcall]; ast.content = [tcall];
return ast; return ast;
} }
if (ast && ast.type === ASTType.TComponent) { // if (ast && ast.type === ASTType.TComponent) {
return { // return {
...ast, // ...ast,
slots: { // slots: { default: { content: tcall, scope: null, on: null, attrs: null } },
default: { // };
content: tcall, // }
scope: null,
on: null,
attrs: null,
attrsTranslationCtx: null,
},
},
};
}
} }
const body = parseChildren(node, ctx); const body = parseChildren(node, ctx);
@@ -748,7 +670,7 @@ function parseTSetNode(node: Element, ctx: ParsingContext): AST | null {
if (node.textContent !== node.innerHTML) { if (node.textContent !== node.innerHTML) {
body = parseChildren(node, ctx); body = parseChildren(node, ctx);
} }
return { type: ASTType.TSet, name, value, defaultValue, body, hasNoRepresentation: true }; return { type: ASTType.TSet, name, value, defaultValue, body };
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -790,19 +712,14 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
const dynamicProps = node.getAttribute("t-props"); const dynamicProps = node.getAttribute("t-props");
node.removeAttribute("t-props"); node.removeAttribute("t-props");
const defaultSlotScope = node.getAttribute("t-slot-scope"); // const defaultSlotScope = node.getAttribute("t-slot-scope");
node.removeAttribute("t-slot-scope"); // node.removeAttribute("t-slot-scope");
let on: ASTComponent["on"] = null; let on: ASTComponent["on"] = null;
let props: ASTComponent["props"] = null; let props: ASTComponent["props"] = null;
let propsTranslationCtx: ASTComponent["propsTranslationCtx"] = null;
for (let name of node.getAttributeNames()) { for (let name of node.getAttributeNames()) {
const value = node.getAttribute(name)!; const value = node.getAttribute(name)!;
if (name.startsWith("t-translation-context-")) { if (name.startsWith("t-")) {
const attrName = name.slice(22);
propsTranslationCtx = propsTranslationCtx || {};
propsTranslationCtx[attrName] = value;
} else if (name.startsWith("t-")) {
if (name.startsWith("t-on-")) { if (name.startsWith("t-on-")) {
on = on || {}; on = on || {};
on[name.slice(5)] = value; on[name.slice(5)] = value;
@@ -816,87 +733,17 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
} }
} }
let slots: ASTComponent["slots"] | null = null; let body: ASTComponent["body"] = null;
// let slots: ASTComponent["slots"] | null = null;
if (node.hasChildNodes()) { if (node.hasChildNodes()) {
const clone = <Element>node.cloneNode(true); body = parseChildNodes(node, ctx);
if (!node.querySelector('[t-set-slot]')) {
// named slots body = {type: ASTType.TSetSlot, name: "default", content: body, on: null, attrs: null, scope: null}
const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
for (let slotNode of slotNodes) {
if (slotNode.tagName !== "t") {
throw new OwlError(
`Directive 't-set-slot' can only be used on <t> nodes (used on a <${slotNode.tagName}>)`
);
}
const name = slotNode.getAttribute("t-set-slot")!;
// check if this is defined in a sub component (in which case it should
// be ignored)
let el = slotNode.parentElement!;
let isInSubComponent = false;
while (el && el !== clone) {
if (el!.hasAttribute("t-component") || el!.tagName[0] === el!.tagName[0].toUpperCase()) {
isInSubComponent = true;
break;
}
el = el.parentElement!;
}
if (isInSubComponent || !el) {
continue;
}
slotNode.removeAttribute("t-set-slot");
slotNode.remove();
const slotAst = parseNode(slotNode, ctx);
let on: SlotDefinition["on"] = null;
let attrs: Attrs | null = null;
let attrsTranslationCtx: Attrs | null = null;
let scope: string | null = null;
for (let attributeName of slotNode.getAttributeNames()) {
const value = slotNode.getAttribute(attributeName)!;
if (attributeName === "t-slot-scope") {
scope = value;
continue;
} else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else if (attributeName.startsWith("t-on-")) {
on = on || {};
on[attributeName.slice(5)] = value;
} else {
attrs = attrs || {};
attrs[attributeName] = value;
}
}
slots = slots || {};
slots[name] = { content: slotAst, on, attrs, attrsTranslationCtx, scope };
} }
// default slot
const defaultContent = parseChildNodes(clone, ctx);
slots = slots || {};
// t-set-slot="default" has priority over content
if (defaultContent && !slots.default) {
slots.default = {
content: defaultContent,
on,
attrs: null,
attrsTranslationCtx: null,
scope: defaultSlotScope,
};
}
} }
return { return { type: ASTType.TComponent, name, isDynamic, dynamicProps, props, body, on };
type: ASTType.TComponent,
name,
isDynamic,
dynamicProps,
props,
propsTranslationCtx,
slots,
on,
};
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -910,17 +757,12 @@ function parseTSlot(node: Element, ctx: ParsingContext): AST | null {
const name = node.getAttribute("t-slot")!; const name = node.getAttribute("t-slot")!;
node.removeAttribute("t-slot"); node.removeAttribute("t-slot");
let attrs: Attrs | null = null; let attrs: Attrs | null = null;
let attrsTranslationCtx: Attrs | null = null;
let on: ASTComponent["on"] = null; let on: ASTComponent["on"] = null;
for (let attributeName of node.getAttributeNames()) { for (let attributeName of node.getAttributeNames()) {
const value = node.getAttribute(attributeName)!; const value = node.getAttribute(attributeName)!;
if (attributeName.startsWith("t-on-")) { if (attributeName.startsWith("t-on-")) {
on = on || {}; on = on || {};
on[attributeName.slice(5)] = value; on[attributeName.slice(5)] = value;
} else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else { } else {
attrs = attrs || {}; attrs = attrs || {};
attrs[attributeName] = value; attrs[attributeName] = value;
@@ -930,22 +772,74 @@ function parseTSlot(node: Element, ctx: ParsingContext): AST | null {
type: ASTType.TSlot, type: ASTType.TSlot,
name, name,
attrs, attrs,
attrsTranslationCtx,
on, on,
defaultContent: parseChildNodes(node, ctx), defaultContent: parseChildNodes(node, ctx),
}; };
} }
// ----------------------------------------------------------------------------- function parseTSetSlot(node: Element, ctx: ParsingContext): AST | null {
// Translation if (!node.hasAttribute("t-set-slot")) {
// ----------------------------------------------------------------------------- return null;
function wrapInTTranslationAST(r: AST | null) {
const ast: ASTTranslation = { type: ASTType.TTranslation, content: r };
if (r?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
} }
return ast; // const t = el.ownerDocument.createElement("t");
// const clone = <Element>node.cloneNode(true);
// // named slots
// const slotNodes = Array.from(clone.querySelectorAll("[t-set-slot]"));
// for (let slotNode of slotNodes) {
if (node.tagName !== "t") {
throw new OwlError(
`Directive 't-set-slot' can only be used on <t> nodes (used on a <${node.tagName}>)`
);
}
const name = node.getAttribute("t-set-slot")!;
// // check if this is defined in a sub component (in which case it should
// // be ignored)
// let el = slotNode.parentElement!;
// let isInSubComponent = false;
// while (el !== clone) {
// if (el!.hasAttribute("t-component") || el!.tagName[0] === el!.tagName[0].toUpperCase()) {
// isInSubComponent = true;
// break;
// }
// el = el.parentElement!;
// }
// if (isInSubComponent) {
// continue;
// }
node.removeAttribute("t-set-slot");
node.remove();
const slotAst = parseNode(node, ctx);
let on: ASTSlotDefinition["on"] = null;
let attrs: Attrs | null = null;
let scope: string | null = null;
for (let attributeName of node.getAttributeNames()) {
const value = node.getAttribute(attributeName)!;
if (attributeName === "t-slot-scope") {
scope = value;
continue;
} else if (attributeName.startsWith("t-on-")) {
on = on || {};
on[attributeName.slice(5)] = value;
} else {
attrs = attrs || {};
attrs[attributeName] = value;
}
}
// slots = slots || {};
return { type: ASTType.TSetSlot, name, content: slotAst, on, attrs, scope };
// }
// // default slot
// const defaultContent = parseChildNodes(clone, ctx);
// slots = slots || {};
// // t-set-slot="default" has priority over content
// if (defaultContent && !slots.default) {
// slots.default = { content: defaultContent, on, attrs: null, scope: defaultSlotScope };
// }
} }
function parseTTranslation(node: Element, ctx: ParsingContext): AST | null { function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
@@ -953,42 +847,10 @@ function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
return null; return null;
} }
node.removeAttribute("t-translation"); node.removeAttribute("t-translation");
const result = parseNode(node, ctx); return {
if (result?.type === ASTType.Multi) { type: ASTType.TTranslation,
const children = result.content.map(wrapInTTranslationAST); content: parseNode(node, ctx),
return makeASTMulti(children);
}
return wrapInTTranslationAST(result);
}
// -----------------------------------------------------------------------------
// Translation Context
// -----------------------------------------------------------------------------
function wrapInTTranslationContextAST(r: AST | null, translationCtx: string) {
const ast: ASTTranslationContext = {
type: ASTType.TTranslationContext,
content: r,
translationCtx,
}; };
if (r?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
function parseTTranslationContext(node: Element, ctx: ParsingContext): AST | null {
const translationCtx = node.getAttribute("t-translation-context");
if (!translationCtx) {
return null;
}
node.removeAttribute("t-translation-context");
const result = parseNode(node, ctx);
if (result?.type === ASTType.Multi) {
const children = result.content.map((c) => wrapInTTranslationContextAST(c, translationCtx));
return makeASTMulti(children);
}
return wrapInTTranslationContextAST(result, translationCtx);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -1037,14 +899,6 @@ function parseChildren(node: Element, ctx: ParsingContext): AST[] {
return children; return children;
} }
function makeASTMulti(children: AST[]) {
const ast: ASTMulti = { type: ASTType.Multi, content: children };
if (children.every((c) => c.hasNoRepresentation)) {
ast.hasNoRepresentation = true;
}
return ast;
}
/** /**
* Parse all the child nodes of a given node and return an ast if possible. * Parse all the child nodes of a given node and return an ast if possible.
* In the case there are multiple children, they are wrapped in a astmulti. * In the case there are multiple children, they are wrapped in a astmulti.
@@ -1057,7 +911,7 @@ function parseChildNodes(node: Element, ctx: ParsingContext): AST | null {
case 1: case 1:
return children[0]; return children[0];
default: default:
return makeASTMulti(children); return { type: ASTType.Multi, content: children };
} }
} }
@@ -1114,23 +968,21 @@ function normalizeTIf(el: Element) {
* *
* @param el the element containing the tree that should be normalized * @param el the element containing the tree that should be normalized
*/ */
function normalizeTEscTOut(el: Element) { function normalizeTEsc(el: Element) {
for (const d of ["t-esc", "t-out"]) { const elements = [...el.querySelectorAll("[t-esc]")].filter(
const elements = [...el.querySelectorAll(`[${d}]`)].filter( (el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component")
(el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component") );
); for (const el of elements) {
for (const el of elements) { if (el.childNodes.length) {
if (el.childNodes.length) { throw new OwlError("Cannot have t-esc on a component that already has content");
throw new OwlError(`Cannot have ${d} on a component that already has content`);
}
const value = el.getAttribute(d);
el.removeAttribute(d);
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute(d, value);
}
el.appendChild(t);
} }
const value = el.getAttribute("t-esc");
el.removeAttribute("t-esc");
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute("t-esc", value);
}
el.appendChild(t);
} }
} }
@@ -1142,5 +994,42 @@ function normalizeTEscTOut(el: Element) {
*/ */
function normalizeXML(el: Element) { function normalizeXML(el: Element) {
normalizeTIf(el); normalizeTIf(el);
normalizeTEscTOut(el); normalizeTEsc(el);
}
/**
* Parses an XML string into an XML document, throwing errors on parser errors
* instead of returning an XML document containing the parseerror.
*
* @param xml the string to parse
* @returns an XML document corresponding to the content of the string
*/
function parseXML(xml: string): XMLDocument {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
if (doc.getElementsByTagName("parsererror").length) {
let msg = "Invalid XML in template.";
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
if (parsererrorText) {
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
const re = /\d+/g;
const firstMatch = re.exec(parsererrorText);
if (firstMatch) {
const lineNumber = Number(firstMatch[0]);
const line = xml.split("\n")[lineNumber - 1];
const secondMatch = re.exec(parsererrorText);
if (line && secondMatch) {
const columnIndex = Number(secondMatch[0]) - 1;
if (line[columnIndex]) {
msg +=
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
`${line}\n${"-".repeat(columnIndex - 1)}^`;
}
}
}
}
throw new OwlError(msg);
}
return doc;
} }
-89
View File
@@ -1,89 +0,0 @@
// -----------------------------------------------------------------------------
// This file exports a function that allows compiling templates ahead of time.
// It is used by the "compile_owl_template" command registered in the "bin"
// section of owl's package.json
// -----------------------------------------------------------------------------
import { readdir, readFile, stat } from "fs/promises";
import path from "path";
import "./setup_jsdom";
// Owl imports must be made after setting up jsdom in the global namespace
import { compile } from "..";
// -----------------------------------------------------------------------------
// helpers
// -----------------------------------------------------------------------------
async function getXmlFiles(paths: string[]): Promise<string[]> {
return (
await Promise.all(
paths.map(async (file) => {
const stats = await stat(path.join(file));
if (stats.isDirectory()) {
return await getXmlFiles(
(await readdir(file)).map((fileName) => path.join(file, fileName))
);
}
if (file.endsWith(".xml")) {
return file;
}
return [];
})
)
).flat();
}
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
const a = "·-_,:;";
const p = new RegExp(a.split("").join("|"), "g");
function slugify(str: string) {
return str
.replace(/\//g, "") // remove /
.replace(/\./g, "_") // Replace . with _
.replace(p, (c) => "_") // Replace special characters
.replace(/&/g, "_and_") // Replace & with and
.replace(/[^\w\-]+/g, ""); // Remove all non-word characters
}
// -----------------------------------------------------------------------------
// main
// -----------------------------------------------------------------------------
export async function compileTemplates(paths: string[]) {
const files = await getXmlFiles(paths);
process.stdout.write(`Processing ${files.length} files`);
let xmlStrings = await Promise.all(files.map((file) => readFile(file, "utf8")));
const templates = [];
const errors = [];
for (let i = 0; i < files.length; i++) {
const fileName = files[i];
const fileContent = xmlStrings[i];
process.stdout.write(`.`);
const parser = new DOMParser();
const doc = parser.parseFromString(fileContent, "text/xml");
for (const template of doc.querySelectorAll("[t-name]")) {
const name = template.getAttribute("t-name");
if (template.hasAttribute("owl")) {
template.removeAttribute("owl");
}
const fnName = slugify(name!);
try {
const fn = compile(template).toString().replace("anonymous", fnName);
templates.push(`"${name}": ${fn},\n`);
} catch (e) {
errors.push({ name, fileName, e });
}
}
}
process.stdout.write(`\n`);
for (let { name, fileName, e } of errors) {
console.warn(`Error while compiling '${name}' (in file ${fileName})`);
console.error(e);
}
console.log(`${templates.length} templates compiled`);
return `export const templates = {\n ${templates.join("\n")} \n}`;
}
-13
View File
@@ -1,13 +0,0 @@
import jsdom from "jsdom";
// -----------------------------------------------------------------------------
// add global DOM stuff for compiler. Needs to be in a separate file so rollup
// doesn't hoist the owl imports above this block of code.
// -----------------------------------------------------------------------------
var document = new jsdom.JSDOM("", {});
var window = document.window;
global.document = window.document;
global.window = window as unknown as Window & typeof globalThis;
global.DOMParser = window.DOMParser;
global.Element = window.Element;
global.Node = window.Node;
-2
View File
@@ -12,7 +12,5 @@ TemplateSet.prototype._compileTemplate = function _compileTemplate(
dev: this.dev, dev: this.dev,
translateFn: this.translateFn, translateFn: this.translateFn,
translatableAttributes: this.translatableAttributes, translatableAttributes: this.translatableAttributes,
customDirectives: this.customDirectives,
hasGlobalValues: this.hasGlobalValues,
}); });
}; };
+41 -104
View File
@@ -1,14 +1,11 @@
import { version } from "../version";
import { Component, ComponentConstructor, Props } from "./component"; import { Component, ComponentConstructor, Props } from "./component";
import { ComponentNode, saveCurrent } from "./component_node"; import { ComponentNode } from "./component_node";
import { nodeErrorHandlers, handleError } from "./error_handling"; import { nodeErrorHandlers, OwlError, handleError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { Fiber, RootFiber, MountOptions } from "./fibers"; import { Fiber, RootFiber, MountOptions } from "./fibers";
import { Scheduler } from "./scheduler"; import { Scheduler } from "./scheduler";
import { validateProps } from "./template_helpers"; import { validateProps } from "./template_helpers";
import { TemplateSet, TemplateSetConfig } from "./template_set"; import { TemplateSet, TemplateSetConfig } from "./template_set";
import { validateTarget } from "./utils"; import { validateTarget } from "./utils";
import { toRaw, reactive } from "./reactivity";
// reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f // reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f
@@ -16,20 +13,23 @@ export interface Env {
[key: string]: any; [key: string]: any;
} }
export interface RootConfig<P, E> { export interface AppConfig<P, E> extends TemplateSetConfig {
props?: P; props?: P;
env?: E; env?: E;
}
export interface AppConfig<P, E> extends TemplateSetConfig, RootConfig<P, E> {
name?: string;
test?: boolean; test?: boolean;
warnIfNoStaticProps?: boolean; warnIfNoStaticProps?: boolean;
} }
let hasBeenLogged = false; let hasBeenLogged = false;
const apps = new Set<App>(); export const DEV_MSG = () => {
const hash = (window as any).owl ? (window as any).owl.__info__.hash : "master";
return `Owl is running in 'dev' mode.
This is not suitable for production use.
See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration for more information.`;
};
declare global { declare global {
interface Window { interface Window {
@@ -37,19 +37,15 @@ declare global {
apps: Set<App>; apps: Set<App>;
Fiber: typeof Fiber; Fiber: typeof Fiber;
RootFiber: typeof RootFiber; RootFiber: typeof RootFiber;
toRaw: typeof toRaw;
reactive: typeof reactive;
}; };
} }
} }
interface Root<P extends Props, E> { window.__OWL_DEVTOOLS__ ||= {
node: ComponentNode<P, E>; apps: new Set<App>(),
mount(target: HTMLElement | ShadowRoot, options?: MountOptions): Promise<Component<P, E>>; Fiber: Fiber,
destroy(): void; RootFiber: RootFiber,
} };
window.__OWL_DEVTOOLS__ ||= { apps, Fiber, RootFiber, toRaw, reactive };
export class App< export class App<
T extends abstract new (...args: any) => any = any, T extends abstract new (...args: any) => any = any,
@@ -57,29 +53,24 @@ export class App<
E = any E = any
> extends TemplateSet { > extends TemplateSet {
static validateTarget = validateTarget; static validateTarget = validateTarget;
static apps = apps;
static version = version;
name: string;
Root: ComponentConstructor<P, E>; Root: ComponentConstructor<P, E>;
props: P; props: P;
env: E; env: E;
scheduler = new Scheduler(); scheduler = new Scheduler();
subRoots: Set<ComponentNode> = new Set();
root: ComponentNode<P, E> | null = null; root: ComponentNode<P, E> | null = null;
warnIfNoStaticProps: boolean; warnIfNoStaticProps: boolean;
constructor(Root: ComponentConstructor<P, E>, config: AppConfig<P, E> = {}) { constructor(Root: ComponentConstructor<P, E>, config: AppConfig<P, E> = {}) {
super(config); super(config);
this.name = config.name || "";
this.Root = Root; this.Root = Root;
apps.add(this); window.__OWL_DEVTOOLS__.apps.add(this);
if (config.test) { if (config.test) {
this.dev = true; this.dev = true;
} }
this.warnIfNoStaticProps = config.warnIfNoStaticProps || false; this.warnIfNoStaticProps = config.warnIfNoStaticProps || false;
if (this.dev && !config.test && !hasBeenLogged) { if (this.dev && !config.test && !hasBeenLogged) {
console.info(`Owl is running in 'dev' mode.`); console.info(DEV_MSG());
hasBeenLogged = true; hasBeenLogged = true;
} }
const env = config.env || {}; const env = config.env || {};
@@ -88,60 +79,22 @@ export class App<
this.props = config.props || ({} as P); this.props = config.props || ({} as P);
} }
mount( mount(target: HTMLElement, options?: MountOptions): Promise<Component<P, E> & InstanceType<T>> {
target: HTMLElement | ShadowRoot, App.validateTarget(target);
options?: MountOptions if (this.dev) {
): Promise<Component<P, E> & InstanceType<T>> { validateProps(this.Root, this.props, { __owl__: { app: this } });
const root = this.createRoot(this.Root, { props: this.props });
this.root = root.node;
this.subRoots.delete(root.node);
return root.mount(target, options) as any;
}
createRoot<Props extends object, SubEnv = any>(
Root: ComponentConstructor<Props, E>,
config: RootConfig<Props, SubEnv> = {}
): Root<Props, SubEnv> {
const props = config.props || ({} as Props);
// hack to make sure the sub root get the sub env if necessary. for owl 3,
// would be nice to rethink the initialization process to make sure that
// we can create a ComponentNode and give it explicitely the env, instead
// of looking it up in the app
const env = this.env;
if (config.env) {
this.env = config.env as any;
} }
const node = this.makeNode(this.Root, this.props);
const restore = saveCurrent(); const prom = this.mountNode(node, target, options);
const node = this.makeNode(Root, props); this.root = node;
restore(); return prom;
if (config.env) {
this.env = env;
}
this.subRoots.add(node);
return {
node,
mount: (target: HTMLElement | ShadowRoot, options?: MountOptions) => {
App.validateTarget(target);
if (this.dev) {
validateProps(Root, props, { __owl__: { app: this } });
}
const prom = this.mountNode(node, target, options);
return prom;
},
destroy: () => {
this.subRoots.delete(node);
node.destroy();
this.scheduler.processTasks();
},
};
} }
makeNode(Component: ComponentConstructor, props: any): ComponentNode { makeNode(Component: ComponentConstructor, props: any): ComponentNode {
return new ComponentNode(Component, props, this, null, null); return new ComponentNode(Component, props, this, null, null);
} }
mountNode(node: ComponentNode, target: HTMLElement | ShadowRoot, options?: MountOptions) { mountNode(node: ComponentNode, target: HTMLElement, options?: MountOptions) {
const promise: any = new Promise((resolve, reject) => { const promise: any = new Promise((resolve, reject) => {
let isResolved = false; let isResolved = false;
// manually set a onMounted callback. // manually set a onMounted callback.
@@ -170,13 +123,10 @@ export class App<
destroy() { destroy() {
if (this.root) { if (this.root) {
for (let subroot of this.subRoots) { this.scheduler.flush();
subroot.destroy();
}
this.root.destroy(); this.root.destroy();
this.scheduler.processTasks();
} }
apps.delete(this); window.__OWL_DEVTOOLS__.apps.delete(this);
} }
createComponent<P extends Props>( createComponent<P extends Props>(
@@ -184,35 +134,22 @@ export class App<
isStatic: boolean, isStatic: boolean,
hasSlotsProp: boolean, hasSlotsProp: boolean,
hasDynamicPropList: boolean, hasDynamicPropList: boolean,
propList: string[] hasNoProp: boolean
) { ) {
const isDynamic = !isStatic; const isDynamic = !isStatic;
let arePropsDifferent: (p1: Object, p2: Object) => boolean; function _arePropsDifferent(props1: Props, props2: Props): boolean {
const hasNoProp = propList.length === 0; for (let k in props1) {
if (hasSlotsProp) { if (props1[k] !== props2[k]) {
arePropsDifferent = (_1, _2) => true; return true;
} else if (hasDynamicPropList) {
arePropsDifferent = function (props1: Props, props2: Props) {
for (let k in props1) {
if (props1[k] !== props2[k]) {
return true;
}
} }
return Object.keys(props1).length !== Object.keys(props2).length; }
}; return hasDynamicPropList && Object.keys(props1).length !== Object.keys(props2).length;
} else if (hasNoProp) {
arePropsDifferent = (_1: any, _2: any) => false;
} else {
arePropsDifferent = function (props1: Props, props2: Props) {
for (let p of propList) {
if (props1[p] !== props2[p]) {
return true;
}
}
return false;
};
} }
const arePropsDifferent = hasSlotsProp
? (_1: any, _2: any) => true
: hasNoProp
? (_1: any, _2: any) => false
: _arePropsDifferent;
const updateAndRender = ComponentNode.prototype.updateAndRender; const updateAndRender = ComponentNode.prototype.updateAndRender;
const initiateRender = ComponentNode.prototype.initiateRender; const initiateRender = ComponentNode.prototype.initiateRender;
+35 -25
View File
@@ -36,18 +36,10 @@ export function createAttrUpdater(attr: string): Setter<HTMLElement> {
export function attrsSetter(this: HTMLElement, attrs: any) { export function attrsSetter(this: HTMLElement, attrs: any) {
if (isArray(attrs)) { if (isArray(attrs)) {
if (attrs[0] === "class") { setAttribute.call(this, attrs[0], attrs[1]);
setClass.call(this, attrs[1]);
} else {
setAttribute.call(this, attrs[0], attrs[1]);
}
} else { } else {
for (let k in attrs) { for (let k in attrs) {
if (k === "class") { setAttribute.call(this, k, attrs[k]);
setClass.call(this, attrs[k]);
} else {
setAttribute.call(this, k, attrs[k]);
}
} }
} }
} }
@@ -60,11 +52,7 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
if (val === oldAttrs[1]) { if (val === oldAttrs[1]) {
return; return;
} }
if (name === "class") { setAttribute.call(this, name, val);
updateClass.call(this, val, oldAttrs[1]);
} else {
setAttribute.call(this, name, val);
}
} else { } else {
removeAttribute.call(this, oldAttrs[0]); removeAttribute.call(this, oldAttrs[0]);
setAttribute.call(this, name, val); setAttribute.call(this, name, val);
@@ -72,21 +60,13 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
} else { } else {
for (let k in oldAttrs) { for (let k in oldAttrs) {
if (!(k in attrs)) { if (!(k in attrs)) {
if (k === "class") { removeAttribute.call(this, k);
updateClass.call(this, "", oldAttrs[k]);
} else {
removeAttribute.call(this, k);
}
} }
} }
for (let k in attrs) { for (let k in attrs) {
const val = attrs[k]; const val = attrs[k];
if (val !== oldAttrs[k]) { if (val !== oldAttrs[k]) {
if (k === "class") { setAttribute.call(this, k, val);
updateClass.call(this, val, oldAttrs[k]);
} else {
setAttribute.call(this, k, val);
}
} }
} }
} }
@@ -160,3 +140,33 @@ export function updateClass(this: HTMLElement, val: any, oldVal: any) {
} }
} }
} }
export function makePropSetter(name: string): Setter<HTMLElement> {
return function setProp(this: HTMLElement, value: any) {
// support 0, fallback to empty string for other falsy values
(this as any)[name] = value === 0 ? 0 : value ? value.valueOf() : "";
};
}
export function isProp(tag: string, key: string): boolean {
switch (tag) {
case "input":
return (
key === "checked" ||
key === "indeterminate" ||
key === "value" ||
key === "readonly" ||
key === "disabled"
);
case "option":
return key === "selected" || key === "disabled";
case "textarea":
return key === "value" || key === "readonly" || key === "disabled";
case "select":
return key === "value" || key === "disabled";
case "button":
case "optgroup":
return key === "disabled";
}
return false;
}
+22 -32
View File
@@ -1,5 +1,13 @@
import { OwlError } from "../../common/owl_error"; import { OwlError } from "../error_handling";
import { attrsSetter, attrsUpdater, createAttrUpdater, setClass, updateClass } from "./attributes"; import {
attrsSetter,
attrsUpdater,
createAttrUpdater,
isProp,
makePropSetter,
setClass,
updateClass,
} from "./attributes";
import { config } from "./config"; import { config } from "./config";
import { createEventHandler } from "./events"; import { createEventHandler } from "./events";
import type { VNode } from "./index"; import type { VNode } from "./index";
@@ -17,13 +25,6 @@ const nodeGetNextSibling = getDescriptor(nodeProto, "nextSibling").get!;
const NO_OP = () => {}; const NO_OP = () => {};
function makePropSetter(name: string): Setter<HTMLElement> {
return function setProp(this: HTMLElement, value: any) {
// support 0, fallback to empty string for other falsy values
(this as any)[name] = value === 0 ? 0 : value ? value.valueOf() : "";
};
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Main compiler code // Main compiler code
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -100,7 +101,7 @@ function normalizeNode(node: HTMLElement | Text) {
interface DynamicInfo { interface DynamicInfo {
idx: number; idx: number;
refIdx?: number; refIdx?: number;
type: "text" | "child" | "handler" | "attribute" | "attributes" | "property" | "ref"; type: "text" | "child" | "handler" | "attribute" | "attributes" | "ref";
isOnlyChild?: boolean; isOnlyChild?: boolean;
name?: string; name?: string;
tag?: string; tag?: string;
@@ -144,7 +145,12 @@ function buildTree(
info.push({ type: "child", idx: index }); info.push({ type: "child", idx: index });
el = document.createTextNode(""); el = document.createTextNode("");
} }
currentNS ||= (node as Element).namespaceURI; const attrs = (node as Element).attributes;
const ns = attrs.getNamedItem("block-ns");
if (ns) {
attrs.removeNamedItem("block-ns");
currentNS = ns.value;
}
if (!el) { if (!el) {
el = currentNS el = currentNS
? document.createElementNS(currentNS, tagName) ? document.createElementNS(currentNS, tagName)
@@ -160,7 +166,6 @@ function buildTree(
const fragment = document.createElement("template").content; const fragment = document.createElement("template").content;
fragment.appendChild(el); fragment.appendChild(el);
} }
const attrs = (node as Element).attributes;
for (let i = 0; i < attrs.length; i++) { for (let i = 0; i < attrs.length; i++) {
const attrName = attrs[i].name; const attrName = attrs[i].name;
const attrValue = attrs[i].value; const attrValue = attrs[i].value;
@@ -179,14 +184,6 @@ function buildTree(
name: attrValue, name: attrValue,
tag: tagName, tag: tagName,
}); });
} else if (attrName.startsWith("block-property-")) {
const idx = parseInt(attrName.slice(15), 10);
info.push({
type: "property",
idx,
name: attrValue,
tag: tagName,
});
} else if (attrName === "block-attributes") { } else if (attrName === "block-attributes") {
info.push({ info.push({
type: "attributes", type: "attributes",
@@ -380,22 +377,15 @@ function updateCtx(ctx: BlockCtx, tree: IntermediateTree) {
}; };
} }
break; break;
case "property": {
const refIdx = info.refIdx!;
const setProp = makePropSetter(info.name!);
ctx.locations.push({
idx: info.idx,
refIdx,
setData: setProp,
updateData: setProp,
});
break;
}
case "attribute": { case "attribute": {
const refIdx = info.refIdx!; const refIdx = info.refIdx!;
let updater: any; let updater: any;
let setter: any; let setter: any;
if (info.name === "class") { if (isProp(info.tag!, info.name!)) {
const setProp = makePropSetter(info.name!);
setter = setProp;
updater = setProp;
} else if (info.name === "class") {
setter = setClass; setter = setClass;
updater = updateClass; updater = updateClass;
} else { } else {
+1 -2
View File
@@ -1,4 +1,3 @@
import { inOwnerDocument } from "../utils";
import { config } from "./config"; import { config } from "./config";
type EventHandlerSetter = (this: HTMLElement, data: any) => void; type EventHandlerSetter = (this: HTMLElement, data: any) => void;
@@ -29,7 +28,7 @@ function createElementHandler(evName: string, capture: boolean = false): EventHa
function listener(ev: Event) { function listener(ev: Event) {
const currentTarget = ev.currentTarget as HTMLElement; const currentTarget = ev.currentTarget as HTMLElement;
if (!currentTarget || !inOwnerDocument(currentTarget)) return; if (!currentTarget || !currentTarget.ownerDocument.contains(currentTarget)) return;
const data = (currentTarget as any)[eventKey]; const data = (currentTarget as any)[eventKey];
if (!data) return; if (!data) return;
config.mainEventHandler(data, ev, currentTarget); config.mainEventHandler(data, ev, currentTarget);
-46
View File
@@ -1,46 +0,0 @@
export type TaskContext = { isCancelled: boolean; cancel: () => void; meta: Record<string, any> };
export const taskContextStack: TaskContext[] = [];
export function getTaskContext() {
return taskContextStack[taskContextStack.length - 1];
}
export function makeTaskContext(): TaskContext {
let isCancelled = false;
return {
get isCancelled() {
return isCancelled;
},
cancel() {
isCancelled = true;
},
meta: {},
};
}
export function useTaskContext(ctx?: TaskContext) {
ctx ??= makeTaskContext();
taskContextStack.push(ctx);
return {
ctx,
cleanup: () => {
taskContextStack.pop();
},
};
}
export function pushTaskContext(context: TaskContext) {
taskContextStack.push(context);
}
export function popTaskContext() {
taskContextStack.pop();
}
export function taskEffect(fn: Function) {
const { ctx, cleanup } = useTaskContext();
fn();
cleanup();
return ctx;
}
+1 -1
View File
@@ -23,7 +23,7 @@ export type ComponentConstructor<P extends Props = any, E = any> = (new (
export class Component<Props = any, Env = any> { export class Component<Props = any, Env = any> {
static template: string = ""; static template: string = "";
static props?: Schema; static props?: any;
static defaultProps?: any; static defaultProps?: any;
props: Props; props: Props;
+36 -88
View File
@@ -1,23 +1,14 @@
import { OwlError } from "../common/owl_error";
import { Atom, ExecutionContext } from "../common/types";
import type { App, Env } from "./app"; import type { App, Env } from "./app";
import { BDom, VNode } from "./blockdom"; import { BDom, VNode } from "./blockdom";
import { makeTaskContext, TaskContext } from "./cancellableContext";
import { Component, ComponentConstructor, Props } from "./component"; import { Component, ComponentConstructor, Props } from "./component";
import { fibersInError } from "./error_handling"; import { fibersInError, OwlError } from "./error_handling";
import { Fiber, makeChildFiber, makeRootFiber, MountFiber, MountOptions } from "./fibers"; import { Fiber, makeChildFiber, makeRootFiber, MountFiber, MountOptions } from "./fibers";
import { addAtomToContext, reactive, targets, withoutReactivity } from "./reactivity"; import { clearReactivesForCallback, getSubscriptions, reactive, targets } from "./reactivity";
import { STATUS } from "./status"; import { STATUS } from "./status";
import { batched, Callback } from "./utils";
let currentNode: ComponentNode | null = null; let currentNode: ComponentNode | null = null;
export function saveCurrent() {
let n = currentNode;
return () => {
currentNode = n;
};
}
export function getCurrent(): ComponentNode { export function getCurrent(): ComponentNode {
if (!currentNode) { if (!currentNode) {
throw new OwlError("No active component (a hook function should only be called in 'setup')"); throw new OwlError("No active component (a hook function should only be called in 'setup')");
@@ -43,7 +34,7 @@ function applyDefaultProps<P extends object>(props: P, defaultProps: Partial<P>)
// Integration with reactivity system (useState) // Integration with reactivity system (useState)
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// const batchedRenderFunctions = new WeakMap<ComponentNode, Callback>(); const batchedRenderFunctions = new WeakMap<ComponentNode, Callback>();
/** /**
* Creates a reactive object that will be observed by the current component. * Creates a reactive object that will be observed by the current component.
* Reading data from the returned object (eg during rendering) will cause the * Reading data from the returned object (eg during rendering) will cause the
@@ -55,7 +46,15 @@ function applyDefaultProps<P extends object>(props: P, defaultProps: Partial<P>)
* @see reactive * @see reactive
*/ */
export function useState<T extends object>(state: T): T { export function useState<T extends object>(state: T): T {
return reactive(state); const node = getCurrent();
let render = batchedRenderFunctions.get(node)!;
if (!render) {
render = batched(node.render.bind(node, false));
batchedRenderFunctions.set(node, render);
// manual implementation of onWillDestroy to break cyclic dependency
node.willDestroy.push(clearReactivesForCallback.bind(null, render));
}
return reactive(state, render);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -74,7 +73,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
forceNextRender: boolean = false; forceNextRender: boolean = false;
parentKey: string | null; parentKey: string | null;
props: P; props: P;
nextProps: P | null = null;
renderFn: Function; renderFn: Function;
parent: ComponentNode | null; parent: ComponentNode | null;
@@ -89,8 +87,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
willPatch: LifecycleHook[] = []; willPatch: LifecycleHook[] = [];
patched: LifecycleHook[] = []; patched: LifecycleHook[] = [];
willDestroy: LifecycleHook[] = []; willDestroy: LifecycleHook[] = [];
taskContext: TaskContext;
executionContext: ExecutionContext;
constructor( constructor(
C: ComponentConstructor<P, E>, C: ComponentConstructor<P, E>,
@@ -104,15 +100,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
this.parent = parent; this.parent = parent;
this.props = props; this.props = props;
this.parentKey = parentKey; this.parentKey = parentKey;
this.taskContext = makeTaskContext();
this.executionContext = {
meta: this,
update: () => {
this.render(false);
},
onReadAtom: (atom: Atom) => addAtomToContext(atom, this.executionContext),
atoms: new Set<Atom>(),
};
const defaultProps = C.defaultProps; const defaultProps = C.defaultProps;
props = Object.assign({}, props); props = Object.assign({}, props);
if (defaultProps) { if (defaultProps) {
@@ -120,18 +107,16 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
const env = (parent && parent.childEnv) || app.env; const env = (parent && parent.childEnv) || app.env;
this.childEnv = env; this.childEnv = env;
// for (const key in props) { for (const key in props) {
// const prop = props[key]; const prop = props[key];
// if (prop && typeof prop === "object" && targets.has(prop)) { if (prop && typeof prop === "object" && targets.has(prop)) {
// props[key] = useState(prop); props[key] = useState(prop);
// } }
// } }
this.component = new C(props, env, this); this.component = new C(props, env, this);
const ctx = Object.assign(Object.create(this.component), { this: this.component }); const ctx = Object.assign(Object.create(this.component), { this: this.component });
this.renderFn = app.getTemplate(C.template).bind(this.component, ctx, this); this.renderFn = app.getTemplate(C.template).bind(this.component, ctx, this);
withoutReactivity(() => { this.component.setup();
this.component.setup();
});
currentNode = null; currentNode = null;
} }
@@ -148,11 +133,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
const component = this.component; const component = this.component;
try { try {
let prom: Promise<any[]>; await Promise.all(this.willStart.map((f) => f.call(component)));
withoutReactivity(() => {
prom = Promise.all(this.willStart.map((f) => f.call(component)));
});
await prom!;
} catch (e) { } catch (e) {
this.app.handleError({ node: this, error: e }); this.app.handleError({ node: this, error: e });
return; return;
@@ -163,9 +144,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
async render(deep: boolean) { async render(deep: boolean) {
if (this.status >= STATUS.CANCELLED) {
return;
}
let current = this.fiber; let current = this.fiber;
if (current && (current.root!.locked || (current as any).bdom === true)) { if (current && (current.root!.locked || (current as any).bdom === true)) {
await Promise.resolve(); await Promise.resolve();
@@ -192,7 +170,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
this.app.scheduler.addFiber(fiber); this.app.scheduler.addFiber(fiber);
await Promise.resolve(); await Promise.resolve();
if (this.status >= STATUS.CANCELLED) { if (this.status === STATUS.DESTROYED) {
return; return;
} }
// We only want to actually render the component if the following two // We only want to actually render the component if the following two
@@ -211,20 +189,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
} }
cancel() {
this._cancel();
delete this.parent!.children[this.parentKey!];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = STATUS.CANCELLED;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() { destroy() {
let shouldRemove = this.status === STATUS.MOUNTED; let shouldRemove = this.status === STATUS.MOUNTED;
this._destroy(); this._destroy();
@@ -256,7 +220,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
async updateAndRender(props: P, parentFiber: Fiber) { async updateAndRender(props: P, parentFiber: Fiber) {
this.nextProps = props; const rawProps = props;
props = Object.assign({}, props); props = Object.assign({}, props);
// update // update
const fiber = makeChildFiber(this, parentFiber); const fiber = makeChildFiber(this, parentFiber);
@@ -268,22 +232,20 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
currentNode = this; currentNode = this;
// for (const key in props) { for (const key in props) {
// const prop = props[key]; const prop = props[key];
// if (prop && typeof prop === "object" && targets.has(prop)) { if (prop && typeof prop === "object" && targets.has(prop)) {
// props[key] = useState(prop); props[key] = useState(prop);
// } }
// } }
currentNode = null; currentNode = null;
let prom: Promise<any[]>; const prom = Promise.all(this.willUpdateProps.map((f) => f.call(component, props)));
withoutReactivity(() => { await prom;
prom = Promise.all(this.willUpdateProps.map((f) => f.call(component, props)));
});
await prom!;
if (fiber !== this.fiber) { if (fiber !== this.fiber) {
return; return;
} }
component.props = props; component.props = props;
this.props = rawProps;
fiber.render(); fiber.render();
const parentRoot = parentFiber.root!; const parentRoot = parentFiber.root!;
if (this.willPatch.length) { if (this.willPatch.length) {
@@ -319,19 +281,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
} }
} }
/**
* Sets a ref to a given HTMLElement.
*
* @param name the name of the ref to set
* @param el the HTMLElement to set the ref to. The ref is not set if the el
* is null, but useRef will not return elements that are not in the DOM
*/
setRef(name: string, el: HTMLElement | null) {
if (el) {
this.refs[name] = el;
}
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Block DOM methods // Block DOM methods
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -365,7 +314,6 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
// by the component will be patched independently in the appropriate // by the component will be patched independently in the appropriate
// fiber.complete // fiber.complete
this._patch(); this._patch();
this.props = this.nextProps!;
} }
} }
_patch() { _patch() {
@@ -397,8 +345,8 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
return this.component.constructor.name; return this.component.constructor.name;
} }
// get subscriptions(): ReturnType<typeof getSubscriptions> { get subscriptions(): ReturnType<typeof getSubscriptions> {
// const render = batchedRenderFunctions.get(this); const render = batchedRenderFunctions.get(this);
// return render ? getSubscriptions(render) : []; return render ? getSubscriptions(render) : [];
// } }
} }

Some files were not shown because too many files have changed in this diff Show More