mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
[FIX] qweb/component: refactoring of scoping/variables/slots
This commit is a significant refactoring of the internal of QWeb. It simplifies the way variables/scoping and slots interact together. The main idea is that we use a simple scope object instead of a context/var/scope object. This commit also implement the actual correct QWeb semantic for the t-call directive with a sub body. Before, we simply extracted the variables from the body and injected them at the top of the sub template. We now simply compile the body before the sub template. This is a joint work with Lucas (lpe). closes #541 closes #544 closes #545 closes #557 closes #556
This commit is contained in:
@@ -70,10 +70,9 @@ interface Internal<T extends Env, Props> {
|
||||
parentLastFiberId: number;
|
||||
|
||||
// when a rendering is initiated by a parent, it may set variables in 'scope'
|
||||
// and 'vars' (typically when the component is rendered in a slot). We need to
|
||||
// (typically when the component is rendered in a slot). We need to
|
||||
// store that information in case the component would be re-rendered later on.
|
||||
scope: any;
|
||||
vars: any;
|
||||
|
||||
boundHandlers: { [key: number]: any };
|
||||
observer: Observer | null;
|
||||
@@ -198,8 +197,7 @@ export class Component<T extends Env, Props extends {}> {
|
||||
renderFn: qweb.render.bind(qweb, template),
|
||||
classObj: null,
|
||||
refs: null,
|
||||
scope: null,
|
||||
vars: null
|
||||
scope: null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -510,9 +508,8 @@ export class Component<T extends Env, Props extends {}> {
|
||||
* The __updateProps method is called by the t-component directive whenever
|
||||
* it updates a component (so, when the parent template is rerendered).
|
||||
*/
|
||||
async __updateProps(nextProps: Props, parentFiber: Fiber, scope: any, vars: any): Promise<void> {
|
||||
async __updateProps(nextProps: Props, parentFiber: Fiber, scope: any): Promise<void> {
|
||||
this.__owl__.scope = scope;
|
||||
this.__owl__.vars = vars;
|
||||
const shouldUpdate = parentFiber.force || this.shouldUpdate(nextProps);
|
||||
if (shouldUpdate) {
|
||||
const __owl__ = this.__owl__;
|
||||
@@ -566,12 +563,11 @@ export class Component<T extends Env, Props extends {}> {
|
||||
|
||||
/**
|
||||
* The __prepare method is only called by the t-component directive, when a
|
||||
* subcomponent is created. It gets its scope and vars, if any, from the
|
||||
* subcomponent is created. It gets its scope, if any, from the
|
||||
* parent template.
|
||||
*/
|
||||
__prepare(parentFiber: Fiber, scope: any, vars: any, cb: CallableFunction): Fiber {
|
||||
__prepare(parentFiber: Fiber, scope: any, cb: CallableFunction): Fiber {
|
||||
this.__owl__.scope = scope;
|
||||
this.__owl__.vars = vars;
|
||||
const fiber = new Fiber(parentFiber, this, parentFiber.force, null);
|
||||
fiber.shouldPatch = false;
|
||||
if (!parentFiber.child) {
|
||||
|
||||
+10
-27
@@ -190,10 +190,10 @@ QWeb.addDirective({
|
||||
priority: 100,
|
||||
atNodeEncounter({ ctx, value, node, qweb }): boolean {
|
||||
ctx.addLine("//COMPONENT");
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
ctx.rootContext.shouldDefineQWeb = true;
|
||||
ctx.rootContext.shouldDefineParent = true;
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
let hasDynamicProps = node.getAttribute("t-props") ? true : false;
|
||||
|
||||
// t-on- events and t-transition
|
||||
@@ -285,7 +285,7 @@ QWeb.addDirective({
|
||||
}
|
||||
let eventsCode = events
|
||||
.map(function([eventName, mods, handlerValue, extraArgs]) {
|
||||
let params = "owner";
|
||||
let params = "context";
|
||||
if (extraArgs) {
|
||||
if (ctx.loopNumber) {
|
||||
let argId = ctx.generateID();
|
||||
@@ -293,20 +293,20 @@ QWeb.addDirective({
|
||||
// be set asynchronously later when the widget is ready, and the
|
||||
// context might be different.
|
||||
ctx.addLine(`let arg${argId} = ${ctx.formatExpression(extraArgs)};`);
|
||||
params = `owner, arg${argId}`;
|
||||
params = `context, arg${argId}`;
|
||||
} else {
|
||||
params = `owner, ${ctx.formatExpression(extraArgs)}`;
|
||||
params = `context, ${ctx.formatExpression(extraArgs)}`;
|
||||
}
|
||||
}
|
||||
let handler = `function (e) {if(!owner.__owl__.isMounted){return}`;
|
||||
let handler = `function (e) {if(!context.__owl__.isMounted){return}`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
return T_COMPONENT_MODS_CODE[mod];
|
||||
})
|
||||
.join("");
|
||||
if (handlerValue) {
|
||||
handler += `const fn = owner['${handlerValue}'];`;
|
||||
handler += `if (fn) { fn.call(${params}, e); } else { owner.${handlerValue}; }`;
|
||||
handler += `const fn = context['${handlerValue}'];`;
|
||||
handler += `if (fn) { fn.call(${params}, e); } else { context.${handlerValue}; }`;
|
||||
}
|
||||
handler += `}`;
|
||||
return `vn.elm.addEventListener('${eventName}', ${handler});`;
|
||||
@@ -348,25 +348,9 @@ QWeb.addDirective({
|
||||
}
|
||||
|
||||
// SLOTS
|
||||
const varDefs: string[] = [];
|
||||
const hasSlots = node.childNodes.length;
|
||||
if (hasSlots) {
|
||||
ctx.rootContext.shouldTrackScope = true;
|
||||
for (let v of Object.values(ctx.variables)) {
|
||||
if (v["id"]) {
|
||||
varDefs.push(v["id"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let scopeVars;
|
||||
if (hasSlots) {
|
||||
let scope = ctx.scopeVars.length ? `Object.assign({}, scope)` : `{}`;
|
||||
let vars = varDefs.length ? `{${varDefs.join(",")}}` : "undefined";
|
||||
scopeVars = `${scope}, ${vars}`;
|
||||
} else {
|
||||
scopeVars = "undefined, undefined";
|
||||
}
|
||||
let scope = hasSlots ? `Object.assign(Object.create(context), scope)` : "undefined";
|
||||
|
||||
ctx.addIf(`w${componentID}`);
|
||||
|
||||
@@ -376,8 +360,7 @@ QWeb.addDirective({
|
||||
styleCode = `.then(()=>{if (w${componentID}.__owl__.isDestroyed) {return};w${componentID}.el.style=${tattStyle};});`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`w${componentID}.__updateProps(props${componentID}, extra.fiber${scopeVars &&
|
||||
", " + scopeVars})${styleCode};`
|
||||
`w${componentID}.__updateProps(props${componentID}, extra.fiber, ${scope})${styleCode};`
|
||||
);
|
||||
ctx.addLine(`let pvnode = w${componentID}.__owl__.pvnode;`);
|
||||
if (registerCode) {
|
||||
@@ -439,7 +422,7 @@ QWeb.addDirective({
|
||||
}
|
||||
|
||||
ctx.addLine(
|
||||
`let fiber = w${componentID}.__prepare(extra.fiber, ${scopeVars}, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
`let fiber = w${componentID}.__prepare(extra.fiber, ${scope}, () => { const vnode = fiber.vnode; pvnode.sel = vnode.sel; ${createHook}});`
|
||||
);
|
||||
// hack: specify empty remove hook to prevent the node from being removed from the DOM
|
||||
const insertHook = refExpr ? `insert(vn) {${refExpr}},` : "";
|
||||
|
||||
@@ -49,7 +49,6 @@ export class Fiber {
|
||||
inserter: (el: HTMLElement) => void | null;
|
||||
|
||||
scope: any;
|
||||
vars: any;
|
||||
|
||||
component: Component<any, any>;
|
||||
vnode: VNode | null = null;
|
||||
@@ -69,7 +68,6 @@ export class Fiber {
|
||||
|
||||
const __owl__ = component.__owl__;
|
||||
this.scope = __owl__.scope;
|
||||
this.vars = __owl__.vars;
|
||||
|
||||
this.root = parent ? parent.root : this;
|
||||
this.parent = parent;
|
||||
|
||||
+84
-90
@@ -19,21 +19,18 @@ import { htmlToVDOM } from "../vdom/html_to_vdom";
|
||||
//------------------------------------------------------------------------------
|
||||
// t-esc and t-raw
|
||||
//------------------------------------------------------------------------------
|
||||
QWeb.utils.getFragment = function(str: string): DocumentFragment {
|
||||
const temp = document.createElement("template");
|
||||
temp.innerHTML = str;
|
||||
return temp.content;
|
||||
};
|
||||
|
||||
QWeb.utils.htmlToVDOM = htmlToVDOM;
|
||||
|
||||
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: CompilationContext) {
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
if (value === "0") {
|
||||
const caller = ctx.getCaller();
|
||||
if (caller) {
|
||||
qweb._compileNode(caller, ctx.getInliningContext());
|
||||
return;
|
||||
if (ctx.parentNode) {
|
||||
// the 'zero' magical symbol is where we can find the result of the rendering
|
||||
// of the body of the t-call.
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.addLine(`c${ctx.parentNode}.push(...scope[utils.zero]);`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.xml instanceof NodeList && !value.id) {
|
||||
@@ -47,7 +44,7 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Compilatio
|
||||
exprID = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${exprID} = ${ctx.formatExpression(value)};`);
|
||||
} else {
|
||||
exprID = value.id;
|
||||
exprID = `scope.${value.id}`;
|
||||
}
|
||||
ctx.addIf(`${exprID} || ${exprID} === 0`);
|
||||
if (ctx.escaping) {
|
||||
@@ -110,6 +107,7 @@ QWeb.addDirective({
|
||||
extraNames: ["value"],
|
||||
priority: 60,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
const variable = node.getAttribute("t-set")!;
|
||||
let value = node.getAttribute("t-value")!;
|
||||
ctx.variables[variable] = ctx.variables[variable] || {};
|
||||
@@ -118,12 +116,12 @@ QWeb.addDirective({
|
||||
if (value) {
|
||||
const formattedValue = ctx.formatExpression(value);
|
||||
if (ctx.variables.hasOwnProperty(variable) && qwebvar.id) {
|
||||
ctx.addLine(`${qwebvar.id} = ${formattedValue}`);
|
||||
ctx.addLine(`${qwebvar.expr} = ${formattedValue}`);
|
||||
} else {
|
||||
const varName = `_${ctx.generateID()}`;
|
||||
ctx.addLine(`var ${varName} = ${formattedValue};`);
|
||||
qwebvar.id = varName;
|
||||
qwebvar.expr = formattedValue;
|
||||
ctx.addLine(`scope.${variable} = ${formattedValue};`);
|
||||
qwebvar.id = variable;
|
||||
qwebvar.expr = `scope.${variable}`;
|
||||
qwebvar.value = formattedValue;
|
||||
}
|
||||
} else {
|
||||
qwebvar.xml = node.childNodes;
|
||||
@@ -140,7 +138,7 @@ QWeb.addDirective({
|
||||
priority: 20,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-if")!);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : cond.id!);
|
||||
ctx.addIf(typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id!}`);
|
||||
return false;
|
||||
},
|
||||
finalize({ ctx }) {
|
||||
@@ -153,7 +151,9 @@ QWeb.addDirective({
|
||||
priority: 30,
|
||||
atNodeEncounter({ node, ctx }): boolean {
|
||||
let cond = ctx.getValue(node.getAttribute("t-elif")!);
|
||||
ctx.addLine(`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : cond.id}) {`);
|
||||
ctx.addLine(
|
||||
`else if (${typeof cond === "string" ? ctx.formatExpression(cond) : `scope.${cond.id}`}) {`
|
||||
);
|
||||
ctx.indent();
|
||||
return false;
|
||||
},
|
||||
@@ -182,6 +182,9 @@ QWeb.addDirective({
|
||||
name: "call",
|
||||
priority: 50,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
// Step 1: sanity checks
|
||||
// ------------------------------------------------
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
if (node.nodeName !== "t") {
|
||||
throw new Error("Invalid tag for t-call directive (should be 't')");
|
||||
}
|
||||
@@ -190,77 +193,63 @@ QWeb.addDirective({
|
||||
if (!nodeTemplate) {
|
||||
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
|
||||
}
|
||||
const nodeCopy = node.cloneNode(true) as Element;
|
||||
nodeCopy.removeAttribute("t-call");
|
||||
|
||||
// extract variables from nodecopy
|
||||
const tempCtx = new CompilationContext();
|
||||
tempCtx.allowMultipleRoots = true;
|
||||
qweb._compileNode(nodeCopy, tempCtx);
|
||||
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
|
||||
|
||||
const templateMap = Object.create(ctx.templates);
|
||||
// open new scope, if necessary
|
||||
const hasNewVariables = Object.keys(tempCtx.variables).length > 0;
|
||||
|
||||
// compile sub template
|
||||
let subCtx = ctx.subContext("caller", nodeCopy).subContext("variables", Object.create(vars));
|
||||
subCtx = subCtx.subContext("templates", templateMap);
|
||||
|
||||
if (templateMap[subTemplate]) {
|
||||
// OUCH, IT IS A RECURSIVE TEMPLATE SITUATION...
|
||||
// This is a tricky situation... We obviously cannot inline the compiled
|
||||
// template. So, what we need to do is to compile it, and make sure we
|
||||
// properly transfer everything from the current scope to the sub template.
|
||||
ctx.rootContext.shouldTrackScope = true;
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
let subTemplateName;
|
||||
if (ctx.hasParentWidget) {
|
||||
subTemplateName = ctx.templateName;
|
||||
} else {
|
||||
subTemplateName = `__${ctx.generateID()}`;
|
||||
subCtx.variables = {};
|
||||
let id = 0;
|
||||
for (let v in vars) {
|
||||
subCtx.variables[v] = vars[v];
|
||||
(vars[v] as any).id = `_v${id++}`;
|
||||
}
|
||||
const subTemplateFn = qweb._compile(subTemplateName, nodeTemplate.elem, subCtx);
|
||||
qweb.recursiveFns[subTemplateName] = subTemplateFn;
|
||||
}
|
||||
let varCode = `{}`;
|
||||
if (Object.keys(vars).length) {
|
||||
let id = 0;
|
||||
const content = Object.values(vars)
|
||||
.map((v: any) => `_v${id++}: ${v.expr}`)
|
||||
.join(",");
|
||||
varCode = `{${content}}`;
|
||||
}
|
||||
ctx.addLine(
|
||||
`this.recursiveFns['${subTemplateName}'].call(this, context, Object.assign({}, extra, {parentNode: c${ctx.parentNode}, vars: ${varCode}, fiber: {scope}}));`
|
||||
);
|
||||
return true;
|
||||
// Step 2: compile target template in sub templates
|
||||
// ------------------------------------------------
|
||||
if (!qweb.subTemplates[subTemplate]) {
|
||||
qweb.subTemplates[subTemplate] = true;
|
||||
const subTemplateFn = qweb._compile(subTemplate, nodeTemplate.elem, ctx);
|
||||
qweb.subTemplates[subTemplate] = subTemplateFn;
|
||||
}
|
||||
templateMap[subTemplate] = true;
|
||||
|
||||
if (hasNewVariables) {
|
||||
ctx.addLine("{");
|
||||
// Step 3: compile t-call body if necessary
|
||||
// ------------------------------------------------
|
||||
let hasBody = node.hasChildNodes();
|
||||
if (hasBody) {
|
||||
// we add a sub scope to protect the ambient scope
|
||||
ctx.addLine(`{`);
|
||||
ctx.indent();
|
||||
// add new variables, if any
|
||||
for (let key in tempCtx.variables) {
|
||||
const v = tempCtx.variables[key];
|
||||
if (v.expr) {
|
||||
ctx.addLine(`let ${v.id} = ${v.expr};`);
|
||||
}
|
||||
// todo: handle XML variables...
|
||||
}
|
||||
}
|
||||
qweb._compileNode(nodeTemplate.elem, subCtx);
|
||||
|
||||
// close new scope
|
||||
if (hasNewVariables) {
|
||||
ctx.addLine(`let origScope = scope;`);
|
||||
ctx.addLine(`scope = Object.assign(Object.create(context), scope);`);
|
||||
const nodeCopy = node.cloneNode(true) as Element;
|
||||
nodeCopy.removeAttribute("t-call");
|
||||
const parentNode = ctx.parentNode;
|
||||
ctx.parentNode = "__0";
|
||||
// this local scope is intended to trap c__0
|
||||
ctx.addLine(`{`);
|
||||
ctx.indent();
|
||||
ctx.addLine("let c__0 = [];");
|
||||
qweb._compileNode(nodeCopy, ctx);
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
ctx.addLine("scope[utils.zero] = c__0;");
|
||||
ctx.parentNode = parentNode;
|
||||
ctx.dedent();
|
||||
ctx.addLine("}");
|
||||
ctx.addLine(`}`);
|
||||
}
|
||||
|
||||
// Step 4: add the appropriate function call to current component
|
||||
// ------------------------------------------------
|
||||
const callingScope = hasBody ? 'scope' : 'Object.assign(Object.create(context), scope)';
|
||||
if (ctx.parentNode) {
|
||||
ctx.addLine(
|
||||
`this.subTemplates['${subTemplate}'].call(this, ${callingScope}, Object.assign({}, extra, {parentNode: c${ctx.parentNode}}));`
|
||||
);
|
||||
} else {
|
||||
// this is a t-call with no parentnode, we need to extract the result
|
||||
ctx.rootContext.shouldDefineResult = true;
|
||||
ctx.addLine(`result = []`);
|
||||
ctx.addLine(
|
||||
`this.subTemplates['${subTemplate}'].call(this, ${callingScope}, Object.assign({}, extra, {parentNode: result}));`
|
||||
);
|
||||
ctx.addLine(`result = result[0]`);
|
||||
}
|
||||
|
||||
// Step 5: restore previous scope
|
||||
// ------------------------------------------------
|
||||
if (hasBody) {
|
||||
ctx.addLine(`scope = origScope;`);
|
||||
ctx.dedent();
|
||||
ctx.addLine(`}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -275,7 +264,7 @@ QWeb.addDirective({
|
||||
extraNames: ["as"],
|
||||
priority: 10,
|
||||
atNodeEncounter({ node, qweb, ctx }): boolean {
|
||||
ctx.rootContext.shouldProtectContext = true;
|
||||
ctx.rootContext.shouldDefineScope = true;
|
||||
ctx = ctx.subContext("loopNumber", ctx.loopNumber + 1);
|
||||
const elems = node.getAttribute("t-foreach")!;
|
||||
const name = node.getAttribute("t-as")!;
|
||||
@@ -290,14 +279,18 @@ QWeb.addDirective({
|
||||
ctx.addLine(`_${valuesID} = Object.values(_${arrayID});`);
|
||||
ctx.closeIf();
|
||||
ctx.addLine(`var _length${keysID} = _${keysID}.length;`);
|
||||
let varsID = ctx.generateID();
|
||||
ctx.addLine(`let _scope${varsID} = scope;`);
|
||||
ctx.addLine(`scope = Object.assign(Object.create(context), _scope${varsID});`);
|
||||
const loopVar = `i${ctx.loopNumber}`;
|
||||
ctx.addLine(`for (let ${loopVar} = 0; ${loopVar} < _length${keysID}; ${loopVar}++) {`);
|
||||
ctx.indent();
|
||||
ctx.addToScope(name + "_first", `${loopVar} === 0`);
|
||||
ctx.addToScope(name + "_last", `${loopVar} === _length${keysID} - 1`);
|
||||
ctx.addToScope(name + "_index", loopVar);
|
||||
ctx.addToScope(name, `_${keysID}[${loopVar}]`);
|
||||
ctx.addToScope(name + "_value", `_${valuesID}[${loopVar}]`);
|
||||
|
||||
ctx.addLine(`scope.${name}_first = ${loopVar} === 0`);
|
||||
ctx.addLine(`scope.${name}_last = ${loopVar} === _length${keysID} - 1`);
|
||||
ctx.addLine(`scope.${name}_index = ${loopVar}`);
|
||||
ctx.addLine(`scope.${name} = _${keysID}[${loopVar}]`);
|
||||
ctx.addLine(`scope.${name}_value = _${valuesID}[${loopVar}]`);
|
||||
const nodeCopy = <Element>node.cloneNode(true);
|
||||
let shouldWarn =
|
||||
!nodeCopy.hasAttribute("t-key") &&
|
||||
@@ -314,6 +307,7 @@ QWeb.addDirective({
|
||||
qweb._compileNode(nodeCopy, ctx);
|
||||
ctx.dedent();
|
||||
ctx.addLine("}");
|
||||
ctx.addLine(`scope = _scope${varsID};`);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -10,35 +10,27 @@ export class CompilationContext {
|
||||
code: string[] = [];
|
||||
variables: { [key: string]: QWebVar } = {};
|
||||
escaping: boolean = false;
|
||||
parentNode: number | null = null;
|
||||
parentNode: number | null | string = null;
|
||||
parentTextNode: number | null = null;
|
||||
rootNode: number | null = null;
|
||||
indentLevel: number = 0;
|
||||
rootContext: CompilationContext;
|
||||
caller: Element | undefined;
|
||||
shouldDefineOwner: boolean = false;
|
||||
shouldDefineParent: boolean = false;
|
||||
shouldDefineScope: boolean = false;
|
||||
shouldDefineQWeb: boolean = false;
|
||||
shouldDefineUtils: boolean = false;
|
||||
shouldDefineRefs: boolean = false;
|
||||
shouldDefineResult: boolean = true;
|
||||
shouldProtectContext: boolean = false;
|
||||
shouldTrackScope: boolean = false;
|
||||
loopNumber: number = 0;
|
||||
inPreTag: boolean = false;
|
||||
templateName: string;
|
||||
allowMultipleRoots: boolean = false;
|
||||
hasParentWidget: boolean = false;
|
||||
scopeVars: any[] = [];
|
||||
currentKey: string = "";
|
||||
templates: { [key: string]: boolean } = {};
|
||||
callingLevel: number = 0;
|
||||
inliningLevel: number = 0;
|
||||
|
||||
constructor(name?: string) {
|
||||
this.rootContext = this;
|
||||
this.templateName = name || "noname";
|
||||
this.templates[this.templateName] = true;
|
||||
this.addLine("var h = this.h;");
|
||||
}
|
||||
|
||||
@@ -71,30 +63,16 @@ export class CompilationContext {
|
||||
}
|
||||
|
||||
generateCode(): string[] {
|
||||
const shouldTrackScope = this.shouldTrackScope && this.scopeVars.length;
|
||||
if (shouldTrackScope) {
|
||||
// add some vars to scope if needed
|
||||
for (let scopeVar of this.scopeVars.reverse()) {
|
||||
let { index, key, indent } = scopeVar;
|
||||
const prefix = new Array(indent + 2).join(" ");
|
||||
this.code.splice(index + 1, 0, prefix + `scope.${key} = context.${key};`);
|
||||
}
|
||||
this.code.unshift(" const scope = Object.create(null);");
|
||||
}
|
||||
if (this.shouldProtectContext) {
|
||||
this.code.unshift(" context = Object.create(context);");
|
||||
}
|
||||
if (this.shouldDefineResult) {
|
||||
this.code.unshift(" let result;");
|
||||
}
|
||||
|
||||
if (this.shouldDefineScope) {
|
||||
this.code.unshift(" let scope = Object.create(context);");
|
||||
}
|
||||
if (this.shouldDefineRefs) {
|
||||
this.code.unshift(" context.__owl__.refs = context.__owl__.refs || {};");
|
||||
}
|
||||
if (this.shouldDefineOwner) {
|
||||
// this is necessary to prevent some directives (t-forach for ex) to
|
||||
// pollute the rendering context by adding some keys in it.
|
||||
this.code.unshift(" let owner = context;");
|
||||
}
|
||||
if (this.shouldDefineParent) {
|
||||
if (this.hasParentWidget) {
|
||||
this.code.unshift(" let parent = extra.parent;");
|
||||
@@ -131,10 +109,6 @@ export class CompilationContext {
|
||||
subContext(key: keyof CompilationContext, value: any): CompilationContext {
|
||||
const newContext = Object.create(this);
|
||||
newContext[key] = value;
|
||||
if (key === "caller") {
|
||||
newContext.callingLevel++;
|
||||
newContext.inliningLevel++;
|
||||
}
|
||||
return newContext;
|
||||
}
|
||||
|
||||
@@ -152,11 +126,6 @@ export class CompilationContext {
|
||||
return this.code.length - 1;
|
||||
}
|
||||
|
||||
addToScope(key: string, expr: string) {
|
||||
const index = this.addLine(`context.${key} = ${expr};`);
|
||||
this.rootContext.scopeVars.push({ index, key, indent: this.indentLevel });
|
||||
}
|
||||
|
||||
addIf(condition: string) {
|
||||
this.addLine(`if (${condition}) {`);
|
||||
this.indent();
|
||||
@@ -172,27 +141,6 @@ export class CompilationContext {
|
||||
this.dedent();
|
||||
this.addLine("}");
|
||||
}
|
||||
/**
|
||||
* Recursively (inverse) fetches the `caller` of a context
|
||||
* Useful to determine to which t-call a t-raw="0" refers
|
||||
*/
|
||||
getCaller(targetLevel?: number): Element | null {
|
||||
if (targetLevel === undefined) {
|
||||
targetLevel = this.inliningLevel;
|
||||
}
|
||||
if (targetLevel === this.callingLevel) {
|
||||
return this.caller || null;
|
||||
}
|
||||
const proto = (this as any).__proto__;
|
||||
return proto ? proto.getCaller(targetLevel) : null;
|
||||
}
|
||||
/**
|
||||
* Marks the context with the current recursive level
|
||||
* in which we are for inlining archs (t-raw="0")
|
||||
*/
|
||||
getInliningContext(): CompilationContext {
|
||||
return this.subContext("inliningLevel", this.inliningLevel - 1);
|
||||
}
|
||||
|
||||
getValue(val: any): QWebVar | string {
|
||||
return val in this.variables ? this.getValue(this.variables[val]) : val;
|
||||
@@ -205,6 +153,7 @@ export class CompilationContext {
|
||||
* - replace already defined variables by their internal name
|
||||
*/
|
||||
formatExpression(expr: string): string {
|
||||
this.rootContext.shouldDefineScope = true;
|
||||
return compileExpr(expr, this.variables);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,9 +39,9 @@ const WORD_REPLACEMENT = {
|
||||
};
|
||||
|
||||
export interface QWebVar {
|
||||
id?: string;
|
||||
expr?: string;
|
||||
xml?: NodeList;
|
||||
id: string; // foo
|
||||
expr: string; // scope.foo (local variables => only foo)
|
||||
value?: string; // 1 + 3
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -233,8 +233,8 @@ export function tokenize(expr: string): Token[] {
|
||||
* the arrow operator, then we add the current (or some previous tokens) token to
|
||||
* the list of variables so it does not get replaced by a lookup in the context
|
||||
*/
|
||||
export function compileExpr(expr: string, vars: { [key: string]: QWebVar }): string {
|
||||
vars = Object.create(vars);
|
||||
export function compileExpr(expr: string, scope: { [key: string]: QWebVar }): string {
|
||||
scope = Object.create(scope);
|
||||
const tokens = tokenize(expr);
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
let token = tokens[i];
|
||||
@@ -258,21 +258,21 @@ export function compileExpr(expr: string, vars: { [key: string]: QWebVar }): str
|
||||
while (j > 0 && tokens[j].type !== "LEFT_PAREN") {
|
||||
if (tokens[j].type === "SYMBOL" && tokens[j].originalValue) {
|
||||
tokens[j].value = tokens[j].originalValue!;
|
||||
vars[tokens[j].value] = { id: tokens[j].value };
|
||||
scope[tokens[j].value] = { id: tokens[j].value, expr: tokens[j].value };
|
||||
}
|
||||
j--;
|
||||
}
|
||||
} else {
|
||||
vars[token.value] = { id: token.value };
|
||||
scope[token.value] = { id: token.value, expr: token.value };
|
||||
}
|
||||
}
|
||||
|
||||
if (isVar) {
|
||||
if (token.value in vars && "id" in vars[token.value]) {
|
||||
token.value = vars[token.value].id!;
|
||||
if (token.value in scope && "id" in scope[token.value]) {
|
||||
token.value = scope[token.value].expr!;
|
||||
} else {
|
||||
token.originalValue = token.value;
|
||||
token.value = `context['${token.value}']`;
|
||||
token.value = `scope['${token.value}']`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ QWeb.addDirective({
|
||||
name: "on",
|
||||
priority: 90,
|
||||
atNodeCreation({ ctx, fullName, value, nodeID }) {
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
const [eventName, ...mods] = fullName.slice(5).split(".");
|
||||
if (!eventName) {
|
||||
throw new Error("Missing event name with t-on directive");
|
||||
@@ -40,7 +39,7 @@ QWeb.addDirective({
|
||||
extraArgs = args.slice(1, -1);
|
||||
return "";
|
||||
});
|
||||
let params = extraArgs ? `owner, ${ctx.formatExpression(extraArgs)}` : "owner";
|
||||
let params = extraArgs ? `context, ${ctx.formatExpression(extraArgs)}` : "context";
|
||||
let handler = `function (e) {if (!context.__owl__.isMounted){return}`;
|
||||
handler += mods
|
||||
.map(function(mod) {
|
||||
@@ -197,7 +196,6 @@ QWeb.addDirective({
|
||||
priority: 80,
|
||||
atNodeEncounter({ ctx, value }): boolean {
|
||||
const slotKey = ctx.generateID();
|
||||
ctx.rootContext.shouldDefineOwner = true;
|
||||
ctx.addLine(
|
||||
`const slot${slotKey} = this.constructor.slots[context.__owl__.slotId + '_' + '${value}'];`
|
||||
);
|
||||
@@ -210,11 +208,8 @@ QWeb.addDirective({
|
||||
ctx.addLine(`let ${parentNode}= []`);
|
||||
ctx.addLine(`result = {}`);
|
||||
}
|
||||
// if we are in a slot of a component, we need to get the vars from the
|
||||
// parent fiber instead.
|
||||
const vars = ctx.allowMultipleRoots ? "extra.fiber.parent.vars" : "extra.fiber.vars";
|
||||
ctx.addLine(
|
||||
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: ${parentNode}, parent: extra.parent || owner, vars: ${vars}}));`
|
||||
`slot${slotKey}.call(this, context.__owl__.scope, Object.assign({}, extra, {parentNode: ${parentNode}, parent: extra.parent || context}));`
|
||||
);
|
||||
if (!ctx.parentNode) {
|
||||
ctx.addLine(`utils.defineProxy(result, ${parentNode}[0]);`);
|
||||
|
||||
+3
-13
@@ -87,6 +87,7 @@ interface Utils {
|
||||
}
|
||||
|
||||
const UTILS: Utils = {
|
||||
zero: Symbol('zero'),
|
||||
toObj(expr) {
|
||||
if (typeof expr === "string") {
|
||||
expr = expr.trim();
|
||||
@@ -171,7 +172,7 @@ export class QWeb extends EventBus {
|
||||
// recursiveTemplates contains sub templates called with t-call, but which
|
||||
// ends up in recursive situations. This is very similar to the slot situation,
|
||||
// as in we need to propagate the scope.
|
||||
recursiveFns = {};
|
||||
subTemplates = {};
|
||||
|
||||
isUpdating: boolean = false;
|
||||
translateFn?: QWebConfig["translateFn"];
|
||||
@@ -360,23 +361,12 @@ export class QWeb extends EventBus {
|
||||
ctx.shouldDefineResult = false;
|
||||
}
|
||||
if (parentContext) {
|
||||
ctx.templates = Object.create(parentContext.templates);
|
||||
ctx.variables = Object.create(parentContext.variables);
|
||||
ctx.parentNode = parentContext.parentNode || ctx.generateID();
|
||||
ctx.allowMultipleRoots = true;
|
||||
ctx.hasParentWidget = true;
|
||||
ctx.shouldDefineResult = false;
|
||||
ctx.addLine(`let c${ctx.parentNode} = extra.parentNode;`);
|
||||
|
||||
for (let v in parentContext.variables) {
|
||||
let variable = <any>parentContext.variables[v];
|
||||
if (variable.id) {
|
||||
ctx.addLine(`let ${variable.id} = extra.vars.${variable.id};`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (parentContext) {
|
||||
ctx.addLine("Object.assign(context, extra.fiber.scope);");
|
||||
}
|
||||
this._compileNode(elem, ctx);
|
||||
|
||||
@@ -673,7 +663,7 @@ export class QWeb extends EventBus {
|
||||
if (name.startsWith("t-att-")) {
|
||||
let attName = name.slice(6);
|
||||
const v = ctx.getValue(value);
|
||||
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : v.id;
|
||||
let formattedValue = typeof v === "string" ? ctx.formatExpression(v) : `scope.${v.id}`;
|
||||
|
||||
if (attName === "class") {
|
||||
ctx.rootContext.shouldDefineUtils = true;
|
||||
|
||||
Reference in New Issue
Block a user