Compare commits

..

1 Commits

Author SHA1 Message Date
Géry Debongnie 0a5a1e61dd [IMP] portal: add support for .closest modifier
It is sometimes useful in practice to be able to configure the portal so
that it looks for a target as close as possible as the portal location.
For example, in odoo, a portal may be set up in a form view that should
target the current form view. But if the form view itself is in a
dialog, it may fail, because it may find a valid target in the form view that is located
underneath.

With this commit, we add a .closest modifier to the `t-portal`
directive.
2023-05-08 11:58:56 +02:00
24 changed files with 165 additions and 405 deletions
+8
View File
@@ -15,3 +15,11 @@ class SomeComponent extends Component {
The `t-portal` directive takes a valid css selector as argument. The content of
the portalled template will be mounted at the corresponding location. Note that
Owl need to insert an empty text node at the location of the portalled content.
The `t-portal` directive supports a `.closest` modifier. It is useful to select
the closest target from the portal location: Owl will look for a target in the
current parent element, then in its parent, and so on until it finds it.
```xml
<div t-portal.closest="'.target'">some content</div>
```
+2 -1
View File
@@ -10,7 +10,7 @@
<link rel="stylesheet" href="assets/milligram.css">
<link rel="stylesheet" href="assets/highlight.tomorrow.css">
<link rel="stylesheet" href="assets/main.css">
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
<script src="./owl.js"></script>
</head>
<body>
<header class="container">
@@ -68,6 +68,7 @@
<p><a href=".">OWL</a> is licensed under LGPLv3.<br>Logo from <a href="https://github.com/googlefonts/noto-emoji">Google Noto Emoji Font</a>, licensed under Apache License 2.0</p>
</footer>
<script src="assets/highlight.pack.js"></script>
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
<script type="module" src="display_code.js"></script>
<script type="module" src="counter.js"></script>
</body>
+7 -10
View File
@@ -447,11 +447,6 @@ export class CodeGenerator {
.join("");
}
translate(str: string): string {
const match = translationRE.exec(str) as any;
return match[1] + this.translateFn(match[2]) + match[3];
}
/**
* @returns the newly created block name, if any
*/
@@ -532,7 +527,8 @@ export class CodeGenerator {
let value = ast.value;
if (value && ctx.translate !== false) {
value = this.translate(value);
const match = translationRE.exec(value) as any;
value = match[1] + this.translateFn(match[2]) + match[3];
}
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
@@ -1099,11 +1095,10 @@ export class CodeGenerator {
} else {
let value: string;
if (ast.defaultValue) {
const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
if (ast.value) {
value = `withDefault(${expr}, \`${defaultValue}\`)`;
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
} else {
value = `\`${defaultValue}\``;
value = `\`${ast.defaultValue}\``;
}
} else {
value = expr;
@@ -1376,7 +1371,9 @@ export class CodeGenerator {
});
const target = compileExpr(ast.target);
const blockString = `${id}({target: ${target},slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, key + \`${key}\`, node, ctx, Portal)`;
const blockString = `${id}({target: ${target},${
ast.isClosest ? "isClosest: true," : ""
}slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, key + \`${key}\`, node, ctx, Portal)`;
if (block) {
this.insertAnchor(block);
}
+16 -7
View File
@@ -169,6 +169,7 @@ export interface ASTTranslation {
export interface ASTTPortal {
type: ASTType.TPortal;
target: string;
isClosest: boolean;
content: AST;
}
@@ -336,10 +337,10 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr)!;
if (attr === "t-on" || attr === "t-on-") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr.startsWith("t-on-")) {
if (attr.startsWith("t-on")) {
if (attr === "t-on") {
throw new OwlError("Missing event name with t-on directive");
}
on = on || {};
on[attr.slice(5)] = value;
} else if (attr.startsWith("t-model")) {
@@ -833,11 +834,18 @@ function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
// -----------------------------------------------------------------------------
function parseTPortal(node: Element, ctx: ParsingContext): AST | null {
if (!node.hasAttribute("t-portal")) {
let target, isClosest;
if (node.hasAttribute("t-portal")) {
target = node.getAttribute("t-portal")!;
node.removeAttribute("t-portal");
isClosest = false;
} else if (node.hasAttribute("t-portal.closest")) {
target = node.getAttribute("t-portal.closest")!;
node.removeAttribute("t-portal.closest");
isClosest = true;
} else {
return null;
}
const target = node.getAttribute("t-portal")!;
node.removeAttribute("t-portal");
const content = parseNode(node, ctx);
if (!content) {
return {
@@ -848,6 +856,7 @@ function parseTPortal(node: Element, ctx: ParsingContext): AST | null {
return {
type: ASTType.TPortal,
target,
isClosest,
content,
};
}
-5
View File
@@ -7,7 +7,6 @@ import { Scheduler } from "./scheduler";
import { validateProps } from "./template_helpers";
import { TemplateSet, TemplateSetConfig } from "./template_set";
import { validateTarget } from "./utils";
import { toRaw, reactive } from "./reactivity";
// reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f
@@ -40,8 +39,6 @@ declare global {
apps: Set<App>;
Fiber: typeof Fiber;
RootFiber: typeof RootFiber;
toRaw: typeof toRaw;
reactive: typeof reactive;
};
}
}
@@ -50,8 +47,6 @@ window.__OWL_DEVTOOLS__ ||= {
apps: new Set<App>(),
Fiber: Fiber,
RootFiber: RootFiber,
toRaw: toRaw,
reactive: reactive,
};
export class App<
+6 -13
View File
@@ -59,35 +59,28 @@ export function useChildSubEnv(envExtension: Env) {
// useEffect
// -----------------------------------------------------------------------------
type EffectDeps<T extends any[]> = T | (T extends [...infer H, never] ? EffectDeps<H> : never);
/**
* @template T
* @param {...T} dependencies the dependencies computed by computeDependencies
* @param {...any} dependencies the dependencies computed by computeDependencies
* @returns {void|(()=>void)} a cleanup function that reverses the side
* effects of the effect callback.
*/
type Effect<T extends [...T]> = (...dependencies: EffectDeps<T>) => void | (() => void);
type Effect = (...dependencies: any[]) => void | (() => void);
/**
* This hook will run a callback when a component is mounted and patched, and
* will run a cleanup function before patching and before unmounting the
* the component.
*
* @template T
* @param {Effect<T>} effect the effect to run on component mount and/or patch
* @param {()=>T} [computeDependencies=()=>[NaN]] a callback to compute
* @param {Effect} effect the effect to run on component mount and/or patch
* @param {()=>any[]} [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
* NaN !== NaN, which will cause the effect to rerun on every patch.
*/
export function useEffect<T extends [...T]>(
effect: Effect<T>,
computeDependencies: () => T = () => [NaN] as never
) {
export function useEffect(effect: Effect, computeDependencies: () => any[] = () => [NaN]) {
let cleanup: (() => void) | void;
let dependencies: T;
let dependencies: any[];
onMounted(() => {
dependencies = computeDependencies();
cleanup = effect(...dependencies);
+24 -7
View File
@@ -5,20 +5,34 @@ import { OwlError } from "./error_handling";
const VText: any = text("").constructor;
function getTarget(
currentParentEl: HTMLElement | Document,
selector: string,
isClosest: boolean
): HTMLElement | null {
if (!isClosest || currentParentEl === document) {
return document.querySelector(selector);
}
const attempt = currentParentEl.querySelector(selector) as HTMLElement | null;
return attempt || getTarget(currentParentEl.parentElement!, selector, true);
}
class VPortal extends VText implements Partial<VNode<VPortal>> {
content: BDom | null;
selector: string;
isClosest: boolean;
target: HTMLElement | null = null;
constructor(selector: string, content: BDom) {
constructor(selector: string, isClosest: boolean, content: BDom) {
super("");
this.selector = selector;
this.isClosest = isClosest;
this.content = content;
}
mount(parent: HTMLElement, anchor: ChildNode) {
super.mount(parent, anchor);
this.target = document.querySelector(this.selector) as any;
this.target = getTarget(parent, this.selector, this.isClosest);
if (this.target) {
this.content!.mount(this.target!, null);
} else {
@@ -54,16 +68,19 @@ class VPortal extends VText implements Partial<VNode<VPortal>> {
export function portalTemplate(app: any, bdom: any, helpers: any) {
let { callSlot } = helpers;
return function template(ctx: any, node: any, key = ""): any {
return new VPortal(ctx.props.target, callSlot(ctx, node, key, "default", false, null));
return new VPortal(
ctx.props.target,
ctx.props.isClosest,
callSlot(ctx, node, key, "default", false, null)
);
};
}
export class Portal extends Component {
static template = "__portal__";
static props = {
target: {
type: String,
},
target: String,
isClosest: { type: Boolean, optional: true },
slots: true,
};
@@ -73,7 +90,7 @@ export class Portal extends Component {
onMounted(() => {
const portal: VPortal = node.bdom;
if (!portal.target) {
const target: HTMLElement = document.querySelector(this.props.target);
const target = getTarget(portal.parentEl, this.props.target, this.props.isClosest);
if (target) {
portal.content!.moveBeforeDOMNode(target.firstChild, target);
} else {
+2 -14
View File
@@ -8,12 +8,6 @@ import { OwlError } from "./error_handling";
import type { ComponentNode } from "./component_node";
const ObjectCreate = Object.create;
const ObjectGetPrototypeOf = Object.getPrototypeOf;
const ObjectGetOwnPropertyDescriptors = Object.getOwnPropertyDescriptors;
const ObjectDefineProperty = Object.defineProperty;
const ObjectEntries = Object.entries;
const hasOwnProperty = (obj: Object, prop: PropertyKey) =>
Object.prototype.hasOwnProperty.call(obj, prop);
/**
* This file contains utility functions that will be injected in each template,
* to perform various useful tasks in the compiled code.
@@ -55,14 +49,8 @@ function callSlot(
function capture(ctx: any): any {
const result = ObjectCreate(ctx);
let current = ctx;
while (current && current !== Object.prototype) {
for (const [key, descriptor] of ObjectEntries(ObjectGetOwnPropertyDescriptors(current))) {
if (!hasOwnProperty(result, key) && "value" in descriptor) {
ObjectDefineProperty(result, key, descriptor);
}
}
current = ObjectGetPrototypeOf(current);
for (let k in ctx) {
result[k] = ctx[k];
}
return result;
}
@@ -1,79 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`translation support body of t-sets are translated 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\\", \`translated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets inside translation=off are not translated 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\\", \`untranslated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block1 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
return block1();
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with text and html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block3 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
const b2 = text(\` translated \`);
const b3 = block3();
return multi([b2, b3]);
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support can set and remove translatable attributes 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -126,21 +52,6 @@ exports[`translation support some attributes are translated 1`] = `
}"
`;
exports[`translation support t-set and falsy t-value: t-body are translated 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\\", withDefault(false, \`translated\`));
return text(ctx['label']);
}
}"
`;
exports[`translation support translation is done on the trimmed text, with extra spaces readded after 1`] = `
"function anonymous(app, bdom, helpers
) {
+11 -24
View File
@@ -1147,24 +1147,6 @@ describe("qweb parser", () => {
});
});
test("t-onclick without dash", async () => {
expect(() => parse(`<button t-onclick="add">Click</button>`)).toThrowError(
"Unknown QWeb directive: 't-onclick'"
);
});
test("t-on without event", async () => {
expect(() => parse(`<button t-on="add">Click</button>`)).toThrowError(
"Missing event name with t-on directive"
);
});
test("t-on- without event", async () => {
expect(() => parse(`<button t-on-="add">Click</button>`)).toThrowError(
"Missing event name with t-on directive"
);
});
// ---------------------------------------------------------------------------
// t-model
// ---------------------------------------------------------------------------
@@ -1293,12 +1275,6 @@ describe("qweb parser", () => {
});
});
test("component with event handler", async () => {
expect(() => parse(`<MyComponent t-onclick="someMethod"/>`)).toThrowError(
"unsupported directive on Component: t-onclick"
);
});
test("component with t-ref", async () => {
expect(() => parse(`<MyComponent t-ref="something"/>`)).toThrow(
"t-ref is no longer supported on components. Consider exposing only the public part of the component's API through a callback prop."
@@ -2022,6 +1998,7 @@ describe("qweb parser", () => {
test("t-portal", async () => {
expect(parse(`<t t-portal="target">Content</t>`)).toEqual({
type: ASTType.TPortal,
isClosest: false,
target: "target",
content: { type: ASTType.Text, value: "Content" },
});
@@ -2032,6 +2009,7 @@ describe("qweb parser", () => {
condition: "condition",
content: {
content: { type: ASTType.Text, value: "Content" },
isClosest: false,
target: "target",
type: ASTType.TPortal,
},
@@ -2040,4 +2018,13 @@ describe("qweb parser", () => {
type: ASTType.TIf,
});
});
test("t-portal with .closest", async () => {
expect(parse(`<t t-portal.closest="target">Content</t>`)).toEqual({
type: ASTType.TPortal,
isClosest: true,
target: "target",
content: { type: ASTType.Text, value: "Content" },
});
});
});
-70
View File
@@ -100,74 +100,4 @@ describe("translation support", () => {
expect(translateFn).toHaveBeenCalledWith("some word");
expect(fixture.innerHTML).toBe("<div>un mot</div>");
});
test("body of t-sets are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label">untranslated</t>
<t t-esc="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("translated");
});
test("body of t-sets inside translation=off are not translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-translation="off">
<t t-set="label">untranslated</t>
<t t-esc="label"/>
</t>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("untranslated");
});
test("body of t-sets with html content are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label"><div>untranslated</div></t>
<t t-out="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div>translated</div>");
});
test("body of t-sets with text and html content are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label">
some text
<div>untranslated</div>
</t>
<t t-out="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe(" translated <div>translated</div>");
});
test("t-set and falsy t-value: t-body are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label" t-value="false">untranslated</t>
<t t-esc="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("translated");
});
});
@@ -1,50 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-call component with an enumerable getter, t-call inside slot 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const callTemplate_1 = app.getTemplate(\`sub\`);
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp1({slots: markRaw({'default': {__render: slot1.bind(this), __ctx: ctx1}})}, key + \`__2\`, node, this, null);
}
}"
`;
exports[`t-call component with an enumerable getter, t-call inside slot 2`] = `
"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['foo'];
return block1([txt1]);
}
}"
`;
exports[`t-call component with an enumerable getter, t-call inside slot 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
return function template(ctx, node, key = \\"\\") {
return callSlot(ctx, node, key, 'default', false, {});
}
}"
`;
exports[`t-call dynamic t-call 1`] = `
"function anonymous(app, bdom, helpers
) {
-22
View File
@@ -425,26 +425,4 @@ describe("t-call", () => {
await nextTick();
expect(fixture.innerHTML).toBe("Bchild");
});
test("component with an enumerable getter, t-call inside slot", async () => {
class Child extends Component {
static template = xml`<t t-slot="default"/>`;
}
class Parent extends Component {
static components = { Child };
static template = xml`<Child><t t-call="sub"/></Child>`;
}
// simulate adding a getter with patch in odoo: getter will be enumarable
Object.defineProperty(Parent.prototype, "foo", {
get() {
return 1;
},
enumerable: true,
});
const app = new App(Parent);
app.addTemplate("sub", `<div t-esc="foo"/>`);
await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>1</div>");
});
});
@@ -999,3 +999,26 @@ exports[`Portal: UI/UX focus is kept across re-renders 2`] = `
}
}"
`;
exports[`portal .closest suffix basic use of .suffix 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const Portal = app.Portal;
const comp1 = app.createComponent(null, false, true, false, false);
let block2 = createBlock(\`<p class=\\"target\\">far target</p>\`);
let block3 = createBlock(\`<div><p class=\\"target\\">close target</p><block-child-0/></div>\`);
function slot1(ctx, node, key = \\"\\") {
return text(\`portal content\`);
}
return function template(ctx, node, key = \\"\\") {
const b2 = block2();
const b5 = comp1({target: '.target',isClosest: true,slots: {'default': {__render: slot1.bind(this), __ctx: ctx}}}, key + \`__1\`, node, ctx, Portal);
const b3 = block3([], [b5]);
return multi([b2, b3]);
}
}"
`;
+18
View File
@@ -1028,3 +1028,21 @@ describe("Portal: Props validation", () => {
expect(error!.message).toBe(`invalid portal target`);
});
});
describe("portal .closest suffix", () => {
test("basic use of .suffix", async () => {
class Parent extends Component {
static template = xml`
<p class="target">far target</p>
<div>
<p class="target">close target</p>
<t t-portal.closest="'.target'">portal content</t>
</div>`;
}
await mount(Parent, fixture);
expect(fixture.innerHTML).toBe(
'<p class="target">far target</p><div><p class="target">close targetportal content</p></div>'
);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "Owl devtools",
"version": "1.1.1",
"version": "1.0",
"manifest_version": 3,
"description": "Chrome devtools extension for Odoo Owl framework",
"icons": {
@@ -72,7 +72,7 @@
</t>
</div>
</div>
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" t-ref="contextmenu">
<ul class="my-1">
<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 t-if="store.activeComponent.path.length !== 1">
@@ -30,7 +30,7 @@
</t>
</div>
</div>
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" 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"'>
@@ -38,8 +38,8 @@
</t>
</ul>
</div>
<t t-if="props.object.toggled" t-key="contextMenuId">
<t t-foreach="props.object.children" t-as="child" t-key="child_index">
<t t-if="props.object.toggled">
<t t-foreach="props.object.children" t-as="child" t-key="child.name">
<ObjectTreeElement t-if="props.object.objectType === 'subscription'" object="child" keys="props.keys"/>
<ObjectTreeElement t-else="" object="child"/>
</t>
@@ -1,11 +1,9 @@
/** @odoo-module **/
import { isElementInCenterViewport, minimizeKey, IS_FIREFOX } from "../../../../utils";
import { isElementInCenterViewport, minimizeKey } from "../../../../utils";
import { useStore } from "../../../store/store";
import { HighlightText } from "./highlight_text/highlight_text";
const browserInstance = IS_FIREFOX ? browser : chrome;
const { Component, useRef, useState, useEffect, onMounted } = owl;
export class TreeElement extends Component {
@@ -107,30 +105,4 @@ export class TreeElement extends Component {
this.store.selectComponent(this.props.component.path);
}
}
// Adds the component name to the components toggle blacklist if not already present
// Else, remove it from the blacklist
toggleComponentToBlacklist() {
if (this.store.settings.componentsToggleBlacklist.has(this.props.component.name)) {
if (!this.props.component.toggled) {
this.props.component.toggled = !this.props.component.toggled;
}
this.store.settings.componentsToggleBlacklist.delete(this.props.component.name);
browserInstance.storage.local.set({
owlDevtoolsComponentsToggleBlacklist: Array.from(
this.store.settings.componentsToggleBlacklist
),
});
} else {
if (this.props.component.toggled) {
this.props.component.toggled = !this.props.component.toggled;
}
this.store.settings.componentsToggleBlacklist.add(this.props.component.name);
browserInstance.storage.local.set({
owlDevtoolsComponentsToggleBlacklist: Array.from(
this.store.settings.componentsToggleBlacklist
),
});
}
}
}
@@ -26,7 +26,7 @@
<span t-if="props.component.depth">&gt;</span>
<span class="version" t-else="">owl=<t t-esc="props.component.version"/></span>
</div>
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-ref="contextmenu">
<div t-if="store.contextMenu.activeMenu === contextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" 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>
@@ -43,10 +43,6 @@
<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>
@@ -43,7 +43,7 @@
</span>
</div>
</t>
<div t-if="store.contextMenu.activeMenu === componentContextMenuId" class="custom-menu" t-ref="componentContextmenu">
<div t-if="store.contextMenu.activeMenu === componentContextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" 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">
@@ -28,14 +28,14 @@
</span>
</div>
</div>
<div t-if="store.contextMenu.activeMenu === nodeContextMenuId" class="custom-menu" t-ref="nodeContextMenu">
<div t-if="store.contextMenu.activeMenu === nodeContextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" 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">
<div t-if="store.contextMenu.activeMenu === componentContextMenuId" class="custom-menu" t-attf-style="top: {{store.contextMenu.top}}; left: {{store.contextMenu.left}}" 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">
+17 -32
View File
@@ -11,9 +11,10 @@ export const store = reactive({
expandByDefault: true,
toggleOnSelected: false,
darkmode: false,
componentsToggleBlacklist: new Set(),
},
contextMenu: {
top: 0,
left: 0,
id: 0,
activeMenu: -1,
// Opens the context menu corresponding with the given menu html element
@@ -28,9 +29,9 @@ export const store = reactive({
if (y + menuHeight > window.innerHeight) {
y = window.innerHeight - menuHeight;
}
menu.style.left = x + "px";
this.left = x + "px";
// Need 25px offset because of the main navbar from the browser devtools
menu.style.top = y - 25 + "px";
this.top = y - 25 + "px";
},
// Close the currently displayed context menu
close() {
@@ -109,7 +110,7 @@ export const store = reactive({
);
this.apps = apps ? apps : [];
if (!fromOld && this.settings.expandByDefault) {
this.apps.forEach((tree) => expandNodes(tree, true));
this.apps.forEach((tree) => expandNodes(tree));
}
const component = await evalFunctionInWindow(
"getComponentDetails",
@@ -502,18 +503,13 @@ export const store = reactive({
},
// Reset all the relevant data about the page currently stored
async resetData() {
await loadSettings();
resetData() {
this.loadComponentsTree(false);
this.events = [];
this.eventsTree = [];
this.activeRecorder = false;
evalFunctionInWindow("toggleEventsRecording", [false, 0]);
this.traceRenderings = false;
evalFunctionInWindow("toggleTracing", [false]);
this.traceSubscriptions = false;
evalFunctionInWindow("toggleSubscriptionTracing", [false]);
this.updateIFrameList();
},
// Triggers manually the rendering of the selected component
@@ -609,7 +605,7 @@ export const store = reactive({
// Refresh the whole extension
async refreshExtension() {
await loadScripts();
await this.resetData();
this.resetData();
},
// Toggle dark mode in the extension and store result in the storage
@@ -620,7 +616,7 @@ export const store = reactive({
} else {
document.querySelector("html").classList.remove("dark-mode");
}
browserInstance.storage.local.set({ owlDevtoolsDarkMode: this.settings.darkMode });
browserInstance.storage.local.set({ owl_devtools_dark_mode: this.settings.darkMode });
},
openDocumentation() {
@@ -640,8 +636,6 @@ async function init() {
evalInWindow("__OWL__DEVTOOLS_GLOBAL_HOOK__.devtoolsId = " + store.devtoolsId + ";");
await loadSettings();
// We want to load the base components tree when the devtools tab is first opened
store.loadComponentsTree(false);
@@ -657,6 +651,8 @@ async function init() {
evalFunctionInWindow("toggleEventsRecording", [false, 0], frame);
}
loadSettings();
browserInstance.runtime.sendMessage({ type: "newDevtoolsPanel", id: store.devtoolsId });
// Heartbeat message to test whether the extension context is still valid or not
@@ -681,14 +677,14 @@ browserInstance.runtime.onConnect.addListener((port) => {
store.owlStatus = await evalInWindow("window.__OWL__DEVTOOLS_GLOBAL_HOOK__ !== undefined;");
if (store.owlStatus) {
evalInWindow("__OWL__DEVTOOLS_GLOBAL_HOOK__.devtoolsId = " + store.devtoolsId + ";");
await store.resetData();
store.resetData();
}
}
// Received when a frame has been delayed when loading the scripts due to owl being lazy loaded
if (msg.type === "FrameReady") {
store.updateIFrameList();
store.owlStatus = true;
await store.resetData();
store.resetData();
}
// We need to reload the components tree when the set of apps in the page is modified
if (msg.type === "RefreshApps") {
@@ -744,12 +740,11 @@ browserInstance.runtime.onConnect.addListener((port) => {
// Load all settings from the chrome sync storage
async function loadSettings() {
let storage = await browserInstance.storage.local.get();
// Darkmode
if (storage.owlDevtoolsDarkMode === undefined) {
if (storage.owl_devtools_dark_mode === undefined) {
// Load dark mode based on the global settings of the chrome devtools
darkMode = browserInstance.devtools.panels.themeName === "dark";
} else {
darkMode = storage.owlDevtoolsDarkMode;
darkMode = storage.owl_devtools_dark_mode;
}
store.settings.darkMode = darkMode;
if (darkMode) {
@@ -757,12 +752,6 @@ async function loadSettings() {
} else {
document.querySelector("html").classList.remove("dark-mode");
}
// Components toggle blacklist
if (storage.owlDevtoolsComponentsToggleBlacklist !== undefined) {
store.settings.componentsToggleBlacklist = new Set(
storage.owlDevtoolsComponentsToggleBlacklist
);
}
}
// Function to handle and store a batch of events coming from the page
@@ -882,14 +871,10 @@ function highlightChildren(component) {
}
// Expand the node given in entry and all of its children
function expandNodes(node, blacklist = false) {
if (blacklist && store.settings.componentsToggleBlacklist.has(node.name)) {
node.toggled = false;
} else {
node.toggled = true;
}
function expandNodes(node) {
node.toggled = true;
for (const child of node.children) {
expandNodes(child, blacklist);
expandNodes(child);
}
}
@@ -11,10 +11,6 @@
this.Fiber = window.__OWL_DEVTOOLS__.Fiber;
// Same but for RootFiber
this.RootFiber = window.__OWL_DEVTOOLS__.RootFiber;
// This is for retrocompatibility purposes since new versions of owl should always expose toRaw and reactive
// in __OWL_DEVTOOLS__
this.toRaw = window.__OWL_DEVTOOLS__.toRaw ?? window.owl?.toRaw;
this.reactive = window.__OWL_DEVTOOLS__.reactive ?? window.owl?.reactive;
// Set to keep track of the fibers that are in the flush queue
this.queuedFibers = new WeakSet();
// Set to keep track of the HTML elements we added to the page
@@ -50,9 +46,6 @@
this.appsPatched = false;
this.destroyPatched = false;
this.patchAppsSetMethods();
if (this.apps.size > 0) {
this.patchAppMethods();
}
this.recordEvents = false;
this.traceRenderings = false;
this.traceSubscriptions = false;
@@ -248,22 +241,13 @@
return;
}
let app = this.apps.values().next().value;
const self = this;
if (app.root) {
this.patchDestroyMethod(app.root);
} else {
const originalMount = app.constructor.prototype.mount;
app.constructor.prototype.mount = async function (...args) {
const result = await originalMount.call(this, ...args);
const root = this.root;
self.patchDestroyMethod(root);
app.constructor.prototype.mount = originalMount;
return result;
};
if (!app) {
return;
}
const originalFlush = app.scheduler.constructor.prototype.flush;
let inFlush = false;
let _render = false;
const self = this;
app.scheduler.constructor.prototype.flush = function () {
// Used to know when a render is triggered inside the flush method or not
inFlush = true;
@@ -404,7 +388,7 @@
let targetToKeysToCallbacks;
// Step 1: extract internal values from owl
const obj = self.reactive({}, () => {});
const obj = owl.reactive({}, () => {});
let count = 0;
WeakMap.prototype.get = function () {
count++;
@@ -732,7 +716,7 @@
}
}
if (obj) {
obj = this.toRaw(obj);
obj = owl.toRaw(obj);
}
}
return obj;
@@ -840,7 +824,7 @@
child.contentType = "undefined";
child.hasChildren = false;
} else {
obj = this.toRaw(obj);
obj = owl.toRaw(obj);
switch (true) {
case obj instanceof Map:
child.contentType = "map";
@@ -1016,6 +1000,19 @@
children.push(entries);
index++;
}
const size = this.serializeObjectChild(
obj,
{ type: "item", value: "size", childIndex: children.length },
depth,
objType,
path,
oldBranch.children[index],
oldTree
);
if (size) {
children.push(size);
index++;
}
Reflect.ownKeys(obj).forEach((key) => {
const child = this.serializeObjectChild(
obj,
@@ -1392,7 +1389,7 @@
}
getter.hasChildren = false;
} else {
obj = this.toRaw(obj);
obj = owl.toRaw(obj);
switch (true) {
case obj instanceof Map:
getter.contentType = "map";
@@ -1487,7 +1484,7 @@
return;
}
if (objectType === "subscription") {
this.reactive(obj)[key] = value;
owl.reactive(obj)[key] = value;
} else {
obj[key] = value;
if (objectType === "props" || objectType === "instance") {