[FIX] qweb: properly handle t-raw in various situations

closes #325
closes #327
This commit is contained in:
Géry Debongnie
2019-10-12 09:07:25 +02:00
parent 41b0618c93
commit 3e8f60cefa
11 changed files with 153 additions and 69 deletions
+5
View File
@@ -285,6 +285,11 @@ rendered with the value `value` set to `<span>foo</span>` in the rendering conte
<p><span>foo</span></p>
```
Note that since the content of the expression is not known beforehand, the `t-raw`
directive has to parse the html (and convert it to a virtual dom structure) for
each rendering. So, it will be much slower than a regular template. It is
therefore advised to limit the use of `t-raw` whenever possible.
### Setting Variables
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
+4 -8
View File
@@ -1,6 +1,7 @@
import { Context } from "./context";
import { QWebExprVar } from "./expression_parser";
import { QWeb } from "./qweb";
import { htmlToVDOM } from "../vdom/html_to_vdom";
/**
* Owl QWeb Directives
@@ -25,6 +26,8 @@ QWeb.utils.getFragment = function(str: string): DocumentFragment {
return temp.content;
};
QWeb.utils.htmlToVDOM = htmlToVDOM;
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
if (value === "0" && ctx.caller) {
qweb._compileNode(ctx.caller, ctx);
@@ -60,15 +63,8 @@ function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
}
}
} else {
let fragID = ctx.generateID();
ctx.rootContext.shouldDefineUtils = true;
ctx.addLine(`var frag${fragID} = utils.getFragment(${exprID})`);
let tempNodeID = ctx.generateID();
ctx.addLine(`var p${tempNodeID} = {hook: {`);
ctx.addLine(` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`);
ctx.addLine(`}};`);
ctx.addLine(`var vn${tempNodeID} = h('div', p${tempNodeID})`);
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
ctx.addLine(`c${ctx.parentNode}.push(...utils.htmlToVDOM(${exprID}));`);
}
if (node.childNodes.length) {
ctx.addElse();
+1 -3
View File
@@ -207,9 +207,7 @@ QWeb.addDirective({
);
ctx.addIf(`slot${slotKey}`);
ctx.addLine(
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c${
ctx.parentNode
}, vars: extra.vars, parent: owner}));`
`slot${slotKey}.call(this, context.__owl__.parent, Object.assign({}, extra, {parentNode: c${ctx.parentNode}, vars: extra.vars, parent: owner}));`
);
ctx.closeIf();
return true;
+2 -2
View File
@@ -458,8 +458,8 @@ export class QWeb extends EventBus {
if (!(dName in QWeb.DIRECTIVE_NAMES)) {
throw new Error(`Unknown QWeb directive: '${attrName}'`);
}
if (node.tagName !== 't' && (attrName === 't-esc' || attrName === 't-raw')) {
const tNode = document.createElement('t');
if (node.tagName !== "t" && (attrName === "t-esc" || attrName === "t-raw")) {
const tNode = document.createElement("t");
tNode.setAttribute(attrName, node.getAttribute(attrName)!);
for (let child of Array.from(node.childNodes)) {
tNode.appendChild(child);
+29
View File
@@ -0,0 +1,29 @@
import { VNode, h } from "./vdom";
const parser = new DOMParser();
export function htmlToVDOM(html: string): VNode[] {
const doc = parser.parseFromString(html, "text/html");
const result: VNode[] = [];
for (let child of doc.body.childNodes) {
result.push(htmlToVNode(child));
}
return result;
}
function htmlToVNode(node: ChildNode): VNode {
if (!(node instanceof Element)) {
return { text: node.textContent! } as VNode;
}
const attrs = {};
for (let attr of node.attributes) {
attrs[attr.name] = attr.textContent;
}
const children: VNode[] = [];
if (node.hasChildNodes) {
for (let c of node.childNodes) {
children.push(htmlToVNode(c));
}
}
return h((node as Element).tagName, { attrs }, children);
}
+2 -2
View File
@@ -96,10 +96,10 @@ describe("Context", () => {
const parent = new Parent(env);
await parent.mount(fixture);
expect(fixture.innerHTML).toBe("<div><span>12</span></div>");
expect(steps).toEqual(['child']);
expect(steps).toEqual(["child"]);
testContext.state.a = 3;
await nextTick();
expect(steps).toEqual(['child', 'child']);
expect(steps).toEqual(["child", "child"]);
});
test("parent and children subscribed to same context", async () => {
+36
View File
@@ -4293,3 +4293,39 @@ describe("support svg components", () => {
);
});
});
describe("t-raw in components", () => {
test("update properly on state changes", async () => {
class TestW extends Widget {
static template = xml`<div><t t-raw="state.value"/></div>`;
state = useState({ value: "<b>content</b>" });
}
const widget = new TestW(env);
await widget.mount(fixture);
expect(fixture.innerHTML).toBe("<div><b>content</b></div>");
widget.state.value = "<span>other content</span>";
await nextTick();
expect(fixture.innerHTML).toBe("<div><span>other content</span></div>");
});
test("can render list of t-raw ", async () => {
class TestW extends Widget {
static template = xml`
<div>
<t t-foreach="state.items" t-as="item">
<t t-esc="item"/>
<t t-raw="item"/>
</t>
</div>`;
state = useState({ items: ["<b>one</b>", "<b>two</b>", "<b>tree</b>"] });
}
const widget = new TestW(env);
await widget.mount(fixture);
expect(fixture.innerHTML).toBe(
"<div>&lt;b&gt;one&lt;/b&gt;<b>one</b>&lt;b&gt;two&lt;/b&gt;<b>two</b>&lt;b&gt;tree&lt;/b&gt;<b>tree</b></div>"
);
});
});
+2 -4
View File
@@ -440,7 +440,7 @@ describe("hooks", () => {
steps.push("onWillStart");
});
onWillUpdateProps(nextProps => {
expect(nextProps).toEqual({value: 2});
expect(nextProps).toEqual({ value: 2 });
steps.push("onWillUpdateProps");
});
}
@@ -454,7 +454,7 @@ describe("hooks", () => {
class App extends Component<any, any> {
static template = xml`<div><MyComponent value="state.value"/></div>`;
static components = { MyComponent };
state = useState({ value: 1});
state = useState({ value: 1 });
}
const app = new App(env);
@@ -469,6 +469,4 @@ describe("hooks", () => {
expect(fixture.innerHTML).toBe("<div><span>2</span></div>");
expect(steps).toEqual(["onWillStart", "onWillUpdateProps"]);
});
});
+6 -36
View File
@@ -630,12 +630,7 @@ exports[`misc global 1`] = `
c1.push(vn21);
var _22 = context['toto'];
if (_22 || _22 === 0) {
var frag23 = utils.getFragment(_22)
var p24 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag23, n.elm),
}};
var vn24 = h('div', p24)
c21.push(vn24);
c21.push(...utils.htmlToVDOM(_22));
} else {
c21.push({text: \`toto default\`});
}
@@ -1670,12 +1665,7 @@ exports[`t-on t-on combined with t-raw 1`] = `
p2.on['click'] = extra.handlers['click' + 2];
var _3 = context['html'];
if (_3 || _3 === 0) {
var frag4 = utils.getFragment(_3)
var p5 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag4, n.elm),
}};
var vn5 = h('div', p5)
c2.push(vn5);
c2.push(...utils.htmlToVDOM(_3));
}
return vn1;
}"
@@ -1851,12 +1841,7 @@ exports[`t-raw literal 1`] = `
var vn1 = h('span', p1, c1);
var _2 = 'ok';
if (_2 || _2 === 0) {
var frag3 = utils.getFragment(_2)
var p4 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag3, n.elm),
}};
var vn4 = h('div', p4)
c1.push(vn4);
c1.push(...utils.htmlToVDOM(_2));
}
return vn1;
}"
@@ -1871,12 +1856,7 @@ exports[`t-raw not escaping 1`] = `
var vn1 = h('div', p1, c1);
var _2 = context['var'];
if (_2 || _2 === 0) {
var frag3 = utils.getFragment(_2)
var p4 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag3, n.elm),
}};
var vn4 = h('div', p4)
c1.push(vn4);
c1.push(...utils.htmlToVDOM(_2));
}
return vn1;
}"
@@ -1895,12 +1875,7 @@ exports[`t-raw t-raw and another sibling node 1`] = `
c2.push({text: \`hello\`});
var _3 = context['var'];
if (_3 || _3 === 0) {
var frag4 = utils.getFragment(_3)
var p5 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag4, n.elm),
}};
var vn5 = h('div', p5)
c1.push(vn5);
c1.push(...utils.htmlToVDOM(_3));
}
return vn1;
}"
@@ -1915,12 +1890,7 @@ exports[`t-raw variable 1`] = `
var vn1 = h('span', p1, c1);
var _2 = context['var'];
if (_2 || _2 === 0) {
var frag3 = utils.getFragment(_2)
var p4 = {hook: {
insert: n => n.elm.parentNode.replaceChild(frag3, n.elm),
}};
var vn4 = h('div', p4)
c1.push(vn4);
c1.push(...utils.htmlToVDOM(_2));
}
return vn1;
}"
+16 -14
View File
@@ -1099,18 +1099,20 @@ describe("t-on", () => {
</t>
</div>`
);
const steps:string[] = [];
const steps: string[] = [];
const owner = {
projects: [{id: 1, name: 'Project 1'}, {id: 2, name: 'Project 2'}],
projects: [{ id: 1, name: "Project 1" }, { id: 2, name: "Project 2" }],
onEdit(projectId, ev) {
expect(ev.defaultPrevented).toBe(true);
steps.push(projectId);
},
}
};
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
expect(node.outerHTML).toBe(`<div><a href="#"> Edit Project 1</a><a href="#"> Edit Project 2</a></div>`);
expect(node.outerHTML).toBe(
`<div><a href="#"> Edit Project 1</a><a href="#"> Edit Project 2</a></div>`
);
const links = node.querySelectorAll("a")!;
links[0].click();
@@ -1122,12 +1124,12 @@ describe("t-on", () => {
test("t-on combined with t-esc", async () => {
expect.assertions(3);
qweb.addTemplate("test", `<div><button t-on-click="onClick" t-esc="text"/></div>`);
const steps:string[] = [];
const steps: string[] = [];
const owner = {
text: 'Click here',
text: "Click here",
onClick() {
steps.push('onClick');
},
steps.push("onClick");
}
};
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
@@ -1135,18 +1137,18 @@ describe("t-on", () => {
node.querySelector("button")!.click();
expect(steps).toEqual(['onClick']);
expect(steps).toEqual(["onClick"]);
});
test("t-on combined with t-raw", async () => {
expect.assertions(3);
qweb.addTemplate("test", `<div><button t-on-click="onClick" t-raw="html"/></div>`);
const steps:string[] = [];
const steps: string[] = [];
const owner = {
html: 'Click <b>here</b>',
html: "Click <b>here</b>",
onClick() {
steps.push('onClick');
},
steps.push("onClick");
}
};
const node = <HTMLElement>renderToDOM(qweb, "test", owner, { handlers: [] });
@@ -1154,7 +1156,7 @@ describe("t-on", () => {
node.querySelector("button")!.click();
expect(steps).toEqual(['onClick']);
expect(steps).toEqual(["onClick"]);
});
});
+50
View File
@@ -1,4 +1,5 @@
import { h, patch } from "../src/vdom";
import { htmlToVDOM } from "../src/vdom/html_to_vdom";
import { init, addNS } from "../src/vdom/vdom";
function map(list, fn) {
@@ -1104,3 +1105,52 @@ describe("snabbdom", function() {
});
});
});
//------------------------------------------------------------------------------
// Html to vdom
//------------------------------------------------------------------------------
describe("html to vdom", function() {
let elm, vnode0;
beforeEach(function() {
elm = document.createElement("div");
vnode0 = elm;
});
test("empty strings return empty list", function() {
expect(htmlToVDOM("")).toEqual([]);
});
test("just text", function() {
const nodeList = htmlToVDOM("simple text");
expect(nodeList).toHaveLength(1);
expect(nodeList[0]).toEqual({ text: "simple text" });
});
test("empty tag", function() {
const nodeList = htmlToVDOM("<span></span>");
expect(nodeList).toHaveLength(1);
elm = patch(vnode0, nodeList[0]).elm;
expect(elm.outerHTML).toEqual("<span></span>");
});
test("tag with text", function() {
const nodeList = htmlToVDOM("<span>abc</span>");
expect(nodeList).toHaveLength(1);
elm = patch(vnode0, nodeList[0]).elm;
expect(elm.outerHTML).toEqual("<span>abc</span>");
});
test("tag with attribute", function() {
const nodeList = htmlToVDOM(`<span a="1" b="2">abc</span>`);
expect(nodeList).toHaveLength(1);
elm = patch(vnode0, nodeList[0]).elm;
expect(elm.outerHTML).toEqual(`<span a="1" b="2">abc</span>`);
});
test("misc", function() {
const nodeList = htmlToVDOM(`<span a="1" b="2">abc<div>1</div></span>`);
expect(nodeList).toHaveLength(1);
elm = patch(vnode0, nodeList[0]).elm;
expect(elm.outerHTML).toEqual(`<span a="1" b="2">abc<div>1</div></span>`);
});
});