[IMP] owl: update to v0.15.0

This commit is contained in:
Géry Debongnie
2019-06-17 16:05:21 +02:00
parent 44e2de9709
commit d7430e9f18
3 changed files with 444 additions and 237 deletions
+131 -44
View File
@@ -1125,7 +1125,6 @@
if (data) { if (data) {
this.addTemplates(data); this.addTemplates(data);
} }
this.addTemplate("default", "<div></div>");
} }
static addDirective(directive) { static addDirective(directive) {
DIRECTIVES.push(directive); DIRECTIVES.push(directive);
@@ -1306,7 +1305,7 @@
for (let i = 0; i < attributes.length; i++) { for (let i = 0; i < attributes.length; i++) {
let attrName = attributes[i].name; let attrName = attributes[i].name;
if (attrName.startsWith("t-")) { if (attrName.startsWith("t-")) {
let dName = attrName.slice(2).split("-")[0]; let dName = attrName.slice(2).split(/-|\./)[0];
if (!(dName in DIRECTIVE_NAMES)) { if (!(dName in DIRECTIVE_NAMES)) {
throw new Error(`Unknown QWeb directive: '${attrName}'`); throw new Error(`Unknown QWeb directive: '${attrName}'`);
} }
@@ -1321,11 +1320,12 @@
for (let j = 0; j < ATTR_N; j++) { for (let j = 0; j < ATTR_N; j++) {
const name = attributes[j].name; const name = attributes[j].name;
if (name === "t-" + directive.name || if (name === "t-" + directive.name ||
name.startsWith("t-" + directive.name + "-")) { name.startsWith("t-" + directive.name + "-") ||
name.startsWith("t-" + directive.name + ".")) {
fullName = name; fullName = name;
value = attributes[j].textContent; value = attributes[j].textContent;
validDirectives.push({ directive, value, fullName }); validDirectives.push({ directive, value, fullName });
if (directive.name === "on") { if (directive.name === "on" || directive.name === 'model') {
withHandlers = true; withHandlers = true;
} }
} }
@@ -1817,19 +1817,7 @@
if (shouldPatch && __owl__.isMounted && renderId === __owl__.renderId) { if (shouldPatch && __owl__.isMounted && renderId === __owl__.renderId) {
// we only update the vnode and the actual DOM if no other rendering // we only update the vnode and the actual DOM if no other rendering
// occurred between now and when the render method was initially called. // occurred between now and when the render method was initially called.
const patchLen = patchQueue.length; this._applyPatchQueue(patchQueue);
for (let i = 0; i < patchLen; i++) {
const patch = patchQueue[i];
patch.push(patch[0].willPatch());
}
for (let i = 0; i < patchLen; i++) {
const patch = patchQueue[i];
patch[0]._patch(patch[1]);
}
for (let i = patchLen - 1; i >= 0; i--) {
const patch = patchQueue[i];
patch[0].patched(patch[2]);
}
} }
} }
/** /**
@@ -1997,7 +1985,7 @@
p = p.__proto__; p = p.__proto__;
} }
if (p === Component) { if (p === Component) {
this.template = "default"; throw new Error(`Could not find template for component "${this.constructor.name}"`);
} }
else { else {
tmap[name] = template; tmap[name] = template;
@@ -2085,6 +2073,28 @@
} }
return props; return props;
} }
/**
* Apply the given patch queue. A patch is a pair [c, vn], where c is a
* Component instance and vn a VNode.
* 1) Call 'willPatch' on the component of each patch
* 2) Call '_patch' on the component of each patch
* 3) Call 'patched' on the component of each patch, in inverse order
*/
_applyPatchQueue(patchQueue) {
const patchLen = patchQueue.length;
for (let i = 0; i < patchLen; i++) {
const patch = patchQueue[i];
patch.push(patch[0].willPatch());
}
for (let i = 0; i < patchLen; i++) {
const patch = patchQueue[i];
patch[0]._patch(patch[1]);
}
for (let i = patchLen - 1; i >= 0; i--) {
const patch = patchQueue[i];
patch[0].patched(patch[2]);
}
}
/** /**
* Validate the component props (or next props) against the (static) props * Validate the component props (or next props) against the (static) props
* description. This is potentially an expensive operation: it may needs to * description. This is potentially an expensive operation: it may needs to
@@ -2534,6 +2544,7 @@
* - t-widget/t-keepalive * - t-widget/t-keepalive
* - t-mounted * - t-mounted
* - t-slot * - t-slot
* - t-model
*/ */
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// t-on // t-on
@@ -2718,13 +2729,6 @@
* // t-widget directive: we start by evaluating the expression given by t-key: * // t-widget directive: we start by evaluating the expression given by t-key:
* let key5 = "somestring"; * let key5 = "somestring";
* *
* // We keep the index of the position of the widget in the closure. We push
* // null to reserve the slot, and will replace it later by the widget vnode,
* // when it will be ready (do not forget that preparing/rendering a widget is
* // asynchronous)
* let _2_index = c1.length;
* c1.push(null);
*
* // def3 is the promise that will contain later either the new widget * // def3 is the promise that will contain later either the new widget
* // creation, or the props update... * // creation, or the props update...
* let def3; * let def3;
@@ -2739,6 +2743,13 @@
* ? context.__owl__.children[context.__owl__.cmap[key5]] * ? context.__owl__.children[context.__owl__.cmap[key5]]
* : false; * : false;
* *
* // We keep the index of the position of the widget in the closure. We push
* // null to reserve the slot, and will replace it later by the widget vnode,
* // when it will be ready (do not forget that preparing/rendering a widget is
* // asynchronous)
* let _2_index = c1.length;
* c1.push(null);
*
* // we evaluate here the props given to the component. It is done here to be * // we evaluate here the props given to the component. It is done here to be
* // able to easily reference it later, and also, it might be an expensive * // able to easily reference it later, and also, it might be an expensive
* // computation, so it is certainly better to do it only once * // computation, so it is certainly better to do it only once
@@ -2852,7 +2863,7 @@
*/ */
QWeb.addDirective({ QWeb.addDirective({
name: "widget", name: "widget",
extraNames: ["props", "keepalive"], extraNames: ["props", "keepalive", "asyncroot"],
priority: 100, priority: 100,
atNodeEncounter({ ctx, value, node, qweb }) { atNodeEncounter({ ctx, value, node, qweb }) {
ctx.addLine("//WIDGET"); ctx.addLine("//WIDGET");
@@ -2860,6 +2871,7 @@
ctx.rootContext.shouldDefineQWeb = true; ctx.rootContext.shouldDefineQWeb = true;
ctx.rootContext.shouldDefineUtils = true; ctx.rootContext.shouldDefineUtils = true;
let keepAlive = node.getAttribute("t-keepalive") ? true : false; let keepAlive = node.getAttribute("t-keepalive") ? true : false;
let async = node.getAttribute("t-asyncroot") ? true : false;
// t-on- events and t-transition // t-on- events and t-transition
const events = []; const events = [];
let transition = ""; let transition = "";
@@ -2904,8 +2916,6 @@
// want to evaluate it only once) // want to evaluate it only once)
ctx.addLine(`let key${keyID} = ${key};`); ctx.addLine(`let key${keyID} = ${key};`);
} }
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
ctx.addLine(`c${ctx.parentNode}.push(null);`);
ctx.addLine(`let def${defID};`); ctx.addLine(`let def${defID};`);
let templateID = key let templateID = key
? `key${keyID}` ? `key${keyID}`
@@ -2990,6 +3000,14 @@
createHook = `vnode.data.hook = {create(_, vn){${classCode}${styleCode}${eventsCode}}};`; createHook = `vnode.data.hook = {create(_, vn){${classCode}${styleCode}${eventsCode}}};`;
} }
ctx.addLine(`let w${widgetID} = ${templateID} in context.__owl__.cmap ? context.__owl__.children[context.__owl__.cmap[${templateID}]] : false;`); ctx.addLine(`let w${widgetID} = ${templateID} in context.__owl__.cmap ? context.__owl__.children[context.__owl__.cmap[${templateID}]] : false;`);
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
if (async) {
ctx.addLine(`const patchQueue${widgetID} = [];`);
ctx.addLine(`c${ctx.parentNode}.push(w${widgetID} && w${widgetID}.__owl__.pvnode || null);`);
}
else {
ctx.addLine(`c${ctx.parentNode}.push(null);`);
}
ctx.addLine(`let props${widgetID} = {${propStr}};`); ctx.addLine(`let props${widgetID} = {${propStr}};`);
ctx.addIf(`w${widgetID} && w${widgetID}.__owl__.renderPromise && !w${widgetID}.__owl__.vnode`); ctx.addIf(`w${widgetID} && w${widgetID}.__owl__.renderPromise && !w${widgetID}.__owl__.vnode`);
ctx.addIf(`utils.shallowEqual(props${widgetID}, w${widgetID}.__owl__.renderProps)`); ctx.addIf(`utils.shallowEqual(props${widgetID}, w${widgetID}.__owl__.renderProps)`);
@@ -3008,32 +3026,46 @@
ctx.addLine(`w${widgetID} = new W${widgetID}(owner, props${widgetID});`); ctx.addLine(`w${widgetID} = new W${widgetID}(owner, props${widgetID});`);
ctx.addLine(`context.__owl__.cmap[${templateID}] = w${widgetID}.__owl__.id;`); ctx.addLine(`context.__owl__.cmap[${templateID}] = w${widgetID}.__owl__.id;`);
// SLOTS // SLOTS
const slotNodes = node.querySelectorAll("[t-set]"); if (node.childElementCount) {
if (slotNodes.length) { const clone = node.cloneNode(true);
const slotNodes = clone.querySelectorAll("[t-set]");
const slotId = qweb.nextSlotId++; const slotId = qweb.nextSlotId++;
for (let i = 0, length = slotNodes.length; i < length; i++) {
const slotNode = slotNodes[i];
const key = slotNode.getAttribute("t-set");
slotNode.removeAttribute("t-set");
const slotFn = qweb._compile(`slot_${key}_template`, slotNode);
qweb.slots[`${slotId}_${key}`] = slotFn.bind(qweb);
}
ctx.addLine(`w${widgetID}.__owl__.slotId = ${slotId};`); ctx.addLine(`w${widgetID}.__owl__.slotId = ${slotId};`);
if (slotNodes.length) {
for (let i = 0, length = slotNodes.length; i < length; i++) {
const slotNode = slotNodes[i];
slotNode.parentElement.removeChild(slotNode);
const key = slotNode.getAttribute("t-set");
slotNode.removeAttribute("t-set");
const slotFn = qweb._compile(`slot_${key}_template`, slotNode);
qweb.slots[`${slotId}_${key}`] = slotFn.bind(qweb);
}
}
if (clone.childElementCount) {
const content = clone.children[0];
const slotFn = qweb._compile(`slot_default_template`, content);
qweb.slots[`${slotId}_default`] = slotFn.bind(qweb);
}
} }
ctx.addLine(`def${defID} = w${widgetID}._prepare();`); ctx.addLine(`def${defID} = w${widgetID}._prepare();`);
// hack: specify empty remove hook to prevent the node from being removed from the DOM // hack: specify empty remove hook to prevent the node from being removed from the DOM
// FIXME: click to re-add widget during remove transition -> leak
ctx.addLine(`def${defID} = def${defID}.then(vnode=>{${createHook}let pvnode=h(vnode.sel, {key: ${templateID}, hook: {insert(vn) {let nvn=w${widgetID}._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeWidgetCode}}}});c${ctx.parentNode}[_${dummyID}_index]=pvnode;w${widgetID}.__owl__.pvnode = pvnode;});`); ctx.addLine(`def${defID} = def${defID}.then(vnode=>{${createHook}let pvnode=h(vnode.sel, {key: ${templateID}, hook: {insert(vn) {let nvn=w${widgetID}._mount(vnode, pvnode.elm);pvnode.elm=nvn.elm;${refExpr}${transitionsInsertCode}},remove() {},destroy(vn) {${finalizeWidgetCode}}}});c${ctx.parentNode}[_${dummyID}_index]=pvnode;w${widgetID}.__owl__.pvnode = pvnode;});`);
ctx.addElse(); ctx.addElse();
// need to update widget // need to update widget
ctx.addLine(`def${defID} = def${defID} || w${widgetID}._updateProps(props${widgetID}, extra.forceUpdate, extra.patchQueue);`); const patchQueueCode = async ? `patchQueue${widgetID}` : "extra.patchQueue";
ctx.addLine(`def${defID} = def${defID} || w${widgetID}._updateProps(props${widgetID}, extra.forceUpdate, ${patchQueueCode});`);
let keepAliveCode = ""; let keepAliveCode = "";
if (keepAlive) { if (keepAlive) {
keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${widgetID}.el,vn.elm);vn.elm=w${widgetID}.el;w${widgetID}._remount();};`; keepAliveCode = `pvnode.data.hook.insert = vn => {vn.elm.parentNode.replaceChild(w${widgetID}.el,vn.elm);vn.elm=w${widgetID}.el;w${widgetID}._remount();};`;
} }
ctx.addLine(`def${defID} = def${defID}.then(()=>{if (w${widgetID}.__owl__.isDestroyed) {return};${tattStyle ? `w${widgetID}.el.style=${tattStyle};` : ""}${updateClassCode}let pvnode=w${widgetID}.__owl__.pvnode;${keepAliveCode}c${ctx.parentNode}[_${dummyID}_index]=pvnode;});`); ctx.addLine(`def${defID} = def${defID}.then(()=>{if (w${widgetID}.__owl__.isDestroyed) {return};${tattStyle ? `w${widgetID}.el.style=${tattStyle};` : ""}${updateClassCode}let pvnode=w${widgetID}.__owl__.pvnode;${keepAliveCode}c${ctx.parentNode}[_${dummyID}_index]=pvnode;});`);
ctx.closeIf(); ctx.closeIf();
ctx.addLine(`extra.promises.push(def${defID});`); if (async) {
ctx.addLine(`def${defID}.then(w${widgetID}._applyPatchQueue.bind(w${widgetID}, patchQueue${widgetID}));`);
}
else {
ctx.addLine(`extra.promises.push(def${defID});`);
}
if (node.hasAttribute("t-if") || if (node.hasAttribute("t-if") ||
node.hasAttribute("t-else") || node.hasAttribute("t-else") ||
node.hasAttribute("t-elif")) { node.hasAttribute("t-elif")) {
@@ -3082,6 +3114,49 @@
return true; return true;
} }
}); });
//------------------------------------------------------------------------------
// t-model
//------------------------------------------------------------------------------
UTILS.toNumber = function (val) {
const n = parseFloat(val);
return isNaN(n) ? val : n;
};
QWeb.addDirective({
name: "model",
priority: 42,
atNodeCreation({ ctx, nodeID, value, node, fullName }) {
const type = node.getAttribute("type");
let handler;
let event = fullName.includes(".lazy") ? "change" : "input";
if (node.tagName === "select") {
ctx.addLine(`p${nodeID}.props = {value: context.state['${value}']};`);
event = "change";
handler = `(ev) => {context.state['${value}'] = ev.target.value}`;
}
else if (type === "checkbox") {
ctx.addLine(`p${nodeID}.props = {checked: context.state['${value}']};`);
handler = `(ev) => {context.state['${value}'] = ev.target.checked}`;
}
else if (type === "radio") {
const nodeValue = node.getAttribute("value");
ctx.addLine(`p${nodeID}.props = {checked:context.state['${value}'] === '${nodeValue}'};`);
handler = `(ev) => {context.state['${value}'] = ev.target.value}`;
event = "click";
}
else {
ctx.addLine(`p${nodeID}.props = {value: context.state['${value}']};`);
const trimCode = fullName.includes(".trim") ? ".trim()" : "";
let valueCode = `ev.target.value${trimCode}`;
if (fullName.includes(".number")) {
ctx.rootContext.shouldDefineUtils = true;
valueCode = `utils.toNumber(${valueCode})`;
}
handler = `(ev) => {context.state['${value}'] = ${valueCode}}`;
}
ctx.addLine(`extra.handlers['${event}' + ${nodeID}] = extra.handlers['${event}' + ${nodeID}] || (${handler});`);
ctx.addLine(`p${nodeID}.on['${event}'] = extra.handlers['${event}' + ${nodeID}];`);
}
});
class Store extends EventBus { class Store extends EventBus {
constructor(config, options = {}) { constructor(config, options = {}) {
@@ -3094,17 +3169,29 @@
this.mutations = config.mutations; this.mutations = config.mutations;
this.env = config.env; this.env = config.env;
this.observer = new Observer(); this.observer = new Observer();
this.observer.notifyCB = this.trigger.bind(this, "update"); this.observer.notifyCB = () => {
this._gettersCache = {};
this.trigger("update");
};
this.observer.allowMutations = false; this.observer.allowMutations = false;
this.observer.observe(this.state); this.observer.observe(this.state);
this.getters = {}; this.getters = {};
this._gettersCache = {};
if (this.debug) { if (this.debug) {
this.history.push({ state: this.state }); this.history.push({ state: this.state });
} }
const cTypes = ["undefined", "number", "string"];
for (let entry of Object.entries(config.getters || {})) { for (let entry of Object.entries(config.getters || {})) {
const name = entry[0]; const name = entry[0];
const func = entry[1]; const func = entry[1];
this.getters[name] = payload => { this.getters[name] = payload => {
if (this._commitLevel === 0 && cTypes.indexOf(typeof payload) >= 0) {
this._gettersCache[name] = this._gettersCache[name] || {};
this._gettersCache[name][payload] =
this._gettersCache[name][payload] ||
func({ state: this.state, getters: this.getters }, payload);
return this._gettersCache[name][payload];
}
return func({ state: this.state, getters: this.getters }, payload); return func({ state: this.state, getters: this.getters }, payload);
}; };
} }
@@ -3402,9 +3489,9 @@
exports.connect = connect; exports.connect = connect;
exports.utils = utils; exports.utils = utils;
exports.__info__.version = '0.14.0'; exports.__info__.version = '0.15.0';
exports.__info__.date = '2019-06-13T10:11:15.338Z'; exports.__info__.date = '2019-06-17T13:59:39.059Z';
exports.__info__.hash = '2701a7d'; exports.__info__.hash = '609c108';
exports.__info__.url = 'https://github.com/odoo/owl'; exports.__info__.url = 'https://github.com/odoo/owl';
}(this.owl = this.owl || {})); }(this.owl = this.owl || {}));
+312 -192
View File
@@ -1,33 +1,6 @@
const CLICK_COUNTER = `class ClickCounter extends owl.Component { const COMPONENTS = `// In this example, we show how components can be defined and created.
constructor() {
super(...arguments);
this.state = { value: 0 };
}
increment() { class Counter extends owl.Component {
this.state.value++;
}
}
const qweb = new owl.QWeb(TEMPLATES);
const counter = new ClickCounter({ qweb });
counter.mount(document.body);
`;
const CLICK_COUNTER_XML = `<templates>
<button t-name="ClickCounter" t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>
</templates>`;
const CLICK_COUNTER_CSS = `button {
color: darkred;
font-size: 30px;
width: 220px;
}`;
const CLICK_COUNTER_ESNEXT = `// This example will not work if your browser does not support ESNext class fields
class ClickCounter extends owl.Component {
state = { value: 0 }; state = { value: 0 };
increment() { increment() {
@@ -35,68 +8,39 @@ class ClickCounter extends owl.Component {
} }
} }
const qweb = new owl.QWeb(TEMPLATES);
const counter = new ClickCounter({ qweb });
counter.mount(document.body);
`;
const WIDGET_COMPOSITION = `// This example will not work if your browser does not support ESNext class fields
class ClickCounter extends owl.Component {
state = { value: 0 };
increment() {
this.state.value++;
}
}
class InputWidget extends owl.Component {
state = {text: ""};
updateVal(event) {
let value = event.target.value;
if (this.props.reverse) {
value = value.split("").reverse().join("");
}
this.state.text = value
}
}
// Main root widget // Main root widget
class App extends owl.Component { class App extends owl.Component {
widgets = {ClickCounter, InputWidget}; widgets = { Counter };
} }
// Application setup // Application setup
// Note that the xml templates are injected into the global TEMPLATES variable.
const qweb = new owl.QWeb(TEMPLATES); const qweb = new owl.QWeb(TEMPLATES);
const app = new App({ qweb }); const app = new App({ qweb });
app.mount(document.body); app.mount(document.body);
`; `;
const WIDGET_COMPOSITION_XML = `<templates> const COMPONENTS_XML = `<templates>
<button t-name="ClickCounter" t-on-click="increment"> <button t-name="Counter" t-on-click="increment">
Click Me! [<t t-esc="state.value"/>] Click Me! [<t t-esc="state.value"/>]
</button> </button>
<div t-name="InputWidget">
<input t-on-input="updateVal" placeholder="type here some text..."/>
<span><t t-esc="state.text"/></span>
</div>
<div t-name="App"> <div t-name="App">
<t t-widget="ClickCounter"/> <t t-widget="Counter"/>
<t t-widget="InputWidget" reverse="true"/> <t t-widget="Counter"/>
</div> </div>
</templates>`; </templates>`;
const WIDGET_COMPOSITION_CSS = `button, input { const COMPONENTS_CSS = `button {
font-size: 20px; font-size: 20px;
width: 220px; width: 220px;
margin: 5px; margin: 5px;
}`; }`;
const ANIMATION = `// This example will not work if your browser does not support ESNext class fields const ANIMATION = `// The goal of this component is to see how the t-transition directive can be
class ClickCounter extends owl.Component { // used to generate simple transition effects.
class Counter extends owl.Component {
state = { value: 0 }; state = { value: 0 };
increment() { increment() {
@@ -105,15 +49,11 @@ class ClickCounter extends owl.Component {
} }
class App extends owl.Component { class App extends owl.Component {
state = {flag: false, widgetFlag: false, numbers: []}; state = { flag: false, widgetFlag: false, numbers: [] };
widgets = {ClickCounter}; widgets = { Counter };
toggle() { toggle(key) {
this.state.flag = !this.state.flag; this.state[key] = !this.state[key];
}
toggleWidget() {
this.state.widgetFlag = !this.state.widgetFlag;
} }
addNumber() { addNumber() {
@@ -129,46 +69,44 @@ app.mount(document.body);
`; `;
const ANIMATION_XML = `<templates> const ANIMATION_XML = `<templates>
<button t-name="ClickCounter" t-on-click="increment" class="clickcounter"> <button t-name="Counter" t-on-click="increment" class="clickcounter">
Click Me! [<t t-esc="state.value"/>] Click Me! [<t t-esc="state.value"/>]
</button> </button>
<div t-name="App"> <div t-name="App">
<h2>Transition on DOM element</h2>
<h2>Transition on DOM element</h2> <div class="demo">
<button t-on-click="toggle('flag')">Toggle square</button>
<div class="demo"> <div>
<button t-on-click="toggle">Toggle square</button> <div t-if="state.flag" class="square" t-transition="fade">Hello</div>
<div> </div>
<div t-if="state.flag" class="square" t-transition="fade">Hello</div>
</div> </div>
</div>
<h2>Transition on sub widgets</h2> <h2>Transition on sub widgets</h2>
<div class="demo"> <div class="demo">
<button t-on-click="toggleWidget"> <button t-on-click="toggle('widgetFlag')">Toggle widget</button>
Toggle widget <div>
</button> <t t-widget="Counter" t-if="state.widgetFlag" t-transition="fade"/>
<div> </div>
<t t-widget="ClickCounter" t-if="state.widgetFlag" t-transition="fade"/>
</div> </div>
</div>
<h2>Transition on lists</h2> <h2>Transition on lists</h2>
<p>Transitions can also be applied on lists</p> <p>Transitions can also be applied on lists</p>
<div class="demo"> <div class="demo">
<button t-on-click="addNumber">Add a number</button> <button t-on-click="addNumber">Add a number</button>
<div> <div>
<t t-foreach="state.numbers" t-as="n"> <t t-foreach="state.numbers" t-as="n">
<span t-transition="fade" class="numberspan"><t t-esc="n"/></span> <span t-transition="fade" class="numberspan"><t t-esc="n"/></span>
</t> </t>
</div>
</div> </div>
</div>
<h2>Simple CSS animation</h2> <h2>Simple CSS animation</h2>
<p>Remember, normal CSS still apply: for example, a simple flash animation with pure css </p> <p>Remember, normal CSS still apply: for example, a simple flash animation with pure css </p>
<div><a class="btn flash">Click</a></div> <div><a class="btn flash">Click</a>
</div>
</div> </div>
</templates> </templates>
`; `;
@@ -177,6 +115,7 @@ const ANIMATION_CSS = `button {
font-size: 18px; font-size: 18px;
height: 35px; height: 35px;
} }
.btn { .btn {
cursor: pointer; cursor: pointer;
padding: 5px; padding: 5px;
@@ -184,7 +123,6 @@ const ANIMATION_CSS = `button {
background-color: #dddddd; background-color: #dddddd;
} }
.flash { .flash {
background-position: center; background-position: center;
transition: background .6s; transition: background .6s;
@@ -195,7 +133,6 @@ const ANIMATION_CSS = `button {
transition: background 0s; transition: background 0s;
} }
.square { .square {
background-color: red; background-color: red;
width: 100px; width: 100px;
@@ -210,6 +147,7 @@ const ANIMATION_CSS = `button {
.fade-enter-active, .fade-leave-active { .fade-enter-active, .fade-leave-active {
transition: opacity .6s; transition: opacity .6s;
} }
.fade-enter, .fade-leave-to { .fade-enter, .fade-leave-to {
opacity: 0; opacity: 0;
} }
@@ -233,7 +171,14 @@ const ANIMATION_CSS = `button {
} }
`; `;
const LIFECYCLE_DEMO = `class HookWidget extends owl.Component { const LIFECYCLE_DEMO = `// This example shows all the possible lifecycle hooks
//
// The root widget controls a sub widget (DemoWidget). It logs all its lifecycle
// methods in the console. Try modifying its state by clicking on it, or by
// clicking on the two main buttons, and look into the console to see what
// happens.
class DemoWidget extends owl.Component {
constructor() { constructor() {
super(...arguments); super(...arguments);
this.state = { n: 0 }; this.state = { n: 0 };
@@ -262,37 +207,60 @@ const LIFECYCLE_DEMO = `class HookWidget extends owl.Component {
} }
} }
class ParentWidget extends owl.Component { class App extends owl.Component {
constructor() { widgets = { DemoWidget };
super(...arguments); state = { n: 0, flag: true };
this.widgets = { HookWidget };
this.state = { n: 0, flag: true };
}
increment() { increment() {
this.state.n++; this.state.n++;
} }
toggleSubWidget() { toggleSubWidget() {
this.state.flag = !this.state.flag; this.state.flag = !this.state.flag;
} }
} }
const qweb = new owl.QWeb(TEMPLATES); const qweb = new owl.QWeb(TEMPLATES);
const widget = new ParentWidget({ qweb }); const app = new App({ qweb });
widget.mount(document.body); app.mount(document.body);
`; `;
const LIFECYCLE_DEMO_XML = `<templates> const LIFECYCLE_DEMO_XML = `<templates>
<div t-name="ParentWidget"> <div t-name="DemoWidget" t-on-click="increment" class="demo">
<button t-on-click="increment">Increment</button> <div>Demo Sub Widget</div>
<button t-on-click="toggleSubWidget">ToggleSubWidget</button> <div>(click on me to update me)</div>
<div t-if="state.flag"> <div>Props: <t t-esc="props.n"/>, State: <t t-esc="state.n"/>. </div>
<t t-widget="HookWidget" n="state.n"/> </div>
</div>
<div t-name="App">
<button t-on-click="increment">Increment Parent State</button>
<button t-on-click="toggleSubWidget">Toggle SubWidget</button>
<div t-if="state.flag">
<t t-widget="DemoWidget" n="state.n"/>
</div> </div>
<div t-name="HookWidget" t-on-click="increment">Demo Sub Widget. Props: <t t-esc="props.n"/>. State: <t t-esc="state.n"/>. (click on me to update me)</div> </div>
</templates>`; </templates>`;
const TODO_APP_STORE = `const ENTER_KEY = 13; const LIFECYCLE_CSS = `button {
font-size: 18px;
margin: 5px;
}
.demo {
margin: 10px;
padding: 10px;
background-color: #dddddd;
width: 250px;
}`;
const TODO_APP_STORE = `// This example is an implementation of the TodoList application, from the
// www.todomvc.com project. This is a non trivial application with some
// interesting user interactions. It uses the local storage for persistence.
//
// In this implementation, we use the owl Store class to manage the state. It
// is very similar to the VueX store.
const ENTER_KEY = 13;
const ESC_KEY = 27; const ESC_KEY = 27;
const LOCALSTORAGE_KEY = "todos-odoo"; const LOCALSTORAGE_KEY = "todos-odoo";
@@ -937,7 +905,20 @@ html .clear-completed:active {
} }
`; `;
const RESPONSIVE = `class Navbar extends owl.Component {} const RESPONSIVE = `// In this example, we show how we can modify keys in the global environment to
// make a responsive application.
//
// The main idea is to have a "isMobile" key in the environment, then listen
// to resize events and update the env if needed. Then, the whole interface
// will be updated, creating and destroying widgets as needed.
//
// To see this in action, try resizing the window. The application will switch
// to mobile mode whenever it has less than 768px.
//------------------------------------------------------------------------------
// Components
//------------------------------------------------------------------------------
class Navbar extends owl.Component {}
class ControlPanel extends owl.Component { class ControlPanel extends owl.Component {
widgets = { MobileSearchView }; widgets = { MobileSearchView };
@@ -958,6 +939,9 @@ class App extends owl.Component {
widgets = { Navbar, ControlPanel, FormView, Chatter }; widgets = { Navbar, ControlPanel, FormView, Chatter };
} }
//------------------------------------------------------------------------------
// Application Startup
//------------------------------------------------------------------------------
function isMobile() { function isMobile() {
return window.innerWidth <= 768; return window.innerWidth <= 768;
} }
@@ -967,6 +951,7 @@ const env = {
isMobile: isMobile() isMobile: isMobile()
}; };
const app = new App(env); const app = new App(env);
app.mount(document.body); app.mount(document.body);
@@ -983,44 +968,44 @@ window.addEventListener("resize", owl.utils.debounce(updateEnv, 20));
`; `;
const RESPONSIVE_XML = `<templates> const RESPONSIVE_XML = `<templates>
<div t-name="Navbar" class="navbar">Navbar</div> <div t-name="Navbar" class="navbar">Navbar</div>
<div t-name="ControlPanel" class="controlpanel"> <div t-name="ControlPanel" class="controlpanel">
<h2>controlpanel</h2> <h2>Control Panel</h2>
<t t-if="env.isMobile" t-widget="MobileSearchView"/> <t t-if="env.isMobile" t-widget="MobileSearchView"/>
</div> </div>
<div t-name="FormView" class="formview"> <div t-name="FormView" class="formview">
<h2>formview</h2> <h2>Form View</h2>
<t t-if="!env.isMobile" t-widget="AdvancedWidget"/> <t t-if="!env.isMobile" t-widget="AdvancedWidget"/>
</div> </div>
<div t-name="Chatter" class="chatter"> <div t-name="Chatter" class="chatter">
<h2>Chatter</h2> <h2>Chatter</h2>
<t t-foreach="100" t-as="item"><div>Message <t t-esc="item"/></div></t> <t t-foreach="100" t-as="item"><div>Message <t t-esc="item"/></div></t>
</div> </div>
<div t-name="MobileSearchView">MOBILE searchview</div> <div t-name="MobileSearchView">Mobile searchview</div>
<div t-name="App" class="app" t-att-class="{mobile: env.isMobile, desktop: !env.isMobile}"> <div t-name="AdvancedWidget">
<t t-widget="Navbar"/> This widget is only created in desktop mode.
<t t-widget="ControlPanel"/> <button>Button!</button>
<div class="content-wrapper" t-if="!env.isMobile"> </div>
<div class="content">
<t t-widget="FormView"/> <div t-name="App" class="app" t-att-class="{mobile: env.isMobile, desktop: !env.isMobile}">
<t t-widget="Chatter"/> <t t-widget="Navbar"/>
</div> <t t-widget="ControlPanel"/>
</div> <div class="content-wrapper" t-if="!env.isMobile">
<t t-else="1"> <div class="content">
<t t-widget="FormView"/> <t t-widget="FormView"/>
<t t-widget="Chatter"/> <t t-widget="Chatter"/>
</t> </div>
</div>
<div t-name="AdvancedWidget">
This widget is only created in desktop mode.
<button>Button!</button>
</div> </div>
<t t-else="1">
<t t-widget="FormView"/>
<t t-widget="Chatter"/>
</t>
</div>
</templates> </templates>
`; `;
@@ -1036,6 +1021,7 @@ const RESPONSIVE_CSS = `body {
.app.desktop { .app.desktop {
display: flex; display: flex;
} }
.navbar { .navbar {
flex: 0 0 30px; flex: 0 0 30px;
height: 30px; height: 30px;
@@ -1081,17 +1067,19 @@ const RESPONSIVE_CSS = `body {
} }
`; `;
const SLOTS = `// This example will not work if your browser does not support ESNext class fields const SLOTS = `// We show here how slots can be used to create generic components.
// In this example, the Card component is basically only a container. It is not
// We show here how slots can be used to create generic components. In this // aware of its content. It just knows where it should be (with t-slot).
// example, the Card component is basically only a container, and is created // The parent widget define the content with t-set.
// by giving it slots, inside the t-widget directive. //
// Note that the t-on-click event, defined in the App template, is executed in
// the context of the App component, even though it is inside the Card component
class Card extends owl.Component { class Card extends owl.Component {
state = { fullDisplay: true }; state = { showContent: true };
toggleDisplay() { toggleDisplay() {
this.state.fullDisplay = !this.state.fullDisplay; this.state.showContent = !this.state.showContent;
} }
} }
@@ -1119,11 +1107,11 @@ const app = new App({ qweb });
app.mount(document.body);`; app.mount(document.body);`;
const SLOTS_XML = `<templates> const SLOTS_XML = `<templates>
<div t-name="Card" class="card" t-att-class="state.fullDisplay ? 'full' : 'small'"> <div t-name="Card" class="card" t-att-class="state.showContent ? 'full' : 'small'">
<div class="card-title"> <div class="card-title">
<t t-esc="props.title"/><button t-on-click="toggleDisplay">Toggle</button> <t t-esc="props.title"/><button t-on-click="toggleDisplay">Toggle</button>
</div> </div>
<t t-if="state.fullDisplay"> <t t-if="state.showContent">
<div class="card-content" > <div class="card-content" >
<t t-slot="content"/> <t t-slot="content"/>
</div> </div>
@@ -1196,32 +1184,161 @@ const SLOTS_CSS = `.main {
border-top: 1px solid white; border-top: 1px solid white;
}`; }`;
const EMPTY = `class App extends owl.Component { const ASYNC_COMPONENTS = `// This example will not work if your browser does not support ESNext class fields
// In this example, we have 2 sub widgets, one of them being async (slow).
// However, we don't want renderings of the other sub widget to be delayed
// because of the slow widget. We use the 't-asyncroot' directive for this
// purpose. Try removing it to see the difference.
class App extends owl.Component {
widgets = {SlowWidget, NotificationList};
state = { value: 0, notifs: [] };
increment() {
this.state.value++;
const notif = "Value will be set to " + this.state.value;
this.state.notifs.push(notif);
setTimeout(() => {
var index = this.state.notifs.indexOf(notif);
this.state.notifs.splice(index, 1);
}, 3000);
}
} }
class SlowWidget extends owl.Component {
willUpdateProps() {
// simulate a widget that needs to perform async stuff (e.g. an RPC)
// with the updated props before re-rendering itself
return new Promise(resolve => setTimeout(resolve, 1500));
}
}
class NotificationList extends owl.Component {}
const qweb = new owl.QWeb(TEMPLATES); const qweb = new owl.QWeb(TEMPLATES);
const app = new App({qweb}); const app = new App({ qweb });
app.mount(document.body); app.mount(document.body);
`; `;
const ASYNC_COMPONENTS_XML = `<templates>
<div t-name="App" class="app">
<button t-on-click="increment">Increment</button>
<t t-widget="SlowWidget" value="state.value"/>
<t t-widget="NotificationList" t-asyncroot="1" notifications="state.notifs"/>
</div>
<div t-name="SlowWidget" class="value" >
Current value: <t t-esc="props.value"/>
</div>
<div t-name="NotificationList" class="notification-list">
<t t-foreach="props.notifications" t-as="notif">
<div class="notification"><t t-esc="notif"/></div>
</t>
</div>
</templates>`;
const ASYNC_COMPONENTS_CSS = `.app {
width: 70%;
}
button {
color: darkred;
font-size: 30px;
width: 220px;
}
.value {
font-size: 26px;
padding: 20px;
}
.notification-list {
position: absolute;
top: 0;
right: 0;
}
.notification {
width: 150px;
margin: 4px 8px;
padding: 16px;
border: 1px solid: black;
background-color: lightgray;
}`;
const FORM = `// This example illustrate how the t-model directive can be used to synchronize
// data between html inputs (and select/textareas) and the state of a component.
// Note that there are two controls with t-model="color": they are totally
// synchronized.
class Form extends owl.Component {
state = {
text: "",
othertext: "",
number: 11,
color: "",
bool: false
};
}
// Application setup
const qweb = new owl.QWeb(TEMPLATES);
const form = new Form({ qweb });
form.mount(document.body);
`;
const FORM_XML = `<templates>
<div t-name="Form">
<h1>Form</h1>
<div>
Text (immediate): <input t-model="text"/>
</div>
<div>
Other text (lazy): <input t-model.lazy="othertext"/>
</div>
<div>
Number: <input t-model.number="number"/>
</div>
<div>
Boolean: <input type="checkbox" t-model="bool"/>
</div>
<div>
Color, with a select:
<select t-model="color">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<div>
Color, with radio buttons:
<span><input type="radio" name="color" id="red" value="red" t-model="color"/><label for="red">Red</label></span>
<span><input type="radio" name="color" id="blue" value="blue" t-model="color"/><label for="blue">Blue</label></span>
</div>
<hr/>
<h1>State</h1>
<div>Text: <t t-esc="state.text"/></div>
<div>Other Text: <t t-esc="state.othertext"/></div>
<div>Number: <t t-esc="state.number"/></div>
<div>Boolean: <t t-if="state.bool">True</t><t t-else="1">False</t></div>
<div>Color: <t t-esc="state.color"/></div>
</div>
</templates>
`;
export const SAMPLES = [ export const SAMPLES = [
{ {
description: "Click Counter", description: "Components",
code: CLICK_COUNTER, code: COMPONENTS,
xml: CLICK_COUNTER_XML, xml: COMPONENTS_XML,
css: CLICK_COUNTER_CSS css: COMPONENTS_CSS
}, },
{ {
description: "Click Counter (ESNext)", description: "Form Input Bindings",
code: CLICK_COUNTER_ESNEXT, code: FORM,
xml: CLICK_COUNTER_XML, xml: FORM_XML
css: CLICK_COUNTER_CSS
},
{
description: "Widget Composition",
code: WIDGET_COMPOSITION,
xml: WIDGET_COMPOSITION_XML,
css: WIDGET_COMPOSITION_CSS
}, },
{ {
description: "Animations", description: "Animations",
@@ -1232,7 +1349,8 @@ export const SAMPLES = [
{ {
description: "Lifecycle demo", description: "Lifecycle demo",
code: LIFECYCLE_DEMO, code: LIFECYCLE_DEMO,
xml: LIFECYCLE_DEMO_XML xml: LIFECYCLE_DEMO_XML,
css: LIFECYCLE_CSS,
}, },
{ {
description: "Todo List App (with store)", description: "Todo List App (with store)",
@@ -1247,13 +1365,15 @@ export const SAMPLES = [
xml: RESPONSIVE_XML xml: RESPONSIVE_XML
}, },
{ {
description: "Slots", description: "Slots And Generic Components",
code: SLOTS, code: SLOTS,
xml: SLOTS_XML, xml: SLOTS_XML,
css: SLOTS_CSS css: SLOTS_CSS
}, },
{ {
description: "Empty", description: "Asynchronous components",
code: EMPTY code: ASYNC_COMPONENTS,
xml: ASYNC_COMPONENTS_XML,
css: ASYNC_COMPONENTS_CSS
} }
]; ];
+1 -1
View File
@@ -2,7 +2,7 @@
<div t-name="TabbedEditor" class="tabbed-editor"> <div t-name="TabbedEditor" class="tabbed-editor">
<div class="tabBar" t-att-class="{resizeable: props.resizeable}" t-on-mousedown="onMouseDown"> <div class="tabBar" t-att-class="{resizeable: props.resizeable}" t-on-mousedown="onMouseDown">
<t t-foreach="['js', 'xml', 'css']" t-as="tab"> <t t-foreach="['js', 'xml', 'css']" t-as="tab">
<a t-ref="{{tab}}" t-if="props[tab]" t-key="tab" class="tab flash" t-att-class="{active: state.currentTab===tab}" t-on-click="setTab(tab)"> <a t-ref="{{tab}}" t-if="props[tab] !== false" t-key="tab" class="tab flash" t-att-class="{active: state.currentTab===tab}" t-on-click="setTab(tab)">
<t t-esc="tab"/> <t t-esc="tab"/>
</a> </a>
</t> </t>