Compare commits

...

6 Commits

Author SHA1 Message Date
Géry Debongnie 0d9d21a5c1 [REL] v2.2
# v2.2

 - [IMP] runtime: add support for Map and other iterables in t-foreach
 - [IMP] runtime: only destroy component in raf callback
 - [REF] runtime: simplify implementation of batched
 - [FIX] compiler: allow t-model.number to work with select
 - [FIX] devtools: Fix crash when no root node
 - [FIX] devtools: fix/imp env display
 - [FIX] devtools: fix symbols handling and display
2023-07-18 16:07:37 +02:00
Samuel Degueldre 836e12b1c5 [IMP] runtime: add support for Map and other iterables in t-foreach
closes: #1352
2023-07-18 13:41:07 +02:00
Géry Debongnie 7538aeae0e [IMP] runtime: only destroy component in raf callback
Before this commit, most of the time, components are destroyed when the
virtual dom is patched and a component node is removed. However, since
Owl is asynchronous and a component may take some time to get ready
(with onWillStart), it can happen that a component is created, then
before it is ready, it is recreated.  In that case, the initial instance
has to be destroyed.

Before this commit, the destroy operation was done immediately, when we
cancel the current fibers.  However, this means that we cannot have a
guarantee between micro task ticks that a component has not been
destroyed in the meantime.

For example, in Odoo, it is common to use the rpc service, which will
throw an error if called by a destroyed component. But because of the
possible destruction of a component at any time, the following code is
unsafe:

async loadSomeData() {
  // guaranteed to be called when component is alive
  await Promise.resolve();
  // however here, component may have been destroyed
  this.rpc(...)
}

So, to prevent this issue, we can slightly delay the destroy operation.
It is not entirely trivial, since we need to find a way to neutralize
the component in the meantime. But it seems like performing all that
kind of operation at the "commit" phase (so, the request animation frame
callback) makes sense to me.

So, this commit modifies the code to add a new component status
(cancelled) and use it to cancel components that are waiting to be
destroyed. These components will then be destroyed as soon as the
requestanimation frame starts, before all other dom operations.
2023-07-17 11:05:34 +02:00
Samuel Degueldre 3e9ba9ca8e [REF] runtime: simplify implementation of batched
Currently the implementation of batched is quite complicated and
difficult to read. This is because this approach tried to block all
calls at the same point and then only let the first one go through, but
an alternative approach is to simply throw away the calls that are made
after the first one has been scheduled. This change makes the
implementation much simpler to understand.

Co-authored-by: Aaron Bohy <aab@odoo.com>
2023-07-17 10:48:00 +02:00
Géry Debongnie e4c296a7d2 [FIX] compiler: allow t-model.number to work with select
Before this commit, owl parser would ignore the `.number` suffix on
<select> options. I do not see a good reason for that, and it prevents
some legitimate usecases.

