Compare commits

...

9 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
Julien Carion (juca) 8b1dc4c43d [FIX] devtools: fix/imp env display
This commit first fixes how object prototype are detected so that it
won't stop as soon as the constructor name of the object is "Object".
This allows displaying every single prototype encountered and closes
https://github.com/odoo/owl/issues/1467.

This commit also improves how the env of a component is displayed by
expanding its chain of prototypes by default while keeping its keys lit
as long as it is their first occurence in the chain.
2023-07-05 11:27:42 +02:00
Julien Carion (juca) c105c6da38 [FIX] devtools: fix symbols handling and display
This commit fixes the three following issues:
- Symbols could never appear in shortened display of objects
- Objects which contained only symbols as keys would be considered to be
  empty and therefore not expandable
- Symbol value edition would create a new property on the object with
  the stringified symbol as key instead of updating its value

closes https://github.com/odoo/owl/issues/1464
2023-06-29 14:15:44 +02:00
Géry Debongnie 3001420a1d [REL] v2.1.4
# v2.1.3

 - [FIX] components: properly differentiate t-call subcomponents
 - [REF] devtools: Better messages forwarding
 - [FIX] devtools: Fix app methods patching
 - [DOC] Fix a code bug in the example of slots
2023-06-28 11:17:24 +02:00
25 changed files with 726 additions and 164 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`)
+129 -64
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`);
@@ -175,11 +177,21 @@ function createAttrUpdater(attr) {
}
function attrsSetter(attrs) {
if (isArray(attrs)) {
setAttribute.call(this, attrs[0], attrs[1]);
if (attrs[0] === "class") {
setClass.call(this, attrs[1]);
}
else {
setAttribute.call(this, attrs[0], attrs[1]);
}
}
else {
for (let k in attrs) {
setAttribute.call(this, k, attrs[k]);
if (k === "class") {
setClass.call(this, attrs[k]);
}
else {
setAttribute.call(this, k, attrs[k]);
}
}
}
}
@@ -191,7 +203,12 @@ function attrsUpdater(attrs, oldAttrs) {
if (val === oldAttrs[1]) {
return;
}
setAttribute.call(this, name, val);
if (name === "class") {
updateClass.call(this, val, oldAttrs[1]);
}
else {
setAttribute.call(this, name, val);
}
}
else {
removeAttribute.call(this, oldAttrs[0]);
@@ -201,13 +218,23 @@ function attrsUpdater(attrs, oldAttrs) {
else {
for (let k in oldAttrs) {
if (!(k in attrs)) {
removeAttribute.call(this, k);
if (k === "class") {
updateClass.call(this, "", oldAttrs[k]);
}
else {
removeAttribute.call(this, k);
}
}
}
for (let k in attrs) {
const val = attrs[k];
if (val !== oldAttrs[k]) {
setAttribute.call(this, k, val);
if (k === "class") {
updateClass.call(this, val, oldAttrs[k]);
}
else {
setAttribute.call(this, k, val);
}
}
}
}
@@ -286,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);
}
};
}
@@ -1632,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) {
@@ -2360,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();
@@ -2385,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
@@ -2403,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();
@@ -2430,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;
@@ -2963,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)];
@@ -3875,6 +3919,10 @@ class CodeGenerator {
})
.join("");
}
translate(str) {
const match = translationRE.exec(str);
return match[1] + this.translateFn(match[2]) + match[3];
}
/**
* @returns the newly created block name, if any
*/
@@ -3952,8 +4000,7 @@ class CodeGenerator {
let { block, forceNewBlock } = ctx;
let value = ast.value;
if (value && ctx.translate !== false) {
const match = translationRE.exec(value);
value = match[1] + this.translateFn(match[2]) + match[3];
value = this.translate(value);
}
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
@@ -4494,11 +4541,12 @@ class CodeGenerator {
else {
let value;
if (ast.defaultValue) {
const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
if (ast.value) {
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
value = `withDefault(${expr}, \`${defaultValue}\`)`;
}
else {
value = `\`${ast.defaultValue}\``;
value = `\`${defaultValue}\``;
}
}
else {
@@ -4879,10 +4927,10 @@ function parseDOMNode(node, ctx) {
let model = null;
for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr);
if (attr.startsWith("t-on")) {
if (attr === "t-on") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr === "t-on" || attr === "t-on-") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr.startsWith("t-on-")) {
on = on || {};
on[attr.slice(5)] = value;
}
@@ -4907,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");
@@ -4922,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
@@ -5506,7 +5552,7 @@ function compile(template, options = {}) {
}
// do not modify manually. This file is generated by the release script.
const version = "2.1.2";
const version = "2.1.4";
// -----------------------------------------------------------------------------
// Scheduler
@@ -5516,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.
@@ -5530,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) {
@@ -5557,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;
}
@@ -5585,6 +5645,8 @@ window.__OWL_DEVTOOLS__ || (window.__OWL_DEVTOOLS__ = {
apps: new Set(),
Fiber: Fiber,
RootFiber: RootFiber,
toRaw: toRaw,
reactive: reactive,
});
class App extends TemplateSet {
constructor(Root, config = {}) {
@@ -5779,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";
}
}
@@ -5837,8 +5901,9 @@ function useChildSubEnv(envExtension) {
* will run a cleanup function before patching and before unmounting the
* the component.
*
* @param {Effect} effect the effect to run on component mount and/or patch
* @param {()=>any[]} [computeDependencies=()=>[NaN]] a callback to compute
* @template T
* @param {Effect<T>} effect the effect to run on component mount and/or patch
* @param {()=>T} [computeDependencies=()=>[NaN]] a callback to compute
* dependencies that will decide if the effect needs to be cleaned up and
* run again. If the dependencies did not change, the effect will not run
* again. The default value returns an array containing only NaN because
@@ -5920,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-04-29T07:45:54.333Z';
__info__.hash = 'aabb755';
__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.3",
"version": "2.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.3",
"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.3";
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 {
@@ -47,7 +47,7 @@ export class ObjectTreeElement extends Component {
classFor(object) {
// Prototype items will be dyed down to appear less important
if (object.path.some((item) => item?.type === "prototype")) {
if (object.path.some((item) => item?.type === "prototype") && !object.keepLit) {
return "attenuate";
}
// Same for subscription items which are not present in the keys while the keys will be bold
+32 -4
View File
@@ -102,7 +102,7 @@ export const store = reactive({
if (IS_FIREFOX) {
await evalInWindow("window.$0 = $0;", this.activeFrame);
}
const [apps, component] = await evalFunctionInWindow(
const [apps, details] = await evalFunctionInWindow(
"getComponentsTree",
fromOld && this.activeComponent
? [this.activeComponent.path, this.apps, this.activeComponent]
@@ -113,7 +113,8 @@ export const store = reactive({
if (!fromOld && this.settings.expandByDefault) {
this.apps.forEach((tree) => expandNodes(tree, true));
}
this.activeComponent = component;
keepEnvLit(details);
this.activeComponent = details;
},
// Select a component by retrieving its details from the page based on its path
@@ -150,9 +151,11 @@ export const store = reactive({
[component.path],
this.activeFrame
);
this.activeComponent = details;
if (!this.activeComponent) {
if (!details) {
await this.loadComponentsTree(false);
} else {
keepEnvLit(details);
this.activeComponent = details;
}
if (this.page !== "ComponentsTab") {
this.switchTab("ComponentsTab");
@@ -887,6 +890,31 @@ function expandNodes(node, blacklist = false) {
}
}
// This function transforms the env part of the details such that all env keys are not
// greyed out in the UI at their first occurence
function keepEnvLit(details) {
let alreadyMet = new Set();
for (let i = 0; i < details.env.children.length; i++) {
if (i < details.env.children.length - 1) {
alreadyMet.add(details.env.children[i].name);
} else {
let lastElement = details.env.children[i];
while (lastElement.children.at(-1).name === "[[Prototype]]") {
for (const [index, child] of lastElement.children.entries()) {
if (index < lastElement.children.length - 1) {
if (!alreadyMet.has(child.name)) {
child.keepLit = true;
alreadyMet.add(child.name);
}
} else {
lastElement = child;
}
}
}
}
}
}
// Fold the node given in entry and all of its children
function foldNodes(node) {
node.toggled = false;
@@ -117,6 +117,15 @@
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);
}
return "{" + result.join(", ") + "}";
},
map(obj) {
@@ -739,6 +748,9 @@
child.contentType = "object";
child.content = this.serializer.serializeItem(Object.getPrototypeOf(parentObj), true);
child.hasChildren = true;
if (!oldTree && type === "env") {
child.toggled = true;
}
break;
case "set entries":
case "map entries":
@@ -815,7 +827,8 @@
break;
case obj instanceof Object:
child.contentType = "object";
child.hasChildren = Object.keys(obj).length > 0;
child.hasChildren =
Object.keys(obj).length || Object.getOwnPropertySymbols(obj).length;
break;
default:
child.contentType = typeof obj;
@@ -880,7 +893,7 @@
const children = [];
depth = depth + 1;
let obj = this.getObjectProperty(path);
let oldBranch = this.getObjectInOldTree(oldTree, path, objType);
let oldBranch = oldTree && this.getObjectInOldTree(oldTree, path, objType);
if (!obj) {
return [];
}
@@ -895,7 +908,7 @@
depth,
objType,
path,
oldBranch.children[0],
oldBranch?.children[0],
oldTree
);
children.push(mapKey);
@@ -905,7 +918,7 @@
depth,
objType,
path,
oldBranch.children[1],
oldBranch?.children[1],
oldTree
);
children.push(mapValue);
@@ -916,7 +929,7 @@
depth,
objType,
path,
oldBranch.children[0],
oldBranch?.children[0],
oldTree
);
children.push(setValue);
@@ -937,7 +950,7 @@
depth,
objType,
path,
oldBranch.children[index],
oldBranch?.children[index],
oldTree
);
if (child) {
@@ -952,7 +965,7 @@
depth,
objType,
path,
oldBranch.children[index],
oldBranch?.children[index],
oldTree
);
if (child) {
@@ -969,7 +982,7 @@
depth,
objType,
path,
oldBranch.children[index],
oldBranch?.children[index],
oldTree
);
if (entries) {
@@ -983,7 +996,7 @@
depth,
objType,
path,
oldBranch.children[index],
oldBranch?.children[index],
oldTree
);
if (child) {
@@ -1018,7 +1031,7 @@
depth,
objType,
path,
oldBranch.children[index],
oldBranch?.children[index],
oldTree
);
if (child) children.push(child);
@@ -1051,14 +1064,14 @@
});
proto = Object.getPrototypeOf(proto);
}
if (!(obj.constructor.name === "Object")) {
if (obj.__proto__) {
prototype = this.serializeObjectChild(
obj,
{ type: "prototype", childIndex: children.length },
depth,
objType,
path,
oldBranch.children.at(-1),
oldBranch?.children.at(-1),
oldTree
);
children.push(prototype);
@@ -1433,8 +1446,11 @@
return;
}
}
const key = path.pop().value;
const item = path.pop();
const obj = this.getObjectProperty(path);
const key = item.hasOwnProperty("symbolIndex")
? Object.getOwnPropertySymbols(obj)[item.symbolIndex]
: item.value;
if (!obj) {
return;
}
@@ -1503,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