Compare commits

..

1 Commits

Author SHA1 Message Date
Samuel Degueldre b04013f82f [IMP] reactivity: add support for derived properties 2024-03-19 13:48:08 +01:00
108 changed files with 6734 additions and 11396 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
-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
-31
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
@@ -66,9 +65,6 @@ The `config` object is an object with some of the following keys:
needs a template. If undefined is returned, owl looks into the app templates. 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 +92,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
+2 -25
View File
@@ -140,28 +140,6 @@ class SomeComponent extends Component {
The `.bind` suffix also implies `.alike`, so these props will not cause additional The `.bind` suffix also implies `.alike`, so these props will not cause additional
renderings. 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:
@@ -260,7 +238,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,8 +276,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: { someObj3: {
type: Object, type: Object,
values: { type: Array, element: String }, values: { type: Array, element: String },
+1 -1
View File
@@ -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
+4 -5
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}}" />
@@ -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
+11 -44
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
@@ -592,35 +588,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
```
-16
View File
@@ -82,22 +82,6 @@ in the sources tab as well.
<img src="screenshots/function_menu.png"/> <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 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 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. component's name. Using the left click on the component's name will focus it in the components tree.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 KiB

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 193 KiB

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 188 KiB

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 346 KiB

After

Width:  |  Height:  |  Size: 536 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 177 KiB

+87 -303
View File
@@ -1625,13 +1625,6 @@ function makeRootFiber(node) {
fibersInError.delete(current); fibersInError.delete(current);
fibersInError.delete(root); fibersInError.delete(root);
current.appliedToDom = false; current.appliedToDom = false;
if (current instanceof RootFiber) {
// it is possible that this fiber is a fiber that crashed while being
// mounted, so the mounted list is possibly corrupted. We restore it to
// its normal initial state (which is empty list or a list with a mount
// fiber.
current.mounted = current instanceof MountFiber ? [current] : [];
}
} }
return current; return current;
} }
@@ -1748,7 +1741,6 @@ class RootFiber extends Fiber {
const node = this.node; const node = this.node;
this.locked = true; this.locked = true;
let current = undefined; let current = undefined;
let mountedFibers = this.mounted;
try { try {
// Step 1: calling all willPatch lifecycle hooks // Step 1: calling all willPatch lifecycle hooks
for (current of this.willPatch) { for (current of this.willPatch) {
@@ -1768,6 +1760,7 @@ class RootFiber extends Fiber {
node._patch(); node._patch();
this.locked = false; this.locked = false;
// Step 4: calling all mounted lifecycle hooks // Step 4: calling all mounted lifecycle hooks
let mountedFibers = this.mounted;
while ((current = mountedFibers.pop())) { while ((current = mountedFibers.pop())) {
current = current; current = current;
if (current.appliedToDom) { if (current.appliedToDom) {
@@ -1788,15 +1781,6 @@ class RootFiber extends Fiber {
} }
} }
catch (e) { catch (e) {
// if mountedFibers is not empty, this means that a crash occured while
// calling the mounted hooks of some component. So, there may still be
// some component that have been mounted, but for which the mounted hooks
// have not been called. Here, we remove the willUnmount hooks for these
// specific component to prevent a worse situation (willUnmount being
// called even though mounted has not been called)
for (let fiber of mountedFibers) {
fiber.node.willUnmount = [];
}
this.locked = false; this.locked = false;
node.app.handleError({ fiber: current || this, error: e }); node.app.handleError({ fiber: current || this, error: e });
} }
@@ -2286,12 +2270,6 @@ function collectionsProxyHandler(target, callback, targetRawType) {
} }
let currentNode = null; let currentNode = null;
function saveCurrent() {
let n = currentNode;
return () => {
currentNode = n;
};
}
function getCurrent() { function getCurrent() {
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')");
@@ -2620,47 +2598,42 @@ class ComponentNode {
} }
const TIMEOUT = Symbol("timeout"); const TIMEOUT = Symbol("timeout");
const HOOK_TIMEOUT = {
onWillStart: 3000,
onWillUpdateProps: 3000,
};
function wrapError(fn, hookName) { function wrapError(fn, hookName) {
const error = new OwlError(); const error = new OwlError(`The following error occurred in ${hookName}: `);
const timeoutError = new OwlError(); const timeoutError = new OwlError(`${hookName}'s promise hasn't resolved after 3 seconds`);
const node = getCurrent(); const node = getCurrent();
return (...args) => { return (...args) => {
const onError = (cause) => { const onError = (cause) => {
error.cause = cause; error.cause = cause;
error.message = if (cause instanceof Error) {
cause instanceof Error error.message += `"${cause.message}"`;
? `The following error occurred in ${hookName}: "${cause.message}"` }
: `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`; else {
error.message = `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`;
}
throw error; throw error;
}; };
let result;
try { try {
result = fn(...args); const result = fn(...args);
if (result instanceof Promise) {
if (hookName === "onWillStart" || hookName === "onWillUpdateProps") {
const fiber = node.fiber;
Promise.race([
result.catch(() => { }),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), 3000)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber) {
console.warn(timeoutError);
}
});
}
return result.catch(onError);
}
return result;
} }
catch (cause) { catch (cause) {
onError(cause); onError(cause);
} }
if (!(result instanceof Promise)) {
return result;
}
const timeout = HOOK_TIMEOUT[hookName];
if (timeout) {
const fiber = node.fiber;
Promise.race([
result.catch(() => { }),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), timeout)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber && node.status <= 2) {
timeoutError.message = `${hookName}'s promise hasn't resolved after ${timeout / 1000} seconds`;
console.log(timeoutError);
}
});
}
return result.catch(onError);
}; };
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -3243,9 +3216,6 @@ class TemplateSet {
} }
} }
this.getRawTemplate = config.getTemplate; this.getRawTemplate = config.getTemplate;
this.customDirectives = config.customDirectives || {};
this.runtimeUtils = { ...helpers, __globals__: config.globalValues || {} };
this.hasGlobalValues = Boolean(config.globalValues && Object.keys(config.globalValues).length);
} }
static registerTemplate(name, fn) { static registerTemplate(name, fn) {
globalTemplates[name] = fn; globalTemplates[name] = fn;
@@ -3302,7 +3272,7 @@ class TemplateSet {
this.templates[name] = function (context, parent) { this.templates[name] = function (context, parent) {
return templates[name].call(this, context, parent); return templates[name].call(this, context, parent);
}; };
const template = templateFn(this, bdom, this.runtimeUtils); const template = templateFn(this, bdom, helpers);
this.templates[name] = template; this.templates[name] = template;
} }
return this.templates[name]; return this.templates[name];
@@ -3353,7 +3323,7 @@ TemplateSet.registerTemplate("__portal__", portalTemplate);
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Misc types, constants and helpers // Misc types, constants and helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
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(","); const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,eval,void,Math,RegExp,Array,Object,Date".split(",");
const WORD_REPLACEMENT = Object.assign(Object.create(null), { const WORD_REPLACEMENT = Object.assign(Object.create(null), {
and: "&&", and: "&&",
or: "||", or: "||",
@@ -3542,7 +3512,7 @@ function compileExprToArray(expr) {
const localVars = new Set(); const localVars = new Set();
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];
let prevToken = tokens[i - 1]; let prevToken = tokens[i - 1];
@@ -3551,12 +3521,10 @@ function compileExprToArray(expr) {
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();
} }
let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value); let isVar = token.type === "SYMBOL" && !RESERVED_WORDS.includes(token.value);
@@ -3668,13 +3636,6 @@ function isProp(tag, key) {
} }
return false; return false;
} }
/**
* Returns a template literal that evaluates to str. You can add interpolation
* sigils into the string if required
*/
function toStringExpression(str) {
return `\`${str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${")}\``;
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// BlockDescription // BlockDescription
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -3738,7 +3699,6 @@ function createContext(parentCtx, params) {
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,
@@ -3826,9 +3786,6 @@ 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() { generateCode() {
const ast = this.ast; const ast = this.ast;
@@ -3841,7 +3798,6 @@ 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
@@ -3860,14 +3816,15 @@ 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}\`);`);
} }
} }
} }
@@ -3979,9 +3936,9 @@ class CodeGenerator {
}) })
.join(""); .join("");
} }
translate(str, translationCtx) { translate(str) {
const match = translationRE.exec(str); const match = translationRE.exec(str);
return match[1] + this.translateFn(match[2], translationCtx) + match[3]; return match[1] + this.translateFn(match[2]) + match[3];
} }
/** /**
* @returns the newly created block name, if any * @returns the newly created block name, if any
@@ -4022,9 +3979,7 @@ class CodeGenerator {
return this.compileTSlot(ast, ctx); return this.compileTSlot(ast, ctx);
case 16 /* TTranslation */: case 16 /* TTranslation */:
return this.compileTTranslation(ast, ctx); return this.compileTTranslation(ast, ctx);
case 17 /* TTranslationContext */: case 17 /* TPortal */:
return this.compileTTranslationContext(ast, ctx);
case 18 /* TPortal */:
return this.compileTPortal(ast, ctx); return this.compileTPortal(ast, ctx);
} }
} }
@@ -4047,7 +4002,7 @@ 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,
}); });
@@ -4062,14 +4017,14 @@ class CodeGenerator {
let { block, forceNewBlock } = ctx; let { block, forceNewBlock } = ctx;
let value = ast.value; let value = ast.value;
if (value && ctx.translate !== false) { if (value && ctx.translate !== false) {
value = this.translate(value, ctx.translationCtx); value = this.translate(value);
} }
if (!ctx.inPreTag) { if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " "); 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,
}); });
@@ -4097,7 +4052,6 @@ class CodeGenerator {
return `[${modifiersCode}${this.captureExpression(handler)}, ctx]`; return `[${modifiersCode}${this.captureExpression(handler)}, ctx]`;
} }
compileTDomNode(ast, ctx) { compileTDomNode(ast, ctx) {
var _a;
let { block, forceNewBlock } = ctx; let { block, forceNewBlock } = ctx;
const isNewBlock = !block || forceNewBlock || ast.dynamicTag !== null || ast.ns; const isNewBlock = !block || forceNewBlock || ast.dynamicTag !== null || ast.ns;
let codeIdx = this.target.code.length; let codeIdx = this.target.code.length;
@@ -4153,8 +4107,7 @@ class CodeGenerator {
} }
} }
else if (this.translatableAttributes.includes(key)) { else if (this.translatableAttributes.includes(key)) {
const attrTranslationCtx = ((_a = ast.attrsTranslationCtx) === null || _a === void 0 ? void 0 : _a[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]}"`;
@@ -4292,8 +4245,7 @@ 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) {
@@ -4546,7 +4498,7 @@ class CodeGenerator {
this.addLine(`${ctxVar}[zero] = ${bl};`); this.addLine(`${ctxVar}[zero] = ${bl};`);
} }
} }
const key = this.generateComponentKey(); 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")) {
@@ -4598,12 +4550,12 @@ class CodeGenerator {
else { else {
let value; let value;
if (ast.defaultValue) { if (ast.defaultValue) {
const defaultValue = toStringExpression(ctx.translate ? this.translate(ast.defaultValue, ctx.translationCtx) : ast.defaultValue); const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
if (ast.value) { if (ast.value) {
value = `withDefault(${expr}, ${defaultValue})`; value = `withDefault(${expr}, \`${defaultValue}\`)`;
} }
else { else {
value = defaultValue; value = `\`${defaultValue}\``;
} }
} }
else { else {
@@ -4614,12 +4566,12 @@ class CodeGenerator {
} }
return null; return null;
} }
generateComponentKey(currentKey = "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("__");
} }
/** /**
* Formats a prop name and value into a string suitable to be inserted in the * Formats a prop name and value into a string suitable to be inserted in the
@@ -4632,14 +4584,8 @@ 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(name, value, attrsTranslationCtx, translationCtx) { formatProp(name, value) {
if (name.endsWith(".translate")) { value = this.captureExpression(value);
const attrTranslationCtx = (attrsTranslationCtx === null || attrsTranslationCtx === void 0 ? void 0 : 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; name = _name;
@@ -4648,17 +4594,16 @@ class CodeGenerator {
value = `(${value}).bind(this)`; value = `(${value}).bind(this)`;
break; break;
case "alike": case "alike":
case "translate":
break; break;
default: default:
throw new OwlError(`Invalid prop suffix: ${suffix}`); throw new OwlError("Invalid prop 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(obj, attrsTranslationCtx, translationCtx) { formatPropObject(obj) {
return Object.entries(obj).map(([k, v]) => this.formatProp(k, v, attrsTranslationCtx, translationCtx)); return Object.entries(obj).map(([k, v]) => this.formatProp(k, v));
} }
getPropString(props, dynProps) { getPropString(props, dynProps) {
let propString = `{${props.join(",")}}`; let propString = `{${props.join(",")}}`;
@@ -4671,9 +4616,7 @@ class CodeGenerator {
let { block } = ctx; let { block } = ctx;
// props // props
const hasSlotsProp = "slots" in (ast.props || {}); const hasSlotsProp = "slots" in (ast.props || {});
const props = ast.props const props = ast.props ? this.formatPropObject(ast.props) : [];
? this.formatPropObject(ast.props, ast.propsTranslationCtx, ctx.translationCtx)
: [];
// slots // slots
let slotDef = ""; let slotDef = "";
if (ast.slots) { if (ast.slots) {
@@ -4696,7 +4639,7 @@ class CodeGenerator {
params.push(`__scope: "${scope}"`); params.push(`__scope: "${scope}"`);
} }
if (ast.slots[slotName].attrs) { if (ast.slots[slotName].attrs) {
params.push(...this.formatPropObject(ast.slots[slotName].attrs, ast.slots[slotName].attrsTranslationCtx, ctx.translationCtx)); params.push(...this.formatPropObject(ast.slots[slotName].attrs));
} }
const slotInfo = `{${params.join(", ")}}`; const slotInfo = `{${params.join(", ")}}`;
slotStr.push(`'${slotName}': ${slotInfo}`); slotStr.push(`'${slotName}': ${slotInfo}`);
@@ -4719,6 +4662,7 @@ class CodeGenerator {
this.addLine(`${propVar}.slots = markRaw(Object.assign(${slotDef}, ${propVar}.slots))`); this.addLine(`${propVar}.slots = markRaw(Object.assign(${slotDef}, ${propVar}.slots))`);
} }
// cmap key // cmap key
const key = this.generateComponentKey();
let expr; let expr;
if (ast.isDynamic) { if (ast.isDynamic) {
expr = generateId("Comp"); expr = generateId("Comp");
@@ -4734,7 +4678,7 @@ class CodeGenerator {
// todo: check the forcenewblock condition // todo: check the forcenewblock condition
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}`;
} }
@@ -4807,11 +4751,9 @@ class CodeGenerator {
} }
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(ast.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);
@@ -4844,18 +4786,13 @@ class CodeGenerator {
} }
return null; return null;
} }
compileTTranslationContext(ast, ctx) {
if (ast.content) {
return this.compileAST(ast.content, Object.assign({}, ctx, { translationCtx: ast.translationCtx }));
}
return null;
}
compileTPortal(ast, ctx) { compileTPortal(ast, ctx) {
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` });
} }
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");
@@ -4868,8 +4805,7 @@ class CodeGenerator {
expr: `app.createComponent(null, false, true, false, false)`, expr: `app.createComponent(null, false, true, false, false)`,
}); });
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);
} }
@@ -4883,33 +4819,29 @@ class CodeGenerator {
// Parser // Parser
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
const cache = new WeakMap(); const cache = new WeakMap();
function parse(xml, customDir) { function parse(xml) {
const ctx = {
inPreTag: false,
customDirectives: customDir,
};
if (typeof xml === "string") { if (typeof xml === "string") {
const elem = parseXML(`<t>${xml}</t>`).firstChild; const elem = parseXML(`<t>${xml}</t>`).firstChild;
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), ctx); ast = _parse(xml.cloneNode(true));
cache.set(xml, ast); cache.set(xml, ast);
} }
return ast; return ast;
} }
function _parse(xml, ctx) { function _parse(xml) {
normalizeXML(xml); normalizeXML(xml);
const ctx = { inPreTag: false };
return parseNode(xml, ctx) || { type: 0 /* Text */, value: "" }; return parseNode(xml, ctx) || { type: 0 /* Text */, value: "" };
} }
function parseNode(node, ctx) { function parseNode(node, ctx) {
if (!(node instanceof Element)) { if (!(node instanceof Element)) {
return parseTextCommentNode(node, ctx); return parseTextCommentNode(node, ctx);
} }
return (parseTCustom(node, ctx) || return (parseTDebugLog(node, ctx) ||
parseTDebugLog(node, ctx) ||
parseTForEach(node, ctx) || parseTForEach(node, ctx) ||
parseTIf(node, ctx) || parseTIf(node, ctx) ||
parseTPortal(node, ctx) || parseTPortal(node, ctx) ||
@@ -4919,7 +4851,6 @@ function parseNode(node, ctx) {
parseTOutNode(node, ctx) || parseTOutNode(node, ctx) ||
parseTKey(node, ctx) || parseTKey(node, ctx) ||
parseTTranslation(node, ctx) || parseTTranslation(node, ctx) ||
parseTTranslationContext(node, ctx) ||
parseTSlot(node, ctx) || parseTSlot(node, ctx) ||
parseComponent(node, ctx) || parseComponent(node, ctx) ||
parseDOMNode(node, ctx) || parseDOMNode(node, ctx) ||
@@ -4952,35 +4883,6 @@ function parseTextCommentNode(node, ctx) {
} }
return null; return null;
} }
function parseTCustom(node, ctx) {
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
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -5028,7 +4930,6 @@ function parseDOMNode(node, ctx) {
node.removeAttribute("t-ref"); node.removeAttribute("t-ref");
const nodeAttrsNames = node.getAttributeNames(); const nodeAttrsNames = node.getAttributeNames();
let attrs = null; let attrs = null;
let attrsTranslationCtx = null;
let on = null; let on = null;
let model = null; let model = null;
for (let attr of nodeAttrsNames) { for (let attr of nodeAttrsNames) {
@@ -5089,11 +4990,6 @@ function parseDOMNode(node, ctx) {
else if (attr === "xmlns") { else if (attr === "xmlns") {
ns = value; 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}'`);
@@ -5115,7 +5011,6 @@ function parseDOMNode(node, ctx) {
tag: tagName, tag: tagName,
dynamicTag, dynamicTag,
attrs, attrs,
attrsTranslationCtx,
on, on,
ref, ref,
content: children, content: children,
@@ -5256,15 +5151,7 @@ function parseTCall(node, ctx) {
if (ast && ast.type === 11 /* TComponent */) { if (ast && ast.type === 11 /* 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,
},
},
}; };
} }
} }
@@ -5379,15 +5266,9 @@ function parseComponent(node, ctx) {
node.removeAttribute("t-slot-scope"); node.removeAttribute("t-slot-scope");
let on = null; let on = null;
let props = null; let props = null;
let 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;
@@ -5431,7 +5312,6 @@ function parseComponent(node, ctx) {
const slotAst = parseNode(slotNode, ctx); const slotAst = parseNode(slotNode, ctx);
let on = null; let on = null;
let attrs = null; let attrs = null;
let attrsTranslationCtx = null;
let scope = null; let scope = null;
for (let attributeName of slotNode.getAttributeNames()) { for (let attributeName of slotNode.getAttributeNames()) {
const value = slotNode.getAttribute(attributeName); const value = slotNode.getAttribute(attributeName);
@@ -5439,11 +5319,6 @@ function parseComponent(node, ctx) {
scope = value; scope = value;
continue; continue;
} }
else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
}
else if (attributeName.startsWith("t-on-")) { else if (attributeName.startsWith("t-on-")) {
on = on || {}; on = on || {};
on[attributeName.slice(5)] = value; on[attributeName.slice(5)] = value;
@@ -5454,32 +5329,17 @@ function parseComponent(node, ctx) {
} }
} }
slots = slots || {}; slots = slots || {};
slots[name] = { content: slotAst, on, attrs, attrsTranslationCtx, scope }; slots[name] = { content: slotAst, on, attrs, scope };
} }
// default slot // default slot
const defaultContent = parseChildNodes(clone, ctx); const defaultContent = parseChildNodes(clone, ctx);
slots = slots || {}; slots = slots || {};
// t-set-slot="default" has priority over content // t-set-slot="default" has priority over content
if (defaultContent && !slots.default) { if (defaultContent && !slots.default) {
slots.default = { slots.default = { content: defaultContent, on, attrs: null, scope: defaultSlotScope };
content: defaultContent,
on,
attrs: null,
attrsTranslationCtx: null,
scope: defaultSlotScope,
};
} }
} }
return { return { type: 11 /* TComponent */, name, isDynamic, dynamicProps, props, slots, on };
type: 11 /* TComponent */,
name,
isDynamic,
dynamicProps,
props,
propsTranslationCtx,
slots,
on,
};
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Slots // Slots
@@ -5491,7 +5351,6 @@ function parseTSlot(node, ctx) {
const name = node.getAttribute("t-slot"); const name = node.getAttribute("t-slot");
node.removeAttribute("t-slot"); node.removeAttribute("t-slot");
let attrs = null; let attrs = null;
let attrsTranslationCtx = null;
let on = null; let on = null;
for (let attributeName of node.getAttributeNames()) { for (let attributeName of node.getAttributeNames()) {
const value = node.getAttribute(attributeName); const value = node.getAttribute(attributeName);
@@ -5499,11 +5358,6 @@ function parseTSlot(node, ctx) {
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;
@@ -5513,14 +5367,10 @@ function parseTSlot(node, ctx) {
type: 14 /* TSlot */, type: 14 /* TSlot */,
name, name,
attrs, attrs,
attrsTranslationCtx,
on, on,
defaultContent: parseChildNodes(node, ctx), defaultContent: parseChildNodes(node, ctx),
}; };
} }
// -----------------------------------------------------------------------------
// Translation
// -----------------------------------------------------------------------------
function parseTTranslation(node, ctx) { function parseTTranslation(node, ctx) {
if (node.getAttribute("t-translation") !== "off") { if (node.getAttribute("t-translation") !== "off") {
return null; return null;
@@ -5532,21 +5382,6 @@ function parseTTranslation(node, ctx) {
}; };
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Translation Context
// -----------------------------------------------------------------------------
function parseTTranslationContext(node, ctx) {
const translationCtx = node.getAttribute("t-translation-context");
if (!translationCtx) {
return null;
}
node.removeAttribute("t-translation-context");
return {
type: 17 /* TTranslationContext */,
content: parseNode(node, ctx),
translationCtx,
};
}
// -----------------------------------------------------------------------------
// Portal // Portal
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
function parseTPortal(node, ctx) { function parseTPortal(node, ctx) {
@@ -5563,7 +5398,7 @@ function parseTPortal(node, ctx) {
}; };
} }
return { return {
type: 18 /* TPortal */, type: 17 /* TPortal */,
target, target,
content, content,
}; };
@@ -5679,11 +5514,9 @@ function normalizeXML(el) {
normalizeTEscTOut(el); normalizeTEscTOut(el);
} }
function compile(template, options = { function compile(template, options = {}) {
hasGlobalValues: false,
}) {
// parsing // parsing
const ast = parse(template, options.customDirectives); const ast = parse(template);
// some work // some work
const hasSafeContext = template instanceof Node const hasSafeContext = template instanceof Node
? !(template instanceof Element) || template.querySelector("[t-set], [t-call]") === null ? !(template instanceof Element) || template.querySelector("[t-set], [t-call]") === null
@@ -5705,7 +5538,7 @@ function compile(template, options = {
} }
// do not modify manually. This file is generated by the release script. // do not modify manually. This file is generated by the release script.
const version = "2.6.0"; const version = "2.2.9";
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Scheduler // Scheduler
@@ -5716,7 +5549,6 @@ class Scheduler {
this.frame = 0; this.frame = 0;
this.delayedRenders = []; this.delayedRenders = [];
this.cancelledNodes = new Set(); this.cancelledNodes = new Set();
this.processing = false;
this.requestAnimationFrame = Scheduler.requestAnimationFrame; this.requestAnimationFrame = Scheduler.requestAnimationFrame;
} }
addFiber(fiber) { addFiber(fiber) {
@@ -5747,10 +5579,6 @@ class Scheduler {
} }
} }
processTasks() { processTasks() {
if (this.processing) {
return;
}
this.processing = true;
this.frame = 0; this.frame = 0;
for (let node of this.cancelledNodes) { for (let node of this.cancelledNodes) {
node._destroy(); node._destroy();
@@ -5764,7 +5592,6 @@ class Scheduler {
this.tasks.delete(task); this.tasks.delete(task);
} }
} }
this.processing = false;
} }
processFiber(fiber) { processFiber(fiber) {
if (fiber.root !== fiber) { if (fiber.root !== fiber) {
@@ -5784,14 +5611,7 @@ class Scheduler {
if (!hasError) { if (!hasError) {
fiber.complete(); fiber.complete();
} }
// at this point, the fiber should have been applied to the DOM, so we can this.tasks.delete(fiber);
// remove it from the task list. If it is not the case, it means that there
// was an error and an error handler triggered a new rendering that recycled
// the fiber, so in that case, we actually want to keep the fiber around,
// otherwise it will just be ignored.
if (fiber.appliedToDom) {
this.tasks.delete(fiber);
}
} }
} }
} }
@@ -5813,7 +5633,6 @@ class App extends TemplateSet {
constructor(Root, config = {}) { constructor(Root, config = {}) {
super(config); super(config);
this.scheduler = new Scheduler(); this.scheduler = new Scheduler();
this.subRoots = new Set();
this.root = null; this.root = null;
this.name = config.name || ""; this.name = config.name || "";
this.Root = Root; this.Root = Root;
@@ -5832,44 +5651,14 @@ class App extends TemplateSet {
this.props = config.props || {}; this.props = config.props || {};
} }
mount(target, options) { mount(target, options) {
const root = this.createRoot(this.Root, { props: this.props }); App.validateTarget(target);
this.root = root.node; if (this.dev) {
this.subRoots.delete(root.node); validateProps(this.Root, this.props, { __owl__: { app: this } });
return root.mount(target, options);
}
createRoot(Root, config = {}) {
const props = config.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;
} }
const restore = saveCurrent(); const node = this.makeNode(this.Root, this.props);
const node = this.makeNode(Root, props); const prom = this.mountNode(node, target, options);
restore(); this.root = node;
if (config.env) { return prom;
this.env = env;
}
this.subRoots.add(node);
return {
node,
mount: (target, options) => {
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, props) { makeNode(Component, props) {
return new ComponentNode(Component, props, this, null, null); return new ComponentNode(Component, props, this, null, null);
@@ -5901,9 +5690,6 @@ class App extends TemplateSet {
} }
destroy() { destroy() {
if (this.root) { if (this.root) {
for (let subroot of this.subRoots) {
subroot.destroy();
}
this.root.destroy(); this.root.destroy();
this.scheduler.processTasks(); this.scheduler.processTasks();
} }
@@ -6175,14 +5961,12 @@ TemplateSet.prototype._compileTemplate = function _compileTemplate(name, templat
dev: this.dev, dev: this.dev,
translateFn: this.translateFn, translateFn: this.translateFn,
translatableAttributes: this.translatableAttributes, translatableAttributes: this.translatableAttributes,
customDirectives: this.customDirectives,
hasGlobalValues: this.hasGlobalValues,
}); });
}; };
export { App, Component, EventBus, OwlError, __info__, batched, blockDom, loadFile, markRaw, markup, mount, onError, onMounted, onPatched, onRendered, onWillDestroy, onWillPatch, onWillRender, onWillStart, onWillUnmount, onWillUpdateProps, reactive, status, toRaw, useChildSubEnv, useComponent, useEffect, useEnv, useExternalListener, useRef, useState, useSubEnv, validate, validateType, whenReady, xml }; export { App, Component, EventBus, OwlError, __info__, blockDom, loadFile, markRaw, markup, mount, onError, onMounted, onPatched, onRendered, onWillDestroy, onWillPatch, onWillRender, onWillStart, onWillUnmount, onWillUpdateProps, reactive, status, toRaw, useChildSubEnv, useComponent, useEffect, useEnv, useExternalListener, useRef, useState, useSubEnv, validate, validateType, whenReady, xml };
__info__.date = '2025-01-15T10:40:24.184Z'; __info__.date = '2024-01-12T14:43:56.804Z';
__info__.hash = 'a9be149'; __info__.hash = '7b3e39b';
__info__.url = 'https://github.com/odoo/owl'; __info__.url = 'https://github.com/odoo/owl';
+3 -2
View File
@@ -41,6 +41,9 @@ const loadFile = (path) => {
* Make an iframe, with all the js, css and xml properly injected. * Make an iframe, with all the js, css and xml properly injected.
*/ */
function makeCodeIframe(js, css, xml) { function makeCodeIframe(js, css, xml) {
// escape backticks in the xml so they don't close the template string
const escapedXml = xml.replace(/`/g, '\\\`');
const iframe = document.createElement("iframe"); const iframe = document.createElement("iframe");
iframe.onload = () => { iframe.onload = () => {
const doc = iframe.contentDocument; const doc = iframe.contentDocument;
@@ -52,8 +55,6 @@ function makeCodeIframe(js, css, xml) {
const script = doc.createElement("script"); const script = doc.createElement("script");
script.type = "module"; script.type = "module";
// escape characters with special meaning in template literals
const escapedXml = xml.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${");
script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`; script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`;
doc.body.appendChild(script); doc.body.appendChild(script);
+212 -827
View File
File diff suppressed because it is too large Load Diff
+3 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@odoo/owl", "name": "@odoo/owl",
"version": "2.6.0", "version": "2.2.9",
"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,7 +9,7 @@
"dist" "dist"
], ],
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=12.18.3"
}, },
"scripts": { "scripts": {
"build:bundle": "rollup -c --failAfterWarnings", "build:bundle": "rollup -c --failAfterWarnings",
@@ -32,10 +32,7 @@
"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,tools/devtools/**/*.js} --check",
"lint": "eslint src/**/*.ts tests/**/*.ts", "lint": "eslint src/**/*.ts tests/**/*.ts",
"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 +46,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",
@@ -101,8 +97,5 @@
"prettier": { "prettier": {
"printWidth": 100, "printWidth": 100,
"endOfLine": "auto" "endOfLine": "auto"
},
"dependencies": {
"jsdom": "^25.0.1"
} }
} }
+25 -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,7 +12,7 @@ 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__.date = '${new Date().toISOString()}'; __info__.date = '${new Date().toISOString()}';
@@ -21,37 +21,39 @@ __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 +71,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 +81,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",
-4
View File
@@ -1,4 +0,0 @@
export type customDirectives = Record<
string,
(node: Element, value: string, modifier: string[]) => void
>;
+34 -90
View File
@@ -24,7 +24,6 @@ import {
ASTTOut, ASTTOut,
ASTTPortal, ASTTPortal,
ASTTranslation, ASTTranslation,
ASTTranslationContext,
ASTTSet, ASTTSet,
ASTType, ASTType,
Attrs, Attrs,
@@ -36,7 +35,7 @@ type BlockType = "block" | "text" | "multi" | "list" | "html" | "comment";
const whitespaceRE = /\s+/g; 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 +43,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
@@ -84,14 +82,6 @@ function isProp(tag: string, key: string): boolean {
return false; 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
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -172,7 +162,6 @@ interface Context {
forceNewBlock: boolean; forceNewBlock: 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;
@@ -187,7 +176,6 @@ 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,
@@ -266,7 +254,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 }[] = [];
@@ -290,9 +278,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 {
@@ -306,7 +291,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
@@ -327,13 +311,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}\`);`);
} }
} }
} }
@@ -461,9 +446,9 @@ export class CodeGenerator {
.join(""); .join("");
} }
translate(str: string, translationCtx: string): string { translate(str: string): string {
const match = translationRE.exec(str) as any; const match = translationRE.exec(str) as any;
return match[1] + this.translateFn(match[2], translationCtx) + match[3]; return match[1] + this.translateFn(match[2]) + match[3];
} }
/** /**
@@ -505,8 +490,6 @@ export class CodeGenerator {
return this.compileTSlot(ast, ctx); return this.compileTSlot(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);
} }
@@ -532,7 +515,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,
}); });
@@ -548,7 +531,7 @@ 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); value = this.translate(value);
} }
if (!ctx.inPreTag) { if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " "); value = value.replace(whitespaceRE, " ");
@@ -556,7 +539,7 @@ export class CodeGenerator {
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,
}); });
@@ -637,8 +620,7 @@ export class CodeGenerator {
} }
} }
} 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;
@@ -792,8 +774,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) {
@@ -1058,7 +1039,7 @@ export class CodeGenerator {
} }
} }
const key = this.generateComponentKey(); 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")) {
@@ -1110,13 +1091,11 @@ export class CodeGenerator {
} else { } else {
let value: string; let value: string;
if (ast.defaultValue) { if (ast.defaultValue) {
const defaultValue = toStringExpression( const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
ctx.translate ? this.translate(ast.defaultValue, ctx.translationCtx) : ast.defaultValue
);
if (ast.value) { if (ast.value) {
value = `withDefault(${expr}, ${defaultValue})`; value = `withDefault(${expr}, \`${defaultValue}\`)`;
} else { } else {
value = defaultValue; value = `\`${defaultValue}\``;
} }
} else { } else {
value = expr; value = expr;
@@ -1127,12 +1106,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("__");
} }
/** /**
@@ -1146,18 +1125,8 @@ 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; name = _name;
@@ -1166,24 +1135,17 @@ export class CodeGenerator {
value = `(${value}).bind(this)`; value = `(${value}).bind(this)`;
break; break;
case "alike": case "alike":
case "translate":
break; break;
default: default:
throw new OwlError(`Invalid prop suffix: ${suffix}`); throw new OwlError("Invalid prop 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 {
@@ -1200,9 +1162,7 @@ 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 slotDef: string = "";
@@ -1226,13 +1186,7 @@ export class CodeGenerator {
params.push(`__scope: "${scope}"`); params.push(`__scope: "${scope}"`);
} }
if (ast.slots[slotName].attrs) { if (ast.slots[slotName].attrs) {
params.push( params.push(...this.formatPropObject(ast.slots[slotName].attrs!));
...this.formatPropObject(
ast.slots[slotName].attrs!,
ast.slots[slotName].attrsTranslationCtx,
ctx.translationCtx
)
);
} }
const slotInfo = `{${params.join(", ")}}`; const slotInfo = `{${params.join(", ")}}`;
slotStr.push(`'${slotName}': ${slotInfo}`); slotStr.push(`'${slotName}': ${slotInfo}`);
@@ -1260,6 +1214,7 @@ export class CodeGenerator {
} }
// 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");
@@ -1277,7 +1232,7 @@ 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}`;
} }
@@ -1356,12 +1311,10 @@ export class CodeGenerator {
} }
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(ast.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);
@@ -1394,15 +1347,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` });
@@ -1410,6 +1354,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");
@@ -1423,8 +1368,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);
} }
+2 -7
View File
@@ -1,4 +1,3 @@
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";
@@ -11,17 +10,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 =
+2 -4
View File
@@ -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();
} }
+10 -126
View File
@@ -1,5 +1,4 @@
import { OwlError } from "../common/owl_error"; import { OwlError } from "../common/owl_error";
import type { customDirectives } from "../common/types";
import { parseXML } from "../common/utils"; import { parseXML } from "../common/utils";
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -27,7 +26,6 @@ export const enum ASTType {
TSlot, TSlot,
TCallBlock, TCallBlock,
TTranslation, TTranslation,
TTranslationContext,
TPortal, TPortal,
} }
@@ -57,7 +55,6 @@ export interface ASTDomNode {
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;
@@ -129,7 +126,6 @@ interface SlotDefinition {
scope: string | null; scope: string | null;
on: EventHandlers | null; on: EventHandlers | null;
attrs: Attrs | null; attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
} }
export interface ASTComponent { export interface ASTComponent {
@@ -139,7 +135,6 @@ export interface ASTComponent {
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;
slots: { [name: string]: SlotDefinition } | null; slots: { [name: string]: SlotDefinition } | null;
} }
@@ -147,7 +142,6 @@ 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;
} }
@@ -173,12 +167,6 @@ export interface ASTTranslation {
content: AST | null; content: AST | null;
} }
export interface ASTTranslationContext {
type: ASTType.TTranslationContext;
content: AST | null;
translationCtx: string;
}
export interface ASTTPortal { export interface ASTTPortal {
type: ASTType.TPortal; type: ASTType.TPortal;
target: string; target: string;
@@ -203,7 +191,6 @@ export type AST =
| ASTLog | ASTLog
| ASTDebug | ASTDebug
| ASTTranslation | ASTTranslation
| ASTTranslationContext
| ASTTPortal; | ASTTPortal;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -211,26 +198,23 @@ 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 };
return parseNode(xml, ctx) || { type: ASTType.Text, value: "" }; return parseNode(xml, ctx) || { type: ASTType.Text, value: "" };
} }
@@ -238,7 +222,6 @@ interface ParsingContext {
tModelInfo?: TModelInfo | null; tModelInfo?: TModelInfo | null;
nameSpace?: string; nameSpace?: string;
inPreTag: boolean; inPreTag: boolean;
customDirectives?: customDirectives;
} }
function parseNode(node: Node, ctx: ParsingContext): AST | null { function parseNode(node: Node, ctx: ParsingContext): AST | null {
@@ -246,7 +229,6 @@ 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) ||
@@ -257,7 +239,6 @@ function parseNode(node: Node, ctx: ParsingContext): AST | null {
parseTOutNode(node, ctx) || parseTOutNode(node, ctx) ||
parseTKey(node, ctx) || parseTKey(node, ctx) ||
parseTTranslation(node, ctx) || parseTTranslation(node, ctx) ||
parseTTranslationContext(node, ctx) ||
parseTSlot(node, ctx) || parseTSlot(node, ctx) ||
parseComponent(node, ctx) || parseComponent(node, ctx) ||
parseDOMNode(node, ctx) || parseDOMNode(node, ctx) ||
@@ -296,37 +277,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
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -381,7 +331,6 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
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;
@@ -442,10 +391,6 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
throw new OwlError(`Invalid attribute: '${attr}'`); throw new OwlError(`Invalid attribute: '${attr}'`);
} else if (attr === "xmlns") { } else if (attr === "xmlns") {
ns = value; 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}'`);
@@ -468,7 +413,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,
@@ -628,15 +572,7 @@ function parseTCall(node: Element, ctx: ParsingContext): AST | null {
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,
},
},
}; };
} }
} }
@@ -771,14 +707,9 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
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;
@@ -826,17 +757,12 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
const slotAst = parseNode(slotNode, ctx); const slotAst = parseNode(slotNode, ctx);
let on: SlotDefinition["on"] = null; let on: SlotDefinition["on"] = null;
let attrs: Attrs | null = null; let attrs: Attrs | null = null;
let attrsTranslationCtx: Attrs | null = null;
let scope: string | null = null; let scope: string | null = null;
for (let attributeName of slotNode.getAttributeNames()) { for (let attributeName of slotNode.getAttributeNames()) {
const value = slotNode.getAttribute(attributeName)!; const value = slotNode.getAttribute(attributeName)!;
if (attributeName === "t-slot-scope") { if (attributeName === "t-slot-scope") {
scope = value; scope = value;
continue; continue;
} else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else if (attributeName.startsWith("t-on-")) { } else if (attributeName.startsWith("t-on-")) {
on = on || {}; on = on || {};
on[attributeName.slice(5)] = value; on[attributeName.slice(5)] = value;
@@ -846,7 +772,7 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
} }
} }
slots = slots || {}; slots = slots || {};
slots[name] = { content: slotAst, on, attrs, attrsTranslationCtx, scope }; slots[name] = { content: slotAst, on, attrs, scope };
} }
// default slot // default slot
@@ -854,25 +780,10 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
slots = slots || {}; slots = slots || {};
// t-set-slot="default" has priority over content // t-set-slot="default" has priority over content
if (defaultContent && !slots.default) { if (defaultContent && !slots.default) {
slots.default = { slots.default = { content: defaultContent, on, attrs: null, scope: defaultSlotScope };
content: defaultContent,
on,
attrs: null,
attrsTranslationCtx: null,
scope: defaultSlotScope,
};
} }
} }
return { return { type: ASTType.TComponent, name, isDynamic, dynamicProps, props, slots, on };
type: ASTType.TComponent,
name,
isDynamic,
dynamicProps,
props,
propsTranslationCtx,
slots,
on,
};
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -886,17 +797,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;
@@ -906,16 +812,11 @@ 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),
}; };
} }
// -----------------------------------------------------------------------------
// Translation
// -----------------------------------------------------------------------------
function parseTTranslation(node: Element, ctx: ParsingContext): AST | null { function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
if (node.getAttribute("t-translation") !== "off") { if (node.getAttribute("t-translation") !== "off") {
return null; return null;
@@ -927,23 +828,6 @@ function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
}; };
} }
// -----------------------------------------------------------------------------
// Translation Context
// -----------------------------------------------------------------------------
function parseTTranslationContext(node: Element, ctx: ParsingContext): AST | null {
const translationCtx = node.getAttribute("t-translation-context");
if (!translationCtx) {
return null;
}
node.removeAttribute("t-translation-context");
return {
type: ASTType.TTranslationContext,
content: parseNode(node, ctx),
translationCtx,
};
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Portal // Portal
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
-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,
}); });
}; };
+10 -58
View File
@@ -1,6 +1,6 @@
import { version } from "../version"; 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, handleError } from "./error_handling";
import { OwlError } from "../common/owl_error"; import { OwlError } from "../common/owl_error";
import { Fiber, RootFiber, MountOptions } from "./fibers"; import { Fiber, RootFiber, MountOptions } from "./fibers";
@@ -16,13 +16,10 @@ export interface Env {
[key: string]: any; [key: string]: any;
} }
export interface RootConfig<P, E> { export interface AppConfig<P, E> extends TemplateSetConfig {
name?: string;
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;
} }
@@ -52,12 +49,6 @@ declare global {
} }
} }
interface Root<P extends Props, E> {
node: ComponentNode<P, E>;
mount(target: HTMLElement | ShadowRoot, options?: MountOptions): Promise<Component<P, E>>;
destroy(): void;
}
window.__OWL_DEVTOOLS__ ||= { apps, Fiber, RootFiber, toRaw, reactive }; window.__OWL_DEVTOOLS__ ||= { apps, Fiber, RootFiber, toRaw, reactive };
export class App< export class App<
@@ -74,7 +65,6 @@ export class App<
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;
@@ -101,49 +91,14 @@ export class App<
target: HTMLElement | ShadowRoot, target: HTMLElement | ShadowRoot,
options?: MountOptions options?: MountOptions
): Promise<Component<P, E> & InstanceType<T>> { ): Promise<Component<P, E> & InstanceType<T>> {
const root = this.createRoot(this.Root, { props: this.props }); App.validateTarget(target);
this.root = root.node; if (this.dev) {
this.subRoots.delete(root.node); validateProps(this.Root, this.props, { __owl__: { app: this } });
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 {
@@ -179,9 +134,6 @@ export class App<
destroy() { destroy() {
if (this.root) { if (this.root) {
for (let subroot of this.subRoots) {
subroot.destroy();
}
this.root.destroy(); this.root.destroy();
this.scheduler.processTasks(); this.scheduler.processTasks();
} }
-7
View File
@@ -10,13 +10,6 @@ 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')");
+1 -17
View File
@@ -30,13 +30,6 @@ export function makeRootFiber(node: ComponentNode): Fiber {
fibersInError.delete(current); fibersInError.delete(current);
fibersInError.delete(root); fibersInError.delete(root);
current.appliedToDom = false; current.appliedToDom = false;
if (current instanceof RootFiber) {
// it is possible that this fiber is a fiber that crashed while being
// mounted, so the mounted list is possibly corrupted. We restore it to
// its normal initial state (which is empty list or a list with a mount
// fiber.
current.mounted = current instanceof MountFiber ? [current] : [];
}
} }
return current; return current;
} }
@@ -159,7 +152,6 @@ export class RootFiber extends Fiber {
const node = this.node; const node = this.node;
this.locked = true; this.locked = true;
let current: Fiber | undefined = undefined; let current: Fiber | undefined = undefined;
let mountedFibers = this.mounted;
try { try {
// Step 1: calling all willPatch lifecycle hooks // Step 1: calling all willPatch lifecycle hooks
for (current of this.willPatch) { for (current of this.willPatch) {
@@ -181,6 +173,7 @@ export class RootFiber extends Fiber {
this.locked = false; this.locked = false;
// Step 4: calling all mounted lifecycle hooks // Step 4: calling all mounted lifecycle hooks
let mountedFibers = this.mounted;
while ((current = mountedFibers.pop())) { while ((current = mountedFibers.pop())) {
current = current; current = current;
if (current.appliedToDom) { if (current.appliedToDom) {
@@ -201,15 +194,6 @@ export class RootFiber extends Fiber {
} }
} }
} catch (e) { } catch (e) {
// if mountedFibers is not empty, this means that a crash occured while
// calling the mounted hooks of some component. So, there may still be
// some component that have been mounted, but for which the mounted hooks
// have not been called. Here, we remove the willUnmount hooks for these
// specific component to prevent a worse situation (willUnmount being
// called even though mounted has not been called)
for (let fiber of mountedFibers) {
fiber.node.willUnmount = [];
}
this.locked = false; this.locked = false;
node.app.handleError({ fiber: current || this, error: e }); node.app.handleError({ fiber: current || this, error: e });
} }
+1 -1
View File
@@ -41,7 +41,7 @@ export { useComponent, useState } from "./component_node";
export { status } from "./status"; export { status } from "./status";
export { reactive, markRaw, toRaw } from "./reactivity"; export { reactive, markRaw, toRaw } from "./reactivity";
export { useEffect, useEnv, useExternalListener, useRef, useChildSubEnv, useSubEnv } from "./hooks"; export { useEffect, useEnv, useExternalListener, useRef, useChildSubEnv, useSubEnv } from "./hooks";
export { batched, EventBus, whenReady, loadFile, markup } from "./utils"; export { EventBus, whenReady, loadFile, markup } from "./utils";
export { export {
onWillStart, onWillStart,
onMounted, onMounted,
+23 -31
View File
@@ -3,50 +3,42 @@ import { nodeErrorHandlers } from "./error_handling";
import { OwlError } from "../common/owl_error"; import { OwlError } from "../common/owl_error";
const TIMEOUT = Symbol("timeout"); const TIMEOUT = Symbol("timeout");
const HOOK_TIMEOUT: { [key: string]: number } = {
onWillStart: 3000,
onWillUpdateProps: 3000,
};
function wrapError(fn: (...args: any[]) => any, hookName: string) { function wrapError(fn: (...args: any[]) => any, hookName: string) {
const error = new OwlError() as Error & { const error = new OwlError(`The following error occurred in ${hookName}: `) as Error & {
cause: any; cause: any;
}; };
const timeoutError = new OwlError(); const timeoutError = new OwlError(`${hookName}'s promise hasn't resolved after 3 seconds`);
const node = getCurrent(); const node = getCurrent();
return (...args: any[]) => { return (...args: any[]) => {
const onError = (cause: any) => { const onError = (cause: any) => {
error.cause = cause; error.cause = cause;
error.message = if (cause instanceof Error) {
cause instanceof Error error.message += `"${cause.message}"`;
? `The following error occurred in ${hookName}: "${cause.message}"` } else {
: `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`; error.message = `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`;
}
throw error; throw error;
}; };
let result;
try { try {
result = fn(...args); const result = fn(...args);
if (result instanceof Promise) {
if (hookName === "onWillStart" || hookName === "onWillUpdateProps") {
const fiber = node.fiber;
Promise.race([
result.catch(() => {}),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), 3000)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber) {
console.warn(timeoutError);
}
});
}
return result.catch(onError);
}
return result;
} catch (cause) { } catch (cause) {
onError(cause); onError(cause);
} }
if (!(result instanceof Promise)) {
return result;
}
const timeout = HOOK_TIMEOUT[hookName];
if (timeout) {
const fiber = node.fiber;
Promise.race([
result.catch(() => {}),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), timeout)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber && node.status <= 2) {
timeoutError.message = `${hookName}'s promise hasn't resolved after ${
timeout / 1000
} seconds`;
console.log(timeoutError);
}
});
}
return result.catch(onError);
}; };
} }
+39
View File
@@ -227,6 +227,30 @@ export function reactive<T extends Target>(target: T, callback: Callback = NO_CA
const proxy = new Proxy(target, handler as ProxyHandler<T>) as Reactive<T>; const proxy = new Proxy(target, handler as ProxyHandler<T>) as Reactive<T>;
reactivesForTarget.set(callback, proxy); reactivesForTarget.set(callback, proxy);
targets.set(proxy, target); targets.set(proxy, target);
// FIXME: this probably slows down reactive creation significantly, we probably don't want to do
// it all the time. Maybe should be a separate function.
const derivedDescriptors = Object.entries(Object.getOwnPropertyDescriptors(target)).filter(
([k, descriptor]) => {
if (toRaw(descriptor.value)?.[IS_DERIVED_DESCRIPTOR]) {
delete target[k as keyof typeof target]; // prevent circular call in effect below
return true;
}
return false;
}
);
for (const [
key,
{
value: [deps, compute],
},
] of derivedDescriptors) {
effect(
(proxy, deps) => {
proxy[key as keyof typeof proxy] = Reflect.apply(compute, proxy, deps);
},
[proxy, deps]
);
}
} }
return reactivesForTarget.get(callback) as Reactive<T>; return reactivesForTarget.get(callback) as Reactive<T>;
} }
@@ -463,3 +487,18 @@ function collectionsProxyHandler<T extends Collection>(
}, },
}) as ProxyHandler<T>; }) as ProxyHandler<T>;
} }
const IS_DERIVED_DESCRIPTOR = Symbol("is derived descriptor");
export function derived<T extends Reactive<any>[], U>(deps: T, compute: (...args: T) => U) {
return Object.assign([deps, compute], { [IS_DERIVED_DESCRIPTOR]: true }) as unknown as U;
}
/**
* Creates a side-effect that runs based on the content of reactive objects.
*/
export function effect<T extends object[]>(cb: (...args: [...T]) => void, deps: [...T]) {
const reactiveDeps = reactive(deps, () => {
cb(...reactiveDeps);
});
cb(...reactiveDeps);
}
+1 -14
View File
@@ -16,7 +16,6 @@ export class Scheduler {
frame: number = 0; frame: number = 0;
delayedRenders: Fiber[] = []; delayedRenders: Fiber[] = [];
cancelledNodes: Set<ComponentNode> = new Set(); cancelledNodes: Set<ComponentNode> = new Set();
processing = false;
constructor() { constructor() {
this.requestAnimationFrame = Scheduler.requestAnimationFrame; this.requestAnimationFrame = Scheduler.requestAnimationFrame;
@@ -54,10 +53,6 @@ export class Scheduler {
} }
processTasks() { processTasks() {
if (this.processing) {
return;
}
this.processing = true;
this.frame = 0; this.frame = 0;
for (let node of this.cancelledNodes) { for (let node of this.cancelledNodes) {
node._destroy(); node._destroy();
@@ -71,7 +66,6 @@ export class Scheduler {
this.tasks.delete(task); this.tasks.delete(task);
} }
} }
this.processing = false;
} }
processFiber(fiber: RootFiber) { processFiber(fiber: RootFiber) {
@@ -93,14 +87,7 @@ export class Scheduler {
if (!hasError) { if (!hasError) {
fiber.complete(); fiber.complete();
} }
// at this point, the fiber should have been applied to the DOM, so we can this.tasks.delete(fiber);
// remove it from the task list. If it is not the case, it means that there
// was an error and an error handler triggered a new rendering that recycled
// the fiber, so in that case, we actually want to keep the fiber around,
// otherwise it will just be ignored.
if (fiber.appliedToDom) {
this.tasks.delete(fiber);
}
} }
} }
} }
+3 -12
View File
@@ -5,18 +5,15 @@ import { Portal, portalTemplate } from "./portal";
import { helpers } from "./template_helpers"; import { helpers } from "./template_helpers";
import { OwlError } from "../common/owl_error"; import { OwlError } from "../common/owl_error";
import { parseXML } from "../common/utils"; import { parseXML } from "../common/utils";
import type { customDirectives } from "../common/types";
const bdom = { text, createBlock, list, multi, html, toggler, comment }; const bdom = { text, createBlock, list, multi, html, toggler, comment };
export interface TemplateSetConfig { export interface TemplateSetConfig {
dev?: boolean; dev?: boolean;
translatableAttributes?: string[]; translatableAttributes?: string[];
translateFn?: (s: string, translationCtx: string) => string; translateFn?: (s: string) => string;
templates?: string | Document | Record<string, string>; templates?: string | Document | Record<string, string>;
getTemplate?: (s: string) => Element | Function | string | void; getTemplate?: (s: string) => Element | Function | string | void;
customDirectives?: customDirectives;
globalValues?: object;
} }
export class TemplateSet { export class TemplateSet {
@@ -27,12 +24,9 @@ export class TemplateSet {
rawTemplates: typeof globalTemplates = Object.create(globalTemplates); rawTemplates: typeof globalTemplates = Object.create(globalTemplates);
templates: { [name: string]: Template } = {}; templates: { [name: string]: Template } = {};
getRawTemplate?: (s: string) => Element | Function | string | void; getRawTemplate?: (s: string) => Element | Function | string | void;
translateFn?: (s: string, translationCtx: string) => string; translateFn?: (s: string) => string;
translatableAttributes?: string[]; translatableAttributes?: string[];
Portal = Portal; Portal = Portal;
customDirectives: customDirectives;
runtimeUtils: object;
hasGlobalValues: boolean;
constructor(config: TemplateSetConfig = {}) { constructor(config: TemplateSetConfig = {}) {
this.dev = config.dev || false; this.dev = config.dev || false;
@@ -48,9 +42,6 @@ export class TemplateSet {
} }
} }
this.getRawTemplate = config.getTemplate; this.getRawTemplate = config.getTemplate;
this.customDirectives = config.customDirectives || {};
this.runtimeUtils = { ...helpers, __globals__: config.globalValues || {} };
this.hasGlobalValues = Boolean(config.globalValues && Object.keys(config.globalValues).length);
} }
addTemplate(name: string, template: string | Element) { addTemplate(name: string, template: string | Element) {
@@ -106,7 +97,7 @@ export class TemplateSet {
this.templates[name] = function (context, parent) { this.templates[name] = function (context, parent) {
return templates[name].call(this, context, parent); return templates[name].call(this, context, parent);
}; };
const template = templateFn(this, bdom, this.runtimeUtils); const template = templateFn(this, bdom, helpers);
this.templates[name] = template; this.templates[name] = template;
} }
return this.templates[name]; return this.templates[name];
+10 -1
View File
@@ -1,7 +1,16 @@
import { OwlError } from "../common/owl_error"; import { OwlError } from "../common/owl_error";
import { toRaw } from "./reactivity"; import { toRaw } from "./reactivity";
type BaseType = { new (...args: any[]): any } | true | "*"; type BaseType =
| typeof String
| typeof Boolean
| typeof Number
| typeof Date
| typeof Object
| typeof Array
| typeof Function
| true
| "*";
interface TypeInfo { interface TypeInfo {
type?: TypeDescription; type?: TypeDescription;
+1 -1
View File
@@ -1,2 +1,2 @@
// do not modify manually. This file is generated by the release script. // do not modify manually. This file is generated by the release script.
export const version = "2.6.0"; export const version = "2.2.9";
-42
View File
@@ -43,48 +43,6 @@ exports[`app app: clear scheduler tasks and destroy cancelled nodes immediately
}" }"
`; `;
exports[`app can add functions to the bdom 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { __globals__ } = helpers;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [()=>__globals__.plop('click'), ctx];
return block1([hdlr1]);
}
}"
`;
exports[`app can call processTask twice in a row without crashing 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`parent\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
return multi([b2, b3]);
}
}"
`;
exports[`app can call processTask twice in a row without crashing 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`app can configure an app with props 1`] = ` exports[`app can configure an app with props 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1,210 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`destroy a subroot while another component is mounted in main app 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`ChildB\`, true, false, false, []);
const comp2 = app.createComponent(\`ChildA\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
if (ctx['state'].flag) {
b2 = comp1({}, key + \`__1\`, node, this, null);
} else {
b3 = comp2({}, key + \`__2\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block3 = createBlock(\`<div block-ref=\\"0\\"/>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`a\`);
let ref1 = (el) => this.__owl__.setRef((\`elem\`), el);
const b3 = block3([ref1]);
return multi([b2, b3]);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`c\`);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`b\`);
}
}"
`;
exports[`subroot by default, env is the same in sub root 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot by default, env is the same in sub root 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can create a root in a setup function, then use a hook 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`a\`);
}
}"
`;
exports[`subroot can create a root in a setup function, then use a hook 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`c\`);
}
}"
`;
exports[`subroot can mount subroot 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot inside own dom 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot inside own dom 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot env can be specified for sub roots 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot env can be specified for sub roots 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot subcomponents can be destroyed, and it properly cleanup the subroots 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot subcomponents can be destroyed, and it properly cleanup the subroots 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
+1 -36
View File
@@ -1,4 +1,4 @@
import { App, Component, mount, onWillPatch, onWillStart, useState, xml } from "../../src"; import { App, Component, mount, onWillStart, useState, xml } from "../../src";
import { status } from "../../src/runtime/status"; import { status } from "../../src/runtime/status";
import { import {
makeTestFixture, makeTestFixture,
@@ -184,39 +184,4 @@ describe("app", () => {
expect(Object.keys(app.templates)).toEqual(["hello"]); expect(Object.keys(app.templates)).toEqual(["hello"]);
expect(Object.keys(app.rawTemplates)).toEqual(["hello", "world"]); expect(Object.keys(app.rawTemplates)).toEqual(["hello", "world"]);
}); });
test("can call processTask twice in a row without crashing", async () => {
class Child extends Component {
static template = xml`<div/>`;
setup() {
onWillPatch(() => app.scheduler.processTasks());
}
}
class SomeComponent extends Component {
static template = xml`parent<Child/>`;
static components = { Child };
}
const app = new App(SomeComponent);
await app.mount(fixture);
expect(fixture.innerHTML).toBe("parent<div></div>");
});
test("can add functions to the bdom", async () => {
const steps: string[] = [];
class SomeComponent extends Component {
static template = xml`<div t-on-click="() => __globals__.plop('click')" class="my-div"/>`;
}
const app = new App(SomeComponent, {
globalValues: {
plop: (string: any) => {
steps.push(string);
},
},
});
await app.mount(fixture);
expect(fixture.innerHTML).toBe(`<div class="my-div"></div>`);
fixture.querySelector("div")!.click();
expect(steps).toEqual(["click"]);
});
}); });
-176
View File
@@ -1,176 +0,0 @@
import { App, Component, onMounted, onWillDestroy, useRef, useState, xml } from "../../src";
import { status } from "../../src/runtime/status";
import { makeTestFixture, nextTick, snapshotEverything } from "../helpers";
let fixture: HTMLElement;
snapshotEverything();
beforeEach(() => {
fixture = makeTestFixture();
});
class SomeComponent extends Component {
static template = xml`<div>main app</div>`;
}
class SubComponent extends Component {
static template = xml`<div>sub root</div>`;
}
describe("subroot", () => {
test("can mount subroot", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const subRoot = app.createRoot(SubComponent);
const subcomp = await subRoot.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div><div>sub root</div>");
app.destroy();
expect(fixture.innerHTML).toBe("");
expect(status(comp)).toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("can mount subroot inside own dom", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const subRoot = app.createRoot(SubComponent);
const subcomp = await subRoot.mount(fixture.querySelector("div")!);
expect(fixture.innerHTML).toBe("<div>main app<div>sub root</div></div>");
app.destroy();
expect(fixture.innerHTML).toBe("");
expect(status(comp)).toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("by default, env is the same in sub root", async () => {
let env, subenv;
class SC extends SomeComponent {
setup() {
env = this.env;
}
}
class Sub extends SubComponent {
setup() {
subenv = this.env;
}
}
const app = new App(SC);
await app.mount(fixture);
const subRoot = app.createRoot(Sub);
await subRoot.mount(fixture);
expect(env).toBeDefined();
expect(subenv).toBeDefined();
expect(env).toBe(subenv);
});
test("env can be specified for sub roots", async () => {
const env1 = { env1: true };
const env2 = {};
let someComponentEnv: any, subComponentEnv: any;
class SC extends SomeComponent {
setup() {
someComponentEnv = this.env;
}
}
class Sub extends SubComponent {
setup() {
subComponentEnv = this.env;
}
}
const app = new App(SC, { env: env1 });
await app.mount(fixture);
const subRoot = app.createRoot(Sub, { env: env2 });
await subRoot.mount(fixture);
// because env is different in app => it is given a sub object, frozen and all
// not sure it is a good idea, but it's the way owl 2 works. maybe we should
// avoid doing anything with the main env and let user code do it if they
// want. in that case, we can change the test here to assert that they are equal
expect(someComponentEnv).not.toBe(env1);
expect(someComponentEnv!.env1).toBe(true);
expect(subComponentEnv).toBe(env2);
});
test("subcomponents can be destroyed, and it properly cleanup the subroots", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const root = app.createRoot(SubComponent);
const subcomp = await root.mount(fixture.querySelector("div")!);
expect(fixture.innerHTML).toBe("<div>main app<div>sub root</div></div>");
root.destroy();
expect(fixture.innerHTML).toBe("<div>main app</div>");
expect(status(comp)).not.toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("can create a root in a setup function, then use a hook", async () => {
class C extends Component {
static template = xml`c`;
}
class A extends Component {
static template = xml`a`;
state: any;
setup() {
app.createRoot(C);
this.state = useState({ value: 1 });
}
}
const app = new App(A);
await app.mount(fixture);
expect(fixture.innerHTML).toBe("a");
});
});
test("destroy a subroot while another component is mounted in main app", async () => {
class C extends Component {
static template = xml`c`;
}
class ChildA extends Component {
static template = xml`a<div t-ref="elem"></div>`;
ref: any;
setup() {
this.ref = useRef("elem");
let root = app.createRoot(C);
onMounted(() => {
root.mount(this.ref.el);
});
onWillDestroy(() => {
root.destroy();
});
}
}
class ChildB extends Component {
static template = xml`b`;
}
class SomeComponent extends Component {
static template = xml`
<t t-if="state.flag"><ChildB/></t>
<t t-else=""><ChildA/></t>
`;
static components = { ChildA, ChildB };
state = useState({ flag: false });
}
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("a<div></div>");
await nextTick();
expect(fixture.innerHTML).toBe("a<div>c</div>");
comp.state.flag = true;
await nextTick();
expect(fixture.innerHTML).toBe("b");
});
@@ -1,38 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`comments comment node with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\\\\ \`);
}
}"
`;
exports[`comments comment node with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\` \`);
}
}"
`;
exports[`comments comment node with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\${very cool} \`);
}
}"
`;
exports[`comments only a comment 1`] = ` exports[`comments only a comment 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -341,39 +341,6 @@ exports[`simple templates, mostly static template with t tag with multiple conte
}" }"
`; `;
exports[`simple templates, mostly static text node with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\\\\\`);
}
}"
`;
exports[`simple templates, mostly static text node with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\`\`);
}
}"
`;
exports[`simple templates, mostly static text node with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\${very cool}\`);
}
}"
`;
exports[`simple templates, mostly static two t-escs next to each other 1`] = ` exports[`simple templates, mostly static two t-escs next to each other 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1,29 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-custom can use t-custom directive on a node 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [ctx['click'], ctx];
return block1([hdlr1]);
}
}"
`;
exports[`t-custom can use t-custom directive with modifiers on a node 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [ctx['click'], ctx];
return block1([hdlr1]);
}
}"
`;
@@ -1,41 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-esc default with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\\\\\`));
}
}"
`;
exports[`t-esc default with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\`\`));
}
}"
`;
exports[`t-esc default with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\${very cool}\`));
}
}"
`;
exports[`t-esc div with falsy values 1`] = ` exports[`t-esc div with falsy values 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1,50 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-set body with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\\\\\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set body with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\`\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set body with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\${very cool}\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set evaluate value expression 1`] = ` exports[`t-set evaluate value expression 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1,128 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`translation context body of t-sets are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`traduit\`);
const b2 = text(ctx['label']);
return multi([b2]);
}
}"
`;
exports[`translation context default slot params and content translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
function defaultContent1(ctx, node, key = \\"\\") {
return text(\` foo \`);
}
return function template(ctx, node, key = \\"\\") {
const b3 = callSlot(ctx, node, key, 'default', false, {param: \`param\`,title: \`título\`}, defaultContent1.bind(this));
return block1([], [b3]);
}
}"
`;
exports[`translation context props with modifier .translate are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`ChildComponent\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({text: \`jeu\`}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`translation context props with modifier .translate are translated in context 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<span><block-text-0/></span>\`);
return function template(ctx, node, key = \\"\\") {
let txt1 = ctx['props'].text;
return block1([txt1]);
}
}"
`;
exports[`translation context slot attrs and text contents are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const comp1 = app.createComponent(\`ChildComponent\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
return text(\`jeu\`);
}
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp1({slots: markRaw({'a': {__render: slot1.bind(this), __ctx: ctx1, title: \`título\`}})}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`translation context slot attrs and text contents are translated in context 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = callSlot(ctx, node, key, 'a', false, {});
return block1([], [b2]);
}
}"
`;
exports[`translation context translation of attributes in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div title=\\"titre\\" label=\\"game\\"/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`translation context translation of text in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block2 = createBlock(\`<div>word</div>\`);
let block3 = createBlock(\`<div>mot</div>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = block2();
const b3 = block3();
return multi([b2, b3]);
}
}"
`;
exports[`translation support body of t-sets are translated 1`] = ` exports[`translation support body of t-sets are translated 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
-15
View File
@@ -26,19 +26,4 @@ describe("comments", () => {
</div>`; </div>`;
expect(renderToString(template)).toBe("<div><span>true</span></div>"); expect(renderToString(template)).toBe("<div><span>true</span></div>");
}); });
test("comment node with backslash at top level", () => {
const template = "<!-- \\ -->";
expect(renderToString(template)).toBe("<!-- \\ -->");
});
test("comment node with backtick at top-level", () => {
const template = "<!-- ` -->";
expect(renderToString(template)).toBe("<!-- ` -->");
});
test("comment node with interpolation sigil at top level", () => {
const template = "<!-- ${very cool} -->";
expect(renderToString(template)).toBe("<!-- ${very cool} -->");
});
}); });
@@ -174,9 +174,6 @@ describe("expression evaluation", () => {
expect(compileExpr("list.data.map((data) => data)")).toBe( expect(compileExpr("list.data.map((data) => data)")).toBe(
"ctx['list'].data.map((_data)=>_data)" "ctx['list'].data.map((_data)=>_data)"
); );
expect(compileExpr("(ev) => { myFunc(v1, v2, ev.target.value); }")).toBe(
"(_ev)=>{ctx['myFunc'](ctx['v1'],ctx['v2'],_ev.target.value);}"
);
}); });
test.skip("arrow functions: not yet supported", () => { test.skip("arrow functions: not yet supported", () => {
// e is added to localvars in inline_expression but not removed after the arrow func body // e is added to localvars in inline_expression but not removed after the arrow func body
+4 -210
View File
@@ -43,7 +43,6 @@ describe("qweb parser", () => {
dynamicTag: null, dynamicTag: null,
content: [], content: [],
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -71,7 +70,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -86,7 +84,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -101,7 +98,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -113,7 +109,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -133,7 +128,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -145,7 +139,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -163,7 +156,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -189,7 +181,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -210,7 +201,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -233,7 +223,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -257,7 +246,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -274,7 +262,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: { class: "abc" }, attrs: { class: "abc" },
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -293,7 +280,6 @@ describe("qweb parser", () => {
height: "90px", height: "90px",
width: "100px", width: "100px",
}, },
attrsTranslationCtx: null,
content: [ content: [
{ {
attrs: { attrs: {
@@ -304,7 +290,6 @@ describe("qweb parser", () => {
stroke: "green", stroke: "green",
"stroke-width": "1", "stroke-width": "1",
}, },
attrsTranslationCtx: null,
content: [], content: [],
dynamicTag: null, dynamicTag: null,
model: null, model: null,
@@ -327,7 +312,6 @@ describe("qweb parser", () => {
parse(`<g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/></g>`) parse(`<g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/></g>`)
).toEqual({ ).toEqual({
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [ content: [
{ {
attrs: { attrs: {
@@ -338,7 +322,6 @@ describe("qweb parser", () => {
stroke: "green", stroke: "green",
"stroke-width": "1", "stroke-width": "1",
}, },
attrsTranslationCtx: null,
content: [], content: [],
dynamicTag: null, dynamicTag: null,
model: null, model: null,
@@ -365,7 +348,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [ content: [
@@ -374,7 +356,6 @@ describe("qweb parser", () => {
tag: "pre", tag: "pre",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [], content: [],
@@ -410,7 +391,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -433,7 +413,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -476,7 +455,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -491,7 +469,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -512,7 +489,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -554,7 +530,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -632,7 +607,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -652,7 +626,6 @@ describe("qweb parser", () => {
tag: "h1", tag: "h1",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -666,7 +639,6 @@ describe("qweb parser", () => {
tag: "h2", tag: "h2",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -713,7 +685,6 @@ describe("qweb parser", () => {
{ {
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
@@ -734,7 +705,6 @@ describe("qweb parser", () => {
{ {
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
@@ -772,7 +742,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -842,7 +811,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -885,7 +853,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -920,7 +887,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -954,7 +920,6 @@ describe("qweb parser", () => {
"t-att-selected": "category.id==options.active_category_id", "t-att-selected": "category.id==options.active_category_id",
"t-att-value": "category.id", "t-att-value": "category.id",
}, },
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -975,7 +940,6 @@ describe("qweb parser", () => {
).toEqual({ ).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -1023,7 +987,6 @@ describe("qweb parser", () => {
ref: null, ref: null,
model: null, model: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
ns: null, ns: null,
content: [{ type: ASTType.TEsc, expr: "item", defaultValue: "" }], content: [{ type: ASTType.TEsc, expr: "item", defaultValue: "" }],
}, },
@@ -1047,7 +1010,6 @@ describe("qweb parser", () => {
name: "Comp", name: "Comp",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
slots: null, slots: null,
on: null, on: null,
}, },
@@ -1137,7 +1099,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -1178,7 +1139,6 @@ describe("qweb parser", () => {
tag: "button", tag: "button",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: { click: "add" }, on: { click: "add" },
ref: null, ref: null,
model: null, model: null,
@@ -1215,7 +1175,6 @@ describe("qweb parser", () => {
tag: "select", tag: "select",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [ content: [
@@ -1224,7 +1183,6 @@ describe("qweb parser", () => {
tag: "option", tag: "option",
dynamicTag: null, dynamicTag: null,
attrs: { value: "1" }, attrs: { value: "1" },
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [], content: [],
@@ -1254,7 +1212,6 @@ describe("qweb parser", () => {
tag: "select", tag: "select",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [ content: [
@@ -1263,7 +1220,6 @@ describe("qweb parser", () => {
tag: "option", tag: "option",
dynamicTag: null, dynamicTag: null,
attrs: { "t-att-value": "valueVar" }, attrs: { "t-att-value": "valueVar" },
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
content: [], content: [],
@@ -1295,7 +1251,6 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: null, slots: null,
isDynamic: false, isDynamic: false,
@@ -1308,7 +1263,6 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: { a: "1", b: "'b'" }, props: { a: "1", b: "'b'" },
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: null, slots: null,
@@ -1321,7 +1275,6 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: "state", dynamicProps: "state",
props: { a: "1" }, props: { a: "1" },
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: null, slots: null,
@@ -1334,7 +1287,6 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: { click: "someMethod" }, on: { click: "someMethod" },
slots: null, slots: null,
@@ -1377,14 +1329,12 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
content: { type: ASTType.Text, value: "foo" }, content: { type: ASTType.Text, value: "foo" },
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
@@ -1400,14 +1350,12 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
content: { type: ASTType.Text, value: "foo" }, content: { type: ASTType.Text, value: "foo" },
attrs: { param: "param" }, attrs: { param: "param" },
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
@@ -1422,7 +1370,6 @@ describe("qweb parser", () => {
isDynamic: false, isDynamic: false,
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
default: { default: {
@@ -1434,7 +1381,6 @@ describe("qweb parser", () => {
tag: "span", tag: "span",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
ref: null, ref: null,
model: null, model: null,
@@ -1446,7 +1392,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
ref: null, ref: null,
model: null, model: null,
@@ -1456,7 +1401,6 @@ describe("qweb parser", () => {
], ],
}, },
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
@@ -1471,11 +1415,9 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
on: null, on: null,
props: null, props: null,
propsTranslationCtx: null,
slots: { slots: {
mySlot: { mySlot: {
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: null, content: null,
on: null, on: null,
scope: null, scope: null,
@@ -1492,16 +1434,9 @@ describe("qweb parser", () => {
isDynamic: false, isDynamic: false,
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
name: { name: { content: { type: ASTType.Text, value: "foo" }, attrs: null, on: null, scope: null },
content: { type: ASTType.Text, value: "foo" },
attrs: null,
attrsTranslationCtx: null,
on: null,
scope: null,
},
}, },
}); });
}); });
@@ -1513,13 +1448,11 @@ describe("qweb parser", () => {
isDynamic: false, isDynamic: false,
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
name: { name: {
content: { type: ASTType.Text, value: "foo" }, content: { type: ASTType.Text, value: "foo" },
attrs: { param: "param" }, attrs: { param: "param" },
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
@@ -1536,14 +1469,12 @@ describe("qweb parser", () => {
isDynamic: false, isDynamic: false,
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
name: { name: {
content: { type: ASTType.Text, value: "foo" }, content: { type: ASTType.Text, value: "foo" },
on: { click: "doStuff" }, on: { click: "doStuff" },
attrs: null, attrs: null,
attrsTranslationCtx: null,
scope: null, scope: null,
}, },
}, },
@@ -1562,24 +1493,16 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
content: { type: ASTType.Text, value: " " }, content: { type: ASTType.Text, value: " " },
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null,
scope: null,
},
name: {
content: { type: ASTType.Text, value: "foo" },
attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
name: { content: { type: ASTType.Text, value: "foo" }, attrs: null, on: null, scope: null },
}, },
}); });
}); });
@@ -1595,24 +1518,11 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
a: { a: { content: { type: ASTType.Text, value: "foo" }, attrs: null, on: null, scope: null },
content: { type: ASTType.Text, value: "foo" }, b: { content: { type: ASTType.Text, value: "bar" }, attrs: null, on: null, scope: null },
attrs: null,
attrsTranslationCtx: null,
on: null,
scope: null,
},
b: {
content: { type: ASTType.Text, value: "bar" },
attrs: null,
attrsTranslationCtx: null,
on: null,
scope: null,
},
}, },
}); });
}); });
@@ -1623,7 +1533,6 @@ describe("qweb parser", () => {
name: "myComponent", name: "myComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: true, isDynamic: true,
on: null, on: null,
slots: null, slots: null,
@@ -1636,7 +1545,6 @@ describe("qweb parser", () => {
name: "mycomponent", name: "mycomponent",
dynamicProps: null, dynamicProps: null,
props: { a: "1", b: "'b'" }, props: { a: "1", b: "'b'" },
propsTranslationCtx: null,
isDynamic: true, isDynamic: true,
on: null, on: null,
slots: null, slots: null,
@@ -1649,7 +1557,6 @@ describe("qweb parser", () => {
name: "mycomponent", name: "mycomponent",
dynamicProps: "state", dynamicProps: "state",
props: { a: "1" }, props: { a: "1" },
propsTranslationCtx: null,
isDynamic: true, isDynamic: true,
on: null, on: null,
slots: null, slots: null,
@@ -1680,14 +1587,12 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
content: { body: null, name: "subTemplate", type: ASTType.TCall, context: null }, content: { body: null, name: "subTemplate", type: ASTType.TCall, context: null },
attrs: null, attrs: null,
attrsTranslationCtx: null,
scope: null, scope: null,
on: null, on: null,
}, },
@@ -1708,13 +1613,11 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
content: { content: {
@@ -1723,13 +1626,11 @@ describe("qweb parser", () => {
name: "Child", name: "Child",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
brol: { brol: {
content: { type: ASTType.Text, value: "coucou" }, content: { type: ASTType.Text, value: "coucou" },
attrs: null, attrs: null,
attrsTranslationCtx: null,
scope: null, scope: null,
on: null, on: null,
}, },
@@ -1753,13 +1654,11 @@ describe("qweb parser", () => {
name: "MyComponent", name: "MyComponent",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
isDynamic: false, isDynamic: false,
on: null, on: null,
slots: { slots: {
default: { default: {
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
content: { content: {
@@ -1768,13 +1667,11 @@ describe("qweb parser", () => {
name: "Child", name: "Child",
dynamicProps: null, dynamicProps: null,
props: null, props: null,
propsTranslationCtx: null,
on: null, on: null,
slots: { slots: {
brol: { brol: {
content: { type: ASTType.Text, value: "coucou" }, content: { type: ASTType.Text, value: "coucou" },
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
scope: null, scope: null,
}, },
@@ -1794,7 +1691,6 @@ describe("qweb parser", () => {
type: ASTType.TSlot, type: ASTType.TSlot,
name: "default", name: "default",
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
defaultContent: null, defaultContent: null,
}); });
@@ -1805,7 +1701,6 @@ describe("qweb parser", () => {
type: ASTType.TSlot, type: ASTType.TSlot,
name: "header", name: "header",
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
defaultContent: { type: ASTType.Text, value: "default content" }, defaultContent: { type: ASTType.Text, value: "default content" },
}); });
@@ -1816,7 +1711,6 @@ describe("qweb parser", () => {
type: ASTType.TSlot, type: ASTType.TSlot,
name: "default", name: "default",
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: { "click.prevent": "doSomething" }, on: { "click.prevent": "doSomething" },
defaultContent: null, defaultContent: null,
}); });
@@ -1834,7 +1728,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -1853,7 +1746,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: null, ref: null,
model: null, model: null,
@@ -1873,7 +1765,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: "name", ref: "name",
model: null, model: null,
@@ -1888,7 +1779,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: "name", ref: "name",
model: null, model: null,
@@ -1905,7 +1795,6 @@ describe("qweb parser", () => {
tag: "div", tag: "div",
dynamicTag: null, dynamicTag: null,
attrs: null, attrs: null,
attrsTranslationCtx: null,
on: null, on: null,
ref: "name", ref: "name",
model: null, model: null,
@@ -1942,7 +1831,6 @@ describe("qweb parser", () => {
body: { body: {
content: { content: {
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [ content: [
{ {
type: ASTType.Text, type: ASTType.Text,
@@ -1971,92 +1859,6 @@ describe("qweb parser", () => {
}); });
}); });
// ---------------------------------------------------------------------------
// t-translation-context
// ---------------------------------------------------------------------------
test('t-translation-context="fr"', async () => {
expect(parse(`<t t-translation-context="fr">word</t>`)).toEqual({
type: ASTType.TTranslationContext,
content: {
type: ASTType.Text,
value: "word",
},
translationCtx: "fr",
});
expect(parse(`<div t-translation-context="fr">word</div>`)).toEqual({
content: {
attrs: null,
attrsTranslationCtx: null,
content: [
{
type: 0,
value: "word",
},
],
dynamicTag: null,
model: null,
ns: null,
on: null,
ref: null,
tag: "div",
type: ASTType.DomNode,
},
translationCtx: "fr",
type: ASTType.TTranslationContext,
});
});
// ---------------------------------------------------------------------------
// t-translation-context-attr
// ---------------------------------------------------------------------------
test('t-translation-context="fr" and t-translation-context-title="pt" for a div attr title', async () => {
expect(
parse(
`<div t-translation-context="fr" title="hello" t-translation-context-title="pt">word</div>`
)
).toEqual({
content: {
attrs: { title: "hello" },
attrsTranslationCtx: { title: "pt" },
content: [
{
type: 0,
value: "word",
},
],
dynamicTag: null,
model: null,
ns: null,
on: null,
ref: null,
tag: "div",
type: ASTType.DomNode,
},
translationCtx: "fr",
type: ASTType.TTranslationContext,
});
});
test('t-translation-context-title="fr" for component prop title', async () => {
expect(parse(`<Comp title="hello" t-translation-context-title="fr" />`)).toEqual({
dynamicProps: null,
isDynamic: false,
name: "Comp",
on: null,
props: {
title: "hello",
},
propsTranslationCtx: {
title: "fr",
},
slots: null,
type: ASTType.TComponent,
});
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// t-model // t-model
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -2064,7 +1866,6 @@ describe("qweb parser", () => {
expect(parse(`<input t-model="state.stuff" />`)).toEqual({ expect(parse(`<input t-model="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2085,7 +1886,6 @@ describe("qweb parser", () => {
expect(parse(`<input t-model="state['stuff']" />`)).toEqual({ expect(parse(`<input t-model="state['stuff']" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2106,7 +1906,6 @@ describe("qweb parser", () => {
expect(parse(`<input t-model.lazy.trim.number="state.stuff" />`)).toEqual({ expect(parse(`<input t-model.lazy.trim.number="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2128,7 +1927,6 @@ describe("qweb parser", () => {
expect(parse(`<textarea t-model="state.stuff" />`)).toEqual({ expect(parse(`<textarea t-model="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2149,7 +1947,6 @@ describe("qweb parser", () => {
expect(parse(`<input type="checkbox" t-model="state.stuff" />`)).toEqual({ expect(parse(`<input type="checkbox" t-model="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: { type: "checkbox" }, attrs: { type: "checkbox" },
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2170,7 +1967,6 @@ describe("qweb parser", () => {
expect(parse(`<input type="radio" t-model="state.stuff" />`)).toEqual({ expect(parse(`<input type="radio" t-model="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: { type: "radio" }, attrs: { type: "radio" },
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2191,7 +1987,6 @@ describe("qweb parser", () => {
expect(parse(`<input type="radio" t-model.lazy.trim.number="state.stuff" />`)).toEqual({ expect(parse(`<input type="radio" t-model.lazy.trim.number="state.stuff" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: { type: "radio" }, attrs: { type: "radio" },
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
@@ -2217,7 +2012,6 @@ describe("qweb parser", () => {
expect(parse(`<div t-tag="theTag" />`)).toEqual({ expect(parse(`<div t-tag="theTag" />`)).toEqual({
type: ASTType.DomNode, type: ASTType.DomNode,
attrs: null, attrs: null,
attrsTranslationCtx: null,
content: [], content: [],
on: null, on: null,
ref: null, ref: null,
-15
View File
@@ -154,19 +154,4 @@ describe("simple templates, mostly static", () => {
</div>`; </div>`;
expect(renderToString(template, { a: "a", b: "b", c: "c" })).toBe("<div>abLoadingc</div>"); expect(renderToString(template, { a: "a", b: "b", c: "c" })).toBe("<div>abLoadingc</div>");
}); });
test("text node with backslash at top level", () => {
const template = "\\";
expect(renderToString(template)).toBe("\\");
});
test("text node with backtick at top-level", () => {
const template = "`";
expect(renderToString(template)).toBe("`");
});
test("text node with interpolation sigil at top level", () => {
const template = "${very cool}";
expect(renderToString(template)).toBe("${very cool}");
});
}); });
-57
View File
@@ -1,57 +0,0 @@
import { App, Component, xml } from "../../src";
import { makeTestFixture, snapshotEverything } from "../helpers";
let fixture: HTMLElement;
snapshotEverything();
beforeEach(() => {
fixture = makeTestFixture();
});
describe("t-custom", () => {
test("can use t-custom directive on a node", async () => {
const steps: string[] = [];
class SomeComponent extends Component {
static template = xml`<div t-custom-plop="click" class="my-div"/>`;
click() {
steps.push("clicked");
}
}
const app = new App(SomeComponent, {
customDirectives: {
plop: (node, value) => {
node.setAttribute("t-on-click", value);
},
},
});
await app.mount(fixture);
expect(fixture.innerHTML).toBe(`<div class="my-div"></div>`);
fixture.querySelector("div")!.click();
expect(steps).toEqual(["clicked"]);
});
test("can use t-custom directive with modifiers on a node", async () => {
const steps: string[] = [];
class SomeComponent extends Component {
static template = xml`<div t-custom-plop.mouse.stop="click" class="my-div"/>`;
click() {
steps.push("clicked");
}
}
const app = new App(SomeComponent, {
customDirectives: {
plop: (node, value, modifiers) => {
node.setAttribute("t-on-click", value);
for (let mod of modifiers) {
steps.push(mod);
}
},
},
});
await app.mount(fixture);
expect(fixture.innerHTML).toBe(`<div class="my-div"></div>`);
fixture.querySelector("div")!.click();
expect(steps).toEqual(["mouse", "stop", "clicked"]);
});
});
-15
View File
@@ -121,19 +121,4 @@ describe("t-esc", () => {
mount(bdom, fixture); mount(bdom, fixture);
expect(fixture.querySelector("span")!.textContent).toBe("<p>escaped</p>"); expect(fixture.querySelector("span")!.textContent).toBe("<p>escaped</p>");
}); });
test("default with backslash at top level", () => {
const template = '<t t-esc="undefined">\\</t>';
expect(renderToString(template)).toBe("\\");
});
test("default with backtick at top-level", () => {
const template = '<t t-esc="undefined">`</t>';
expect(renderToString(template)).toBe("`");
});
test("default with interpolation sigil at top level", () => {
const template = '<t t-esc="undefined">${very cool}</t>';
expect(renderToString(template)).toBe("${very cool}");
});
}); });
-15
View File
@@ -54,21 +54,6 @@ describe("t-set", () => {
expect(renderToString(template)).toBe("ok"); expect(renderToString(template)).toBe("ok");
}); });
test("body with backslash at top level", () => {
const template = '<t t-set="value">\\</t><t t-esc="value"/>';
expect(renderToString(template)).toBe("\\");
});
test("body with backtick at top-level", () => {
const template = '<t t-set="value">`</t><t t-esc="value"/>';
expect(renderToString(template)).toBe("`");
});
test("body with interpolation sigil at top level", () => {
const template = '<t t-set="value">${very cool}</t><t t-esc="value"/>';
expect(renderToString(template)).toBe("${very cool}");
});
test("set from body literal (with t-if/t-else", () => { test("set from body literal (with t-if/t-else", () => {
const template = ` const template = `
<t> <t>
+2 -125
View File
@@ -86,7 +86,7 @@ describe("translation support", () => {
await mount(SomeComponent, fixture, { translateFn }); await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div> mot </div>"); expect(fixture.innerHTML).toBe("<div> mot </div>");
expect(translateFn).toHaveBeenCalledWith("word", ""); expect(translateFn).toHaveBeenCalledWith("word");
}); });
test("translation works, even if initial string has inner consecutive white space", async () => { test("translation works, even if initial string has inner consecutive white space", async () => {
@@ -97,7 +97,7 @@ describe("translation support", () => {
const translateFn = jest.fn((expr: string) => (expr === "some word" ? "un mot" : expr)); const translateFn = jest.fn((expr: string) => (expr === "some word" ? "un mot" : expr));
await mount(SomeComponent, fixture, { translateFn }); await mount(SomeComponent, fixture, { translateFn });
expect(translateFn).toHaveBeenCalledWith("some word", ""); expect(translateFn).toHaveBeenCalledWith("some word");
expect(fixture.innerHTML).toBe("<div>un mot</div>"); expect(fixture.innerHTML).toBe("<div>un mot</div>");
}); });
@@ -171,126 +171,3 @@ describe("translation support", () => {
expect(fixture.innerHTML).toBe("translated"); expect(fixture.innerHTML).toBe("translated");
}); });
}); });
describe("translation context", () => {
test("translation of text in context", async () => {
class SomeComponent extends Component {
static template = xml`
<div>word</div>
<div t-translation-context="fr">word</div>
`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "fr" ? (expr === "word" ? "mot" : expr) : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div>word</div><div>mot</div>");
expect(translateFn).toHaveBeenCalledWith("word", "");
expect(translateFn).toHaveBeenCalledWith("word", "fr");
});
test("translation of attributes in context", async () => {
class SomeComponent extends Component {
static template = xml`
<div t-translation-context="en" t-translation-context-title="fr" title="title" label="game"/>
`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "fr" ? (expr === "title" ? "titre" : expr) : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe(`<div title="titre" label="game"></div>`);
expect(translateFn).toHaveBeenCalledWith("title", "fr");
expect(translateFn).toHaveBeenCalledWith("game", "en");
});
test("body of t-sets are translated in context", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label" t-translation-context="fr">untranslated</t>
<t t-esc="label"/>`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "fr" ? "traduit" : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("traduit");
expect(translateFn).toHaveBeenCalledWith("untranslated", "fr");
});
test("props with modifier .translate are translated in context", async () => {
class ChildComponent extends Component {
static props = ["text"];
static template = xml`<span t-esc="props.text"/>`;
}
class SomeComponent extends Component {
static components = { ChildComponent };
static template = xml`
<ChildComponent text.translate="game" t-translation-context-text.translate="fr" />`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "fr" ? "jeu" : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<span>jeu</span>");
expect(translateFn).toHaveBeenCalledWith("game", "fr");
});
test("slot attrs and text contents are translated in context", async () => {
class ChildComponent extends Component {
static template = xml`
<div t-translation-context="ja">
<t t-slot="a"/>
</div>`;
}
class SomeComponent extends Component {
static components = { ChildComponent };
static template = xml`
<ChildComponent t-translation-context="fr">
<t t-set-slot="a" title.translate="title" t-translation-context-title.translate="pt">game</t>
</ChildComponent>
`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "fr" ? "jeu" : translationCtx === "pt" ? "título" : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div>jeu</div>");
expect(translateFn).toHaveBeenCalledWith("game", "fr");
expect(translateFn).toHaveBeenCalledWith("title", "pt");
});
test("default slot params and content translated in context", async () => {
class SomeComponent extends Component {
static template = xml`
<div>
<t
t-slot="default"
t-translation-context="fr"
param.translate="param"
title.translate="title"
t-translation-context-title.translate="pt"
>
foo
</t>
</div>`;
}
const translateFn = jest.fn((expr: string, translationCtx: string) =>
translationCtx === "pt" ? "título" : expr
);
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div> foo </div>");
expect(translateFn).toHaveBeenCalledWith("foo", "fr");
expect(translateFn).toHaveBeenCalledWith("param", "fr");
expect(translateFn).toHaveBeenCalledWith("title", "pt");
});
});
+1 -1
View File
@@ -48,7 +48,7 @@ describe("basic validation", () => {
test("compilation error", () => { test("compilation error", () => {
const template = `<div t-att-class="a b">test</div>`; const template = `<div t-att-class="a b">test</div>`;
expect(() => renderToString(template)) expect(() => renderToString(template))
.toThrow(`Failed to compile anonymous template: Unexpected identifier 'ctx' .toThrow(`Failed to compile anonymous template: Unexpected identifier
generated code: generated code:
function(app, bdom, helpers) { function(app, bdom, helpers) {
@@ -97,19 +97,6 @@ exports[`basics a component cannot be mounted in a detached node (even if node i
}" }"
`; `;
exports[`basics a component cannot be mounted in a detached node 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`basics a component inside a component 1`] = ` exports[`basics a component inside a component 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -274,19 +261,6 @@ exports[`basics can mount a simple component with props 1`] = `
}" }"
`; `;
exports[`basics cannot mount on a documentFragment 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>content</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`basics child can be updated 1`] = ` exports[`basics child can be updated 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1028,19 +1002,6 @@ exports[`basics three level of components with collapsing root nodes 3`] = `
}" }"
`; `;
exports[`basics throws if mounting on target=null 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<span>simple vnode</span>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`basics two child components 1`] = ` exports[`basics two child components 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -320,50 +320,6 @@ exports[`can catch errors can catch an error in a component render function 3`]
}" }"
`; `;
exports[`can catch errors can catch an error in onmounted 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(null, false, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
b2 = text(\`Main\`);
if (ctx['state'].ok) {
const Comp1 = ctx['component'];
b3 = toggler(Comp1, comp1({}, (Comp1).name + key + \`__1\`, node, this, Comp1));
}
return multi([b2, b3]);
}
}"
`;
exports[`can catch errors can catch an error in onmounted 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>Error!!!</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`can catch errors can catch an error in onmounted 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>perfect</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`can catch errors can catch an error in the constructor call of a component render function 1`] = ` exports[`can catch errors can catch an error in the constructor call of a component render function 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1191,135 +1147,6 @@ exports[`can catch errors error in mounted on a component with a sibling (proper
}" }"
`; `;
exports[`can catch errors error in onMounted, graceful recovery 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(null, false, false, false, []);
return function template(ctx, node, key = \\"\\") {
const Comp1 = ctx['component'];
return toggler(Comp1, comp1({}, (Comp1).name + key + \`__1\`, node, this, Comp1));
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
const comp2 = app.createComponent(\`Boom\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`parent\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
const b4 = comp2({}, key + \`__2\`, node, this, null);
return multi([b2, b3, b4]);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`abc\`);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`boom\`);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`def\`);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery, variation 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(null, false, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
b2 = text(\`R\`);
if (ctx['state'].gogogo) {
const Comp1 = ctx['component'];
b3 = toggler(Comp1, comp1({}, (Comp1).name + key + \`__1\`, node, this, Comp1));
}
return multi([b2, b3]);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery, variation 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
const comp2 = app.createComponent(\`Boom\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`parent\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
const b4 = comp2({}, key + \`__2\`, node, this, null);
return multi([b2, b3, b4]);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery, variation 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`abc\`);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery, variation 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`boom\`);
}
}"
`;
exports[`can catch errors error in onMounted, graceful recovery, variation 6`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`def\`);
}
}"
`;
exports[`can catch errors onError in class inheritance is called if rethrown 1`] = ` exports[`can catch errors onError in class inheritance is called if rethrown 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -683,7 +683,7 @@ exports[`lifecycle hooks sub widget (inside sub node): hooks are correctly calle
}" }"
`; `;
exports[`lifecycle hooks timeout in onWillStart doesn't emit a console log if app is destroyed 1`] = ` exports[`lifecycle hooks timeout in onWillStart emits a warning 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom; let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -696,20 +696,7 @@ exports[`lifecycle hooks timeout in onWillStart doesn't emit a console log if ap
}" }"
`; `;
exports[`lifecycle hooks timeout in onWillStart emits a console log 1`] = ` exports[`lifecycle hooks timeout in onWillUpdateProps emits a warning 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<span/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`lifecycle hooks timeout in onWillUpdateProps emits a console log 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom; let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -723,7 +710,7 @@ exports[`lifecycle hooks timeout in onWillUpdateProps emits a console log 1`] =
}" }"
`; `;
exports[`lifecycle hooks timeout in onWillUpdateProps emits a console log 2`] = ` exports[`lifecycle hooks timeout in onWillUpdateProps emits a warning 2`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom; let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -66,29 +66,6 @@ exports[`.alike suffix in a simple case 2`] = `
}" }"
`; `;
exports[`.translate props are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({message: \`translated message\`}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`.translate props are translated 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(ctx['props'].message);
}
}"
`;
exports[`basics accept ES6-like syntax for props (with getters) 1`] = ` exports[`basics accept ES6-like syntax for props (with getters) 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -435,29 +412,6 @@ exports[`can bind function prop with bind suffix 2`] = `
}" }"
`; `;
exports[`can use .translate suffix 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({message: \`some message\`}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`can use .translate suffix 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(ctx['props'].message);
}
}"
`;
exports[`do not crash when binding anonymous function prop with bind suffix 1`] = ` exports[`do not crash when binding anonymous function prop with bind suffix 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -167,45 +167,6 @@ exports[`props validation can specify that additional props are allowed (object)
}" }"
`; `;
exports[`props validation can use custom class as type 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, [\\"customObj\\"]);
return function template(ctx, node, key = \\"\\") {
const props1 = {customObj: ctx['customObj']};
helpers.validateProps(\`Child\`, props1, this);
return comp1(props1, key + \`__1\`, node, this, null);
}
}"
`;
exports[`props validation can use custom class as type 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(ctx['props'].customObj.val);
}
}"
`;
exports[`props validation can use custom class as type: validation failure 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, [\\"customObj\\"]);
return function template(ctx, node, key = \\"\\") {
const props1 = {customObj: ctx['customObj']};
helpers.validateProps(\`Child\`, props1, this);
return comp1(props1, key + \`__1\`, node, this, null);
}
}"
`;
exports[`props validation can validate a prop with multiple types 1`] = ` exports[`props validation can validate a prop with multiple types 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -924,20 +885,6 @@ exports[`props validation props: list of strings 1`] = `
}" }"
`; `;
exports[`props validation validate props for root component 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><block-text-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
let txt1 = ctx['message'];
return block1([txt1]);
}
}"
`;
exports[`props validation validate simple types 1`] = ` exports[`props validation validate simple types 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -1,30 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`slots .translate slot props are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp1({slots: markRaw({'default': {message: \`translated message\`}})}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`slots .translate slot props are translated 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(ctx['props'].slots.default.message);
}
}"
`;
exports[`slots can define a default content 1`] = ` exports[`slots can define a default content 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
@@ -226,31 +201,6 @@ exports[`slots can render only empty slot 1`] = `
}" }"
`; `;
exports[`slots can use .translate suffix on slot props 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp1({slots: markRaw({'default': {message: \`some message\`}})}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`slots can use .translate suffix on slot props 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(ctx['props'].slots.default.message);
}
}"
`;
exports[`slots can use component in default-content of t-slot 1`] = ` exports[`slots can use component in default-content of t-slot 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
+2 -272
View File
@@ -157,7 +157,7 @@ describe("basics", () => {
} catch (e) { } catch (e) {
error = e as Error; error = e as Error;
} }
const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier 'ctx' const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier
generated code: generated code:
function(app, bdom, helpers) { function(app, bdom, helpers) {
@@ -182,7 +182,7 @@ function(app, bdom, helpers) {
static components = { Child }; static components = { Child };
static template = xml`<Child/>`; static template = xml`<Child/>`;
} }
const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier 'ctx' const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier
generated code: generated code:
function(app, bdom, helpers) { function(app, bdom, helpers) {
@@ -564,82 +564,6 @@ describe("can catch errors", () => {
expect(mockConsoleWarn).toBeCalledTimes(0); expect(mockConsoleWarn).toBeCalledTimes(0);
}); });
test("can catch an error in onmounted", async () => {
class ErrorComponent extends Component {
static template = xml`<div>Error!!!</div>`;
setup() {
useLogLifecycle();
onMounted(() => {
throw new Error("error");
});
}
}
class PerfectComponent extends Component {
static template = xml`<div>perfect</div>`;
setup() {
useLogLifecycle();
}
}
class Main extends Component {
static template = xml`Main<t t-if="state.ok" t-component="component"/>`;
component: any;
state: any;
setup() {
this.state = useState({ ok: false });
useLogLifecycle();
this.component = ErrorComponent;
onError(() => {
this.component = PerfectComponent;
this.render();
});
}
}
const app = await mount(Main, fixture);
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Main:setup",
"Main:willStart",
"Main:willRender",
"Main:rendered",
"Main:mounted",
]
`);
expect(fixture.innerHTML).toBe("Main");
(app as any).state.ok = true;
await nextTick();
expect(fixture.innerHTML).toBe("Main<div>Error!!!</div>");
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Main:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"Main:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"Main:willPatch",
"ErrorComponent:mounted",
"Main:willRender",
"PerfectComponent:setup",
"PerfectComponent:willStart",
"Main:rendered",
]
`);
await nextTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"PerfectComponent:willRender",
"PerfectComponent:rendered",
"Main:willPatch",
"ErrorComponent:willUnmount",
"ErrorComponent:willDestroy",
"PerfectComponent:mounted",
"Main:patched",
]
`);
expect(fixture.innerHTML).toBe("Main<div>perfect</div>");
});
test("calling a hook outside setup should crash", async () => { test("calling a hook outside setup should crash", async () => {
class Root extends Component { class Root extends Component {
static template = xml`<t t-esc="state.value"/>`; static template = xml`<t t-esc="state.value"/>`;
@@ -1678,198 +1602,4 @@ describe("can catch errors", () => {
`); `);
expect(fixture.innerHTML).toBe("2"); expect(fixture.innerHTML).toBe("2");
}); });
test("error in onMounted, graceful recovery", async () => {
class Child extends Component {
static template = xml`abc`;
setup() {
useLogLifecycle();
}
}
class OtherChild extends Component {
static template = xml`def`;
setup() {
useLogLifecycle();
}
}
class Boom extends Component {
static template = xml`boom`;
setup() {
useLogLifecycle();
onMounted(() => {
throw new Error("boom");
});
}
}
class Parent extends Component {
static template = xml`parent<Child/><Boom/>`;
static components = { Child, Boom };
setup() {
useLogLifecycle();
}
}
class Root extends Component {
static template = xml`<t t-component="component"/>`;
component: any = Parent;
setup() {
useLogLifecycle();
onError(() => {
logStep("error");
this.component = OtherChild;
this.render();
});
}
}
await mount(Root, fixture);
expect(fixture.innerHTML).toBe("def");
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:setup",
"Root:willStart",
"Root:willRender",
"Parent:setup",
"Parent:willStart",
"Root:rendered",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Boom:setup",
"Boom:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Boom:willRender",
"Boom:rendered",
"Boom:mounted",
"error",
"Root:willRender",
"OtherChild:setup",
"OtherChild:willStart",
"Root:rendered",
"OtherChild:willRender",
"OtherChild:rendered",
"OtherChild:mounted",
"Root:mounted",
]
`);
});
test("error in onMounted, graceful recovery, variation", async () => {
class Child extends Component {
static template = xml`abc`;
setup() {
useLogLifecycle();
}
}
class OtherChild extends Component {
static template = xml`def`;
setup() {
useLogLifecycle();
}
}
class Boom extends Component {
static template = xml`boom`;
setup() {
useLogLifecycle();
onMounted(() => {
throw new Error("boom");
});
}
}
class Parent extends Component {
static template = xml`parent<Child/><Boom/>`;
static components = { Child, Boom };
setup() {
useLogLifecycle();
}
}
class Root extends Component {
static template = xml`R<t t-if="state.gogogo" t-component="component"/>`;
component: any = Parent;
state = useState({ gogogo: false });
setup() {
useLogLifecycle();
onError(() => {
logStep("error");
this.component = OtherChild;
this.render();
});
}
}
const root = await mount(Root, fixture);
expect(fixture.innerHTML).toBe("R");
// standard mounting process
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:setup",
"Root:willStart",
"Root:willRender",
"Root:rendered",
"Root:mounted",
]
`);
root.state.gogogo = true;
await nextTick();
expect(fixture.innerHTML).toBe("Rparentabcboom");
// rerender, root creates sub components, it crashes, tries to recover
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:willRender",
"Parent:setup",
"Parent:willStart",
"Root:rendered",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Boom:setup",
"Boom:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Boom:willRender",
"Boom:rendered",
"Root:willPatch",
"Boom:mounted",
"error",
"Root:willRender",
"OtherChild:setup",
"OtherChild:willStart",
"Root:rendered",
]
`);
await nextTick();
expect(fixture.innerHTML).toBe("Rdef");
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"OtherChild:willRender",
"OtherChild:rendered",
"Root:willPatch",
"Child:willDestroy",
"Boom:willUnmount",
"Boom:willDestroy",
"Parent:willDestroy",
"OtherChild:mounted",
"Root:patched",
]
`);
});
}); });
+44 -89
View File
@@ -1,9 +1,5 @@
import { App, Component, mount, onMounted, onWillStart, useState, xml } from "../../src";
import { import {
App,
Component,
mount,
useState,
xml,
onWillPatch, onWillPatch,
onWillUnmount, onWillUnmount,
onPatched, onPatched,
@@ -11,9 +7,7 @@ import {
onWillRender, onWillRender,
onWillDestroy, onWillDestroy,
onRendered, onRendered,
onMounted, } from "../../src/runtime/lifecycle_hooks";
onWillStart,
} from "../../src";
import { status } from "../../src/runtime/status"; import { status } from "../../src/runtime/status";
import { import {
elem, elem,
@@ -112,10 +106,10 @@ describe("lifecycle hooks", () => {
await mount(Test, fixture); await mount(Test, fixture);
}); });
test("timeout in onWillStart emits a console log", async () => { test("timeout in onWillStart emits a warning", async () => {
const { log } = console; const { warn } = console;
let logArgs: any[]; let warnArgs: any[];
console.log = jest.fn((...args) => (logArgs = args)); console.warn = jest.fn((...args) => (warnArgs = args));
const { setTimeout } = window; const { setTimeout } = window;
let timeoutCbs: any = {}; let timeoutCbs: any = {};
let timeoutId = 0; let timeoutId = 0;
@@ -123,63 +117,27 @@ describe("lifecycle hooks", () => {
timeoutCbs[++timeoutId] = cb; timeoutCbs[++timeoutId] = cb;
return timeoutId; return timeoutId;
}) as any; }) as any;
try { class Test extends Component {
class Test extends Component { static template = xml`<span/>`;
static template = xml`<span/>`; setup() {
setup() { onWillStart(() => new Promise(() => {}));
onWillStart(() => new Promise(() => {}));
}
} }
mount(Test, fixture, { test: true });
nextTick();
for (const id in timeoutCbs) {
timeoutCbs[id]();
delete timeoutCbs[id];
}
await nextMicroTick();
await nextMicroTick();
expect(console.log).toHaveBeenCalledTimes(1);
expect(logArgs![0]!.message).toBe("onWillStart's promise hasn't resolved after 3 seconds");
} finally {
console.log = log;
window.setTimeout = setTimeout;
} }
mount(Test, fixture, { test: true });
nextTick();
for (const id in timeoutCbs) {
timeoutCbs[id]();
delete timeoutCbs[id];
}
await nextMicroTick();
await nextMicroTick();
expect(console.warn).toHaveBeenCalledTimes(1);
expect(warnArgs![0]!.message).toBe("onWillStart's promise hasn't resolved after 3 seconds");
console.warn = warn;
window.setTimeout = setTimeout;
}); });
test("timeout in onWillStart doesn't emit a console log if app is destroyed", async () => { test("timeout in onWillUpdateProps emits a warning", async () => {
const { log } = console;
console.log = jest.fn();
const { setTimeout } = window;
let timeoutCbs: any = {};
let timeoutId = 0;
window.setTimeout = ((cb: any) => {
timeoutCbs[++timeoutId] = cb;
return timeoutId;
}) as any;
try {
class Test extends Component {
static template = xml`<span/>`;
setup() {
onWillStart(() => new Promise(() => {}));
}
}
const app = new App(Test, { test: true });
app.mount(fixture);
app.destroy();
for (const id in timeoutCbs) {
timeoutCbs[id]();
delete timeoutCbs[id];
}
await nextMicroTick();
await nextMicroTick();
expect(console.log).toHaveBeenCalledTimes(0);
} finally {
console.log = log;
window.setTimeout = setTimeout;
}
});
test("timeout in onWillUpdateProps emits a console log", async () => {
class Child extends Component { class Child extends Component {
static template = xml``; static template = xml``;
setup() { setup() {
@@ -193,9 +151,9 @@ describe("lifecycle hooks", () => {
} }
const parent = await mount(Parent, fixture, { test: true }); const parent = await mount(Parent, fixture, { test: true });
const { log } = console; const { warn } = console;
let logArgs: any[]; let warnArgs: any[];
console.log = jest.fn((...args) => (logArgs = args)); console.warn = jest.fn((...args) => (warnArgs = args));
const { setTimeout } = window; const { setTimeout } = window;
let timeoutCbs: any = {}; let timeoutCbs: any = {};
let timeoutId = 0; let timeoutId = 0;
@@ -204,28 +162,25 @@ describe("lifecycle hooks", () => {
return timeoutId; return timeoutId;
}) as any; }) as any;
try { parent.state.prop = 2;
parent.state.prop = 2; let tick = nextTick();
let tick = nextTick(); for (const id in timeoutCbs) {
for (const id in timeoutCbs) { timeoutCbs[id]();
timeoutCbs[id](); delete timeoutCbs[id];
delete timeoutCbs[id];
}
await tick;
tick = nextTick();
for (const id in timeoutCbs) {
timeoutCbs[id]();
delete timeoutCbs[id];
}
await tick;
expect(console.log).toHaveBeenCalledTimes(1);
expect(logArgs![0]!.message).toBe(
"onWillUpdateProps's promise hasn't resolved after 3 seconds"
);
} finally {
console.log = log;
window.setTimeout = setTimeout;
} }
await tick;
tick = nextTick();
for (const id in timeoutCbs) {
timeoutCbs[id]();
delete timeoutCbs[id];
}
await tick;
expect(console.warn).toHaveBeenCalledTimes(1);
expect(warnArgs![0]!.message).toBe(
"onWillUpdateProps's promise hasn't resolved after 3 seconds"
);
console.warn = warn;
window.setTimeout = setTimeout;
}); });
test("mounted hook is called if mounted in DOM", async () => { test("mounted hook is called if mounted in DOM", async () => {
+1 -29
View File
@@ -299,34 +299,6 @@ test("bound functions are considered 'alike'", async () => {
expect(fixture.innerHTML).toBe("3child"); expect(fixture.innerHTML).toBe("3child");
}); });
test("can use .translate suffix", async () => {
class Child extends Component {
static template = xml`<t t-esc="props.message"/>`;
}
class Parent extends Component {
static template = xml`<Child message.translate="some message"/>`;
static components = { Child };
}
await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("some message");
});
test(".translate props are translated", async () => {
class Child extends Component {
static template = xml`<t t-esc="props.message"/>`;
}
class Parent extends Component {
static template = xml`<Child message.translate="some message"/>`;
static components = { Child };
}
await mount(Parent, fixture, { translateFn: () => "translated message" });
expect(fixture.innerHTML).toBe("translated message");
});
test("throw if prop uses an unknown suffix", async () => { test("throw if prop uses an unknown suffix", async () => {
class Child extends Component { class Child extends Component {
static template = xml`<t t-esc="props.val"/>`; static template = xml`<t t-esc="props.val"/>`;
@@ -339,7 +311,7 @@ test("throw if prop uses an unknown suffix", async () => {
await expect(async () => { await expect(async () => {
await mount(Parent, fixture); await mount(Parent, fixture);
}).rejects.toThrowError("Invalid prop suffix: somesuffix"); }).rejects.toThrowError("Invalid prop suffix");
}); });
test(".alike suffix in a simple case", async () => { test(".alike suffix in a simple case", async () => {
-46
View File
@@ -829,52 +829,6 @@ describe("props validation", () => {
expect(error!).toBeDefined(); expect(error!).toBeDefined();
expect(error!.message).toBe("Invalid props for component 'Child': 'message' is missing"); expect(error!.message).toBe("Invalid props for component 'Child': 'message' is missing");
}); });
test("can use custom class as type", async () => {
class CustomClass {
val = "hey";
}
class Child extends Component {
static props = { customObj: CustomClass };
static template = xml`<t t-esc="props.customObj.val"/>`;
}
class Parent extends Component {
static components = { Child };
static template = xml`<Child customObj="customObj" />`;
customObj = new CustomClass();
}
const app = new App(Parent, { test: true });
await app.mount(fixture);
expect(fixture.innerHTML).toBe("hey");
});
test("can use custom class as type: validation failure", async () => {
class CustomClass {}
class Child extends Component {
static props = { customObj: CustomClass };
static template = xml`<div>hey</div>`;
}
class Parent extends Component {
static components = { Child };
static template = xml`<Child customObj="customObj" />`;
customObj = {};
}
const app = new App(Parent, { test: true });
let error: OwlError | undefined;
const mountProm = app.mount(fixture).catch((e: Error) => (error = e));
await expect(nextAppError(app)).resolves.toThrow(
"Invalid props for component 'Child': 'customObj' is not a customclass"
);
await mountProm;
expect(error!).toBeDefined();
expect(error!.message).toBe(
"Invalid props for component 'Child': 'customObj' is not a customclass"
);
});
}); });
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
-28
View File
@@ -179,34 +179,6 @@ describe("slots", () => {
expect(fixture.innerHTML).toBe("<span>default empty</span>"); expect(fixture.innerHTML).toBe("<span>default empty</span>");
}); });
test("can use .translate suffix on slot props", async () => {
class Child extends Component {
static template = xml`<t t-esc="props.slots.default.message"/>`;
}
class Parent extends Component {
static template = xml`<Child><t t-set-slot="default" message.translate="some message"/></Child>`;
static components = { Child };
}
await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("some message");
});
test(".translate slot props are translated", async () => {
class Child extends Component {
static template = xml`<t t-esc="props.slots.default.message"/>`;
}
class Parent extends Component {
static template = xml`<Child><t t-set-slot="default" message.translate="some message"/></Child>`;
static components = { Child };
}
await mount(Parent, fixture, { translateFn: () => "translated message" });
expect(fixture.innerHTML).toBe("translated message");
});
test("default slot with slot scope: shorthand syntax", async () => { test("default slot with slot scope: shorthand syntax", async () => {
let child: any; let child: any;
class Child extends Component { class Child extends Component {
+154 -1
View File
@@ -9,7 +9,7 @@ import {
markRaw, markRaw,
toRaw, toRaw,
} from "../src"; } from "../src";
import { reactive, getSubscriptions } from "../src/runtime/reactivity"; import { reactive, getSubscriptions, derived } from "../src/runtime/reactivity";
import { batched } from "../src/runtime/utils"; import { batched } from "../src/runtime/utils";
import { import {
makeDeferred, makeDeferred,
@@ -2424,3 +2424,156 @@ describe("Reactivity: useState", () => {
expect(fixture.innerHTML).toBe("<div><p><span>2b</span></p></div>"); expect(fixture.innerHTML).toBe("<div><p><span>2b</span></p></div>");
}); });
}); });
describe("derived", () => {
test("can read", async () => {
const state = reactive({ a: derived([], () => 1) });
expect(state.a).toBe(1);
});
test("can create new keys", () => {
const state: any = reactive({ b: derived([], () => 2) });
state.a = 1;
expect(state.a).toBe(1);
});
test("can update", () => {
const o = reactive({ a: 1 });
let computeCall = 0;
const state = reactive({
a: derived([o], (o) => {
computeCall++;
return o.a;
}),
});
expect(computeCall).toBe(1);
expect(state.a).toBe(1);
o.a = 2;
expect(computeCall).toBe(2);
expect(state.a).toBe(2);
});
test("callback is called when changing an observed property", async () => {
let notifyCount = 0;
const o = reactive({ a: 1 });
let computeCall = 0;
const state = reactive(
{
a: derived([o], (o) => {
computeCall++;
return o.a;
}),
},
() => notifyCount++
);
expect(computeCall).toBe(1);
expect(notifyCount).toBe(0);
expect(state.a).toBe(1);
o.a = 2;
expect(computeCall).toBe(2);
expect(notifyCount).toBe(1);
expect(state.a).toBe(2);
o.a = 5;
expect(computeCall).toBe(3);
expect(notifyCount).toBe(2);
expect(state.a).toBe(5);
});
test("multiple dependencies", async () => {
let notifyCount = 0;
const a = reactive({ val: 1 });
const b = reactive({ val: 2 });
let computeCall = 0;
const state = reactive(
{
c: derived([a, b], (a, b) => {
computeCall++;
return a.val + b.val;
}),
},
() => notifyCount++
);
expect(computeCall).toBe(1);
a.val = 2;
expect(computeCall).toBe(2);
expect(notifyCount).toBe(0);
expect(state.c).toBe(4);
a.val = 4;
expect(computeCall).toBe(3);
expect(notifyCount).toBe(1);
expect(state.c).toBe(6);
b.val = 3;
expect(computeCall).toBe(4);
expect(notifyCount).toBe(2);
expect(state.c).toBe(7);
});
test("dependency on own fields", async () => {
let notifyCount = 0;
const a = reactive({ val: 1 });
let computeCall = 0;
const state = reactive(
{
b: 2,
c: derived([a], function (this: any, a) {
computeCall++;
return a.val + this.b;
}),
},
() => notifyCount++
);
expect(computeCall).toBe(1);
a.val = 2;
expect(computeCall).toBe(2);
expect(notifyCount).toBe(0);
expect(state.c).toBe(4);
a.val = 4;
expect(computeCall).toBe(3);
expect(notifyCount).toBe(1);
expect(state.c).toBe(6);
state.b = 3;
expect(computeCall).toBe(4);
expect(notifyCount).toBe(2);
expect(state.c).toBe(7);
});
test("dependency on derived property", () => {
let computeB = 0;
let computeC = 0;
const state = reactive({
a: 1,
b: derived([], function (this: any) {
computeB++;
return this.a + 1;
}),
c: derived([], function (this: any) {
computeC++;
return this.b + 1;
}),
});
expect(computeB).toBe(1);
expect(computeC).toBe(1);
expect(state.c).toBe(3);
});
test("dependency on derived property appearing later in object", () => {
let computeB = 0;
let computeC = 0;
const state = reactive({
a: 1,
c: derived([], function (this: any) {
computeC++;
return this.b + 1;
}),
b: derived([], function (this: any) {
computeB++;
return this.a + 1;
}),
});
expect(computeB).toBe(1);
// because computation is eager and naive, C is first computed to be undefined, then B is computed
// to be 2, and the computation of B causes C to recompute and become 3. This causes C to compute twice.
expect(computeC).toBe(2);
expect(state.c).toBe(3);
});
});
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env node
// this is the "compile_owl_templates" command that owl makes available when
// installed as a node_module.
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { dirname } from "path";
import { compileTemplates } from "../dist/compile_templates.mjs";
import { parseArgs } from "util";
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
output: {
type: "string",
short: "o",
default: "templates.js",
},
},
});
if (positionals.length) {
const result = await compileTemplates(positionals);
const outputPath = values.output;
const dir = dirname(outputPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(outputPath, result);
} else {
console.log("Please provide a path");
}
+113
View File
@@ -0,0 +1,113 @@
const fs = require("fs");
const path = require("path");
const jsdom = require("jsdom");
// -----------------------------------------------------------------------------
// add global DOM stuff for compiler
// -----------------------------------------------------------------------------
var document = new jsdom.JSDOM("", {});
var window = document.window;
global.document = window.document;
global.window = window;
global.DOMParser = window.DOMParser;
global.Element = window.Element;
global.Node = window.Node;
// this needs to be below the jsdom stuff
const { compile } = require("../dist/compiler.js");
// -----------------------------------------------------------------------------
// helpers
// -----------------------------------------------------------------------------
async function getXmlFiles(dir) {
let xmls = [];
const files = await fs.promises.readdir(dir);
const filesStats = await Promise.all(files.map((file) => fs.promises.stat(path.join(dir, file))));
for (let i in files) {
const name = path.join(dir, files[i]);
if (filesStats[i].isDirectory()) {
xmls = xmls.concat(await getXmlFiles(name));
} else {
if (name.endsWith(".xml")) {
xmls.push(name);
}
}
}
return xmls;
}
function writeToFile(filepath, data) {
if (!fs.existsSync(path.dirname(filepath))) {
fs.mkdirSync(path.dirname(filepath), { recursive: true });
}
fs.writeFile(filepath, data, (err) => {
if (err) {
process.stdout.write(`Error while writing file ${filepath}: ${err}`);
return;
}
});
}
// 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) {
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
// -----------------------------------------------------------------------------
async function compileTemplates(files) {
process.stdout.write(`Processing ${files.length} files`);
let xmlStrings = await Promise.all(files.map((file) => fs.promises.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}`;
}
const templatesPath = process.argv[2];
if (templatesPath && templatesPath.length) {
getXmlFiles(templatesPath).then(async (files) => {
const result = await compileTemplates(files);
writeToFile("templates.js", result);
});
} else {
console.log("Please provide a path");
}
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "Owl devtools", "name": "Owl devtools",
"version": "1.3.0", "version": "1.2.2",
"manifest_version": 3, "manifest_version": 3,
"description": "Chrome devtools extension for Odoo Owl framework", "description": "Chrome devtools extension for Odoo Owl framework",
"icons": { "icons": {
@@ -14,7 +14,7 @@
"default_popup": "popup_app/popup.html" "default_popup": "popup_app/popup.html"
}, },
"permissions": ["scripting", "storage"], "permissions": ["scripting", "storage"],
"host_permissions": ["http://*/*", "https://*/*", "file://*"], "host_permissions": ["http://*/*", "https://*/*"],
"content_security_policy": { "content_security_policy": {
"script-src": "self", "script-src": "self",
"object-src": "self" "object-src": "self"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "Owl devtools", "name": "Owl devtools",
"version": "1.1.0", "version": "1.0.0",
"description": "Firefox devtools extension for Odoo Owl framework", "description": "Firefox devtools extension for Odoo Owl framework",
"manifest_version": 2, "manifest_version": 2,
"browser_specific_settings": { "browser_specific_settings": {
@@ -1,36 +0,0 @@
import { useStore } from "../store/store";
const { Component, useEffect, useRef } = owl;
export class ContextMenu extends Component {
static template = "devtools.ContextMenu";
static props = {
items: Array,
};
setup() {
this.store = useStore();
this.contextMenu = useRef("contextmenu");
useEffect(
(position) => {
const menu = this.contextMenu.el;
const menuWidth = menu.offsetWidth;
const menuHeight = menu.offsetHeight;
let { x, y } = position;
if (x + menuWidth > window.innerWidth) {
x = window.innerWidth - menuWidth;
}
if (y + menuHeight > window.innerHeight) {
y = window.innerHeight - menuHeight;
}
menu.style.left = x + "px";
// Need 25px offset because of the main navbar from the browser devtools
menu.style.top = y + "px";
},
() => [this.store.contextMenu?.position]
);
}
onClickItem(action) {
action();
this.store.contextMenu = null;
}
}
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="devtools.ContextMenu">
<div class="custom-menu" t-ref="contextmenu">
<ul class="my-1">
<li t-foreach="props.items" t-as="item" t-key="item_index" t-if="item.show" t-esc="item.title" t-on-click.stop="() => this.onClickItem(item.action)" class="custom-menu-item py-1 px-4"/>
</ul>
</div>
</t>
</templates>
@@ -1,4 +1,4 @@
const { Component } = owl; const { Component, useRef, useEffect } = owl;
import { useStore } from "../../../store/store"; import { useStore } from "../../../store/store";
import { ObjectTreeElement } from "./object_tree_element/object_tree_element"; import { ObjectTreeElement } from "./object_tree_element/object_tree_element";
@@ -7,64 +7,23 @@ export class DetailsWindow extends Component {
static components = { ObjectTreeElement }; static components = { ObjectTreeElement };
setup() { setup() {
this.store = useStore(); this.store = useStore();
} this.contextMenu = useRef("contextmenu");
this.contextMenuId = this.store.contextMenu.id++;
get contextMenuItems() { this.contextMenuEvent;
return [ // Open the context menu when the ids match
{ useEffect(
title: "Inspect source code", (menuId) => {
show: true, if (menuId === this.contextMenuId) {
action: () => this.store.inspectComponent("source", this.store.activeComponent.path), this.store.contextMenu.open(this.contextMenuEvent, this.contextMenu.el);
}
}, },
{ () => [this.store.contextMenu.activeMenu]
title: "Store as global variable", );
show: this.store.activeComponent.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.store.activeComponent.path,
{ type: "item", value: "component" },
]),
},
{
title: "Inspect in Elements tab",
show: this.store.activeComponent.path.length !== 1,
action: () => this.store.inspectComponent("DOM", this.store.activeComponent.path),
},
{
title: "Force rerender",
show: this.store.activeComponent.path.length !== 1,
action: () => this.store.refreshComponent(this.store.activeComponent.path),
},
{
title: "Store observed states as global variable",
show: this.store.activeComponent.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.store.activeComponent.path,
{ type: "item", value: "subscriptions" },
]),
},
{
title: "Inspect compiled template",
show: this.store.activeComponent.path.length !== 1,
action: () =>
this.store.inspectComponent("compiled template", this.store.activeComponent.path),
},
{
title: "Log raw template",
show: this.store.activeComponent.path.length !== 1,
action: () => this.store.inspectComponent("raw template", this.store.activeComponent.path),
},
{
title: "Store as global variable",
show: this.store.activeComponent.path.length === 1,
action: () => this.store.logObjectInConsole([...this.store.activeComponent.path]),
},
];
} }
openMenu(ev) { openMenu(ev) {
this.store.openContextMenu(ev, this.contextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.contextMenuId;
} }
toggleCategory(ev, category) { toggleCategory(ev, category) {
@@ -20,17 +20,6 @@
</t> </t>
</div> </div>
<div class="details-container"> <div class="details-container">
<div t-if="store.observedVariables.length and store.observedVariables.some((v) => v.visible)" id="observedVariables" class="details-panel ps-2 py-1">
<div class="d-flex mb-2">
<div class="w-100">
<b class="ps-2">observed variables</b>
</div>
<i title="Remove observed variables" class="fa fa-times utility-icon p-1" t-on-click.stop="() => this.store.clearObservedVariable()"></i>
</div>
<t t-foreach="store.observedVariables" t-as="observed" t-key="observed_index" t-if="observed.visible">
<ObjectTreeElement object="observed" index="observed_index"/>
</t>
</div>
<div t-if="store.activeComponent.env.children.length > 0" id="env" class="details-panel ps-2 py-1"> <div t-if="store.activeComponent.env.children.length > 0" id="env" class="details-panel ps-2 py-1">
<div class="d-flex mb-2"> <div class="d-flex mb-2">
<div class="w-100" t-on-click.stop="(ev) => this.toggleCategory(ev, 'env')"> <div class="w-100" t-on-click.stop="(ev) => this.toggleCategory(ev, 'env')">
@@ -70,7 +59,7 @@
</t> </t>
</div> </div>
</div> </div>
<div t-if="store.activeComponent.instance.children.length > 0" id="instance" class="details-panel ps-2 py-1"> <div t-if="store.activeComponent.instance.children.length > 0" id="instance" class="details-panel ps-2 py-1">
<div class="d-flex mb-2"> <div class="d-flex mb-2">
<div class="w-100 text-truncate" t-on-click.stop="(ev) => this.toggleCategory(ev, 'instance')"> <div class="w-100 text-truncate" t-on-click.stop="(ev) => this.toggleCategory(ev, 'instance')">
<i class="fa mx-1 pointer-icon" <i class="fa mx-1 pointer-icon"
@@ -86,19 +75,22 @@
<ObjectTreeElement object="instance"/> <ObjectTreeElement object="instance"/>
</t> </t>
</div> </div>
<div t-if="store.activeComponent.hooks?.children.length > 0" id="hooks" class="details-panel ps-2 py-1"> </div>
<div class="d-flex mb-2"> <div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<div class="w-100" t-on-click.stop="(ev) => this.toggleCategory(ev, 'hooks')"> <ul class="my-1">
<i class="fa mx-1 pointer-icon" <li t-on-click.stop="() => this.store.inspectComponent('source', store.activeComponent.path)" class="custom-menu-item py-1 px-4">Inspect source code</li>
t-att-class="{'fa-caret-right': !store.activeComponent.hooks.toggled, 'fa-caret-down': store.activeComponent.hooks.toggled}" <t t-if="store.activeComponent.path.length !== 1">
/><b>hooks</b> <li t-on-click.stop="() => this.store.logObjectInConsole([...store.activeComponent.path, { type: 'item', value: 'component'}])" class="custom-menu-item py-1 px-4">Store as global variable</li>
</div> <li t-on-click.stop="() => this.store.inspectComponent('DOM', store.activeComponent.path)" class="custom-menu-item py-1 px-4">Inspect in Elements tab</li>
<i title="Remove breakpoints" class="fa fa-times utility-icon p-1" t-on-click.stop="() => this.store.removeBreakpoints()"></i> <li t-on-click.stop="() => this.store.refreshComponent(store.activeComponent.path)" class="custom-menu-item py-1 px-4">Force rerender</li>
</div> <li t-on-click.stop="() => this.store.logObjectInConsole([...store.activeComponent.path, { type: 'item', value: 'subscriptions'}])" class="custom-menu-item py-1 px-4">Store observed states as global variable</li>
<t t-if="store.activeComponent.hooks.toggled" t-foreach="store.activeComponent.hooks.children" t-as="hook" t-key="hook_index"> <li t-on-click.stop="() => this.store.inspectComponent('compiled template', store.activeComponent.path)" class="custom-menu-item py-1 px-4">Inspect compiled template</li>
<ObjectTreeElement object="hook"/> <li t-on-click.stop="() => this.store.inspectComponent('raw template', store.activeComponent.path)" class="custom-menu-item py-1 px-4">Log raw template</li>
</t> </t>
</div> <t t-else="">
<li t-on-click.stop="() => this.store.logObjectInConsole([...store.activeComponent.path])" class="custom-menu-item py-1 px-4">Store as global variable</li>
</t>
</ul>
</div> </div>
</t> </t>
</templates> </templates>
@@ -13,8 +13,19 @@ export class ObjectTreeElement extends Component {
menuTop: 0, menuTop: 0,
menuLeft: 0, menuLeft: 0,
}); });
this.contextMenu = useRef("contextmenu");
const inputRef = useRef("input"); const inputRef = useRef("input");
this.store = useStore(); this.store = useStore();
this.contextMenuId = this.store.contextMenu.id++;
this.contextMenuEvent,
useEffect(
(menuId) => {
if (menuId === this.contextMenuId) {
this.store.contextMenu.open(this.contextMenuEvent, this.contextMenu.el);
}
},
() => [this.store.contextMenu.activeMenu]
);
useEffect( useEffect(
(editMode) => { (editMode) => {
// Focus on the input when it is created // Focus on the input when it is created
@@ -52,76 +63,16 @@ export class ObjectTreeElement extends Component {
return this.props.object.depth * 0.8 + 0.3; return this.props.object.depth * 0.8 + 0.3;
} }
get contextMenuItems() {
return [
{
title: "Store as global variable",
show: true,
action: () => this.store.logObjectInConsole(this.props.object.path),
},
{
title: "Inspect function source code",
show: this.props.object.contentType === "function",
action: () => this.store.inspectFunctionSource(this.props.object.path),
},
{
title: "Observe variable",
show: this.props.object.objectType !== "observed",
action: () => this.store.observeVariable(this.props.object.path),
},
{
title: "Unobserve variable",
show: this.props.object.objectType === "observed",
action: () => this.store.clearObservedVariable(this.props.index),
},
{
title: "Inject breakpoint on component",
show: this.props.object.contentType === "array" && this.props.object.objectType === "hook",
action: () =>
this.store.injectBreakpoint(this.props.object.name, this.store.activeComponent.path),
},
{
title: "Inject conditional breakpoint on component",
show: this.props.object.contentType === "array" && this.props.object.objectType === "hook",
action: () => {
const condition = window.prompt("Enter the condition");
if (condition) {
this.store.injectBreakpoint(
this.props.object.name,
this.store.activeComponent.path,
false,
condition
);
}
},
},
{
title: "Inject breakpoint on instance",
show:
this.props.object.contentType === "array" &&
this.props.object.objectType === "hook" &&
!["mounted", "willStart"].includes(this.props.object.name),
action: () =>
this.store.injectBreakpoint(
this.props.object.name,
this.store.activeComponent.path,
true
),
},
];
}
openMenu(ev) { openMenu(ev) {
this.store.openContextMenu(ev, this.contextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.contextMenuId;
} }
setupEditMode() { setupEditMode() {
if ( if (!this.state.editMode) {
!this.state.editMode && if (!this.props.object.hasChildren) {
!this.props.object.hasChildren && this.state.editMode = true;
!(this.props.object.objectType === "observed") }
) {
this.state.editMode = true;
} }
} }
@@ -4,7 +4,7 @@
<div class="m-0 p-0 text-nowrap w-100 object-line" <div class="m-0 p-0 text-nowrap w-100 object-line"
t-att-class="props.class + (props.object.hasChildren ? ' bg-feedback' : '')" t-att-class="props.class + (props.object.hasChildren ? ' bg-feedback' : '')"
t-on-click.stop="() => this.store.toggleObjectTreeElementsDisplay(this.props.object)" t-on-click.stop="() => this.store.toggleObjectTreeElementsDisplay(this.props.object)"
t-on-contextmenu.prevent="openMenu" t-on-contextmenu.prevent="openMenu"
> >
<div t-attf-style="padding-left: {{objectPadding}}rem"> <div t-attf-style="padding-left: {{objectPadding}}rem">
<i class="fa px-1 pointer-icon caret" <i class="fa px-1 pointer-icon caret"
@@ -12,7 +12,7 @@
t-attf-style="visibility: {{props.object.hasChildren ? '' : 'hidden'}};" t-attf-style="visibility: {{props.object.hasChildren ? '' : 'hidden'}};"
/> />
<t t-esc="props.object.name"/> <t t-esc="props.object.name"/>
<t t-if="props.object.content.length > 0">: </t> <t t-if="props.object.content.length > 0">: </t>
<t t-if="props.object.contentType == 'getter'"> <t t-if="props.object.contentType == 'getter'">
<span class="getter-content object-content" t-att-class="objectLineClass" t-on-click.stop="() => this.store.loadGetterContent(this.props.object)"> <span class="getter-content object-content" t-att-class="objectLineClass" t-on-click.stop="() => this.store.loadGetterContent(this.props.object)">
<t t-esc="props.object.content"/> <t t-esc="props.object.content"/>
@@ -20,17 +20,25 @@
</t> </t>
<t t-else=""> <t t-else="">
<span class="object-content" t-att-class="objectLineClass" t-on-dblclick.stop="setupEditMode"> <span class="object-content" t-att-class="objectLineClass" t-on-dblclick.stop="setupEditMode">
<t t-if="state.editMode"> <t t-if="state.editMode">
<input t-attf-id="objectEditionInput/{{pathAsString}}" t-ref="input" type="text" placeholder="" t-att-value="props.object.content" t-on-keydown.stop="editObject"/> <input t-attf-id="objectEditionInput/{{pathAsString}}" t-ref="input" type="text" placeholder="" t-att-value="props.object.content" t-on-keydown.stop="editObject"/>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="props.object.content"/> <t t-esc="props.object.content"/>
</t> </t>
</span> </span>
</t> </t>
<span t-if="keyChanges" class="key-changes ms-1 badge p-1" title="Key additions/deletions are observed">+/-</span> <span t-if="keyChanges" class="key-changes ms-1 badge p-1" title="Key additions/deletions are observed">+/-</span>
</div> </div>
</div> </div>
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<ul class="my-1">
<li t-on-click="() => this.store.logObjectInConsole(this.props.object.path)" class="custom-menu-item py-1 px-4 text-nowrap">Store as global variable</li>
<t t-if='props.object.contentType == "function"'>
<li t-on-click="() => this.store.inspectFunctionSource(this.props.object.path)" class="custom-menu-item py-1 px-4 text-nowrap">Inspect function source code</li>
</t>
</ul>
</div>
<t t-if="props.object.toggled" t-key="contextMenuId"> <t t-if="props.object.toggled" t-key="contextMenuId">
<t t-foreach="props.object.children" t-as="child" t-key="child_index"> <t t-foreach="props.object.children" t-as="child" t-key="child_index">
<ObjectTreeElement object="child" class="this.classFor(child)"/> <ObjectTreeElement object="child" class="this.classFor(child)"/>
@@ -16,7 +16,10 @@ export class TreeElement extends Component {
searched: false, searched: false,
}); });
this.store = useStore(); this.store = useStore();
this.contextMenu = useRef("contextmenu");
this.element = useRef("element"); this.element = useRef("element");
this.contextMenuId = this.store.contextMenu.id++;
this.contextMenuEvent;
this.stringifiedPath = JSON.stringify(this.props.component.path); this.stringifiedPath = JSON.stringify(this.props.component.path);
// Scroll to the selected element when it changes // Scroll to the selected element when it changes
onMounted(() => { onMounted(() => {
@@ -35,6 +38,15 @@ export class TreeElement extends Component {
}, },
() => [this.props.component.selected] () => [this.props.component.selected]
); );
// Open the context menu when the ids match
useEffect(
(menuId) => {
if (menuId === this.contextMenuId) {
this.store.contextMenu.open(this.contextMenuEvent, this.contextMenu.el);
}
},
() => [this.store.contextMenu.activeMenu]
);
// Effect to apply a short highlight effect to the component when it is rendered // Effect to apply a short highlight effect to the component when it is rendered
useEffect( useEffect(
() => { () => {
@@ -74,86 +86,9 @@ export class TreeElement extends Component {
return minimizeKey(this.props.component.key); return minimizeKey(this.props.component.key);
} }
get contextMenuItems() {
return [
{
title: "Expand children",
show: true,
action: () => this.store.toggleComponentAndChildren(this.props.component, true),
},
{
title: "Fold all children",
show: true,
action: () => this.store.toggleComponentAndChildren(this.props.component, false),
},
{
title: "Fold direct children",
show: true,
action: () => this.store.foldDirectChildren(this.props.component),
},
{
title: "Inspect source code",
show: true,
action: () => this.store.inspectComponent("source", this.props.component.path),
},
{
title: "Store as global variable",
show: this.props.component.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.component.path,
{ type: "item", value: "component" },
]),
},
{
title: "Inspect in Elements tab",
show: this.props.component.path.length !== 1,
action: () => this.store.inspectComponent("DOM", this.props.component.path),
},
{
title: "Force rerender",
show: this.props.component.path.length !== 1,
action: () => this.store.refreshComponent(this.props.component.path),
},
{
title: "Store observed states as global variable",
show: this.props.component.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.component.path,
{ type: "item", value: "subscriptions" },
]),
},
{
title: "Inspect compiled template",
show: this.props.component.path.length !== 1,
action: () => this.store.inspectComponent("compiled template", this.props.component.path),
},
{
title: "Log raw template",
show: this.props.component.path.length !== 1,
action: () => this.store.inspectComponent("raw template", this.props.component.path),
},
{
title: "Store as global variable",
show: this.props.component.path.length === 1,
action: () => this.store.logObjectInConsole([...this.props.component.path]),
},
{
title: "Don't fold component by default",
show: this.store.settings.componentsToggleBlacklist.has(this.props.component.name),
action: () => this.toggleComponentToBlacklist(),
},
{
title: "Fold component by default",
show: !this.store.settings.componentsToggleBlacklist.has(this.props.component.name),
action: () => this.toggleComponentToBlacklist(),
},
];
}
openMenu(ev) { openMenu(ev) {
this.store.openContextMenu(ev, this.contextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.contextMenuId;
} }
// Expand/fold the component node // Expand/fold the component node
@@ -2,15 +2,15 @@
<templates xml:space="preserve"> <templates xml:space="preserve">
<t t-name="devtools.TreeElement" owl="1"> <t t-name="devtools.TreeElement" owl="1">
<div t-ref="element" <div t-ref="element"
t-att-class="{'component-selected': props.component.selected,'component-highlighted': props.component.highlighted}" t-att-class="{'component-selected': props.component.selected,'component-highlighted': props.component.highlighted}"
class="tree-component m-0 p-0 w-100 text-nowrap user-select-none" class="tree-component m-0 p-0 w-100 text-nowrap user-select-none"
t-on-contextmenu.prevent="openMenu" t-on-contextmenu.prevent="openMenu"
t-on-mouseover.stop="() => this.store.highlightComponent(props.component.path)" t-on-mouseover.stop="() => this.store.highlightComponent(props.component.path)"
t-on-click.stop="toggleComponent" t-on-click.stop="toggleComponent"
> >
<div class="component-wrapper" t-attf-style="padding-left: {{componentPadding}}rem"> <div class="component-wrapper" t-attf-style="padding-left: {{componentPadding}}rem">
<i class="fa px-1 pointer-icon caret" <i class="fa px-1 pointer-icon caret"
t-att-class="{'fa-caret-right': !props.component.toggled, 'fa-caret-down': props.component.toggled}" t-att-class="{'fa-caret-right': !props.component.toggled, 'fa-caret-down': props.component.toggled}"
t-on-click.stop="toggleDisplay" t-on-click.stop="toggleDisplay"
t-attf-style="{{props.component.children.length > 0 ? '' : 'visibility: hidden;'}}" t-attf-style="{{props.component.children.length > 0 ? '' : 'visibility: hidden;'}}"
/> />
@@ -26,6 +26,29 @@
<span t-if="props.component.depth">&gt;</span> <span t-if="props.component.depth">&gt;</span>
<span class="version" t-else="">owl=<t t-esc="props.component.version"/></span> <span class="version" t-else="">owl=<t t-esc="props.component.version"/></span>
</div> </div>
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<ul class="my-1">
<li t-on-click.stop="() => this.store.toggleComponentAndChildren(props.component, true)" class="custom-menu-item py-1 px-4">Expand children</li>
<li t-on-click.stop="() => this.store.toggleComponentAndChildren(props.component, false)" class="custom-menu-item py-1 px-4">Fold all children</li>
<li t-on-click.stop="() => this.store.foldDirectChildren(props.component)" class="custom-menu-item py-1 px-4">Fold direct children</li>
<li t-on-click.stop="() => this.store.inspectComponent('source', props.component.path)" class="custom-menu-item py-1 px-4">Inspect source code</li>
<t t-if="props.component.path.length !== 1">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.component.path, { type: 'item', value: 'component'}])" class="custom-menu-item py-1 px-4">Store as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('DOM', props.component.path)" class="custom-menu-item py-1 px-4">Inspect in Elements tab</li>
<li t-on-click.stop="() => this.store.refreshComponent(props.component.path)" class="custom-menu-item py-1 px-4">Force rerender</li>
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.component.path, { type: 'item', value: 'subscriptions'}])" class="custom-menu-item py-1 px-4">Store observed states as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('compiled template', props.component.path)" class="custom-menu-item py-1 px-4">Inspect compiled template</li>
<li t-on-click.stop="() => this.store.inspectComponent('raw template', props.component.path)" class="custom-menu-item py-1 px-4">Log raw template</li>
</t>
<t t-else="">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.component.path])" class="custom-menu-item py-1 px-4">Store as global variable</li>
</t>
<li t-on-click.stop="() => this.toggleComponentToBlacklist()" class="custom-menu-item py-1 px-4">
<t t-if="store.settings.componentsToggleBlacklist.has(props.component.name)">Don't fold component by default</t>
<t t-else="">Fold component by default</t>
</li>
</ul>
</div>
</div> </div>
<t t-if="props.component.toggled"> <t t-if="props.component.toggled">
<t t-foreach="props.component.children" t-as="child" t-key="child.key"> <t t-foreach="props.component.children" t-as="child" t-key="child.key">
@@ -1,14 +1,13 @@
const { Component } = owl; const { Component } = owl;
import { ContextMenu } from "../context_menu/context_menu";
import { useStore } from "../store/store";
import { ComponentsTab } from "./components_tab/components_tab"; import { ComponentsTab } from "./components_tab/components_tab";
import { ProfilerTab } from "./profiler_tab/profiler_tab";
import { Tab } from "./tab/tab"; import { Tab } from "./tab/tab";
import { ProfilerTab } from "./profiler_tab/profiler_tab";
import { useStore } from "../store/store";
export class DevtoolsWindow extends Component { export class DevtoolsWindow extends Component {
static props = []; static props = [];
static template = "devtools.DevtoolsWindow"; static template = "devtools.DevtoolsWindow";
static components = { ComponentsTab, Tab, ProfilerTab, ContextMenu }; static components = { ComponentsTab, Tab, ProfilerTab };
setup() { setup() {
this.store = useStore(); this.store = useStore();
} }
@@ -28,7 +28,6 @@
Owl is not loaded on this page. Owl is not loaded on this page.
</div> </div>
</t> </t>
<ContextMenu t-if="store.contextMenu" items="store.contextMenu.items"/>
</div> </div>
</t> </t>
</templates> </templates>
@@ -1,13 +1,24 @@
import { minimizeKey } from "../../../../utils"; import { minimizeKey } from "../../../../utils";
import { useStore } from "../../../store/store"; import { useStore } from "../../../store/store";
const { Component } = owl; const { Component, useEffect, useRef } = owl;
export class Event extends Component { export class Event extends Component {
static template = "devtools.Event"; static template = "devtools.Event";
setup() { setup() {
this.store = useStore(); this.store = useStore();
this.componentContextMenu = useRef("componentContextmenu");
this.componentContextMenuId = this.store.contextMenu.id++;
this.contextMenuEvent,
useEffect(
(menuId) => {
if (menuId === this.componentContextMenuId) {
this.store.contextMenu.open(this.contextMenuEvent, this.componentContextMenu.el);
}
},
() => [this.store.contextMenu.activeMenu]
);
} }
// Formatting for displaying the key of the component // Formatting for displaying the key of the component
@@ -43,65 +54,13 @@ export class Event extends Component {
} }
} }
get contextMenuItems() { openComponentMenu(ev) {
return [
{
title: "Inspect source code",
show: true,
action: () => this.store.inspectComponent("source", this.props.event.path),
},
{
title: "Store as global variable",
show: this.props.event.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.event.path,
{ type: "item", value: "component" },
]),
},
{
title: "Inspect in Elements tab",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("DOM", this.props.event.path),
},
{
title: "Force rerender",
show: this.props.event.path.length !== 1,
action: () => this.store.refreshComponent(this.props.event.path),
},
{
title: "Store observed states as global variable",
show: this.props.event.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.event.path,
{ type: "item", value: "subscriptions" },
]),
},
{
title: "Inspect compiled template",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("compiled template", this.props.event.path),
},
{
title: "Log raw template",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("raw template", this.props.event.path),
},
{
title: "Store as global variable",
show: this.props.event.path.length === 1,
action: () => this.store.logObjectInConsole([...this.props.event.path]),
},
];
}
openMenu(ev) {
if (this.props.event.type === "destroy") { if (this.props.event.type === "destroy") {
return; return;
} else { } else {
ev.preventDefault(); ev.preventDefault();
this.store.openContextMenu(ev, this.contextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.componentContextMenuId;
} }
} }
} }
@@ -8,11 +8,11 @@
t-att-class="{'fa-caret-right': !props.event.toggled, 'fa-caret-down': props.event.toggled}" t-att-class="{'fa-caret-right': !props.event.toggled, 'fa-caret-down': props.event.toggled}"
t-attf-style="visibility: {{props.event.origin ? '' : 'hidden'}};" t-attf-style="visibility: {{props.event.origin ? '' : 'hidden'}};"
/> />
<t t-esc="props.event.type"/>: <t t-esc="props.event.type"/>:
&lt;<span style="cursor:pointer; color: var(--component-color);" &lt;<span style="cursor:pointer; color: var(--component-color);"
t-on-click.stop="() => this.store.selectComponent(props.event.path)" t-on-click.stop="() => this.store.selectComponent(props.event.path)"
t-on-mouseover.stop="() => this.store.highlightComponent(props.event.path)" t-on-mouseover.stop="() => this.store.highlightComponent(props.event.path)"
t-on-contextmenu="openMenu" t-on-contextmenu="openComponentMenu"
t-esc="props.event.component" t-esc="props.event.component"
/> />
<t t-if="minimizedKey.length > 0"> <t t-if="minimizedKey.length > 0">
@@ -29,10 +29,10 @@
<div class="my-0 pt-1 object-line"> <div class="my-0 pt-1 object-line">
<i class="fa fa-caret-right mx-1 pe-2" style="visibility: hidden;"></i> <i class="fa fa-caret-right mx-1 pe-2" style="visibility: hidden;"></i>
<span> <span>
origin: origin:
&lt;<span style="cursor:pointer; color: var(--component-color);" &lt;<span style="cursor:pointer; color: var(--component-color);"
t-on-click.stop="() => this.store.selectComponent(props.event.origin.path)" t-on-click.stop="() => this.store.selectComponent(props.event.origin.path)"
t-on-mouseover.stop="() => this.store.highlightComponent(props.event.origin.path)" t-on-mouseover.stop="() => this.store.highlightComponent(props.event.origin.path)"
t-esc="props.event.origin.component" t-esc="props.event.origin.component"
/> />
<t t-if="originMinimizedKey.length > 0"> <t t-if="originMinimizedKey.length > 0">
@@ -43,6 +43,22 @@
</span> </span>
</div> </div>
</t> </t>
<div t-if="store.contextMenu.activeMenu === componentContextMenuId" class="custom-menu" t-ref="componentContextmenu">
<ul class="my-1">
<li t-on-click.stop="() => this.store.inspectComponent('source', props.event.path)" class="custom-menu-item py-1 px-4">Inspect source code</li>
<t t-if="props.event.path.length !== 1">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path, { type: 'item', value: 'component'}])" class="custom-menu-item py-1 px-4">Store as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('DOM', props.event.path)" class="custom-menu-item py-1 px-4">Inspect in Elements tab</li>
<li t-on-click.stop="() => this.store.refreshComponent(props.event.path)" class="custom-menu-item py-1 px-4">Force rerender</li>
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path, { type: 'item', value: 'subscriptions'}])" class="custom-menu-item py-1 px-4">Store observed states as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('compiled template', props.event.path)" class="custom-menu-item py-1 px-4">Inspect compiled template</li>
<li t-on-click.stop="() => this.store.inspectComponent('raw template', props.event.path)" class="custom-menu-item py-1 px-4">Log raw template</li>
</t>
<t t-else="">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path])" class="custom-menu-item py-1 px-4">Store as global variable</li>
</t>
</ul>
</div>
</div> </div>
</t> </t>
</templates> </templates>
@@ -1,7 +1,7 @@
import { minimizeKey } from "../../../../utils"; import { minimizeKey } from "../../../../utils";
import { useStore } from "../../../store/store"; import { useStore } from "../../../store/store";
const { Component } = owl; const { Component, useRef, useEffect } = owl;
export class EventNode extends Component { export class EventNode extends Component {
static template = "devtools.EventNode"; static template = "devtools.EventNode";
@@ -10,89 +10,33 @@ export class EventNode extends Component {
setup() { setup() {
this.store = useStore(); this.store = useStore();
this.nodeContextMenu = useRef("nodeContextMenu");
this.nodeContextMenuId = this.store.contextMenu.id++;
this.componentContextMenu = useRef("componentContextmenu");
this.componentContextMenuId = this.store.contextMenu.id++;
this.contextMenuEvent,
useEffect(
(menuId) => {
if (menuId === this.nodeContextMenuId) {
this.store.contextMenu.open(this.contextMenuEvent, this.nodeContextMenu.el);
}
if (menuId === this.componentContextMenuId) {
this.store.contextMenu.open(this.contextMenuEvent, this.componentContextMenu.el);
}
},
() => [this.store.contextMenu.activeMenu]
);
} }
get eventPadding() { get eventPadding() {
return this.props.event.depth * 0.8 + 0.3; return this.props.event.depth * 0.8 + 0.3;
} }
get nodeContextMenuItems() {
return [
{
title: "Expand children",
show: true,
action: () => this.store.toggleEventAndChildren(this.props.event, true),
},
{
title: "Fold all children",
show: true,
action: () => this.store.toggleEventAndChildren(this.props.event, false),
},
{
title: "Fold direct children",
show: true,
action: () => this.store.foldDirectChildren(this.props.event),
},
];
}
get componentContextMenuItems() {
return [
{
title: "Inspect source code",
show: true,
action: () => this.store.inspectComponent("source", this.props.event.path),
},
{
title: "Store as global variable",
show: this.props.event.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.event.path,
{ type: "item", value: "component" },
]),
},
{
title: "Inspect in Elements tab",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("DOM", this.props.event.path),
},
{
title: "Force rerender",
show: this.props.event.path.length !== 1,
action: () => this.store.refreshComponent(this.props.event.path),
},
{
title: "Store observed states as global variable",
show: this.props.event.path.length !== 1,
action: () =>
this.store.logObjectInConsole([
...this.props.event.path,
{ type: "item", value: "subscriptions" },
]),
},
{
title: "Inspect compiled template",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("compiled template", this.props.event.path),
},
{
title: "Log raw template",
show: this.props.event.path.length !== 1,
action: () => this.store.inspectComponent("raw template", this.props.event.path),
},
{
title: "Store as global variable",
show: this.props.event.path.length === 1,
action: () => this.store.logObjectInConsole([...this.props.event.path]),
},
];
}
openNodeMenu(ev) { openNodeMenu(ev) {
if (this.props.event.children.length) { if (this.props.event.children.length) {
ev.preventDefault(); ev.preventDefault();
this.store.openContextMenu(ev, this.nodeContextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.nodeContextMenuId;
} }
} }
@@ -101,7 +45,8 @@ export class EventNode extends Component {
return; return;
} else { } else {
ev.preventDefault(); ev.preventDefault();
this.store.openContextMenu(ev, this.componentContextMenuItems); this.contextMenuEvent = ev;
this.store.contextMenu.activeMenu = this.componentContextMenuId;
} }
} }
@@ -2,8 +2,8 @@
<templates xml:space="preserve"> <templates xml:space="preserve">
<t t-name="devtools.EventNode" owl="1"> <t t-name="devtools.EventNode" owl="1">
<div class="my-0 p-0 object-line" <div class="my-0 p-0 object-line"
t-on-click.stop="toggleDisplay" t-on-click.stop="toggleDisplay"
t-on-contextmenu="openNodeMenu" t-on-contextmenu="openNodeMenu"
> >
<div class="text-nowrap" t-attf-style="padding-left: {{eventPadding}}rem"> <div class="text-nowrap" t-attf-style="padding-left: {{eventPadding}}rem">
<i class="fa px-1 pointer-icon caret" <i class="fa px-1 pointer-icon caret"
@@ -11,11 +11,11 @@
t-attf-style="visibility: {{props.event.children.length > 0 ? '' : 'hidden'}};" t-attf-style="visibility: {{props.event.children.length > 0 ? '' : 'hidden'}};"
/> />
<span> <span>
<t t-esc="props.event.type"/>: <t t-esc="props.event.type"/>:
&lt;<span style="cursor:pointer; color: var(--component-color);" &lt;<span style="cursor:pointer; color: var(--component-color);"
t-on-click.stop="() => this.store.selectComponent(props.event.path)" t-on-click.stop="() => this.store.selectComponent(props.event.path)"
t-on-mouseover.stop="() => this.store.highlightComponent(props.event.path)" t-on-mouseover.stop="() => this.store.highlightComponent(props.event.path)"
t-on-contextmenu.stop="openComponentMenu" t-on-contextmenu.stop="openComponentMenu"
t-esc="props.event.component"/> t-esc="props.event.component"/>
<t t-if="minimizedKey.length > 0"> <t t-if="minimizedKey.length > 0">
<span t-if="minimizedKey.length > 0" style="color: var(--key-name);"> key</span>=<span style="color: var(--key-content);"> <span t-if="minimizedKey.length > 0" style="color: var(--key-name);"> key</span>=<span style="color: var(--key-content);">
@@ -28,6 +28,29 @@
</span> </span>
</div> </div>
</div> </div>
<div t-if="store.contextMenu.activeMenu === nodeContextMenuId" class="custom-menu" t-ref="nodeContextMenu">
<ul class="my-1">
<li t-on-click.stop="() => this.store.toggleEventAndChildren(props.event, true)" class="custom-menu-item py-1 px-4">Expand children</li>
<li t-on-click.stop="() => this.store.toggleEventAndChildren(props.event, false)" class="custom-menu-item py-1 px-4">Fold all children</li>
<li t-on-click.stop="() => this.store.foldDirectChildren(props.event)" class="custom-menu-item py-1 px-4">Fold direct children</li>
</ul>
</div>
<div t-if="store.contextMenu.activeMenu === componentContextMenuId" class="custom-menu" t-ref="componentContextmenu">
<ul class="my-1">
<li t-on-click.stop="() => this.store.inspectComponent('source', props.event.path)" class="custom-menu-item py-1 px-4">Inspect source code</li>
<t t-if="props.event.path.length !== 1">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path, { type: 'item', value: 'component'}])" class="custom-menu-item py-1 px-4">Store as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('DOM', props.event.path)" class="custom-menu-item py-1 px-4">Inspect in Elements tab</li>
<li t-on-click.stop="() => this.store.refreshComponent(props.event.path)" class="custom-menu-item py-1 px-4">Force rerender</li>
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path, { type: 'item', value: 'subscriptions'}])" class="custom-menu-item py-1 px-4">Store observed states as global variable</li>
<li t-on-click.stop="() => this.store.inspectComponent('compiled template', props.event.path)" class="custom-menu-item py-1 px-4">Inspect compiled template</li>
<li t-on-click.stop="() => this.store.inspectComponent('raw template', props.event.path)" class="custom-menu-item py-1 px-4">Log raw template</li>
</t>
<t t-else="">
<li t-on-click.stop="() => this.store.logObjectInConsole([...props.event.path])" class="custom-menu-item py-1 px-4">Store as global variable</li>
</t>
</ul>
</div>
<t t-if="props.event.toggled"> <t t-if="props.event.toggled">
<t t-foreach="props.event.children" t-as="child" t-key="child.id"> <t t-foreach="props.event.children" t-as="child" t-key="child.id">
<EventNode event="child"/> <EventNode event="child"/>
+26 -72
View File
@@ -11,7 +11,30 @@ export const store = reactive({
darkmode: false, darkmode: false,
componentsToggleBlacklist: new Set(), componentsToggleBlacklist: new Set(),
}, },
contextMenu: null, contextMenu: {
id: 0,
activeMenu: -1,
// Opens the context menu corresponding with the given menu html element
open(event, menu) {
const menuWidth = menu.offsetWidth;
const menuHeight = menu.offsetHeight;
let x = event.clientX;
let y = event.clientY;
if (x + menuWidth > window.innerWidth) {
x = window.innerWidth - menuWidth;
}
if (y + menuHeight > window.innerHeight) {
y = window.innerHeight - menuHeight;
}
menu.style.left = x + "px";
// Need 25px offset because of the main navbar from the browser devtools
menu.style.top = y - 25 + "px";
},
// Close the currently displayed context menu
close() {
this.activeMenu = -1;
},
},
isFirefox: IS_FIREFOX, isFirefox: IS_FIREFOX,
frameUrls: ["top"], frameUrls: ["top"],
activeFrame: "top", activeFrame: "top",
@@ -33,11 +56,9 @@ export const store = reactive({
props: { toggled: true, children: [] }, props: { toggled: true, children: [] },
env: { toggled: false, children: [] }, env: { toggled: false, children: [] },
instance: { toggled: true, children: [] }, instance: { toggled: true, children: [] },
hooks: { toggled: true, children: [] },
version: "1.0", version: "1.0",
}, },
selectedElement: null, selectedElement: null,
observedVariables: [],
componentSearch: { componentSearch: {
search: "", search: "",
searchResults: [], searchResults: [],
@@ -72,16 +93,6 @@ export const store = reactive({
evalFunctionInWindow("disableHTMLSelector", [], this.activeFrame); evalFunctionInWindow("disableHTMLSelector", [], this.activeFrame);
}, },
openContextMenu(event, items) {
this.contextMenu = {
position: {
x: event.clientX,
y: event.clientY,
},
items,
};
},
// Load all data related to the components tree using the global hook loaded on the page // Load all data related to the components tree using the global hook loaded on the page
// Use fromOld to specify if we want to keep most of the toggled/selected data of the old tree // Use fromOld to specify if we want to keep most of the toggled/selected data of the old tree
// when generating the new one // when generating the new one
@@ -566,42 +577,6 @@ export const store = reactive({
} }
}, },
async injectBreakpoint(hook, path, instanceOnly = false, condition = "1") {
path = [...path];
await evalFunctionInWindow(
"injectBreakpoint",
[hook, path, instanceOnly, condition],
this.activeFrame
);
await this.loadComponentsTree(true);
},
async removeBreakpoints() {
await evalFunctionInWindow("removeBreakpoints", [], this.activeFrame);
await this.loadComponentsTree(true);
},
async observeVariable(path) {
this.observedVariables.push({ path: [...path], visible: false });
this.observedVariables = await evalFunctionInWindow(
"getObservedVariables",
[store.observedVariables],
store.activeFrame
);
await browserInstance.storage.local.set({
observedVariables: toRaw(this.observedVariables).map((o) => o.path),
});
},
clearObservedVariable(index) {
if (index !== undefined) {
this.observedVariables.splice(index, 1);
} else {
this.observedVariables = [];
}
browserInstance.storage.local.set({ observedVariables: toRaw(this.observedVariables) });
},
// Trigger the highlight on the component in the page // Trigger the highlight on the component in the page
highlightComponent(path) { highlightComponent(path) {
evalFunctionInWindow("highlightComponent", [path], this.activeFrame); evalFunctionInWindow("highlightComponent", [path], this.activeFrame);
@@ -671,9 +646,8 @@ async function init() {
store.updateIFrameList(); store.updateIFrameList();
// Global listeners to close the currently shown context menu when the user clicks or opens another // Global listeners to close the currently shown context menu when the user clicks or opens another
document.addEventListener("click", () => (store.contextMenu = null), { capture: true }); document.addEventListener("click", () => store.contextMenu.close(), { capture: true });
document.addEventListener("contextmenu", () => (store.contextMenu = null), { capture: true }); document.addEventListener("contextmenu", () => store.contextMenu.close(), { capture: true });
window.addEventListener("blur", () => (store.contextMenu = null), { capture: true });
// Make sure the events recorder is at its initial state in every frame // Make sure the events recorder is at its initial state in every frame
for (const frame of store.frameUrls) { for (const frame of store.frameUrls) {
@@ -692,16 +666,6 @@ async function init() {
} }
} }
}, 500); }, 500);
// Refresh observed variables values every 200 ms
setInterval(async () => {
if (store.owlStatus) {
store.observedVariables = await evalFunctionInWindow(
"getObservedVariables",
[[...store.observedVariables]],
store.activeFrame
);
}
}, 200);
} }
let rootRendersTimeout = false; let rootRendersTimeout = false;
@@ -796,16 +760,6 @@ async function loadSettings() {
storage.owlDevtoolsComponentsToggleBlacklist storage.owlDevtoolsComponentsToggleBlacklist
); );
} }
// Observed variables
if (storage.observedVariables) {
store.observedVariables = [];
for (const path of storage.observedVariables) {
store.observedVariables.push({
path: [...path],
visible: false,
});
}
}
} }
// Function to handle and store a batch of events coming from the page // Function to handle and store a batch of events coming from the page
@@ -51,8 +51,6 @@
this.requestedFrame = false; this.requestedFrame = false;
this.enabledSelector = false; this.enabledSelector = false;
this.eventsBatch = []; this.eventsBatch = [];
this.breakpointsClassMap = new Map();
this.breakpointsHookMap = new Map();
// Object which defines how different types of data should be displayed when passed to the devtools // Object which defines how different types of data should be displayed when passed to the devtools
this.serializer = { this.serializer = {
// Defines how leaf object nodes should be displayed in the extension when inside a bigger structure // Defines how leaf object nodes should be displayed in the extension when inside a bigger structure
@@ -60,16 +58,15 @@
// The asConstructorName parameter can be passed to change the display of objects and functions to // The asConstructorName parameter can be passed to change the display of objects and functions to
// be their constructor name (useful for prototype, map and set display) // be their constructor name (useful for prototype, map and set display)
serializeItem(value, asConstructorName = false) { serializeItem(value, asConstructorName = false) {
if (typeof value === "object") { if (typeof value === "array") {
return "Array(" + value.length + ")";
} else if (typeof value === "object") {
if (value == null) { if (value == null) {
return "null"; return "null";
} }
if (asConstructorName) { if (asConstructorName) {
return value.constructor.name; return value.constructor.name;
} }
if (value instanceof Array) {
return "Array(" + value.length + ")";
}
return "{...}"; return "{...}";
} else if (typeof value === "undefined") { } else if (typeof value === "undefined") {
return "undefined"; return "undefined";
@@ -112,39 +109,23 @@
object(obj) { object(obj) {
const result = []; const result = [];
let length = 0; let length = 0;
if (obj instanceof String) { for (const [key, value] of Object.entries(obj)) {
result[0] = `'${obj.toString()}'`; if (length > 25) {
} else if (obj instanceof Array) { result.push("...");
return `${obj.constructor.name} ${this.array([...obj])}`; break;
} else if (obj instanceof Number) {
result[0] = obj.toString();
} else {
for (const key of Reflect.ownKeys(obj)) {
if (length > 25) {
result.push("...");
break;
}
let element;
if (Object.getOwnPropertyDescriptor(obj, key).hasOwnProperty("get")) {
element = key.toString() + ": (...)";
} else {
element = key.toString() + ": " + this.serializeItem(obj[key]);
}
length += element.length;
result.push(element);
}
for (const key of Object.getOwnPropertySymbols(obj)) {
if (length > 25) {
result.push("...");
break;
}
const element = key.toString() + ": " + this.serializeItem(obj[key]);
length += element.length;
result.push(element);
} }
const element = key + ": " + this.serializeItem(value);
length += element.length;
result.push(element);
} }
if (obj.constructor && obj.constructor.name !== "Object") { for (const key of Object.getOwnPropertySymbols(obj)) {
return obj.constructor.name + " {" + result.join(", ") + "}"; if (length > 25) {
result.push("...");
break;
}
const element = key.toString() + ": " + this.serializeItem(obj[key]);
length += element.length;
result.push(element);
} }
return "{" + result.join(", ") + "}"; return "{" + result.join(", ") + "}";
}, },
@@ -703,7 +684,7 @@
try { try {
obj = Object.getOwnPropertyDescriptor(obj, key.value).get.call(obj); obj = Object.getOwnPropertyDescriptor(obj, key.value).get.call(obj);
} catch (e) { } catch (e) {
obj = "Exception: " + e.toString(); obj = e.toString();
} }
break; break;
case "prototype getter": case "prototype getter":
@@ -721,13 +702,13 @@
try { try {
obj = Object.getOwnPropertyDescriptor(obj, key.value).get; obj = Object.getOwnPropertyDescriptor(obj, key.value).get;
} catch (e) { } catch (e) {
obj = "Exception: " + e.toString(); obj = e.toString();
} }
} else { } else {
try { try {
obj = obj[key.value]; obj = obj[key.value];
} catch (e) { } catch (e) {
obj = "Exception: " + e.toString(); obj = e.toString();
} }
} }
} }
@@ -740,20 +721,15 @@
// Returns the asked property given its global path // Returns the asked property given its global path
getObjectProperty(path) { getObjectProperty(path) {
// Just return the corresponding app if path is of length 1 and not simplified // Just return the corresponding app if path is of length 1
if (path.length === 1 && !isNaN(path[0])) { if (path.length === 1) {
return [...this.apps][path[0]]; return [...this.apps][path[0]];
} }
// Path to the component node is only strings, becomes objects for properties // Path to the component node is only strings, becomes objects for properties
const index = path.findIndex((key) => typeof key !== "string"); const index = path.findIndex((key) => typeof key !== "string");
if (index === -1) { const componentNode = this.getComponentNode(path.slice(0, index));
return this.getComponentNode(path); const obj = this.getObject(componentNode, path.slice(index));
} return obj;
const componentNode = this.getComponentNode(index === 1 ? [path[0]] : path.slice(0, index));
if (componentNode) {
return this.getObject(componentNode, path.slice(index));
}
return "Exception: component not found";
} }
// Returns a modified version of an object node that has compatible format with the devtools ObjectTreeElement component // Returns a modified version of an object node that has compatible format with the devtools ObjectTreeElement component
@@ -801,11 +777,6 @@
child.name = "value"; child.name = "value";
obj = parentObj[1]; obj = parentObj[1];
break; break;
case "getter":
child.name = key.value;
obj = parentObj[key.value];
break;
case "prototype getter":
case "set entry": case "set entry":
case "map entry": case "map entry":
case "item": case "item":
@@ -821,8 +792,6 @@
parentObj parentObj
).findIndex((sym) => sym === key.value); ).findIndex((sym) => sym === key.value);
child.path[child.path.length - 1].value = key.value.toString(); child.path[child.path.length - 1].value = key.value.toString();
} else if (key.hasOwnProperty("symbolIndex")) {
obj = parentObj[Object.getOwnPropertySymbols(parentObj)[key.symbolIndex]];
} else { } else {
obj = parentObj[key.value]; obj = parentObj[key.value];
} }
@@ -854,7 +823,7 @@
child.contentType = "set"; child.contentType = "set";
child.hasChildren = true; child.hasChildren = true;
break; break;
case obj.constructor?.name === "Array": case obj instanceof Array:
child.contentType = "array"; child.contentType = "array";
child.hasChildren = obj.length > 0; child.hasChildren = obj.length > 0;
break; break;
@@ -862,12 +831,10 @@
child.contentType = "function"; child.contentType = "function";
child.hasChildren = true; child.hasChildren = true;
break; break;
case typeof obj === "object": case obj instanceof Object:
child.contentType = "object"; child.contentType = "object";
child.hasChildren = child.hasChildren =
Object.keys(obj).length > 0 || Object.keys(obj).length || Object.getOwnPropertySymbols(obj).length;
Object.getOwnPropertySymbols(obj).length > 0 ||
obj.constructor.name !== "Object";
break; break;
default: default:
child.contentType = typeof obj; child.contentType = typeof obj;
@@ -910,15 +877,12 @@
path.shift(); path.shift();
} }
// the value is either "props" or "env" here // the value is either "props" or "env" here
if (objType !== "instance" && objType !== "hook") { if (objType !== "instance") {
obj = oldTree[path[0].value].children; obj = oldTree[path[0].value].children;
path.shift(); path.shift();
// there is nothing otherwise but extension side it is in instance // there is nothing otherwise but extension side it is in instance
} else if (objType === "instance") {
obj = oldTree.instance.children;
} else { } else {
obj = oldTree.hooks.children; obj = oldTree.instance.children;
path.shift();
} }
// the first element here is directly in an array instead of a children array // the first element here is directly in an array instead of a children array
obj = obj[path[0].childIndex]; obj = obj[path[0].childIndex];
@@ -1049,40 +1013,36 @@
break; break;
case "object": case "object":
case "function": case "function":
Reflect.ownKeys(obj) Reflect.ownKeys(obj).forEach((key) => {
.sort(compareKeys) if (
.forEach((key) => { key !== "__proto__" &&
if ( Object.getOwnPropertyDescriptor(obj, key).hasOwnProperty("get")
key !== "__proto__" && ) {
Object.getOwnPropertyDescriptor(obj, key).hasOwnProperty("get") let child = {
) { name: key,
let child = { depth: depth,
name: key, toggled: false,
depth: depth, objectType: objType,
toggled: false, path: [...path, { type: "getter", value: key, childIndex: children.length }],
objectType: objType, contentType: "getter",
path: [...path, { type: "getter", value: key, childIndex: children.length }], content: "(...)",
contentType: "getter", hasChildren: false,
content: "(...)", children: [],
hasChildren: false, };
children: [], children.push(child);
}; }
children.push(child); const child = this.serializeObjectChild(
} obj,
const child = this.serializeObjectChild( { type: "item", value: key, childIndex: children.length },
obj, depth,
{ type: "item", value: key, childIndex: children.length }, objType,
depth, path,
objType, oldBranch?.children[index],
path, oldTree
oldBranch?.children[index], );
oldTree if (child) children.push(child);
); index++;
if (child) { });
children.push(child);
}
index++;
});
} }
let proto = Object.getPrototypeOf(obj); let proto = Object.getPrototypeOf(obj);
while (proto) { while (proto) {
@@ -1126,44 +1086,25 @@
} }
// Returns the Component node given its path and the root component node // Returns the Component node given its path and the root component node
getComponentNode(path) { getComponentNode(path) {
// All paths that consists in an array containing a single stringified number lead to an app // The node is an app and not a component
if (path.length === 1 && !isNaN(path[0])) { if (path.length === 1) {
return [...this.apps][path[0]]; return [...this.apps][path[0]];
} }
let node; // The second element in the path will always be the root of the app
// If the path is longer and its first item is indeed an app number, it is a regular path let node = [...this.apps][path[0]]?.root;
if (!isNaN(path[0])) { if (!node) {
// The second element in the path will always be the root of the app return null;
node = [...this.apps][path[0]]?.root; }
if (!node) { for (let i = 2; i < path.length; i++) {
// From this point onwards, it is an object path inside the component node
if (typeof path[i] !== "string") {
break;
}
if (node.children.hasOwnProperty(path[i])) {
node = node.children[path[i]];
} else {
return null; return null;
} }
for (let i = 2; i < path.length; i++) {
// From this point onwards, it is an object path inside the component node
if (typeof path[i] !== "string") {
break;
}
if (node.children.hasOwnProperty(path[i])) {
node = node.children[path[i]];
} else {
return null;
}
}
// If the first path item is a more complex string, it is a simplified path where elements
// are a series of component names and indexes separated by slashes
} else {
const simplifiedPathArray = path[0].split("/");
node = [...this.apps][simplifiedPathArray[0]]?.root;
if (node.name !== simplifiedPathArray[1]) {
return null;
}
for (let i = 2; i < simplifiedPathArray.length; i += 2) {
const key = Reflect.ownKeys(node.children)[simplifiedPathArray[i]];
node = node.children[key];
if (node.name !== simplifiedPathArray[i + 1]) {
return null;
}
}
} }
return node; return node;
} }
@@ -1201,46 +1142,42 @@
const propsPath = isApp const propsPath = isApp
? [...path, { type: "item", value: "props" }] ? [...path, { type: "item", value: "props" }]
: [...path, { type: "item", value: "component" }, { type: "item", value: "props" }]; : [...path, { type: "item", value: "component" }, { type: "item", value: "props" }];
Reflect.ownKeys(props) Reflect.ownKeys(props).forEach((key) => {
.sort(compareKeys) let oldBranch = oldTree?.props.children[component.props.children.length];
.forEach((key) => { const property = this.serializeObjectChild(
let oldBranch = oldTree?.props.children[component.props.children.length]; props,
const property = this.serializeObjectChild( { type: "item", value: key, childIndex: component.props.children.length },
props, 0,
{ type: "item", value: key, childIndex: component.props.children.length }, "props",
0, propsPath,
"props", oldBranch,
propsPath, oldTree
oldBranch, );
oldTree if (property) {
); component.props.children.push(property);
if (property) { }
component.props.children.push(property); });
}
});
// Load env of the component // Load env of the component
const env = isApp ? node.env : node.component.env; const env = isApp ? node.env : node.component.env;
component.env = { toggled: oldTree ? oldTree.env.toggled : false, children: [] }; component.env = { toggled: oldTree ? oldTree.env.toggled : false, children: [] };
const envPath = isApp const envPath = isApp
? [...path, { type: "item", value: "env" }] ? [...path, { type: "item", value: "env" }]
: [...path, { type: "item", value: "component" }, { type: "item", value: "env" }]; : [...path, { type: "item", value: "component" }, { type: "item", value: "env" }];
Reflect.ownKeys(env) Reflect.ownKeys(env).forEach((key) => {
.sort(compareKeys) let oldBranch = oldTree?.env.children[component.env.children.length];
.forEach((key) => { const envElement = this.serializeObjectChild(
let oldBranch = oldTree?.env.children[component.env.children.length]; env,
const envElement = this.serializeObjectChild( { type: "item", value: key, childIndex: component.env.children.length },
env, 0,
{ type: "item", value: key, childIndex: component.env.children.length }, "env",
0, envPath,
"env", oldBranch,
envPath, oldTree
oldBranch, );
oldTree if (envElement) {
); component.env.children.push(envElement);
if (envElement) { }
component.env.children.push(envElement); });
}
});
// Load env getters // Load env getters
let obj = Object.getPrototypeOf(env); let obj = Object.getPrototypeOf(env);
Reflect.ownKeys(obj).forEach((key) => { Reflect.ownKeys(obj).forEach((key) => {
@@ -1279,25 +1216,23 @@
const instance = isApp ? node : node.component; const instance = isApp ? node : node.component;
component.instance = { toggled: oldTree ? oldTree.instance.toggled : true, children: [] }; component.instance = { toggled: oldTree ? oldTree.instance.toggled : true, children: [] };
const instancePath = isApp ? path : [...path, { type: "item", value: "component" }]; const instancePath = isApp ? path : [...path, { type: "item", value: "component" }];
Reflect.ownKeys(instance) Reflect.ownKeys(instance).forEach((key) => {
.sort(compareKeys) if (!["env", "props"].includes(key)) {
.forEach((key) => { let oldBranch = oldTree?.instance.children[component.instance.children.length];
if (!["env", "props"].includes(key)) { const instanceElement = this.serializeObjectChild(
let oldBranch = oldTree?.instance.children[component.instance.children.length]; instance,
const instanceElement = this.serializeObjectChild( { type: "item", value: key, childIndex: component.instance.children.length },
instance, 0,
{ type: "item", value: key, childIndex: component.instance.children.length }, "instance",
0, instancePath,
"instance", oldBranch,
instancePath, oldTree
oldBranch, );
oldTree if (instanceElement) {
); component.instance.children.push(instanceElement);
if (instanceElement) {
component.instance.children.push(instanceElement);
}
} }
}); }
});
// Load instance getters // Load instance getters
obj = Object.getPrototypeOf(instance); obj = Object.getPrototypeOf(instance);
while (obj) { while (obj) {
@@ -1413,39 +1348,6 @@
component.subscriptions.children.push(subscription); component.subscriptions.children.push(subscription);
}); });
} }
// Load hooks of the component
if (!isApp) {
component.hooks = { toggled: oldTree ? oldTree.hooks.toggled : true, children: [] };
const hooksList = [
"mounted",
"patched",
"willDestroy",
"willPatch",
"willStart",
"willUnmount",
"willUpdateProps",
];
const hooksPath = [...instancePath, { type: "item", value: "__owl__" }];
Reflect.ownKeys(instance.__owl__)
.sort(compareKeys)
.forEach((key) => {
if (hooksList.includes(key)) {
let oldBranch = oldTree?.hooks.children[component.hooks.children.length];
const property = this.serializeObjectChild(
instance.__owl__,
{ type: "item", value: key, childIndex: component.hooks.children.length },
0,
"hook",
hooksPath,
oldBranch,
oldTree
);
if (property) {
component.hooks.children.push(property);
}
}
});
}
return component; return component;
} }
// Replace the content of a parsed getter object with the result of the corresponding get method // Replace the content of a parsed getter object with the result of the corresponding get method
@@ -1720,37 +1622,6 @@
} }
return children; return children;
} }
getObservedVariables(current) {
const res = [...current];
for (let i = 0; i < current.length; i++) {
const path = current[i].path;
const parent = this.getObjectProperty(path.slice(0, path.length - 1));
if (parent && !(typeof parent === "string" && parent.startsWith("Exception: "))) {
const result = this.serializeObjectChild(
parent,
path.at(-1),
0,
"observed",
path.slice(0, path.length - 1),
{},
{}
);
result.hasChildren = false;
result.visible = true;
const index = path.findIndex((key) => typeof key !== "string");
if (index > 1) {
const componentNode = this.getComponentNode(path.slice(0, index));
result.path = [this.getComponentSimplifiedPath(componentNode)].concat(
path.slice(index)
);
}
res[i] = result;
} else {
res[i].visible = false;
}
}
return res;
}
// Returns the path of the given component node // Returns the path of the given component node
getComponentPath(componentNode) { getComponentPath(componentNode) {
let path = []; let path = [];
@@ -1767,23 +1638,6 @@
path.unshift(index.toString()); path.unshift(index.toString());
return path; return path;
} }
// Returns the simplified path of the given component node (using component names and indexes)
getComponentSimplifiedPath(componentNode) {
let path = componentNode.name;
if (componentNode.parentKey) {
while (componentNode.parent) {
const previousKey = componentNode.parentKey;
componentNode = componentNode.parent;
path = `${componentNode.name}/${Reflect.ownKeys(componentNode.children).indexOf(
previousKey
)}/${path}`;
}
}
const appsArray = [...this.apps];
let index = appsArray.findIndex((app) => app === componentNode.app);
path = index.toString() + (path.length ? `/${path}` : "");
return path;
}
// Store the object into a temp window variable and log it to the console // Store the object into a temp window variable and log it to the console
sendObjectToConsole(path) { sendObjectToConsole(path) {
const obj = this.getObjectProperty(path); const obj = this.getObjectProperty(path);
@@ -1831,48 +1685,6 @@
} }
} }
injectBreakpoint(hook, path, instanceOnly, condition) {
const componentNode = this.getObjectProperty(path);
const injectFunctionInHook = (comp, hook, fn) => {
comp[hook].push(fn);
};
const originalHook = [...componentNode.component.__owl__[hook]];
injectFunctionInHook(componentNode.component.__owl__, hook, () => {
debugger;
});
if (!this.breakpointsHookMap.get([componentNode.component.__owl__, hook])) {
this.breakpointsHookMap.set([componentNode.component.__owl__, hook], originalHook);
}
if (!instanceOnly) {
const componentClass = componentNode.component.constructor;
const originalSetup = componentClass.prototype.setup;
if (!this.breakpointsClassMap.get(componentClass)) {
this.breakpointsClassMap.set(componentClass, originalSetup);
}
componentClass.prototype.setup = function () {
const debuggerFunc = () => {
if (eval(condition)) {
this;
debugger;
}
};
injectFunctionInHook(this.__owl__, hook, debuggerFunc);
originalSetup.call(this, ...arguments);
};
}
}
removeBreakpoints() {
for (const [component, setup] of this.breakpointsClassMap) {
component.prototype.setup = setup;
}
this.breakpointsClassMap.clear();
for (const [ref, originalHook] of this.breakpointsHookMap) {
ref[0][ref[1]] = originalHook;
}
this.breakpointsHookMap.clear();
}
targetName(target, node) { targetName(target, node) {
// check on component // check on component
const { component } = node; const { component } = node;
@@ -1922,19 +1734,6 @@
} }
} }
function compareKeys(a, b) {
const isSymbolA = typeof a === "symbol";
const isSymbolB = typeof b === "symbol";
if (isSymbolA && !isSymbolB) {
return 1; // Place Symbols at the end
} else if (!isSymbolA && isSymbolB) {
return -1; // Place non-Symbols at the beginning
} else {
return String(a).localeCompare(String(b), undefined, { numeric: true }); // Sort other keys alphabetically
}
}
function checkOwlStatus() { function checkOwlStatus() {
let owlStatus = 2; let owlStatus = 2;
if (!window.__OWL__DEVTOOLS_GLOBAL_HOOK__) { if (!window.__OWL__DEVTOOLS_GLOBAL_HOOK__) {
-22
View File
@@ -4,28 +4,6 @@ All notable changes to the "owl-vision" extension will be documented in this fil
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
## [0.1.0] - 2024-11-06
### Added
- Basic autocomplete in xml files. This includes autocompletion for elements, components,
props, attributes, and javascript expressions.
The current implementation, while relatively simple, has a couple of drawbacks:
- Javascript imports are not resolved by the xml autocomplete, this means that it does not
understand the types of imported functions or objects. That said, I've added custom support
for frequently used Owl imports, namely `useState` and `useRef`. You can add more in
the settings if needed.
- The autocomplete is limited to templates directly linked to components, sub-templates
used via t-call will not get autocompletion as no component/context can be bound to them.
- "Go To Definition" support for props and javascript expressions in xml
- Support for the following directives: t-att, t-model, t-tag, t-debug, t-log
### Fixed
- Changed t-else syntax highlight from dynamic to static attribute
## [0.0.2] - 2023-2-11 ## [0.0.2] - 2023-2-11
### Added ### Added
+5528 -5558
View File
File diff suppressed because it is too large Load Diff
+2 -13
View File
@@ -4,7 +4,7 @@
"description": "Owl framework extension that highlights templates and ease navigation between components and templates.", "description": "Owl framework extension that highlights templates and ease navigation between components and templates.",
"publisher": "Odoo", "publisher": "Odoo",
"license": "LGPL-3.0-only", "license": "LGPL-3.0-only",
"version": "0.1.0", "version": "0.0.2",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/odoo/owl/tree/master/tools/owl-vision" "url": "https://github.com/odoo/owl/tree/master/tools/owl-vision"
@@ -63,13 +63,6 @@
"type": "string", "type": "string",
"default": "**/node_modules/**,**/lib/**,**/tests/**", "default": "**/node_modules/**,**/lib/**,**/tests/**",
"description": "Files to exclude in search" "description": "Files to exclude in search"
},
"owl-vision.autocomplete-mocks": {
"order": 2,
"type": "string",
"editPresentation": "multilineText",
"default": "/**\n* @template T\n* @param {T} obj\n* @returns {T}\n*/\nfunction useState(obj) {}\n\n/**\n* @typedef {Object} Ref\n* @property {HTMLElement} el\n*/\n/**\n* @returns {Ref}\n*/\nfunction useRef(name) {}",
"description": "Mocks for functions or object that are imported but not resolved by the autcomplete. Add docstring comments for them to work properly."
} }
} }
}, },
@@ -135,7 +128,6 @@
"devDependencies": { "devDependencies": {
"@types/node": "20.2.5", "@types/node": "20.2.5",
"@types/vscode": "^1.73.0", "@types/vscode": "^1.73.0",
"@types/xmldoc": "^1.1.9",
"@typescript-eslint/eslint-plugin": "^5.59.8", "@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8", "@typescript-eslint/parser": "^5.59.8",
"@vscode/test-electron": "^2.3.2", "@vscode/test-electron": "^2.3.2",
@@ -143,8 +135,5 @@
"esbuild": "^0.19.5", "esbuild": "^0.19.5",
"eslint": "^8.41.0", "eslint": "^8.41.0",
"typescript": "^5.1.3" "typescript": "^5.1.3"
},
"dependencies": {
"xmldoc": "^1.3.0"
} }
} }
@@ -62,6 +62,7 @@ export const propsAttributes = createAttributePatterns("props-attributes", {
export const owlAttributesDynamic = createAttributePatterns("owl-attributes-dynamic", { export const owlAttributesDynamic = createAttributePatterns("owl-attributes-dynamic", {
match: [ match: [
"t-if", "t-if",
"t-else",
"t-elif", "t-elif",
"t-foreach", "t-foreach",
"t-as", "t-as",
@@ -74,10 +75,6 @@ export const owlAttributesDynamic = createAttributePatterns("owl-attributes-dyna
"t-value", "t-value",
"t-portal", "t-portal",
"t-slot-scope", "t-slot-scope",
"t-att",
"t-tag",
"t-log",
"t-model",
"t-att-[a-z_:.-]+", "t-att-[a-z_:.-]+",
"t-on-[a-z_:.-]+" "t-on-[a-z_:.-]+"
].join("|"), ].join("|"),
@@ -89,13 +86,12 @@ export const owlAttributesDynamic = createAttributePatterns("owl-attributes-dyna
export const owlAttributesStatic = createAttributePatterns("owl-attributes-static", { export const owlAttributesStatic = createAttributePatterns("owl-attributes-static", {
match: [ match: [
"t-name", "t-name",
"t-else",
"t-ref", "t-ref",
"t-set-slot", "t-set-slot",
"t-model",
"t-inherit", "t-inherit",
"t-inherit-mode", "t-inherit-mode",
"t-translation", "t-translation"
"t-debug",
].join("|"), ].join("|"),
attributeName: "owl.attribute owl.attribute.static", attributeName: "owl.attribute owl.attribute.static",
}); });
@@ -0,0 +1,29 @@
import * as vscode from 'vscode';
import { getSelectedText, showStatusMessage, hideStatusMessage } from './utils';
import { Search } from './search';
export class ComponentDefinitionProvider implements vscode.DefinitionProvider {
search: Search;
constructor(search: Search) {
this.search = search;
}
/**
* Interface implementation to provide definition when ctrl+click on Component
* tag in template.
*/
async provideDefinition(document: vscode.TextDocument, position: vscode.Position) {
const currentWord = getSelectedText(/<\/?[A-Z][a-zA-Z]+/, document, position);
if (!currentWord) {
return;
}
const componentName = currentWord.replace(/[\/<]/g, "").trim();
showStatusMessage(`Searching for component "${componentName}"`);
const result = await this.search.findComponent(componentName);
hideStatusMessage();
return result;
}
}

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