closes #1444
2023-07-12 10:23:36 +02:00
Julien Carion (juca) 44748270da [FIX] devtools: Fix crash when no root node
This commit fixes a crash in the retrieval of the components tree which
happened when the first app did not contain a root node. The default
inspected component is now set to be the first root component found in
the apps.
2023-07-12 10:01:38 +02:00
23 changed files with 617 additions and 131 deletions
+1
View File
@@ -451,5 +451,6 @@ console.log(status(component));
// logs either:
// - 'new', if the component is new and has not been mounted yet
// - 'mounted', if the component is currently mounted
// - 'cancelled', if the component has not been mounted yet but will be destroyed soon
// - 'destroyed' if the component is currently destroyed
```
+8 -7
View File
@@ -376,15 +376,16 @@ An important difference should be made with the usual `QWeb` behaviour: Owl
requires the presence of a `t-key` directive, to be able to properly reconcile
renderings.
`t-foreach` can iterate on an array (the current item will be the current value)
or an object (the current item will be the current key).
`t-foreach` can iterate on any iterable, and also has special support for objects
and maps, it will expose the key of the current iteration as the contents of the
`t-as`, and the corresponding value with the same name and the suffix `_value`.
In addition to the name passed via t-as, `t-foreach` provides a few other
variables for various data points (note: `$as` will be replaced with the name
passed to `t-as`):
In addition to the name passed via t-as, `t-foreach` provides a few other useful
variables (note: `$as` will be replaced with the name passed to `t-as`):
- `$as_value`: the current iteration value, identical to `$as` for lists and
integers, but for objects, it provides the value (where `$as` provides the key)
- `$as_value`: the current iteration value, identical to `$as` for arrays and
other iterables, but for objects and maps, it provides the value (where `$as`
provides the key)
- `$as_index`: the current iteration index (the first item of the iteration has index 0)
- `$as_first`: whether the current item is the first of the iteration
(equivalent to `$as_index == 0`)
+82 -49
View File
@@ -122,14 +122,16 @@ function handleError(params) {
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber;
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root, error);
if (fiber) {
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root, error);
}
const handled = _handleError(node, error);
if (!handled) {
console.warn(`[Owl] Unhandled error. Destroying the root component`);
@@ -311,20 +313,13 @@ function updateClass(val, oldVal) {
* @returns a batched version of the original callback
*/
function batched(callback) {
let called = false;
return async () => {
// This await blocks all calls to the callback here, then releases them sequentially
// in the next microtick. This line decides the granularity of the batch.
await Promise.resolve();
if (!called) {
called = true;
// wait for all calls in this microtick to fall through before resetting "called"
// so that only the first call to the batched function calls the original callback.
// Schedule this before calling the callback so that calls to the batched function
// within the callback will proceed only after resetting called to false, and have
// a chance to execute the callback again
Promise.resolve().then(() => (called = false));
callback();
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
@@ -1657,8 +1652,7 @@ function cancelFibers(fibers) {
let node = fiber.node;
fiber.render = throwOnRender;
if (node.status === 0 /* NEW */) {
node.destroy();
delete node.parent.children[node.parentKey];
node.cancel();
}
node.fiber = null;
if (fiber.bdom) {
@@ -2385,6 +2379,9 @@ class ComponentNode {
}
}
async render(deep) {
if (this.status >= 2 /* CANCELLED */) {
return;
}
let current = this.fiber;
if (current && (current.root.locked || current.bdom === true)) {
await Promise.resolve();
@@ -2410,7 +2407,7 @@ class ComponentNode {
this.fiber = fiber;
this.app.scheduler.addFiber(fiber);
await Promise.resolve();
if (this.status === 2 /* DESTROYED */) {
if (this.status >= 2 /* CANCELLED */) {
return;
}
// We only want to actually render the component if the following two
@@ -2428,6 +2425,18 @@ class ComponentNode {
fiber.render();
}
}
cancel() {
this._cancel();
delete this.parent.children[this.parentKey];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = 2 /* CANCELLED */;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() {
let shouldRemove = this.status === 1 /* MOUNTED */;
this._destroy();
@@ -2455,7 +2464,7 @@ class ComponentNode {
this.app.handleError({ error: e, node: this });
}
}
this.status = 2 /* DESTROYED */;
this.status = 3 /* DESTROYED */;
}
async updateAndRender(props, parentFiber) {
this.nextProps = props;
@@ -2988,12 +2997,22 @@ function prepareList(collection) {
keys = collection;
values = collection;
}
else if (collection) {
values = Object.keys(collection);
keys = Object.values(collection);
else if (collection instanceof Map) {
keys = [...collection.keys()];
values = [...collection.values()];
}
else if (collection && typeof collection === "object") {
if (Symbol.iterator in collection) {
keys = [...collection];
values = keys;
}
else {
values = Object.keys(collection);
keys = Object.values(collection);
}
}
else {
throw new OwlError("Invalid loop expression");
throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
}
const n = values.length;
return [keys, values, n, new Array(n)];
@@ -4936,10 +4955,8 @@ function parseDOMNode(node, ctx) {
const typeAttr = node.getAttribute("type");
const isInput = tagName === "input";
const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio";
const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
@@ -4951,8 +4968,8 @@ function parseDOMNode(node, ctx) {
specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType,
hasDynamicChildren: false,
shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
shouldTrim: hasTrimMod,
shouldNumberize: hasNumberMod,
};
if (isSelect) {
// don't pollute the original ctx
@@ -5535,7 +5552,7 @@ function compile(template, options = {}) {
}
// do not modify manually. This file is generated by the release script.
const version = "2.1.3";
const version = "2.1.4";
// -----------------------------------------------------------------------------
// Scheduler
@@ -5545,11 +5562,18 @@ class Scheduler {
this.tasks = new Set();
this.frame = 0;
this.delayedRenders = [];
this.cancelledNodes = new Set();
this.requestAnimationFrame = Scheduler.requestAnimationFrame;
}
addFiber(fiber) {
this.tasks.add(fiber.root);
}
scheduleDestroy(node) {
this.cancelledNodes.add(node);
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
/**
* Process all current tasks. This only applies to the fibers that are ready.
* Other tasks are left unchanged.
@@ -5559,21 +5583,28 @@ class Scheduler {
let renders = this.delayedRenders;
this.delayedRenders = [];
for (let f of renders) {
if (f.root && f.node.status !== 2 /* DESTROYED */ && f.node.fiber === f) {
if (f.root && f.node.status !== 3 /* DESTROYED */ && f.node.fiber === f) {
f.render();
}
}
}
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => {
this.frame = 0;
this.tasks.forEach((fiber) => this.processFiber(fiber));
for (let task of this.tasks) {
if (task.node.status === 2 /* DESTROYED */) {
this.tasks.delete(task);
}
}
});
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
processTasks() {
this.frame = 0;
for (let node of this.cancelledNodes) {
node._destroy();
}
this.cancelledNodes.clear();
for (let task of this.tasks) {
this.processFiber(task);
}
for (let task of this.tasks) {
if (task.node.status === 3 /* DESTROYED */) {
this.tasks.delete(task);
}
}
}
processFiber(fiber) {
@@ -5586,7 +5617,7 @@ class Scheduler {
this.tasks.delete(fiber);
return;
}
if (fiber.node.status === 2 /* DESTROYED */) {
if (fiber.node.status === 3 /* DESTROYED */) {
this.tasks.delete(fiber);
return;
}
@@ -5810,9 +5841,11 @@ function status(component) {
switch (component.__owl__.status) {
case 0 /* NEW */:
return "new";
case 2 /* CANCELLED */:
return "cancelled";
case 1 /* MOUNTED */:
return "mounted";
case 2 /* DESTROYED */:
case 3 /* DESTROYED */:
return "destroyed";
}
}
@@ -5952,6 +5985,6 @@ TemplateSet.prototype._compileTemplate = function _compileTemplate(name, templat
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 = '2023-06-28T09:17:13.630Z';
__info__.hash = '432ff44';
__info__.date = '2023-07-18T14:07:26.565Z';
__info__.hash = '836e12b';
__info__.url = 'https://github.com/odoo/owl';
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.4",
"version": "2.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.4",
"version": "2.2",
"description": "Odoo Web Library (OWL)",
"main": "dist/owl.cjs.js",
"module": "dist/owl.es.js",
+2 -4
View File
@@ -365,10 +365,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
const typeAttr = node.getAttribute("type");
const isInput = tagName === "input";
const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio";
const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
@@ -381,8 +379,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType,
hasDynamicChildren: false,
shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
shouldTrim: hasTrimMod,
shouldNumberize: hasNumberMod,
};
if (isSelect) {
// don't pollute the original ctx
+18 -1
View File
@@ -145,6 +145,9 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
async render(deep: boolean) {
if (this.status >= STATUS.CANCELLED) {
return;
}
let current = this.fiber;
if (current && (current.root!.locked || (current as any).bdom === true)) {
await Promise.resolve();
@@ -171,7 +174,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
this.app.scheduler.addFiber(fiber);
await Promise.resolve();
if (this.status === STATUS.DESTROYED) {
if (this.status >= STATUS.CANCELLED) {
return;
}
// We only want to actually render the component if the following two
@@ -190,6 +193,20 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
}
cancel() {
this._cancel();
delete this.parent!.children[this.parentKey!];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = STATUS.CANCELLED;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() {
let shouldRemove = this.status === STATUS.MOUNTED;
this._destroy();
+11 -9
View File
@@ -51,17 +51,19 @@ export function handleError(params: ErrorParams) {
);
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber!;
const fiber = "fiber" in params ? params.fiber : node.fiber;
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
if (fiber) {
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root!, error);
fibersInError.set(fiber.root!, error);
}
const handled = _handleError(node, error);
if (!handled) {
+1 -2
View File
@@ -55,8 +55,7 @@ function cancelFibers(fibers: Fiber[]): number {
let node = fiber.node;
fiber.render = throwOnRender;
if (node.status === STATUS.NEW) {
node.destroy();
delete node.parent!.children[node.parentKey!];
node.cancel();
}
node.fiber = null;
if (fiber.bdom) {
+26 -9
View File
@@ -1,3 +1,4 @@
import type { ComponentNode } from "./component_node";
import { fibersInError } from "./error_handling";
import { Fiber, RootFiber } from "./fibers";
import { STATUS } from "./status";
@@ -14,6 +15,7 @@ export class Scheduler {
requestAnimationFrame: Window["requestAnimationFrame"];
frame: number = 0;
delayedRenders: Fiber[] = [];
cancelledNodes: Set<ComponentNode> = new Set();
constructor() {
this.requestAnimationFrame = Scheduler.requestAnimationFrame;
@@ -23,6 +25,13 @@ export class Scheduler {
this.tasks.add(fiber.root!);
}
scheduleDestroy(node: ComponentNode) {
this.cancelledNodes.add(node);
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
/**
* Process all current tasks. This only applies to the fibers that are ready.
* Other tasks are left unchanged.
@@ -39,15 +48,23 @@ export class Scheduler {
}
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => {
this.frame = 0;
this.tasks.forEach((fiber) => this.processFiber(fiber));
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
});
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
processTasks() {
this.frame = 0;
for (let node of this.cancelledNodes) {
node._destroy();
}
this.cancelledNodes.clear();
for (let task of this.tasks) {
this.processFiber(task);
}
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
}
+6 -1
View File
@@ -7,15 +7,20 @@ import type { Component } from "./component";
export const enum STATUS {
NEW,
MOUNTED, // is ready, and in DOM. It has a valid el
// component has been created, but has been replaced by a newer component before being mounted
// it is cancelled until the next animation frame where it will be destroyed
CANCELLED,
DESTROYED,
}
type STATUS_DESCR = "new" | "mounted" | "destroyed";
type STATUS_DESCR = "new" | "mounted" | "cancelled" | "destroyed";
export function status(component: Component): STATUS_DESCR {
switch (component.__owl__.status) {
case STATUS.NEW:
return "new";
case STATUS.CANCELLED:
return "cancelled";
case STATUS.MOUNTED:
return "mounted";
case STATUS.DESTROYED:
+15 -7
View File
@@ -60,18 +60,26 @@ function withKey(elem: any, k: string) {
return elem;
}
function prepareList(collection: any): [any[], any[], number, any[]] {
let keys: any[];
let values: any[];
function prepareList(collection: unknown): [unknown[], unknown[], number, undefined[]] {
let keys: unknown[];
let values: unknown[];
if (Array.isArray(collection)) {
keys = collection;
values = collection;
} else if (collection) {
values = Object.keys(collection);
keys = Object.values(collection);
} else if (collection instanceof Map) {
keys = [...collection.keys()];
values = [...collection.values()];
} else if (collection && typeof collection === "object") {
if (Symbol.iterator in collection) {
keys = [...(<Iterable<unknown>>collection)];
values = keys;
} else {
values = Object.keys(collection);
keys = Object.values(collection);
}
} else {
throw new OwlError("Invalid loop expression");
throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
}
const n = values.length;
return [keys, values, n, new Array(n)];
+7 -14
View File
@@ -9,20 +9,13 @@ export type Callback = () => void;
* @returns a batched version of the original callback
*/
export function batched(callback: Callback): Callback {
let called = false;
return async () => {
// This await blocks all calls to the callback here, then releases them sequentially
// in the next microtick. This line decides the granularity of the batch.
await Promise.resolve();
if (!called) {
called = true;
// wait for all calls in this microtick to fall through before resetting "called"
// so that only the first call to the batched function calls the original callback.
// Schedule this before calling the callback so that calls to the batched function
// within the callback will proceed only after resetting called to false, and have
// a chance to execute the callback again
Promise.resolve().then(() => (called = false));
callback();
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
+1 -1
View File
@@ -1,2 +1,2 @@
// do not modify manually. This file is generated by the release script.
export const version = "2.1.4";
export const version = "2.2";
@@ -77,6 +77,62 @@ exports[`t-foreach iterate on items 1`] = `
}"
`;
exports[`t-foreach iterate, Map param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, Set param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, dict param 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -108,6 +164,62 @@ exports[`t-foreach iterate, dict param 1`] = `
}"
`;
exports[`t-foreach iterate, generator param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['gen']());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, iterable param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['map'].values());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, position 1`] = `
"function anonymous(app, bdom, helpers
) {
+2 -2
View File
@@ -1991,8 +1991,8 @@ describe("qweb parser", () => {
baseExpr: "state",
expr: "'stuff'",
eventType: "click",
shouldNumberize: false,
shouldTrim: false,
shouldNumberize: true,
shouldTrim: true,
targetAttr: "value",
hasDynamicChildren: false,
specialInitTargetAttr: "checked",
+61 -1
View File
@@ -105,6 +105,64 @@ describe("t-foreach", () => {
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, Map param", () => {
const template = `
<t t-foreach="value" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 a] [1: 2 b] [2: 3 c] `;
const context = {
value: new Map([
["a", 1],
["b", 2],
["c", 3],
]),
};
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, Set param", () => {
const template = `
<t t-foreach="value" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = { value: new Set([1, 2, 3]) };
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, iterable param", () => {
const template = `
<t t-foreach="map.values()" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = {
map: new Map([
["a", 1],
["b", 2],
["c", 3],
]),
};
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, generator param", () => {
const template = `
<t t-foreach="gen()" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = {
*gen() {
yield 1;
yield 2;
yield 3;
},
};
expect(renderToString(template, context)).toBe(expected);
});
test("does not pollute the rendering context", () => {
const template = `
<div>
@@ -193,7 +251,9 @@ describe("t-foreach", () => {
test("throws error if invalid loop expression", () => {
const test = `<div><t t-foreach="abc" t-as="item" t-key="item"><span t-key="item_index"/></t></div>`;
expect(() => renderToString(test)).toThrow("Invalid loop expression");
expect(() => renderToString(test)).toThrow(
'Invalid loop expression: "undefined" is not iterable'
);
});
test("t-foreach with t-if inside", () => {
@@ -212,6 +212,73 @@ exports[`changing state before first render does not trigger a render 1`] = `
}"
`;
exports[`component destroyed just after render 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`component destroyed just after render 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`B\`);
const b3 = text(ctx['state'].value);
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
b2 = text(\`A\`);
if (ctx['state'].flag) {
b3 = comp1({}, key + \`__1\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`C\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`B\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 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[`concurrent renderings scenario 1 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -468,6 +468,36 @@ exports[`t-model directive t-model on select with static options 1`] = `
}"
`;
exports[`t-model directive t-model with dynamic number values on select options in foreach 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { toNumber, prepareList, withKey } = helpers;
let block1 = createBlock(\`<select block-handler-0=\\"change\\"><block-child-0/></select>\`);
let block3 = createBlock(\`<option block-attribute-0=\\"value\\" block-attribute-1=\\"selected\\"><block-text-2/></option>\`);
return function template(ctx, node, key = \\"\\") {
const bExpr1 = ctx['state'];
const expr1 = 'value';
const bValue1 = bExpr1[expr1];
let hdlr1 = [(ev) => { bExpr1[expr1] = toNumber(ev.target.value); }];
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].options);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`o\`] = v_block2[i1];
const key1 = ctx['o'].value;
let attr1 = ctx['o'].value;
let attr2 = bValue1 === ctx['o'].value;
let txt1 = ctx['o'].value;
c_block2[i1] = withKey(block3([attr1, attr2, txt1]), key1);
}
const b2 = list(c_block2);
return block1([hdlr1], [b2]);
}
}"
`;
exports[`t-model directive t-model with dynamic values on select options -- 2 1`] = `
"function anonymous(app, bdom, helpers
) {
+123 -18
View File
@@ -115,13 +115,7 @@ test("destroying/recreating a subwidget with different props (if start is not ov
await nextMicroTick();
expect(n).toBe(2);
expect([
"Child:willDestroy",
"W:willRender",
"Child:setup",
"Child:willStart",
"W:rendered",
]).toBeLogged();
expect(["W:willRender", "Child:setup", "Child:willStart", "W:rendered"]).toBeLogged();
def.resolve();
await nextTick();
@@ -130,6 +124,7 @@ test("destroying/recreating a subwidget with different props (if start is not ov
expect([
"Child:willRender",
"Child:rendered",
"Child:willDestroy",
"W:willPatch",
"Child:mounted",
"W:patched",
@@ -178,13 +173,13 @@ test("destroying/recreating a subcomponent, other scenario", async () => {
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willDestroy",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:willDestroy",
"Parent:willPatch",
"Child:mounted",
"Parent:patched",
@@ -251,13 +246,13 @@ test("creating two async components, scenario 1", async () => {
await nextTick();
expect(fixture.innerHTML).toBe("");
expect([
"ChildA:willDestroy",
"Parent:willRender",
"ChildA:setup",
"ChildA:willStart",
"ChildB:setup",
"ChildB:willStart",
"Parent:rendered",
"ChildA:willDestroy",
]).toBeLogged();
defB.resolve();
@@ -703,13 +698,13 @@ test("rendering component again in next microtick", async () => {
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willDestroy",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:willDestroy",
"Parent:willPatch",
"Child:mounted",
"Parent:patched",
@@ -1732,9 +1727,9 @@ test("concurrent renderings scenario 10", async () => {
expect(fixture.innerHTML).toBe("<div><p></p></div>");
expect([
"ComponentA:willRender",
"ComponentC:willDestroy",
"ComponentB:willUpdateProps",
"ComponentA:rendered",
"ComponentC:willDestroy",
]).toBeLogged();
defB.resolve();
@@ -2282,7 +2277,6 @@ test("concurrent renderings scenario 16", async () => {
"D:setup",
"D:willStart",
"C:rendered",
"D:willDestroy",
"B:willRender",
"C:willUpdateProps",
"B:rendered",
@@ -2290,6 +2284,7 @@ test("concurrent renderings scenario 16", async () => {
"D:setup",
"D:willStart",
"C:rendered",
"D:willDestroy",
]).toBeLogged();
// at this point, C rendering is still pending, and nothing should have been
@@ -2997,11 +2992,11 @@ test("t-key on dom node having a component", async () => {
expect(fixture.innerHTML).toBe("<div>3</div>");
expect([
"Child (2):willDestroy",
"Child (3):setup",
"Child (3):willStart",
"Child (3):willRender",
"Child (3):rendered",
"Child (2):willDestroy",
"Child (1):willUnmount",
"Child (1):willDestroy",
"Child (3):mounted",
@@ -3055,11 +3050,11 @@ test("t-key on dynamic async component (toggler is never patched)", async () =>
expect(fixture.innerHTML).toBe("<div>3</div>");
expect([
"Child (2):willDestroy",
"Child (3):setup",
"Child (3):willStart",
"Child (3):willRender",
"Child (3):rendered",
"Child (2):willDestroy",
"Child (1):willUnmount",
"Child (1):willDestroy",
"Child (3):mounted",
@@ -3114,11 +3109,11 @@ test("t-foreach with dynamic async component", async () => {
expect(fixture.innerHTML).toBe("<div>3</div>");
expect([
"Child (2):willDestroy",
"Child (3):setup",
"Child (3):willStart",
"Child (3):willRender",
"Child (3):rendered",
"Child (2):willDestroy",
"Child (1):willUnmount",
"Child (1):willDestroy",
"Child (3):mounted",
@@ -3801,7 +3796,7 @@ test("destroyed component causes other soon to be destroyed component to rerende
static template = xml`<t t-esc="state.val + props.value"/>`;
state = useState({ val: 0 });
setup() {
c = this;
c = c || this;
useLogLifecycle();
}
}
@@ -3846,8 +3841,6 @@ test("destroyed component causes other soon to be destroyed component to rerende
parent.state.valueB = 2;
await nextTick();
expect([
"B:willDestroy",
"C:willDestroy",
"A:willRender",
"B:setup",
"B:willStart",
@@ -3858,6 +3851,8 @@ test("destroyed component causes other soon to be destroyed component to rerende
"B:rendered",
"C:willRender",
"C:rendered",
"B:willDestroy",
"C:willDestroy",
"A:willPatch",
"C:mounted",
"B:mounted",
@@ -4200,6 +4195,116 @@ test("delayed render is not cancelled by upcoming render", async () => {
]).toBeLogged();
});
test("components are not destroyed between animation frame", async () => {
const def = makeDeferred();
class C extends Component {
static template = xml`C`;
setup() {
useLogLifecycle();
}
}
class B extends Component {
static template = xml`B<C/>`;
static components = { C };
setup() {
useLogLifecycle();
onWillStart(() => {
return def;
});
}
}
class A extends Component {
static template = xml`A<B t-if="state.flag"/>`;
static components = { B };
state = useState({ flag: false });
setup() {
useLogLifecycle();
}
}
const a = await mount(A, fixture);
expect(fixture.innerHTML).toBe("A");
expect(["A:setup", "A:willStart", "A:willRender", "A:rendered", "A:mounted"]).toBeLogged();
// turn the flag on, this will render A and stops at B because of def
a.state.flag = true;
await nextTick();
expect(["A:willRender", "B:setup", "B:willStart", "A:rendered"]).toBeLogged();
// force a render of A
// => owl will need to create a new B component
// => initial B component will be cancelled
a.render();
await nextMicroTick();
expect([
// note that B is not destroyed here. It is cancelled instead
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
]).toBeLogged();
// resolve def, so B render is unblocked
def.resolve();
await nextTick();
expect([
"B:willRender",
"C:setup",
"C:willStart",
"B:rendered",
"C:willRender",
"C:rendered",
// animation frame callback starts here
"B:willDestroy", // B is destroyed here
"A:willPatch",
"C:mounted",
"B:mounted",
"A:patched",
]).toBeLogged();
});
test("component destroyed just after render", async () => {
let stateB: any;
class B extends Component {
static template = xml`B<t t-esc="state.value"/>`;
state = useState({ value: 1 });
setup() {
stateB = this.state;
useLogLifecycle();
}
}
class A extends Component {
static template = xml`<B/>`;
static components = { B };
setup() {
useLogLifecycle();
}
}
const a = await mount(A, fixture);
expect(fixture.innerHTML).toBe("B1");
expect([
"A:setup",
"A:willStart",
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
"B:willRender",
"B:rendered",
"B:mounted",
"A:mounted",
]).toBeLogged();
stateB!.value++; // force a render of B
await nextMicroTick(); // wait for B render to actually start
a.__owl__.app.destroy();
expect(["A:willUnmount", "B:willUnmount", "B:willDestroy", "A:willDestroy"]).toBeLogged();
await nextTick();
// check that B was not rendered after being destroyed
expect([]).toBeLogged();
});
// test.skip("components with shouldUpdate=false", async () => {
// const state = { p: 1, cc: 10 };
+6 -2
View File
@@ -1444,6 +1444,7 @@ describe("can catch errors", () => {
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
@@ -1506,12 +1507,15 @@ describe("can catch errors", () => {
parent.state.hasChild = false;
await nextTick();
expect([
"Parent:willRender",
"Parent:rendered",
"Child:willDestroy",
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
]).toBeLogged();
expect(fixture.innerHTML).toBe("1");
await nextTick();
expect(["Parent:willPatch", "Parent:patched"]).toBeLogged();
expect(fixture.innerHTML).toBe("2");
});
});
+33
View File
@@ -626,6 +626,39 @@ describe("t-model directive", () => {
expect(fixture.querySelector("select")!.value).toEqual("b");
});
test("t-model with dynamic number values on select options in foreach", async () => {
class Test extends Component {
static template = xml`
<select t-model.number="state.value">
<t t-foreach="state.options" t-as="o" t-key="o.value">
<option t-att-value="o.value" t-esc="o.value"/>
</t>
</select>
`;
state: any;
setup() {
this.state = useState({
value: 2,
options: [{ value: 1 }, { value: 2 }, { value: 3 }],
});
}
}
const comp = await mount(Test, fixture);
// check that we have a value of 2 selected
expect(fixture.querySelector("select")!.value).toEqual("2");
expect(comp.state.value).toBe(2);
// emulate a click on the option=3 element
fixture.querySelectorAll("option")[2].selected = true;
fixture.querySelector("select")!.dispatchEvent(new Event("change"));
await nextTick();
// check that we have now selected the number 3 (and not the string)
expect(fixture.querySelector("select")!.value).toEqual("3");
expect(comp.state.value).toBe(3);
});
test("t-model is applied before t-on-input", async () => {
expect.assertions(3);
class SomeComponent extends Component {
@@ -1519,8 +1519,9 @@
}
}
}
// If nothing was found, return the first app's root component path
return ["0", "root"];
// If nothing was found, return the path of the first root component found in the apps
const appIndex = [...this.apps].findIndex((app) => app.root);
return [appIndex.toString(), "root"];
}
// Returns the tree of components of the inspected page in a parsed format
// Use inspectedPath to specify the path of the selected component