@odoo/owl 2.0.0-alpha.3 → 2.0.0-beta-6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/owl.iife.js CHANGED
@@ -212,7 +212,8 @@
212
212
  }
213
213
  function makePropSetter(name) {
214
214
  return function setProp(value) {
215
- this[name] = value || "";
215
+ // support 0, fallback to empty string for other falsy values
216
+ this[name] = value === 0 ? 0 : value || "";
216
217
  };
217
218
  }
218
219
  function isProp(tag, key) {
@@ -266,10 +267,14 @@
266
267
  this[eventKey] = data;
267
268
  this.addEventListener(evName, listener, { capture });
268
269
  }
270
+ function remove() {
271
+ delete this[eventKey];
272
+ this.removeEventListener(evName, listener, { capture });
273
+ }
269
274
  function update(data) {
270
275
  this[eventKey] = data;
271
276
  }
272
- return { setup, update };
277
+ return { setup, update, remove };
273
278
  }
274
279
  // Synthetic handler: a form of event delegation that allows placing only one
275
280
  // listener per event type.
@@ -286,7 +291,10 @@
286
291
  _data[currentId] = data;
287
292
  this[eventKey] = _data;
288
293
  }
289
- return { setup, update: setup };
294
+ function remove() {
295
+ delete this[eventKey];
296
+ }
297
+ return { setup, update: setup, remove };
290
298
  }
291
299
  function nativeToSyntheticEvent(eventKey, event) {
292
300
  let dom = event.target;
@@ -511,7 +519,7 @@
511
519
  const characterDataSetData = getDescriptor$1(characterDataProto, "data").set;
512
520
  const nodeGetFirstChild = getDescriptor$1(nodeProto$2, "firstChild").get;
513
521
  const nodeGetNextSibling = getDescriptor$1(nodeProto$2, "nextSibling").get;
514
- const NO_OP$1 = () => { };
522
+ const NO_OP = () => { };
515
523
  const cache$1 = {};
516
524
  /**
517
525
  * Compiling blocks is a multi-step process:
@@ -815,7 +823,7 @@
815
823
  idx: info.idx,
816
824
  refIdx: info.refIdx,
817
825
  setData: makeRefSetter(index, ctx.refList),
818
- updateData: NO_OP$1,
826
+ updateData: NO_OP,
819
827
  });
820
828
  }
821
829
  }
@@ -1281,6 +1289,75 @@
1281
1289
  return new VHtml(str);
1282
1290
  }
1283
1291
 
1292
+ function createCatcher(eventsSpec) {
1293
+ let setupFns = [];
1294
+ let removeFns = [];
1295
+ for (let name in eventsSpec) {
1296
+ let index = eventsSpec[name];
1297
+ let { setup, remove } = createEventHandler(name);
1298
+ setupFns[index] = setup;
1299
+ removeFns[index] = remove;
1300
+ }
1301
+ let n = setupFns.length;
1302
+ class VCatcher {
1303
+ constructor(child, handlers) {
1304
+ this.afterNode = null;
1305
+ this.child = child;
1306
+ this.handlers = handlers;
1307
+ }
1308
+ mount(parent, afterNode) {
1309
+ this.parentEl = parent;
1310
+ this.afterNode = afterNode;
1311
+ this.child.mount(parent, afterNode);
1312
+ for (let i = 0; i < n; i++) {
1313
+ let origFn = this.handlers[i][0];
1314
+ const self = this;
1315
+ this.handlers[i][0] = function (ev) {
1316
+ const target = ev.target;
1317
+ let currentNode = self.child.firstNode();
1318
+ const afterNode = self.afterNode;
1319
+ while (currentNode !== afterNode) {
1320
+ if (currentNode.contains(target)) {
1321
+ return origFn.call(this, ev);
1322
+ }
1323
+ currentNode = currentNode.nextSibling;
1324
+ }
1325
+ };
1326
+ setupFns[i].call(parent, this.handlers[i]);
1327
+ }
1328
+ }
1329
+ moveBefore(other, afterNode) {
1330
+ this.afterNode = null;
1331
+ this.child.moveBefore(other ? other.child : null, afterNode);
1332
+ }
1333
+ patch(other, withBeforeRemove) {
1334
+ if (this === other) {
1335
+ return;
1336
+ }
1337
+ this.handlers = other.handlers;
1338
+ this.child.patch(other.child, withBeforeRemove);
1339
+ }
1340
+ beforeRemove() {
1341
+ this.child.beforeRemove();
1342
+ }
1343
+ remove() {
1344
+ for (let i = 0; i < n; i++) {
1345
+ removeFns[i].call(this.parentEl);
1346
+ }
1347
+ this.child.remove();
1348
+ }
1349
+ firstNode() {
1350
+ return this.child.firstNode();
1351
+ }
1352
+ toString() {
1353
+ return this.child.toString();
1354
+ }
1355
+ }
1356
+ return function (child, handlers) {
1357
+ return new VCatcher(child, handlers);
1358
+ };
1359
+ }
1360
+
1284
1361
  function mount$1(vnode, fixture, afterNode = null) {
1285
1362
  vnode.mount(fixture, afterNode);
1286
1363
  }
@@ -1294,143 +1371,464 @@
1294
1371
  vnode.remove();
1295
1372
  }
1296
1373
 
1374
+ const mainEventHandler = (data, ev, currentTarget) => {
1375
+ const { data: _data, modifiers } = filterOutModifiersFromData(data);
1376
+ data = _data;
1377
+ let stopped = false;
1378
+ if (modifiers.length) {
1379
+ let selfMode = false;
1380
+ const isSelf = ev.target === currentTarget;
1381
+ for (const mod of modifiers) {
1382
+ switch (mod) {
1383
+ case "self":
1384
+ selfMode = true;
1385
+ if (isSelf) {
1386
+ continue;
1387
+ }
1388
+ else {
1389
+ return stopped;
1390
+ }
1391
+ case "prevent":
1392
+ if ((selfMode && isSelf) || !selfMode)
1393
+ ev.preventDefault();
1394
+ continue;
1395
+ case "stop":
1396
+ if ((selfMode && isSelf) || !selfMode)
1397
+ ev.stopPropagation();
1398
+ stopped = true;
1399
+ continue;
1400
+ }
1401
+ }
1402
+ }
1403
+ // If handler is empty, the array slot 0 will also be empty, and data will not have the property 0
1404
+ // We check this rather than data[0] being truthy (or typeof function) so that it crashes
1405
+ // as expected when there is a handler expression that evaluates to a falsy value
1406
+ if (Object.hasOwnProperty.call(data, 0)) {
1407
+ const handler = data[0];
1408
+ if (typeof handler !== "function") {
1409
+ throw new Error(`Invalid handler (expected a function, received: '${handler}')`);
1410
+ }
1411
+ let node = data[1] ? data[1].__owl__ : null;
1412
+ if (node ? node.status === 1 /* MOUNTED */ : true) {
1413
+ handler.call(node ? node.component : null, ev);
1414
+ }
1415
+ }
1416
+ return stopped;
1417
+ };
1418
+
1419
+ // Allows to get the target of a Reactive (used for making a new Reactive from the underlying object)
1420
+ const TARGET = Symbol("Target");
1421
+ // Escape hatch to prevent reactivity system to turn something into a reactive
1422
+ const SKIP = Symbol("Skip");
1423
+ // Special key to subscribe to, to be notified of key creation/deletion
1424
+ const KEYCHANGES = Symbol("Key changes");
1425
+ const objectToString = Object.prototype.toString;
1426
+ const objectHasOwnProperty = Object.prototype.hasOwnProperty;
1427
+ const SUPPORTED_RAW_TYPES = new Set(["Object", "Array", "Set", "Map", "WeakMap"]);
1428
+ const COLLECTION_RAWTYPES = new Set(["Set", "Map", "WeakMap"]);
1297
1429
  /**
1298
- * Apply default props (only top level).
1430
+ * extract "RawType" from strings like "[object RawType]" => this lets us ignore
1431
+ * many native objects such as Promise (whose toString is [object Promise])
1432
+ * or Date ([object Date]), while also supporting collections without using
1433
+ * instanceof in a loop
1299
1434
  *
1300
- * Note that this method does modify in place the props
1435
+ * @param obj the object to check
1436
+ * @returns the raw type of the object
1301
1437
  */
1302
- function applyDefaultProps(props, ComponentClass) {
1303
- const defaultProps = ComponentClass.defaultProps;
1304
- if (defaultProps) {
1305
- for (let propName in defaultProps) {
1306
- if (props[propName] === undefined) {
1307
- props[propName] = defaultProps[propName];
1308
- }
1309
- }
1438
+ function rawType(obj) {
1439
+ return objectToString.call(obj).slice(8, -1);
1440
+ }
1441
+ /**
1442
+ * Checks whether a given value can be made into a reactive object.
1443
+ *
1444
+ * @param value the value to check
1445
+ * @returns whether the value can be made reactive
1446
+ */
1447
+ function canBeMadeReactive(value) {
1448
+ if (typeof value !== "object") {
1449
+ return false;
1310
1450
  }
1451
+ return SUPPORTED_RAW_TYPES.has(rawType(value));
1311
1452
  }
1312
- //------------------------------------------------------------------------------
1313
- // Prop validation helper
1314
- //------------------------------------------------------------------------------
1315
- function getPropDescription(staticProps) {
1316
- if (staticProps instanceof Array) {
1317
- return Object.fromEntries(staticProps.map((p) => (p.endsWith("?") ? [p.slice(0, -1), false] : [p, true])));
1453
+ /**
1454
+ * Creates a reactive from the given object/callback if possible and returns it,
1455
+ * returns the original object otherwise.
1456
+ *
1457
+ * @param value the value make reactive
1458
+ * @returns a reactive for the given object when possible, the original otherwise
1459
+ */
1460
+ function possiblyReactive(val, cb) {
1461
+ return canBeMadeReactive(val) ? reactive(val, cb) : val;
1462
+ }
1463
+ /**
1464
+ * Mark an object or array so that it is ignored by the reactivity system
1465
+ *
1466
+ * @param value the value to mark
1467
+ * @returns the object itself
1468
+ */
1469
+ function markRaw(value) {
1470
+ value[SKIP] = true;
1471
+ return value;
1472
+ }
1473
+ /**
1474
+ * Given a reactive objet, return the raw (non reactive) underlying object
1475
+ *
1476
+ * @param value a reactive value
1477
+ * @returns the underlying value
1478
+ */
1479
+ function toRaw(value) {
1480
+ return value[TARGET] || value;
1481
+ }
1482
+ const targetToKeysToCallbacks = new WeakMap();
1483
+ /**
1484
+ * Observes a given key on a target with an callback. The callback will be
1485
+ * called when the given key changes on the target.
1486
+ *
1487
+ * @param target the target whose key should be observed
1488
+ * @param key the key to observe (or Symbol(KEYCHANGES) for key creation
1489
+ * or deletion)
1490
+ * @param callback the function to call when the key changes
1491
+ */
1492
+ function observeTargetKey(target, key, callback) {
1493
+ if (!targetToKeysToCallbacks.get(target)) {
1494
+ targetToKeysToCallbacks.set(target, new Map());
1318
1495
  }
1319
- return staticProps || { "*": true };
1496
+ const keyToCallbacks = targetToKeysToCallbacks.get(target);
1497
+ if (!keyToCallbacks.get(key)) {
1498
+ keyToCallbacks.set(key, new Set());
1499
+ }
1500
+ keyToCallbacks.get(key).add(callback);
1501
+ if (!callbacksToTargets.has(callback)) {
1502
+ callbacksToTargets.set(callback, new Set());
1503
+ }
1504
+ callbacksToTargets.get(callback).add(target);
1320
1505
  }
1321
1506
  /**
1322
- * Validate the component props (or next props) against the (static) props
1323
- * description. This is potentially an expensive operation: it may needs to
1324
- * visit recursively the props and all the children to check if they are valid.
1325
- * This is why it is only done in 'dev' mode.
1507
+ * Notify Reactives that are observing a given target that a key has changed on
1508
+ * the target.
1509
+ *
1510
+ * @param target target whose Reactives should be notified that the target was
1511
+ * changed.
1512
+ * @param key the key that changed (or Symbol `KEYCHANGES` if a key was created
1513
+ * or deleted)
1326
1514
  */
1327
- function validateProps(name, props, parent) {
1328
- const ComponentClass = typeof name !== "string"
1329
- ? name
1330
- : parent.constructor.components[name];
1331
- if (!ComponentClass) {
1332
- // this is an error, wrong component. We silently return here instead so the
1333
- // error is triggered by the usual path ('component' function)
1515
+ function notifyReactives(target, key) {
1516
+ const keyToCallbacks = targetToKeysToCallbacks.get(target);
1517
+ if (!keyToCallbacks) {
1334
1518
  return;
1335
1519
  }
1336
- applyDefaultProps(props, ComponentClass);
1337
- const defaultProps = ComponentClass.defaultProps || {};
1338
- let propsDef = getPropDescription(ComponentClass.props);
1339
- const allowAdditionalProps = "*" in propsDef;
1340
- for (let propName in propsDef) {
1341
- if (propName === "*") {
1342
- continue;
1343
- }
1344
- const propDef = propsDef[propName];
1345
- let isMandatory = !!propDef;
1346
- if (typeof propDef === "object" && "optional" in propDef) {
1347
- isMandatory = !propDef.optional;
1348
- }
1349
- if (isMandatory && propName in defaultProps) {
1350
- throw new Error(`A default value cannot be defined for a mandatory prop (name: '${propName}', component: ${ComponentClass.name})`);
1351
- }
1352
- if (props[propName] === undefined) {
1353
- if (isMandatory) {
1354
- throw new Error(`Missing props '${propName}' (component '${ComponentClass.name}')`);
1355
- }
1356
- else {
1357
- continue;
1358
- }
1359
- }
1360
- let isValid;
1361
- try {
1362
- isValid = isValidProp(props[propName], propDef);
1363
- }
1364
- catch (e) {
1365
- e.message = `Invalid prop '${propName}' in component ${ComponentClass.name} (${e.message})`;
1366
- throw e;
1367
- }
1368
- if (!isValid) {
1369
- throw new Error(`Invalid Prop '${propName}' in component '${ComponentClass.name}'`);
1370
- }
1520
+ const callbacks = keyToCallbacks.get(key);
1521
+ if (!callbacks) {
1522
+ return;
1371
1523
  }
1372
- if (!allowAdditionalProps) {
1373
- for (let propName in props) {
1374
- if (!(propName in propsDef)) {
1375
- throw new Error(`Unknown prop '${propName}' given to component '${ComponentClass.name}'`);
1376
- }
1377
- }
1524
+ // Loop on copy because clearReactivesForCallback will modify the set in place
1525
+ for (const callback of [...callbacks]) {
1526
+ clearReactivesForCallback(callback);
1527
+ callback();
1378
1528
  }
1379
1529
  }
1530
+ const callbacksToTargets = new WeakMap();
1380
1531
  /**
1381
- * Check if an invidual prop value matches its (static) prop definition
1532
+ * Clears all subscriptions of the Reactives associated with a given callback.
1533
+ *
1534
+ * @param callback the callback for which the reactives need to be cleared
1382
1535
  */
1383
- function isValidProp(prop, propDef) {
1384
- if (propDef === true) {
1385
- return true;
1536
+ function clearReactivesForCallback(callback) {
1537
+ const targetsToClear = callbacksToTargets.get(callback);
1538
+ if (!targetsToClear) {
1539
+ return;
1386
1540
  }
1387
- if (typeof propDef === "function") {
1388
- // Check if a value is constructed by some Constructor. Note that there is a
1389
- // slight abuse of language: we want to consider primitive values as well.
1390
- //
1391
- // So, even though 1 is not an instance of Number, we want to consider that
1392
- // it is valid.
1393
- if (typeof prop === "object") {
1394
- return prop instanceof propDef;
1541
+ for (const target of targetsToClear) {
1542
+ const observedKeys = targetToKeysToCallbacks.get(target);
1543
+ if (!observedKeys) {
1544
+ continue;
1395
1545
  }
1396
- return typeof prop === propDef.name.toLowerCase();
1397
- }
1398
- else if (propDef instanceof Array) {
1399
- // If this code is executed, this means that we want to check if a prop
1400
- // matches at least one of its descriptor.
1401
- let result = false;
1402
- for (let i = 0, iLen = propDef.length; i < iLen; i++) {
1403
- result = result || isValidProp(prop, propDef[i]);
1546
+ for (const callbacks of observedKeys.values()) {
1547
+ callbacks.delete(callback);
1404
1548
  }
1405
- return result;
1406
1549
  }
1407
- // propsDef is an object
1408
- if (propDef.optional && prop === undefined) {
1409
- return true;
1550
+ targetsToClear.clear();
1551
+ }
1552
+ function getSubscriptions(callback) {
1553
+ const targets = callbacksToTargets.get(callback) || [];
1554
+ return [...targets].map((target) => {
1555
+ const keysToCallbacks = targetToKeysToCallbacks.get(target);
1556
+ return {
1557
+ target,
1558
+ keys: keysToCallbacks ? [...keysToCallbacks.keys()] : [],
1559
+ };
1560
+ });
1561
+ }
1562
+ const reactiveCache = new WeakMap();
1563
+ /**
1564
+ * Creates a reactive proxy for an object. Reading data on the reactive object
1565
+ * subscribes to changes to the data. Writing data on the object will cause the
1566
+ * notify callback to be called if there are suscriptions to that data. Nested
1567
+ * objects and arrays are automatically made reactive as well.
1568
+ *
1569
+ * Whenever you are notified of a change, all subscriptions are cleared, and if
1570
+ * you would like to be notified of any further changes, you should go read
1571
+ * the underlying data again. We assume that if you don't go read it again after
1572
+ * being notified, it means that you are no longer interested in that data.
1573
+ *
1574
+ * Subscriptions:
1575
+ * + Reading a property on an object will subscribe you to changes in the value
1576
+ * of that property.
1577
+ * + Accessing an object keys (eg with Object.keys or with `for..in`) will
1578
+ * subscribe you to the creation/deletion of keys. Checking the presence of a
1579
+ * key on the object with 'in' has the same effect.
1580
+ * - getOwnPropertyDescriptor does not currently subscribe you to the property.
1581
+ * This is a choice that was made because changing a key's value will trigger
1582
+ * this trap and we do not want to subscribe by writes. This also means that
1583
+ * Object.hasOwnProperty doesn't subscribe as it goes through this trap.
1584
+ *
1585
+ * @param target the object for which to create a reactive proxy
1586
+ * @param callback the function to call when an observed property of the
1587
+ * reactive has changed
1588
+ * @returns a proxy that tracks changes to it
1589
+ */
1590
+ function reactive(target, callback = () => { }) {
1591
+ if (!canBeMadeReactive(target)) {
1592
+ throw new Error(`Cannot make the given value reactive`);
1410
1593
  }
1411
- let result = propDef.type ? isValidProp(prop, propDef.type) : true;
1412
- if (propDef.validate) {
1413
- result = result && propDef.validate(prop);
1594
+ if (SKIP in target) {
1595
+ return target;
1414
1596
  }
1415
- if (propDef.type === Array && propDef.element) {
1416
- for (let i = 0, iLen = prop.length; i < iLen; i++) {
1417
- result = result && isValidProp(prop[i], propDef.element);
1418
- }
1597
+ const originalTarget = target[TARGET];
1598
+ if (originalTarget) {
1599
+ return reactive(originalTarget, callback);
1419
1600
  }
1420
- if (propDef.type === Object && propDef.shape) {
1421
- const shape = propDef.shape;
1422
- for (let key in shape) {
1423
- result = result && isValidProp(prop[key], shape[key]);
1424
- }
1425
- if (result) {
1426
- for (let propName in prop) {
1427
- if (!(propName in shape)) {
1428
- throw new Error(`unknown prop '${propName}'`);
1429
- }
1601
+ if (!reactiveCache.has(target)) {
1602
+ reactiveCache.set(target, new Map());
1603
+ }
1604
+ const reactivesForTarget = reactiveCache.get(target);
1605
+ if (!reactivesForTarget.has(callback)) {
1606
+ const targetRawType = rawType(target);
1607
+ const handler = COLLECTION_RAWTYPES.has(targetRawType)
1608
+ ? collectionsProxyHandler(target, callback, targetRawType)
1609
+ : basicProxyHandler(callback);
1610
+ const proxy = new Proxy(target, handler);
1611
+ reactivesForTarget.set(callback, proxy);
1612
+ }
1613
+ return reactivesForTarget.get(callback);
1614
+ }
1615
+ /**
1616
+ * Creates a basic proxy handler for regular objects and arrays.
1617
+ *
1618
+ * @param callback @see reactive
1619
+ * @returns a proxy handler object
1620
+ */
1621
+ function basicProxyHandler(callback) {
1622
+ return {
1623
+ get(target, key, proxy) {
1624
+ if (key === TARGET) {
1625
+ return target;
1626
+ }
1627
+ // non-writable non-configurable properties cannot be made reactive
1628
+ const desc = Object.getOwnPropertyDescriptor(target, key);
1629
+ if (desc && !desc.writable && !desc.configurable) {
1630
+ return Reflect.get(target, key, proxy);
1631
+ }
1632
+ observeTargetKey(target, key, callback);
1633
+ return possiblyReactive(Reflect.get(target, key, proxy), callback);
1634
+ },
1635
+ set(target, key, value, proxy) {
1636
+ const isNewKey = !objectHasOwnProperty.call(target, key);
1637
+ const originalValue = Reflect.get(target, key, proxy);
1638
+ const ret = Reflect.set(target, key, value, proxy);
1639
+ if (isNewKey) {
1640
+ notifyReactives(target, KEYCHANGES);
1641
+ }
1642
+ // While Array length may trigger the set trap, it's not actually set by this
1643
+ // method but is updated behind the scenes, and the trap is not called with the
1644
+ // new value. We disable the "same-value-optimization" for it because of that.
1645
+ if (originalValue !== value || (Array.isArray(target) && key === "length")) {
1646
+ notifyReactives(target, key);
1430
1647
  }
1648
+ return ret;
1649
+ },
1650
+ deleteProperty(target, key) {
1651
+ const ret = Reflect.deleteProperty(target, key);
1652
+ // TODO: only notify when something was actually deleted
1653
+ notifyReactives(target, KEYCHANGES);
1654
+ notifyReactives(target, key);
1655
+ return ret;
1656
+ },
1657
+ ownKeys(target) {
1658
+ observeTargetKey(target, KEYCHANGES, callback);
1659
+ return Reflect.ownKeys(target);
1660
+ },
1661
+ has(target, key) {
1662
+ // TODO: this observes all key changes instead of only the presence of the argument key
1663
+ // observing the key itself would observe value changes instead of presence changes
1664
+ // so we may need a finer grained system to distinguish observing value vs presence.
1665
+ observeTargetKey(target, KEYCHANGES, callback);
1666
+ return Reflect.has(target, key);
1667
+ },
1668
+ };
1669
+ }
1670
+ /**
1671
+ * Creates a function that will observe the key that is passed to it when called
1672
+ * and delegates to the underlying method.
1673
+ *
1674
+ * @param methodName name of the method to delegate to
1675
+ * @param target @see reactive
1676
+ * @param callback @see reactive
1677
+ */
1678
+ function makeKeyObserver(methodName, target, callback) {
1679
+ return (key) => {
1680
+ key = toRaw(key);
1681
+ observeTargetKey(target, key, callback);
1682
+ return possiblyReactive(target[methodName](key), callback);
1683
+ };
1684
+ }
1685
+ /**
1686
+ * Creates an iterable that will delegate to the underlying iteration method and
1687
+ * observe keys as necessary.
1688
+ *
1689
+ * @param methodName name of the method to delegate to
1690
+ * @param target @see reactive
1691
+ * @param callback @see reactive
1692
+ */
1693
+ function makeIteratorObserver(methodName, target, callback) {
1694
+ return function* () {
1695
+ observeTargetKey(target, KEYCHANGES, callback);
1696
+ const keys = target.keys();
1697
+ for (const item of target[methodName]()) {
1698
+ const key = keys.next().value;
1699
+ observeTargetKey(target, key, callback);
1700
+ yield possiblyReactive(item, callback);
1431
1701
  }
1432
- }
1433
- return result;
1702
+ };
1703
+ }
1704
+ /**
1705
+ * Creates a forEach function that will delegate to forEach on the underlying
1706
+ * collection while observing key changes, and keys as they're iterated over,
1707
+ * and making the passed keys/values reactive.
1708
+ *
1709
+ * @param target @see reactive
1710
+ * @param callback @see reactive
1711
+ */
1712
+ function makeForEachObserver(target, callback) {
1713
+ return function forEach(forEachCb, thisArg) {
1714
+ observeTargetKey(target, KEYCHANGES, callback);
1715
+ target.forEach(function (val, key, targetObj) {
1716
+ observeTargetKey(target, key, callback);
1717
+ forEachCb.call(thisArg, possiblyReactive(val, callback), possiblyReactive(key, callback), possiblyReactive(targetObj, callback));
1718
+ }, thisArg);
1719
+ };
1720
+ }
1721
+ /**
1722
+ * Creates a function that will delegate to an underlying method, and check if
1723
+ * that method has modified the presence or value of a key, and notify the
1724
+ * reactives appropriately.
1725
+ *
1726
+ * @param setterName name of the method to delegate to
1727
+ * @param getterName name of the method which should be used to retrieve the
1728
+ * value before calling the delegate method for comparison purposes
1729
+ * @param target @see reactive
1730
+ */
1731
+ function delegateAndNotify(setterName, getterName, target) {
1732
+ return (key, value) => {
1733
+ key = toRaw(key);
1734
+ const hadKey = target.has(key);
1735
+ const originalValue = target[getterName](key);
1736
+ const ret = target[setterName](key, value);
1737
+ const hasKey = target.has(key);
1738
+ if (hadKey !== hasKey) {
1739
+ notifyReactives(target, KEYCHANGES);
1740
+ }
1741
+ if (originalValue !== value) {
1742
+ notifyReactives(target, key);
1743
+ }
1744
+ return ret;
1745
+ };
1746
+ }
1747
+ /**
1748
+ * Creates a function that will clear the underlying collection and notify that
1749
+ * the keys of the collection have changed.
1750
+ *
1751
+ * @param target @see reactive
1752
+ */
1753
+ function makeClearNotifier(target) {
1754
+ return () => {
1755
+ const allKeys = [...target.keys()];
1756
+ target.clear();
1757
+ notifyReactives(target, KEYCHANGES);
1758
+ for (const key of allKeys) {
1759
+ notifyReactives(target, key);
1760
+ }
1761
+ };
1762
+ }
1763
+ /**
1764
+ * Maps raw type of an object to an object containing functions that can be used
1765
+ * to build an appropritate proxy handler for that raw type. Eg: when making a
1766
+ * reactive set, calling the has method should mark the key that is being
1767
+ * retrieved as observed, and calling the add or delete method should notify the
1768
+ * reactives that the key which is being added or deleted has been modified.
1769
+ */
1770
+ const rawTypeToFuncHandlers = {
1771
+ Set: (target, callback) => ({
1772
+ has: makeKeyObserver("has", target, callback),
1773
+ add: delegateAndNotify("add", "has", target),
1774
+ delete: delegateAndNotify("delete", "has", target),
1775
+ keys: makeIteratorObserver("keys", target, callback),
1776
+ values: makeIteratorObserver("values", target, callback),
1777
+ entries: makeIteratorObserver("entries", target, callback),
1778
+ [Symbol.iterator]: makeIteratorObserver(Symbol.iterator, target, callback),
1779
+ forEach: makeForEachObserver(target, callback),
1780
+ clear: makeClearNotifier(target),
1781
+ get size() {
1782
+ observeTargetKey(target, KEYCHANGES, callback);
1783
+ return target.size;
1784
+ },
1785
+ }),
1786
+ Map: (target, callback) => ({
1787
+ has: makeKeyObserver("has", target, callback),
1788
+ get: makeKeyObserver("get", target, callback),
1789
+ set: delegateAndNotify("set", "get", target),
1790
+ delete: delegateAndNotify("delete", "has", target),
1791
+ keys: makeIteratorObserver("keys", target, callback),
1792
+ values: makeIteratorObserver("values", target, callback),
1793
+ entries: makeIteratorObserver("entries", target, callback),
1794
+ [Symbol.iterator]: makeIteratorObserver(Symbol.iterator, target, callback),
1795
+ forEach: makeForEachObserver(target, callback),
1796
+ clear: makeClearNotifier(target),
1797
+ get size() {
1798
+ observeTargetKey(target, KEYCHANGES, callback);
1799
+ return target.size;
1800
+ },
1801
+ }),
1802
+ WeakMap: (target, callback) => ({
1803
+ has: makeKeyObserver("has", target, callback),
1804
+ get: makeKeyObserver("get", target, callback),
1805
+ set: delegateAndNotify("set", "get", target),
1806
+ delete: delegateAndNotify("delete", "has", target),
1807
+ }),
1808
+ };
1809
+ /**
1810
+ * Creates a proxy handler for collections (Set/Map/WeakMap)
1811
+ *
1812
+ * @param callback @see reactive
1813
+ * @param target @see reactive
1814
+ * @returns a proxy handler object
1815
+ */
1816
+ function collectionsProxyHandler(target, callback, targetRawType) {
1817
+ // TODO: if performance is an issue we can create the special handlers lazily when each
1818
+ // property is read.
1819
+ const specialHandlers = rawTypeToFuncHandlers[targetRawType](target, callback);
1820
+ return Object.assign(basicProxyHandler(callback), {
1821
+ get(target, key) {
1822
+ if (key === TARGET) {
1823
+ return target;
1824
+ }
1825
+ if (objectHasOwnProperty.call(specialHandlers, key)) {
1826
+ return specialHandlers[key];
1827
+ }
1828
+ observeTargetKey(target, key, callback);
1829
+ return possiblyReactive(target[key], callback);
1830
+ },
1831
+ });
1434
1832
  }
1435
1833
 
1436
1834
  /**
@@ -1448,11 +1846,13 @@
1448
1846
  await Promise.resolve();
1449
1847
  if (!called) {
1450
1848
  called = true;
1451
- callback();
1452
1849
  // wait for all calls in this microtick to fall through before resetting "called"
1453
- // so that only the first call to the batched function calls the original callback
1454
- await Promise.resolve();
1455
- called = false;
1850
+ // so that only the first call to the batched function calls the original callback.
1851
+ // Schedule this before calling the callback so that calls to the batched function
1852
+ // within the callback will proceed only after resetting called to false, and have
1853
+ // a chance to execute the callback again
1854
+ Promise.resolve().then(() => (called = false));
1855
+ callback();
1456
1856
  }
1457
1857
  };
1458
1858
  }
@@ -1499,562 +1899,206 @@
1499
1899
  */
1500
1900
  function markup(value) {
1501
1901
  return new Markup(value);
1502
- }
1503
-
1504
- // Allows to get the target of a Reactive (used for making a new Reactive from the underlying object)
1505
- const TARGET = Symbol("Target");
1506
- // Escape hatch to prevent reactivity system to turn something into a reactive
1507
- const SKIP = Symbol("Skip");
1508
- // Special key to subscribe to, to be notified of key creation/deletion
1509
- const KEYCHANGES = Symbol("Key changes");
1510
- const objectToString = Object.prototype.toString;
1511
- /**
1512
- * Checks whether a given value can be made into a reactive object.
1513
- *
1514
- * @param value the value to check
1515
- * @returns whether the value can be made reactive
1516
- */
1517
- function canBeMadeReactive(value) {
1518
- if (typeof value !== "object") {
1519
- return false;
1520
- }
1521
- // extract "RawType" from strings like "[object RawType]" => this lets us
1522
- // ignore many native objects such as Promise (whose toString is [object Promise])
1523
- // or Date ([object Date]).
1524
- const rawType = objectToString.call(value).slice(8, -1);
1525
- return rawType === "Object" || rawType === "Array";
1526
- }
1527
- /**
1528
- * Mark an object or array so that it is ignored by the reactivity system
1529
- *
1530
- * @param value the value to mark
1531
- * @returns the object itself
1532
- */
1533
- function markRaw(value) {
1534
- value[SKIP] = true;
1535
- return value;
1536
1902
  }
1537
- /**
1538
- * Given a reactive objet, return the raw (non reactive) underlying object
1539
- *
1540
- * @param value a reactive value
1541
- * @returns the underlying value
1542
- */
1543
- function toRaw(value) {
1544
- return value[TARGET] || value;
1903
+ // -----------------------------------------------------------------------------
1904
+ // xml tag helper
1905
+ // -----------------------------------------------------------------------------
1906
+ const globalTemplates = {};
1907
+ function xml(...args) {
1908
+ const name = `__template__${xml.nextId++}`;
1909
+ const value = String.raw(...args);
1910
+ globalTemplates[name] = value;
1911
+ return name;
1545
1912
  }
1546
- const targetToKeysToCallbacks = new WeakMap();
1547
- /**
1548
- * Observes a given key on a target with an callback. The callback will be
1549
- * called when the given key changes on the target.
1550
- *
1551
- * @param target the target whose key should be observed
1552
- * @param key the key to observe (or Symbol(KEYCHANGES) for key creation
1553
- * or deletion)
1554
- * @param callback the function to call when the key changes
1555
- */
1556
- function observeTargetKey(target, key, callback) {
1557
- if (!targetToKeysToCallbacks.get(target)) {
1558
- targetToKeysToCallbacks.set(target, new Map());
1913
+ xml.nextId = 1;
1914
+
1915
+ // Maps fibers to thrown errors
1916
+ const fibersInError = new WeakMap();
1917
+ const nodeErrorHandlers = new WeakMap();
1918
+ function _handleError(node, error) {
1919
+ if (!node) {
1920
+ return false;
1559
1921
  }
1560
- const keyToCallbacks = targetToKeysToCallbacks.get(target);
1561
- if (!keyToCallbacks.get(key)) {
1562
- keyToCallbacks.set(key, new Set());
1922
+ const fiber = node.fiber;
1923
+ if (fiber) {
1924
+ fibersInError.set(fiber, error);
1563
1925
  }
1564
- keyToCallbacks.get(key).add(callback);
1565
- if (!callbacksToTargets.has(callback)) {
1566
- callbacksToTargets.set(callback, new Set());
1926
+ const errorHandlers = nodeErrorHandlers.get(node);
1927
+ if (errorHandlers) {
1928
+ let handled = false;
1929
+ // execute in the opposite order
1930
+ for (let i = errorHandlers.length - 1; i >= 0; i--) {
1931
+ try {
1932
+ errorHandlers[i](error);
1933
+ handled = true;
1934
+ break;
1935
+ }
1936
+ catch (e) {
1937
+ error = e;
1938
+ }
1939
+ }
1940
+ if (handled) {
1941
+ return true;
1942
+ }
1567
1943
  }
1568
- callbacksToTargets.get(callback).add(target);
1944
+ return _handleError(node.parent, error);
1569
1945
  }
1570
- /**
1571
- * Notify Reactives that are observing a given target that a key has changed on
1572
- * the target.
1573
- *
1574
- * @param target target whose Reactives should be notified that the target was
1575
- * changed.
1576
- * @param key the key that changed (or Symbol `KEYCHANGES` if a key was created
1577
- * or deleted)
1578
- */
1579
- function notifyReactives(target, key) {
1580
- const keyToCallbacks = targetToKeysToCallbacks.get(target);
1581
- if (!keyToCallbacks) {
1582
- return;
1583
- }
1584
- const callbacks = keyToCallbacks.get(key);
1585
- if (!callbacks) {
1586
- return;
1946
+ function handleError(params) {
1947
+ const error = params.error;
1948
+ const node = "node" in params ? params.node : params.fiber.node;
1949
+ const fiber = "fiber" in params ? params.fiber : node.fiber;
1950
+ // resets the fibers on components if possible. This is important so that
1951
+ // new renderings can be properly included in the initial one, if any.
1952
+ let current = fiber;
1953
+ do {
1954
+ current.node.fiber = current;
1955
+ current = current.parent;
1956
+ } while (current);
1957
+ fibersInError.set(fiber.root, error);
1958
+ const handled = _handleError(node, error);
1959
+ if (!handled) {
1960
+ console.warn(`[Owl] Unhandled error. Destroying the root component`);
1961
+ try {
1962
+ node.app.destroy();
1963
+ }
1964
+ catch (e) {
1965
+ console.error(e);
1966
+ }
1587
1967
  }
1588
- // Loop on copy because clearReactivesForCallback will modify the set in place
1589
- for (const callback of [...callbacks]) {
1590
- clearReactivesForCallback(callback);
1591
- callback();
1968
+ }
1969
+
1970
+ function makeChildFiber(node, parent) {
1971
+ let current = node.fiber;
1972
+ if (current) {
1973
+ cancelFibers(current.children);
1974
+ current.root = null;
1592
1975
  }
1976
+ return new Fiber(node, parent);
1593
1977
  }
1594
- const callbacksToTargets = new WeakMap();
1595
- /**
1596
- * Clears all subscriptions of the Reactives associated with a given callback.
1597
- *
1598
- * @param callback the callback for which the reactives need to be cleared
1599
- */
1600
- function clearReactivesForCallback(callback) {
1601
- const targetsToClear = callbacksToTargets.get(callback);
1602
- if (!targetsToClear) {
1603
- return;
1604
- }
1605
- for (const target of targetsToClear) {
1606
- const observedKeys = targetToKeysToCallbacks.get(target);
1607
- if (!observedKeys) {
1608
- continue;
1609
- }
1610
- for (const callbacks of observedKeys.values()) {
1611
- callbacks.delete(callback);
1978
+ function makeRootFiber(node) {
1979
+ let current = node.fiber;
1980
+ if (current) {
1981
+ let root = current.root;
1982
+ // lock root fiber because canceling children fibers may destroy components,
1983
+ // which means any arbitrary code can be run in onWillDestroy, which may
1984
+ // trigger new renderings
1985
+ root.locked = true;
1986
+ root.setCounter(root.counter + 1 - cancelFibers(current.children));
1987
+ root.locked = false;
1988
+ current.children = [];
1989
+ current.childrenMap = {};
1990
+ current.bdom = null;
1991
+ if (fibersInError.has(current)) {
1992
+ fibersInError.delete(current);
1993
+ fibersInError.delete(root);
1994
+ current.appliedToDom = false;
1612
1995
  }
1996
+ return current;
1613
1997
  }
1614
- targetsToClear.clear();
1615
- }
1616
- const reactiveCache = new WeakMap();
1617
- /**
1618
- * Creates a reactive proxy for an object. Reading data on the reactive object
1619
- * subscribes to changes to the data. Writing data on the object will cause the
1620
- * notify callback to be called if there are suscriptions to that data. Nested
1621
- * objects and arrays are automatically made reactive as well.
1622
- *
1623
- * Whenever you are notified of a change, all subscriptions are cleared, and if
1624
- * you would like to be notified of any further changes, you should go read
1625
- * the underlying data again. We assume that if you don't go read it again after
1626
- * being notified, it means that you are no longer interested in that data.
1627
- *
1628
- * Subscriptions:
1629
- * + Reading a property on an object will subscribe you to changes in the value
1630
- * of that property.
1631
- * + Accessing an object keys (eg with Object.keys or with `for..in`) will
1632
- * subscribe you to the creation/deletion of keys. Checking the presence of a
1633
- * key on the object with 'in' has the same effect.
1634
- * - getOwnPropertyDescriptor does not currently subscribe you to the property.
1635
- * This is a choice that was made because changing a key's value will trigger
1636
- * this trap and we do not want to subscribe by writes. This also means that
1637
- * Object.hasOwnProperty doesn't subscribe as it goes through this trap.
1638
- *
1639
- * @param target the object for which to create a reactive proxy
1640
- * @param callback the function to call when an observed property of the
1641
- * reactive has changed
1642
- * @returns a proxy that tracks changes to it
1643
- */
1644
- function reactive(target, callback = () => { }) {
1645
- if (!canBeMadeReactive(target)) {
1646
- throw new Error(`Cannot make the given value reactive`);
1647
- }
1648
- if (SKIP in target) {
1649
- return target;
1650
- }
1651
- const originalTarget = target[TARGET];
1652
- if (originalTarget) {
1653
- return reactive(originalTarget, callback);
1654
- }
1655
- if (!reactiveCache.has(target)) {
1656
- reactiveCache.set(target, new Map());
1998
+ const fiber = new RootFiber(node, null);
1999
+ if (node.willPatch.length) {
2000
+ fiber.willPatch.push(fiber);
1657
2001
  }
1658
- const reactivesForTarget = reactiveCache.get(target);
1659
- if (!reactivesForTarget.has(callback)) {
1660
- const proxy = new Proxy(target, {
1661
- get(target, key, proxy) {
1662
- if (key === TARGET) {
1663
- return target;
1664
- }
1665
- observeTargetKey(target, key, callback);
1666
- const value = Reflect.get(target, key, proxy);
1667
- if (!canBeMadeReactive(value)) {
1668
- return value;
1669
- }
1670
- return reactive(value, callback);
1671
- },
1672
- set(target, key, value, proxy) {
1673
- const isNewKey = !Object.hasOwnProperty.call(target, key);
1674
- const originalValue = Reflect.get(target, key, proxy);
1675
- const ret = Reflect.set(target, key, value, proxy);
1676
- if (isNewKey) {
1677
- notifyReactives(target, KEYCHANGES);
1678
- }
1679
- // While Array length may trigger the set trap, it's not actually set by this
1680
- // method but is updated behind the scenes, and the trap is not called with the
1681
- // new value. We disable the "same-value-optimization" for it because of that.
1682
- if (originalValue !== value || (Array.isArray(target) && key === "length")) {
1683
- notifyReactives(target, key);
1684
- }
1685
- return ret;
1686
- },
1687
- deleteProperty(target, key) {
1688
- const ret = Reflect.deleteProperty(target, key);
1689
- notifyReactives(target, KEYCHANGES);
1690
- notifyReactives(target, key);
1691
- return ret;
1692
- },
1693
- ownKeys(target) {
1694
- observeTargetKey(target, KEYCHANGES, callback);
1695
- return Reflect.ownKeys(target);
1696
- },
1697
- has(target, key) {
1698
- // TODO: this observes all key changes instead of only the presence of the argument key
1699
- observeTargetKey(target, KEYCHANGES, callback);
1700
- return Reflect.has(target, key);
1701
- },
1702
- });
1703
- reactivesForTarget.set(callback, proxy);
2002
+ if (node.patched.length) {
2003
+ fiber.patched.push(fiber);
1704
2004
  }
1705
- return reactivesForTarget.get(callback);
1706
- }
1707
-
2005
+ return fiber;
2006
+ }
1708
2007
  /**
1709
- * This file contains utility functions that will be injected in each template,
1710
- * to perform various useful tasks in the compiled code.
2008
+ * @returns number of not-yet rendered fibers cancelled
1711
2009
  */
1712
- function withDefault(value, defaultValue) {
1713
- return value === undefined || value === null || value === false ? defaultValue : value;
1714
- }
1715
- function callSlot(ctx, parent, key, name, dynamic, extra, defaultContent) {
1716
- key = key + "__slot_" + name;
1717
- const slots = ctx.props[TARGET].slots || {};
1718
- const { __render, __ctx, __scope } = slots[name] || {};
1719
- const slotScope = Object.create(__ctx || {});
1720
- if (__scope) {
1721
- slotScope[__scope] = extra || {};
1722
- }
1723
- const slotBDom = __render ? __render.call(__ctx.__owl__.component, slotScope, parent, key) : null;
1724
- if (defaultContent) {
1725
- let child1 = undefined;
1726
- let child2 = undefined;
1727
- if (slotBDom) {
1728
- child1 = dynamic ? toggler(name, slotBDom) : slotBDom;
2010
+ function cancelFibers(fibers) {
2011
+ let result = 0;
2012
+ for (let fiber of fibers) {
2013
+ let node = fiber.node;
2014
+ if (node.status === 0 /* NEW */) {
2015
+ node.destroy();
2016
+ }
2017
+ node.fiber = null;
2018
+ if (fiber.bdom) {
2019
+ // if fiber has been rendered, this means that the component props have
2020
+ // been updated. however, this fiber will not be patched to the dom, so
2021
+ // it could happen that the next render compare the current props with
2022
+ // the same props, and skip the render completely. With the next line,
2023
+ // we kindly request the component code to force a render, so it works as
2024
+ // expected.
2025
+ node.forceNextRender = true;
1729
2026
  }
1730
2027
  else {
1731
- child2 = defaultContent.call(ctx.__owl__.component, ctx, parent, key);
2028
+ result++;
1732
2029
  }
1733
- return multi([child1, child2]);
1734
- }
1735
- return slotBDom || text("");
1736
- }
1737
- function capture(ctx) {
1738
- const component = ctx.__owl__.component;
1739
- const result = Object.create(component);
1740
- for (let k in ctx) {
1741
- result[k] = ctx[k];
2030
+ result += cancelFibers(fiber.children);
1742
2031
  }
1743
2032
  return result;
1744
2033
  }
1745
- function withKey(elem, k) {
1746
- elem.key = k;
1747
- return elem;
1748
- }
1749
- function prepareList(collection) {
1750
- let keys;
1751
- let values;
1752
- if (Array.isArray(collection)) {
1753
- keys = collection;
1754
- values = collection;
1755
- }
1756
- else if (collection) {
1757
- values = Object.keys(collection);
1758
- keys = Object.values(collection);
1759
- }
1760
- else {
1761
- throw new Error("Invalid loop expression");
1762
- }
1763
- const n = values.length;
1764
- return [keys, values, n, new Array(n)];
1765
- }
1766
- const isBoundary = Symbol("isBoundary");
1767
- function setContextValue(ctx, key, value) {
1768
- const ctx0 = ctx;
1769
- while (!ctx.hasOwnProperty(key) && !ctx.hasOwnProperty(isBoundary)) {
1770
- const newCtx = ctx.__proto__;
1771
- if (!newCtx) {
1772
- ctx = ctx0;
1773
- break;
2034
+ class Fiber {
2035
+ constructor(node, parent) {
2036
+ this.bdom = null;
2037
+ this.children = [];
2038
+ this.appliedToDom = false;
2039
+ this.deep = false;
2040
+ this.childrenMap = {};
2041
+ this.node = node;
2042
+ this.parent = parent;
2043
+ if (parent) {
2044
+ this.deep = parent.deep;
2045
+ const root = parent.root;
2046
+ root.setCounter(root.counter + 1);
2047
+ this.root = root;
2048
+ parent.children.push(this);
1774
2049
  }
1775
- ctx = newCtx;
1776
- }
1777
- ctx[key] = value;
1778
- }
1779
- function toNumber(val) {
1780
- const n = parseFloat(val);
1781
- return isNaN(n) ? val : n;
1782
- }
1783
- function shallowEqual$1(l1, l2) {
1784
- for (let i = 0, l = l1.length; i < l; i++) {
1785
- if (l1[i] !== l2[i]) {
1786
- return false;
2050
+ else {
2051
+ this.root = this;
1787
2052
  }
1788
2053
  }
1789
- return true;
1790
- }
1791
- class LazyValue {
1792
- constructor(fn, ctx, node) {
1793
- this.fn = fn;
1794
- this.ctx = capture(ctx);
1795
- this.node = node;
1796
- }
1797
- evaluate() {
1798
- return this.fn(this.ctx, this.node);
2054
+ render() {
2055
+ // if some parent has a fiber => register in followup
2056
+ let prev = this.root.node;
2057
+ let scheduler = prev.app.scheduler;
2058
+ let current = prev.parent;
2059
+ while (current) {
2060
+ if (current.fiber) {
2061
+ let root = current.fiber.root;
2062
+ if (root.counter === 0 && prev.parentKey in current.fiber.childrenMap) {
2063
+ current = root.node;
2064
+ }
2065
+ else {
2066
+ scheduler.delayedRenders.push(this);
2067
+ return;
2068
+ }
2069
+ }
2070
+ prev = current;
2071
+ current = current.parent;
2072
+ }
2073
+ // there are no current rendering from above => we can render
2074
+ this._render();
1799
2075
  }
1800
- toString() {
1801
- return this.evaluate().toString();
2076
+ _render() {
2077
+ const node = this.node;
2078
+ const root = this.root;
2079
+ if (root) {
2080
+ try {
2081
+ this.bdom = true;
2082
+ this.bdom = node.renderFn();
2083
+ }
2084
+ catch (e) {
2085
+ handleError({ node, error: e });
2086
+ }
2087
+ root.setCounter(root.counter - 1);
2088
+ }
1802
2089
  }
1803
2090
  }
1804
- /*
1805
- * Safely outputs `value` as a block depending on the nature of `value`
1806
- */
1807
- function safeOutput(value) {
1808
- if (!value) {
1809
- return value;
1810
- }
1811
- let safeKey;
1812
- let block;
1813
- if (value instanceof Markup) {
1814
- safeKey = `string_safe`;
1815
- block = html(value);
1816
- }
1817
- else if (value instanceof LazyValue) {
1818
- safeKey = `lazy_value`;
1819
- block = value.evaluate();
1820
- }
1821
- else if (value instanceof String || typeof value === "string") {
1822
- safeKey = "string_unsafe";
1823
- block = text(value);
1824
- }
1825
- else {
1826
- // Assuming it is a block
1827
- safeKey = "block_safe";
1828
- block = value;
1829
- }
1830
- return toggler(safeKey, block);
1831
- }
1832
- let boundFunctions = new WeakMap();
1833
- function bind(ctx, fn) {
1834
- let component = ctx.__owl__.component;
1835
- let boundFnMap = boundFunctions.get(component);
1836
- if (!boundFnMap) {
1837
- boundFnMap = new WeakMap();
1838
- boundFunctions.set(component, boundFnMap);
1839
- }
1840
- let boundFn = boundFnMap.get(fn);
1841
- if (!boundFn) {
1842
- boundFn = fn.bind(component);
1843
- boundFnMap.set(fn, boundFn);
1844
- }
1845
- return boundFn;
1846
- }
1847
- function multiRefSetter(refs, name) {
1848
- let count = 0;
1849
- return (el) => {
1850
- if (el) {
1851
- count++;
1852
- if (count > 1) {
1853
- throw new Error("Cannot have 2 elements with same ref name at the same time");
1854
- }
1855
- }
1856
- if (count === 0 || el) {
1857
- refs[name] = el;
1858
- }
1859
- };
1860
- }
1861
- const UTILS = {
1862
- withDefault,
1863
- zero: Symbol("zero"),
1864
- isBoundary,
1865
- callSlot,
1866
- capture,
1867
- withKey,
1868
- prepareList,
1869
- setContextValue,
1870
- multiRefSetter,
1871
- shallowEqual: shallowEqual$1,
1872
- toNumber,
1873
- validateProps,
1874
- LazyValue,
1875
- safeOutput,
1876
- bind,
1877
- };
1878
-
1879
- const mainEventHandler = (data, ev, currentTarget) => {
1880
- const { data: _data, modifiers } = filterOutModifiersFromData(data);
1881
- data = _data;
1882
- let stopped = false;
1883
- if (modifiers.length) {
1884
- let selfMode = false;
1885
- const isSelf = ev.target === currentTarget;
1886
- for (const mod of modifiers) {
1887
- switch (mod) {
1888
- case "self":
1889
- selfMode = true;
1890
- if (isSelf) {
1891
- continue;
1892
- }
1893
- else {
1894
- return stopped;
1895
- }
1896
- case "prevent":
1897
- if ((selfMode && isSelf) || !selfMode)
1898
- ev.preventDefault();
1899
- continue;
1900
- case "stop":
1901
- if ((selfMode && isSelf) || !selfMode)
1902
- ev.stopPropagation();
1903
- stopped = true;
1904
- continue;
1905
- }
1906
- }
1907
- }
1908
- // If handler is empty, the array slot 0 will also be empty, and data will not have the property 0
1909
- // We check this rather than data[0] being truthy (or typeof function) so that it crashes
1910
- // as expected when there is a handler expression that evaluates to a falsy value
1911
- if (Object.hasOwnProperty.call(data, 0)) {
1912
- const handler = data[0];
1913
- if (typeof handler !== "function") {
1914
- throw new Error(`Invalid handler (expected a function, received: '${handler}')`);
1915
- }
1916
- let node = data[1] ? data[1].__owl__ : null;
1917
- if (node ? node.status === 1 /* MOUNTED */ : true) {
1918
- handler.call(node ? node.component : null, ev);
1919
- }
1920
- }
1921
- return stopped;
1922
- };
1923
-
1924
- // Maps fibers to thrown errors
1925
- const fibersInError = new WeakMap();
1926
- const nodeErrorHandlers = new WeakMap();
1927
- function _handleError(node, error, isFirstRound = false) {
1928
- if (!node) {
1929
- return false;
1930
- }
1931
- const fiber = node.fiber;
1932
- if (fiber) {
1933
- fibersInError.set(fiber, error);
1934
- }
1935
- const errorHandlers = nodeErrorHandlers.get(node);
1936
- if (errorHandlers) {
1937
- let stopped = false;
1938
- // execute in the opposite order
1939
- for (let i = errorHandlers.length - 1; i >= 0; i--) {
1940
- try {
1941
- errorHandlers[i](error);
1942
- stopped = true;
1943
- break;
1944
- }
1945
- catch (e) {
1946
- error = e;
1947
- }
1948
- }
1949
- if (stopped) {
1950
- if (isFirstRound && fiber && fiber.node.fiber) {
1951
- fiber.root.counter--;
1952
- }
1953
- return true;
1954
- }
1955
- }
1956
- return _handleError(node.parent, error);
1957
- }
1958
- function handleError(params) {
1959
- const error = params.error;
1960
- const node = "node" in params ? params.node : params.fiber.node;
1961
- const fiber = "fiber" in params ? params.fiber : node.fiber;
1962
- // resets the fibers on components if possible. This is important so that
1963
- // new renderings can be properly included in the initial one, if any.
1964
- let current = fiber;
1965
- do {
1966
- current.node.fiber = current;
1967
- current = current.parent;
1968
- } while (current);
1969
- fibersInError.set(fiber.root, error);
1970
- const handled = _handleError(node, error, true);
1971
- if (!handled) {
1972
- console.warn(`[Owl] Unhandled error. Destroying the root component`);
1973
- try {
1974
- node.app.destroy();
1975
- }
1976
- catch (e) {
1977
- console.error(e);
1978
- }
1979
- }
1980
- }
1981
-
1982
- function makeChildFiber(node, parent) {
1983
- let current = node.fiber;
1984
- if (current) {
1985
- cancelFibers(current.children);
1986
- current.root = null;
1987
- }
1988
- return new Fiber(node, parent);
1989
- }
1990
- function makeRootFiber(node) {
1991
- let current = node.fiber;
1992
- if (current) {
1993
- let root = current.root;
1994
- root.counter = root.counter + 1 - cancelFibers(current.children);
1995
- current.children = [];
1996
- current.bdom = null;
1997
- if (fibersInError.has(current)) {
1998
- fibersInError.delete(current);
1999
- fibersInError.delete(root);
2000
- current.appliedToDom = false;
2001
- }
2002
- return current;
2003
- }
2004
- const fiber = new RootFiber(node, null);
2005
- if (node.willPatch.length) {
2006
- fiber.willPatch.push(fiber);
2007
- }
2008
- if (node.patched.length) {
2009
- fiber.patched.push(fiber);
2010
- }
2011
- return fiber;
2012
- }
2013
- /**
2014
- * @returns number of not-yet rendered fibers cancelled
2015
- */
2016
- function cancelFibers(fibers) {
2017
- let result = 0;
2018
- for (let fiber of fibers) {
2019
- fiber.node.fiber = null;
2020
- if (!fiber.bdom) {
2021
- result++;
2022
- }
2023
- result += cancelFibers(fiber.children);
2024
- }
2025
- return result;
2026
- }
2027
- class Fiber {
2028
- constructor(node, parent) {
2029
- this.bdom = null;
2030
- this.children = [];
2031
- this.appliedToDom = false;
2032
- this.deep = false;
2033
- this.node = node;
2034
- this.parent = parent;
2035
- if (parent) {
2036
- this.deep = parent.deep;
2037
- const root = parent.root;
2038
- root.counter++;
2039
- this.root = root;
2040
- parent.children.push(this);
2041
- }
2042
- else {
2043
- this.root = this;
2044
- }
2045
- }
2046
- }
2047
- class RootFiber extends Fiber {
2048
- constructor() {
2049
- super(...arguments);
2050
- this.counter = 1;
2051
- // only add stuff in this if they have registered some hooks
2052
- this.willPatch = [];
2053
- this.patched = [];
2054
- this.mounted = [];
2055
- // A fiber is typically locked when it is completing and the patch has not, or is being applied.
2056
- // i.e.: render triggered in onWillUnmount or in willPatch will be delayed
2057
- this.locked = false;
2091
+ class RootFiber extends Fiber {
2092
+ constructor() {
2093
+ super(...arguments);
2094
+ this.counter = 1;
2095
+ // only add stuff in this if they have registered some hooks
2096
+ this.willPatch = [];
2097
+ this.patched = [];
2098
+ this.mounted = [];
2099
+ // A fiber is typically locked when it is completing and the patch has not, or is being applied.
2100
+ // i.e.: render triggered in onWillUnmount or in willPatch will be delayed
2101
+ this.locked = false;
2058
2102
  }
2059
2103
  complete() {
2060
2104
  const node = this.node;
@@ -2104,6 +2148,12 @@
2104
2148
  handleError({ fiber: current || this, error: e });
2105
2149
  }
2106
2150
  }
2151
+ setCounter(newValue) {
2152
+ this.counter = newValue;
2153
+ if (newValue === 0) {
2154
+ this.node.app.scheduler.flush();
2155
+ }
2156
+ }
2107
2157
  }
2108
2158
  class MountFiber extends RootFiber {
2109
2159
  constructor(node, target, options = {}) {
@@ -2115,6 +2165,7 @@
2115
2165
  let current = this;
2116
2166
  try {
2117
2167
  const node = this.node;
2168
+ node.children = this.childrenMap;
2118
2169
  node.app.constructor.validateTarget(this.target);
2119
2170
  if (node.bdom) {
2120
2171
  // this is a complicated situation: if we mount a fiber with an existing
@@ -2153,23 +2204,162 @@
2153
2204
  }
2154
2205
  }
2155
2206
 
2156
- let currentNode = null;
2157
- function getCurrent() {
2158
- if (!currentNode) {
2159
- throw new Error("No active component (a hook function should only be called in 'setup')");
2207
+ /**
2208
+ * Apply default props (only top level).
2209
+ *
2210
+ * Note that this method does modify in place the props
2211
+ */
2212
+ function applyDefaultProps(props, ComponentClass) {
2213
+ const defaultProps = ComponentClass.defaultProps;
2214
+ if (defaultProps) {
2215
+ for (let propName in defaultProps) {
2216
+ if (props[propName] === undefined) {
2217
+ props[propName] = defaultProps[propName];
2218
+ }
2219
+ }
2160
2220
  }
2161
- return currentNode;
2162
2221
  }
2163
- function useComponent() {
2164
- return currentNode.component;
2222
+ //------------------------------------------------------------------------------
2223
+ // Prop validation helper
2224
+ //------------------------------------------------------------------------------
2225
+ function getPropDescription(staticProps) {
2226
+ if (staticProps instanceof Array) {
2227
+ return Object.fromEntries(staticProps.map((p) => (p.endsWith("?") ? [p.slice(0, -1), false] : [p, true])));
2228
+ }
2229
+ return staticProps || { "*": true };
2165
2230
  }
2166
- // -----------------------------------------------------------------------------
2167
- // Integration with reactivity system (useState)
2168
- // -----------------------------------------------------------------------------
2169
- const batchedRenderFunctions = new WeakMap();
2170
2231
  /**
2171
- * Creates a reactive object that will be observed by the current component.
2172
- * Reading data from the returned object (eg during rendering) will cause the
2232
+ * Validate the component props (or next props) against the (static) props
2233
+ * description. This is potentially an expensive operation: it may needs to
2234
+ * visit recursively the props and all the children to check if they are valid.
2235
+ * This is why it is only done in 'dev' mode.
2236
+ */
2237
+ function validateProps(name, props, parent) {
2238
+ const ComponentClass = typeof name !== "string"
2239
+ ? name
2240
+ : parent.constructor.components[name];
2241
+ if (!ComponentClass) {
2242
+ // this is an error, wrong component. We silently return here instead so the
2243
+ // error is triggered by the usual path ('component' function)
2244
+ return;
2245
+ }
2246
+ applyDefaultProps(props, ComponentClass);
2247
+ const defaultProps = ComponentClass.defaultProps || {};
2248
+ let propsDef = getPropDescription(ComponentClass.props);
2249
+ const allowAdditionalProps = "*" in propsDef;
2250
+ for (let propName in propsDef) {
2251
+ if (propName === "*") {
2252
+ continue;
2253
+ }
2254
+ const propDef = propsDef[propName];
2255
+ let isMandatory = !!propDef;
2256
+ if (typeof propDef === "object" && "optional" in propDef) {
2257
+ isMandatory = !propDef.optional;
2258
+ }
2259
+ if (isMandatory && propName in defaultProps) {
2260
+ throw new Error(`A default value cannot be defined for a mandatory prop (name: '${propName}', component: ${ComponentClass.name})`);
2261
+ }
2262
+ if (props[propName] === undefined) {
2263
+ if (isMandatory) {
2264
+ throw new Error(`Missing props '${propName}' (component '${ComponentClass.name}')`);
2265
+ }
2266
+ else {
2267
+ continue;
2268
+ }
2269
+ }
2270
+ let isValid;
2271
+ try {
2272
+ isValid = isValidProp(props[propName], propDef);
2273
+ }
2274
+ catch (e) {
2275
+ e.message = `Invalid prop '${propName}' in component ${ComponentClass.name} (${e.message})`;
2276
+ throw e;
2277
+ }
2278
+ if (!isValid) {
2279
+ throw new Error(`Invalid Prop '${propName}' in component '${ComponentClass.name}'`);
2280
+ }
2281
+ }
2282
+ if (!allowAdditionalProps) {
2283
+ for (let propName in props) {
2284
+ if (!(propName in propsDef)) {
2285
+ throw new Error(`Unknown prop '${propName}' given to component '${ComponentClass.name}'`);
2286
+ }
2287
+ }
2288
+ }
2289
+ }
2290
+ /**
2291
+ * Check if an invidual prop value matches its (static) prop definition
2292
+ */
2293
+ function isValidProp(prop, propDef) {
2294
+ if (propDef === true) {
2295
+ return true;
2296
+ }
2297
+ if (typeof propDef === "function") {
2298
+ // Check if a value is constructed by some Constructor. Note that there is a
2299
+ // slight abuse of language: we want to consider primitive values as well.
2300
+ //
2301
+ // So, even though 1 is not an instance of Number, we want to consider that
2302
+ // it is valid.
2303
+ if (typeof prop === "object") {
2304
+ return prop instanceof propDef;
2305
+ }
2306
+ return typeof prop === propDef.name.toLowerCase();
2307
+ }
2308
+ else if (propDef instanceof Array) {
2309
+ // If this code is executed, this means that we want to check if a prop
2310
+ // matches at least one of its descriptor.
2311
+ let result = false;
2312
+ for (let i = 0, iLen = propDef.length; i < iLen; i++) {
2313
+ result = result || isValidProp(prop, propDef[i]);
2314
+ }
2315
+ return result;
2316
+ }
2317
+ // propsDef is an object
2318
+ if (propDef.optional && prop === undefined) {
2319
+ return true;
2320
+ }
2321
+ let result = propDef.type ? isValidProp(prop, propDef.type) : true;
2322
+ if (propDef.validate) {
2323
+ result = result && propDef.validate(prop);
2324
+ }
2325
+ if (propDef.type === Array && propDef.element) {
2326
+ for (let i = 0, iLen = prop.length; i < iLen; i++) {
2327
+ result = result && isValidProp(prop[i], propDef.element);
2328
+ }
2329
+ }
2330
+ if (propDef.type === Object && propDef.shape) {
2331
+ const shape = propDef.shape;
2332
+ for (let key in shape) {
2333
+ result = result && isValidProp(prop[key], shape[key]);
2334
+ }
2335
+ if (result) {
2336
+ for (let propName in prop) {
2337
+ if (!(propName in shape)) {
2338
+ throw new Error(`unknown prop '${propName}'`);
2339
+ }
2340
+ }
2341
+ }
2342
+ }
2343
+ return result;
2344
+ }
2345
+
2346
+ let currentNode = null;
2347
+ function getCurrent() {
2348
+ if (!currentNode) {
2349
+ throw new Error("No active component (a hook function should only be called in 'setup')");
2350
+ }
2351
+ return currentNode;
2352
+ }
2353
+ function useComponent() {
2354
+ return currentNode.component;
2355
+ }
2356
+ // -----------------------------------------------------------------------------
2357
+ // Integration with reactivity system (useState)
2358
+ // -----------------------------------------------------------------------------
2359
+ const batchedRenderFunctions = new WeakMap();
2360
+ /**
2361
+ * Creates a reactive object that will be observed by the current component.
2362
+ * Reading data from the returned object (eg during rendering) will cause the
2173
2363
  * component to subscribe to that data and be rerendered when it changes.
2174
2364
  *
2175
2365
  * @param state the state to observe
@@ -2181,7 +2371,7 @@
2181
2371
  const node = getCurrent();
2182
2372
  let render = batchedRenderFunctions.get(node);
2183
2373
  if (!render) {
2184
- render = batched(node.render.bind(node));
2374
+ render = batched(node.render.bind(node, false));
2185
2375
  batchedRenderFunctions.set(node, render);
2186
2376
  // manual implementation of onWillDestroy to break cyclic dependency
2187
2377
  node.willDestroy.push(clearReactivesForCallback.bind(null, render));
@@ -2199,22 +2389,23 @@
2199
2389
  function component(name, props, key, ctx, parent) {
2200
2390
  let node = ctx.children[key];
2201
2391
  let isDynamic = typeof name !== "string";
2202
- if (node) {
2203
- if (node.status < 1 /* MOUNTED */) {
2204
- node.destroy();
2205
- node = undefined;
2206
- }
2207
- else if (node.status === 2 /* DESTROYED */) {
2208
- node = undefined;
2209
- }
2392
+ if (node && node.status === 2 /* DESTROYED */) {
2393
+ node = undefined;
2210
2394
  }
2211
2395
  if (isDynamic && node && node.component.constructor !== name) {
2212
2396
  node = undefined;
2213
2397
  }
2214
2398
  const parentFiber = ctx.fiber;
2215
2399
  if (node) {
2216
- const currentProps = node.component.props[TARGET];
2217
- if (parentFiber.deep || arePropsDifferent(currentProps, props)) {
2400
+ let shouldRender = node.forceNextRender;
2401
+ if (shouldRender) {
2402
+ node.forceNextRender = false;
2403
+ }
2404
+ else {
2405
+ const currentProps = node.component.props[TARGET];
2406
+ shouldRender = parentFiber.deep || arePropsDifferent(currentProps, props);
2407
+ }
2408
+ if (shouldRender) {
2218
2409
  node.updateAndRender(props, parentFiber);
2219
2410
  }
2220
2411
  }
@@ -2230,17 +2421,19 @@
2230
2421
  throw new Error(`Cannot find the definition of component "${name}"`);
2231
2422
  }
2232
2423
  }
2233
- node = new ComponentNode(C, props, ctx.app, ctx);
2424
+ node = new ComponentNode(C, props, ctx.app, ctx, key);
2234
2425
  ctx.children[key] = node;
2235
2426
  node.initiateRender(new Fiber(node, parentFiber));
2236
2427
  }
2428
+ parentFiber.childrenMap[key] = node;
2237
2429
  return node;
2238
2430
  }
2239
2431
  class ComponentNode {
2240
- constructor(C, props, app, parent) {
2432
+ constructor(C, props, app, parent, parentKey) {
2241
2433
  this.fiber = null;
2242
2434
  this.bdom = null;
2243
2435
  this.status = 0 /* NEW */;
2436
+ this.forceNextRender = false;
2244
2437
  this.children = Object.create(null);
2245
2438
  this.refs = {};
2246
2439
  this.willStart = [];
@@ -2252,7 +2445,8 @@
2252
2445
  this.willDestroy = [];
2253
2446
  currentNode = this;
2254
2447
  this.app = app;
2255
- this.parent = parent || null;
2448
+ this.parent = parent;
2449
+ this.parentKey = parentKey;
2256
2450
  this.level = parent ? parent.level + 1 : 0;
2257
2451
  applyDefaultProps(props, C);
2258
2452
  const env = (parent && parent.childEnv) || app.env;
@@ -2282,12 +2476,12 @@
2282
2476
  return;
2283
2477
  }
2284
2478
  if (this.status === 0 /* NEW */ && this.fiber === fiber) {
2285
- this._render(fiber);
2479
+ fiber.render();
2286
2480
  }
2287
2481
  }
2288
- async render(deep = false) {
2482
+ async render(deep) {
2289
2483
  let current = this.fiber;
2290
- if (current && current.root.locked) {
2484
+ if (current && (current.root.locked || current.bdom === true)) {
2291
2485
  await Promise.resolve();
2292
2486
  // situation may have changed after the microtask tick
2293
2487
  current = this.fiber;
@@ -2326,16 +2520,7 @@
2326
2520
  // embedded in a rendering coming from above, so the fiber will be rendered
2327
2521
  // in the next microtick anyway, so we should not render it again.
2328
2522
  if (this.fiber === fiber && (current || !fiber.parent)) {
2329
- this._render(fiber);
2330
- }
2331
- }
2332
- _render(fiber) {
2333
- try {
2334
- fiber.bdom = this.renderFn();
2335
- fiber.root.counter--;
2336
- }
2337
- catch (e) {
2338
- handleError({ node: this, error: e });
2523
+ fiber.render();
2339
2524
  }
2340
2525
  }
2341
2526
  destroy() {
@@ -2355,8 +2540,15 @@
2355
2540
  for (let child of Object.values(this.children)) {
2356
2541
  child._destroy();
2357
2542
  }
2358
- for (let cb of this.willDestroy) {
2359
- cb.call(component);
2543
+ if (this.willDestroy.length) {
2544
+ try {
2545
+ for (let cb of this.willDestroy) {
2546
+ cb.call(component);
2547
+ }
2548
+ }
2549
+ catch (e) {
2550
+ handleError({ error: e, node: this });
2551
+ }
2360
2552
  }
2361
2553
  this.status = 2 /* DESTROYED */;
2362
2554
  }
@@ -2375,7 +2567,7 @@
2375
2567
  return;
2376
2568
  }
2377
2569
  component.props = props;
2378
- this._render(fiber);
2570
+ fiber.render();
2379
2571
  const parentRoot = parentFiber.root;
2380
2572
  if (this.willPatch.length) {
2381
2573
  parentRoot.willPatch.push(fiber);
@@ -2422,6 +2614,7 @@
2422
2614
  bdom.mount(parent, anchor);
2423
2615
  this.status = 1 /* MOUNTED */;
2424
2616
  this.fiber.appliedToDom = true;
2617
+ this.children = this.fiber.childrenMap;
2425
2618
  this.fiber = null;
2426
2619
  }
2427
2620
  moveBefore(other, afterNode) {
@@ -2437,10 +2630,8 @@
2437
2630
  }
2438
2631
  _patch() {
2439
2632
  const hasChildren = Object.keys(this.children).length > 0;
2633
+ this.children = this.fiber.childrenMap;
2440
2634
  this.bdom.patch(this.fiber.bdom, hasChildren);
2441
- if (hasChildren) {
2442
- this.cleanOutdatedChildren();
2443
- }
2444
2635
  this.fiber.appliedToDom = true;
2445
2636
  this.fiber = null;
2446
2637
  }
@@ -2450,111 +2641,82 @@
2450
2641
  remove() {
2451
2642
  this.bdom.remove();
2452
2643
  }
2453
- cleanOutdatedChildren() {
2454
- const children = this.children;
2455
- for (const key in children) {
2456
- const node = children[key];
2457
- const status = node.status;
2458
- if (status !== 1 /* MOUNTED */) {
2459
- delete children[key];
2460
- if (status !== 2 /* DESTROYED */) {
2461
- node.destroy();
2462
- }
2463
- }
2464
- }
2644
+ // ---------------------------------------------------------------------------
2645
+ // Some debug helpers
2646
+ // ---------------------------------------------------------------------------
2647
+ get name() {
2648
+ return this.component.constructor.name;
2649
+ }
2650
+ get subscriptions() {
2651
+ const render = batchedRenderFunctions.get(this);
2652
+ return render ? getSubscriptions(render) : [];
2465
2653
  }
2466
2654
  }
2467
2655
 
2468
- function wrapError(fn, hookName) {
2469
- const error = new Error(`The following error occurred in ${hookName}: `);
2470
- return (...args) => {
2471
- try {
2472
- const result = fn(...args);
2473
- if (result instanceof Promise) {
2474
- return result.catch((cause) => {
2475
- error.cause = cause;
2476
- if (cause instanceof Error) {
2477
- error.message += `"${cause.message}"`;
2478
- }
2479
- throw error;
2480
- });
2656
+ // -----------------------------------------------------------------------------
2657
+ // Scheduler
2658
+ // -----------------------------------------------------------------------------
2659
+ class Scheduler {
2660
+ constructor() {
2661
+ this.tasks = new Set();
2662
+ this.frame = 0;
2663
+ this.delayedRenders = [];
2664
+ this.requestAnimationFrame = Scheduler.requestAnimationFrame;
2665
+ }
2666
+ addFiber(fiber) {
2667
+ this.tasks.add(fiber.root);
2668
+ }
2669
+ /**
2670
+ * Process all current tasks. This only applies to the fibers that are ready.
2671
+ * Other tasks are left unchanged.
2672
+ */
2673
+ flush() {
2674
+ if (this.delayedRenders.length) {
2675
+ let renders = this.delayedRenders;
2676
+ this.delayedRenders = [];
2677
+ for (let f of renders) {
2678
+ if (f.root && f.node.status !== 2 /* DESTROYED */) {
2679
+ f.render();
2680
+ }
2481
2681
  }
2482
- return result;
2483
2682
  }
2484
- catch (cause) {
2485
- if (cause instanceof Error) {
2486
- error.message += `"${cause.message}"`;
2683
+ if (this.frame === 0) {
2684
+ this.frame = this.requestAnimationFrame(() => {
2685
+ this.frame = 0;
2686
+ this.tasks.forEach((fiber) => this.processFiber(fiber));
2687
+ for (let task of this.tasks) {
2688
+ if (task.node.status === 2 /* DESTROYED */) {
2689
+ this.tasks.delete(task);
2690
+ }
2691
+ }
2692
+ });
2693
+ }
2694
+ }
2695
+ processFiber(fiber) {
2696
+ if (fiber.root !== fiber) {
2697
+ this.tasks.delete(fiber);
2698
+ return;
2699
+ }
2700
+ const hasError = fibersInError.has(fiber);
2701
+ if (hasError && fiber.counter !== 0) {
2702
+ this.tasks.delete(fiber);
2703
+ return;
2704
+ }
2705
+ if (fiber.node.status === 2 /* DESTROYED */) {
2706
+ this.tasks.delete(fiber);
2707
+ return;
2708
+ }
2709
+ if (fiber.counter === 0) {
2710
+ if (!hasError) {
2711
+ fiber.complete();
2487
2712
  }
2488
- throw error;
2713
+ this.tasks.delete(fiber);
2489
2714
  }
2490
- };
2491
- }
2492
- // -----------------------------------------------------------------------------
2493
- // hooks
2494
- // -----------------------------------------------------------------------------
2495
- function onWillStart(fn) {
2496
- const node = getCurrent();
2497
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2498
- node.willStart.push(decorate(fn.bind(node.component), "onWillStart"));
2499
- }
2500
- function onWillUpdateProps(fn) {
2501
- const node = getCurrent();
2502
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2503
- node.willUpdateProps.push(decorate(fn.bind(node.component), "onWillUpdateProps"));
2504
- }
2505
- function onMounted(fn) {
2506
- const node = getCurrent();
2507
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2508
- node.mounted.push(decorate(fn.bind(node.component), "onMounted"));
2509
- }
2510
- function onWillPatch(fn) {
2511
- const node = getCurrent();
2512
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2513
- node.willPatch.unshift(decorate(fn.bind(node.component), "onWillPatch"));
2514
- }
2515
- function onPatched(fn) {
2516
- const node = getCurrent();
2517
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2518
- node.patched.push(decorate(fn.bind(node.component), "onPatched"));
2519
- }
2520
- function onWillUnmount(fn) {
2521
- const node = getCurrent();
2522
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2523
- node.willUnmount.unshift(decorate(fn.bind(node.component), "onWillUnmount"));
2524
- }
2525
- function onWillDestroy(fn) {
2526
- const node = getCurrent();
2527
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2528
- node.willDestroy.push(decorate(fn.bind(node.component), "onWillDestroy"));
2529
- }
2530
- function onWillRender(fn) {
2531
- const node = getCurrent();
2532
- const renderFn = node.renderFn;
2533
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2534
- node.renderFn = decorate(() => {
2535
- fn.call(node.component);
2536
- return renderFn();
2537
- }, "onWillRender");
2715
+ }
2538
2716
  }
2539
- function onRendered(fn) {
2540
- const node = getCurrent();
2541
- const renderFn = node.renderFn;
2542
- const decorate = node.app.dev ? wrapError : (fn) => fn;
2543
- node.renderFn = decorate(() => {
2544
- const result = renderFn();
2545
- fn.call(node.component);
2546
- return result;
2547
- }, "onRendered");
2548
- }
2549
- function onError(callback) {
2550
- const node = getCurrent();
2551
- let handlers = nodeErrorHandlers.get(node);
2552
- if (!handlers) {
2553
- handlers = [];
2554
- nodeErrorHandlers.set(node, handlers);
2555
- }
2556
- handlers.push(callback.bind(node.component));
2557
- }
2717
+ // capture the value of requestAnimationFrame as soon as possible, to avoid
2718
+ // interactions with other code, such as test frameworks that override them
2719
+ Scheduler.requestAnimationFrame = window.requestAnimationFrame.bind(window);
2558
2720
 
2559
2721
  /**
2560
2722
  * Owl QWeb Expression Parser
@@ -2708,24 +2870,31 @@
2708
2870
  function tokenize(expr) {
2709
2871
  const result = [];
2710
2872
  let token = true;
2711
- while (token) {
2712
- expr = expr.trim();
2713
- if (expr) {
2714
- for (let tokenizer of TOKENIZERS) {
2715
- token = tokenizer(expr);
2716
- if (token) {
2717
- result.push(token);
2718
- expr = expr.slice(token.size || token.value.length);
2719
- break;
2873
+ let error;
2874
+ let current = expr;
2875
+ try {
2876
+ while (token) {
2877
+ current = current.trim();
2878
+ if (current) {
2879
+ for (let tokenizer of TOKENIZERS) {
2880
+ token = tokenizer(current);
2881
+ if (token) {
2882
+ result.push(token);
2883
+ current = current.slice(token.size || token.value.length);
2884
+ break;
2885
+ }
2720
2886
  }
2721
2887
  }
2888
+ else {
2889
+ token = false;
2890
+ }
2722
2891
  }
2723
- else {
2724
- token = false;
2725
- }
2726
2892
  }
2727
- if (expr.length) {
2728
- throw new Error(`Tokenizer error: could not tokenize "${expr}"`);
2893
+ catch (e) {
2894
+ error = e; // Silence all errors and throw a generic error below
2895
+ }
2896
+ if (current.length || error) {
2897
+ throw new Error(`Tokenizer error: could not tokenize \`${expr}\``);
2729
2898
  }
2730
2899
  return result;
2731
2900
  }
@@ -2930,7 +3099,7 @@
2930
3099
  }, params);
2931
3100
  }
2932
3101
  class CodeTarget {
2933
- constructor(name) {
3102
+ constructor(name, on) {
2934
3103
  this.indentLevel = 0;
2935
3104
  this.loopLevel = 0;
2936
3105
  this.code = [];
@@ -2941,6 +3110,7 @@
2941
3110
  this.refInfo = {};
2942
3111
  this.shouldProtectScope = false;
2943
3112
  this.name = name;
3113
+ this.on = on || null;
2944
3114
  }
2945
3115
  addLine(line, idx) {
2946
3116
  const prefix = new Array(this.indentLevel + 2).join(" ");
@@ -2990,7 +3160,7 @@
2990
3160
  this.targets = [];
2991
3161
  this.target = new CodeTarget("template");
2992
3162
  this.translatableAttributes = TRANSLATABLE_ATTRS;
2993
- this.staticCalls = [];
3163
+ this.staticDefs = [];
2994
3164
  this.helpers = new Set();
2995
3165
  this.translateFn = options.translateFn || ((s) => s);
2996
3166
  if (options.translatableAttributes) {
@@ -3033,8 +3203,8 @@
3033
3203
  if (this.templateName) {
3034
3204
  mainCode.push(`// Template name: "${this.templateName}"`);
3035
3205
  }
3036
- for (let { id, template } of this.staticCalls) {
3037
- mainCode.push(`const ${id} = getTemplate(${template});`);
3206
+ for (let { id, expr } of this.staticDefs) {
3207
+ mainCode.push(`const ${id} = ${expr};`);
3038
3208
  }
3039
3209
  // define all blocks
3040
3210
  if (this.blocks.length) {
@@ -3070,19 +3240,21 @@
3070
3240
  }
3071
3241
  return code;
3072
3242
  }
3073
- compileInNewTarget(prefix, ast, ctx) {
3243
+ compileInNewTarget(prefix, ast, ctx, on) {
3074
3244
  const name = this.generateId(prefix);
3075
3245
  const initialTarget = this.target;
3076
- const target = new CodeTarget(name);
3246
+ const target = new CodeTarget(name, on);
3077
3247
  this.targets.push(target);
3078
3248
  this.target = target;
3079
- const subCtx = createContext(ctx);
3080
- this.compileAST(ast, subCtx);
3249
+ this.compileAST(ast, createContext(ctx));
3081
3250
  this.target = initialTarget;
3082
3251
  return name;
3083
3252
  }
3084
- addLine(line) {
3085
- this.target.addLine(line);
3253
+ addLine(line, idx) {
3254
+ this.target.addLine(line, idx);
3255
+ }
3256
+ define(varName, expr) {
3257
+ this.addLine(`const ${varName} = ${expr};`);
3086
3258
  }
3087
3259
  generateId(prefix = "") {
3088
3260
  this.ids[prefix] = (this.ids[prefix] || 0) + 1;
@@ -3124,10 +3296,13 @@
3124
3296
  blockExpr = `toggler(${tKeyExpr}, ${blockExpr})`;
3125
3297
  }
3126
3298
  if (block.isRoot && !ctx.preventRoot) {
3299
+ if (this.target.on) {
3300
+ blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on);
3301
+ }
3127
3302
  this.addLine(`return ${blockExpr};`);
3128
3303
  }
3129
3304
  else {
3130
- this.addLine(`let ${block.varName} = ${blockExpr};`);
3305
+ this.define(block.varName, blockExpr);
3131
3306
  }
3132
3307
  }
3133
3308
  /**
@@ -3155,7 +3330,7 @@
3155
3330
  if (!mapping.has(tok.varName)) {
3156
3331
  const varId = this.generateId("v");
3157
3332
  mapping.set(tok.varName, varId);
3158
- this.addLine(`const ${varId} = ${tok.value};`);
3333
+ this.define(varId, tok.value);
3159
3334
  }
3160
3335
  tok.value = mapping.get(tok.varName);
3161
3336
  }
@@ -3294,7 +3469,7 @@
3294
3469
  this.blocks.push(block);
3295
3470
  if (ast.dynamicTag) {
3296
3471
  const tagExpr = this.generateId("tag");
3297
- this.addLine(`let ${tagExpr} = ${compileExpr(ast.dynamicTag)};`);
3472
+ this.define(tagExpr, compileExpr(ast.dynamicTag));
3298
3473
  block.dynamicTagName = tagExpr;
3299
3474
  }
3300
3475
  }
@@ -3376,10 +3551,10 @@
3376
3551
  const { hasDynamicChildren, baseExpr, expr, eventType, shouldNumberize, shouldTrim, targetAttr, specialInitTargetAttr, } = ast.model;
3377
3552
  const baseExpression = compileExpr(baseExpr);
3378
3553
  const bExprId = this.generateId("bExpr");
3379
- this.addLine(`const ${bExprId} = ${baseExpression};`);
3554
+ this.define(bExprId, baseExpression);
3380
3555
  const expression = compileExpr(expr);
3381
3556
  const exprId = this.generateId("expr");
3382
- this.addLine(`const ${exprId} = ${expression};`);
3557
+ this.define(exprId, expression);
3383
3558
  const fullExpression = `${bExprId}[${exprId}]`;
3384
3559
  let idx;
3385
3560
  if (specialInitTargetAttr) {
@@ -3389,7 +3564,7 @@
3389
3564
  else if (hasDynamicChildren) {
3390
3565
  const bValueId = this.generateId("bValue");
3391
3566
  tModelSelectedExpr = `${bValueId}`;
3392
- this.addLine(`let ${tModelSelectedExpr} = ${fullExpression}`);
3567
+ this.define(tModelSelectedExpr, fullExpression);
3393
3568
  }
3394
3569
  else {
3395
3570
  idx = block.insertData(`${fullExpression}`, "attr");
@@ -3437,14 +3612,14 @@
3437
3612
  const children = block.children.slice();
3438
3613
  let current = children.shift();
3439
3614
  for (let i = codeIdx; i < code.length; i++) {
3440
- if (code[i].trimStart().startsWith(`let ${current.varName} `)) {
3441
- code[i] = code[i].replace(`let ${current.varName}`, current.varName);
3615
+ if (code[i].trimStart().startsWith(`const ${current.varName} `)) {
3616
+ code[i] = code[i].replace(`const ${current.varName}`, current.varName);
3442
3617
  current = children.shift();
3443
3618
  if (!current)
3444
3619
  break;
3445
3620
  }
3446
3621
  }
3447
- this.target.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3622
+ this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3448
3623
  }
3449
3624
  }
3450
3625
  }
@@ -3532,14 +3707,14 @@
3532
3707
  const children = block.children.slice();
3533
3708
  let current = children.shift();
3534
3709
  for (let i = codeIdx; i < code.length; i++) {
3535
- if (code[i].trimStart().startsWith(`let ${current.varName} `)) {
3536
- code[i] = code[i].replace(`let ${current.varName}`, current.varName);
3710
+ if (code[i].trimStart().startsWith(`const ${current.varName} `)) {
3711
+ code[i] = code[i].replace(`const ${current.varName}`, current.varName);
3537
3712
  current = children.shift();
3538
3713
  if (!current)
3539
3714
  break;
3540
3715
  }
3541
3716
  }
3542
- this.target.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3717
+ this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3543
3718
  }
3544
3719
  // note: this part is duplicated from end of compilemulti:
3545
3720
  const args = block.children.map((c) => c.varName).join(", ");
@@ -3560,10 +3735,10 @@
3560
3735
  const l = `l_block${block.id}`;
3561
3736
  const c = `c_block${block.id}`;
3562
3737
  this.helpers.add("prepareList");
3563
- this.addLine(`const [${keys}, ${vals}, ${l}, ${c}] = prepareList(${compileExpr(ast.collection)});`);
3738
+ this.define(`[${keys}, ${vals}, ${l}, ${c}]`, `prepareList(${compileExpr(ast.collection)});`);
3564
3739
  // Throw errors on duplicate keys in dev mode
3565
3740
  if (this.dev) {
3566
- this.addLine(`const keys${block.id} = new Set();`);
3741
+ this.define(`keys${block.id}`, `new Set()`);
3567
3742
  }
3568
3743
  this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
3569
3744
  this.target.indentLevel++;
@@ -3580,7 +3755,7 @@
3580
3755
  if (!ast.hasNoValue) {
3581
3756
  this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
3582
3757
  }
3583
- this.addLine(`let key${this.target.loopLevel} = ${ast.key ? compileExpr(ast.key) : loopVar};`);
3758
+ this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar);
3584
3759
  if (this.dev) {
3585
3760
  // Throw error on duplicate keys in dev mode
3586
3761
  this.addLine(`if (keys${block.id}.has(key${this.target.loopLevel})) { throw new Error(\`Got duplicate key in t-foreach: \${key${this.target.loopLevel}}\`)}`);
@@ -3590,8 +3765,8 @@
3590
3765
  if (ast.memo) {
3591
3766
  this.target.hasCache = true;
3592
3767
  id = this.generateId();
3593
- this.addLine(`let memo${id} = ${compileExpr(ast.memo)}`);
3594
- this.addLine(`let vnode${id} = cache[key${this.target.loopLevel}];`);
3768
+ this.define(`memo${id}`, compileExpr(ast.memo));
3769
+ this.define(`vnode${id}`, `cache[key${this.target.loopLevel}];`);
3595
3770
  this.addLine(`if (vnode${id}) {`);
3596
3771
  this.target.indentLevel++;
3597
3772
  this.addLine(`if (shallowEqual(vnode${id}.memo, memo${id})) {`);
@@ -3619,7 +3794,7 @@
3619
3794
  }
3620
3795
  compileTKey(ast, ctx) {
3621
3796
  const tKeyExpr = this.generateId("tKey_");
3622
- this.addLine(`const ${tKeyExpr} = ${compileExpr(ast.expr)};`);
3797
+ this.define(tKeyExpr, compileExpr(ast.expr));
3623
3798
  ctx = createContext(ctx, {
3624
3799
  tKeyExpr,
3625
3800
  block: ctx.block,
@@ -3664,14 +3839,14 @@
3664
3839
  const children = block.children.slice();
3665
3840
  let current = children.shift();
3666
3841
  for (let i = codeIdx; i < code.length; i++) {
3667
- if (code[i].trimStart().startsWith(`let ${current.varName} `)) {
3668
- code[i] = code[i].replace(`let ${current.varName}`, current.varName);
3842
+ if (code[i].trimStart().startsWith(`const ${current.varName} `)) {
3843
+ code[i] = code[i].replace(`const ${current.varName}`, current.varName);
3669
3844
  current = children.shift();
3670
3845
  if (!current)
3671
3846
  break;
3672
3847
  }
3673
3848
  }
3674
- this.target.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3849
+ this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
3675
3850
  }
3676
3851
  }
3677
3852
  const args = block.children.map((c) => c.varName).join(", ");
@@ -3702,7 +3877,7 @@
3702
3877
  const key = `key + \`${this.generateComponentKey()}\``;
3703
3878
  if (isDynamic) {
3704
3879
  const templateVar = this.generateId("template");
3705
- this.addLine(`const ${templateVar} = ${subTemplate};`);
3880
+ this.define(templateVar, subTemplate);
3706
3881
  block = this.createBlock(block, "multi", ctx);
3707
3882
  this.helpers.add("call");
3708
3883
  this.insertBlock(`call(this, ${templateVar}, ctx, node, ${key})`, block, {
@@ -3713,7 +3888,7 @@
3713
3888
  else {
3714
3889
  const id = this.generateId(`callTemplate_`);
3715
3890
  this.helpers.add("getTemplate");
3716
- this.staticCalls.push({ id, template: subTemplate });
3891
+ this.staticDefs.push({ id, expr: `getTemplate(${subTemplate})` });
3717
3892
  block = this.createBlock(block, "multi", ctx);
3718
3893
  this.insertBlock(`${id}.call(this, ctx, node, ${key})`, block, {
3719
3894
  ...ctx,
@@ -3807,27 +3982,29 @@
3807
3982
  compileComponent(ast, ctx) {
3808
3983
  let { block } = ctx;
3809
3984
  // props
3810
- const hasSlotsProp = "slots" in ast.props;
3985
+ const hasSlotsProp = "slots" in (ast.props || {});
3811
3986
  const props = [];
3812
- const propExpr = this.formatPropObject(ast.props);
3987
+ const propExpr = this.formatPropObject(ast.props || {});
3813
3988
  if (propExpr) {
3814
3989
  props.push(propExpr);
3815
3990
  }
3816
3991
  // slots
3817
- const hasSlot = !!Object.keys(ast.slots).length;
3818
3992
  let slotDef = "";
3819
- if (hasSlot) {
3993
+ if (ast.slots) {
3820
3994
  let ctxStr = "ctx";
3821
3995
  if (this.target.loopLevel || !this.hasSafeContext) {
3822
3996
  ctxStr = this.generateId("ctx");
3823
3997
  this.helpers.add("capture");
3824
- this.addLine(`const ${ctxStr} = capture(ctx);`);
3998
+ this.define(ctxStr, `capture(ctx)`);
3825
3999
  }
3826
4000
  let slotStr = [];
3827
4001
  for (let slotName in ast.slots) {
3828
- const slotAst = ast.slots[slotName].content;
3829
- const name = this.compileInNewTarget("slot", slotAst, ctx);
3830
- const params = [`__render: ${name}, __ctx: ${ctxStr}`];
4002
+ const slotAst = ast.slots[slotName];
4003
+ const params = [];
4004
+ if (slotAst.content) {
4005
+ const name = this.compileInNewTarget("slot", slotAst.content, ctx, slotAst.on);
4006
+ params.push(`__render: ${name}, __ctx: ${ctxStr}`);
4007
+ }
3831
4008
  const scope = ast.slots[slotName].scope;
3832
4009
  if (scope) {
3833
4010
  params.push(`__scope: "${scope}"`);
@@ -3852,7 +4029,7 @@
3852
4029
  let propVar;
3853
4030
  if ((slotDef && (ast.dynamicProps || hasSlotsProp)) || this.dev) {
3854
4031
  propVar = this.generateId("props");
3855
- this.addLine(`const ${propVar} = ${propString};`);
4032
+ this.define(propVar, propString);
3856
4033
  propString = propVar;
3857
4034
  }
3858
4035
  if (slotDef && (ast.dynamicProps || hasSlotsProp)) {
@@ -3864,7 +4041,7 @@
3864
4041
  let expr;
3865
4042
  if (ast.isDynamic) {
3866
4043
  expr = this.generateId("Comp");
3867
- this.addLine(`let ${expr} = ${compileExpr(ast.name)};`);
4044
+ this.define(expr, compileExpr(ast.name));
3868
4045
  }
3869
4046
  else {
3870
4047
  expr = `\`${ast.name}\``;
@@ -3885,9 +4062,28 @@
3885
4062
  if (ast.isDynamic) {
3886
4063
  blockExpr = `toggler(${expr}, ${blockExpr})`;
3887
4064
  }
4065
+ // event handling
4066
+ if (ast.on) {
4067
+ blockExpr = this.wrapWithEventCatcher(blockExpr, ast.on);
4068
+ }
3888
4069
  block = this.createBlock(block, "multi", ctx);
3889
4070
  this.insertBlock(blockExpr, block, ctx);
3890
4071
  }
4072
+ wrapWithEventCatcher(expr, on) {
4073
+ this.helpers.add("createCatcher");
4074
+ let name = this.generateId("catcher");
4075
+ let spec = {};
4076
+ let handlers = [];
4077
+ for (let ev in on) {
4078
+ let handlerId = this.generateId("hdlr");
4079
+ let idx = handlers.push(handlerId) - 1;
4080
+ spec[ev] = idx;
4081
+ const handler = this.generateHandlerCode(ev, on[ev]);
4082
+ this.define(handlerId, handler);
4083
+ }
4084
+ this.staticDefs.push({ id: name, expr: `createCatcher(${JSON.stringify(spec)})` });
4085
+ return `${name}(${expr}, [${handlers.join(",")}])`;
4086
+ }
3891
4087
  compileTSlot(ast, ctx) {
3892
4088
  this.helpers.add("callSlot");
3893
4089
  let { block } = ctx;
@@ -3909,13 +4105,17 @@
3909
4105
  else {
3910
4106
  if (dynamic) {
3911
4107
  let name = this.generateId("slot");
3912
- this.addLine(`const ${name} = ${slotName};`);
3913
- blockString = `toggler(${name}, callSlot(ctx, node, key, ${name}), ${dynamic}, ${scope})`;
4108
+ this.define(name, slotName);
4109
+ blockString = `toggler(${name}, callSlot(ctx, node, key, ${name}, ${dynamic}, ${scope}))`;
3914
4110
  }
3915
4111
  else {
3916
4112
  blockString = `callSlot(ctx, node, key, ${slotName}, ${dynamic}, ${scope})`;
3917
4113
  }
3918
4114
  }
4115
+ // event handling
4116
+ if (ast.on) {
4117
+ blockString = this.wrapWithEventCatcher(blockString, ast.on);
4118
+ }
3919
4119
  if (block) {
3920
4120
  this.insertAnchor(block);
3921
4121
  }
@@ -3936,7 +4136,7 @@
3936
4136
  if (this.target.loopLevel || !this.hasSafeContext) {
3937
4137
  ctxStr = this.generateId("ctx");
3938
4138
  this.helpers.add("capture");
3939
- this.addLine(`const ${ctxStr} = capture(ctx);`);
4139
+ this.define(ctxStr, `capture(ctx);`);
3940
4140
  }
3941
4141
  const blockString = `component(Portal, {target: ${ast.target},slots: {'default': {__render: ${name}, __ctx: ${ctxStr}}}}, key + \`${key}\`, node, ctx)`;
3942
4142
  if (block) {
@@ -4070,8 +4270,8 @@
4070
4270
  const ref = node.getAttribute("t-ref");
4071
4271
  node.removeAttribute("t-ref");
4072
4272
  const nodeAttrsNames = node.getAttributeNames();
4073
- const attrs = {};
4074
- const on = {};
4273
+ let attrs = null;
4274
+ let on = null;
4075
4275
  let model = null;
4076
4276
  for (let attr of nodeAttrsNames) {
4077
4277
  const value = node.getAttribute(attr);
@@ -4079,6 +4279,7 @@
4079
4279
  if (attr === "t-on") {
4080
4280
  throw new Error("Missing event name with t-on directive");
4081
4281
  }
4282
+ on = on || {};
4082
4283
  on[attr.slice(5)] = value;
4083
4284
  }
4084
4285
  else if (attr.startsWith("t-model")) {
@@ -4116,6 +4317,7 @@
4116
4317
  targetAttr: isCheckboxInput ? "checked" : "value",
4117
4318
  specialInitTargetAttr: isRadioInput ? "checked" : null,
4118
4319
  eventType,
4320
+ hasDynamicChildren: false,
4119
4321
  shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
4120
4322
  shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
4121
4323
  };
@@ -4136,6 +4338,7 @@
4136
4338
  if (tModel && ["t-att-value", "t-attf-value"].includes(attr)) {
4137
4339
  tModel.hasDynamicChildren = true;
4138
4340
  }
4341
+ attrs = attrs || {};
4139
4342
  attrs[attr] = value;
4140
4343
  }
4141
4344
  }
@@ -4286,7 +4489,7 @@
4286
4489
  if (ast && ast.type === 11 /* TComponent */) {
4287
4490
  return {
4288
4491
  ...ast,
4289
- slots: { default: { content: tcall } },
4492
+ slots: { default: { content: tcall, scope: null, on: null, attrs: null } },
4290
4493
  };
4291
4494
  }
4292
4495
  }
@@ -4370,7 +4573,6 @@
4370
4573
  // -----------------------------------------------------------------------------
4371
4574
  // Error messages when trying to use an unsupported directive on a component
4372
4575
  const directiveErrorMap = new Map([
4373
- ["t-on", "t-on is no longer supported on components. Consider passing a callback in props."],
4374
4576
  [
4375
4577
  "t-ref",
4376
4578
  "t-ref is no longer supported on components. Consider exposing only the public part of the component's API through a callback prop.",
@@ -4399,18 +4601,26 @@
4399
4601
  node.removeAttribute("t-props");
4400
4602
  const defaultSlotScope = node.getAttribute("t-slot-scope");
4401
4603
  node.removeAttribute("t-slot-scope");
4402
- const props = {};
4604
+ let on = null;
4605
+ let props = null;
4403
4606
  for (let name of node.getAttributeNames()) {
4404
4607
  const value = node.getAttribute(name);
4405
4608
  if (name.startsWith("t-")) {
4406
- const message = directiveErrorMap.get(name.split("-").slice(0, 2).join("-"));
4407
- throw new Error(message || `unsupported directive on Component: ${name}`);
4609
+ if (name.startsWith("t-on-")) {
4610
+ on = on || {};
4611
+ on[name.slice(5)] = value;
4612
+ }
4613
+ else {
4614
+ const message = directiveErrorMap.get(name.split("-").slice(0, 2).join("-"));
4615
+ throw new Error(message || `unsupported directive on Component: ${name}`);
4616
+ }
4408
4617
  }
4409
4618
  else {
4619
+ props = props || {};
4410
4620
  props[name] = value;
4411
4621
  }
4412
4622
  }
4413
- const slots = {};
4623
+ let slots = null;
4414
4624
  if (node.hasChildNodes()) {
4415
4625
  const clone = node.cloneNode(true);
4416
4626
  // named slots
@@ -4437,33 +4647,35 @@
4437
4647
  slotNode.removeAttribute("t-set-slot");
4438
4648
  slotNode.remove();
4439
4649
  const slotAst = parseNode(slotNode, ctx);
4440
- if (slotAst) {
4441
- const slotInfo = { content: slotAst };
4442
- const attrs = {};
4443
- for (let attributeName of slotNode.getAttributeNames()) {
4444
- const value = slotNode.getAttribute(attributeName);
4445
- if (attributeName === "t-slot-scope") {
4446
- slotInfo.scope = value;
4447
- continue;
4448
- }
4449
- attrs[attributeName] = value;
4650
+ let on = null;
4651
+ let attrs = null;
4652
+ let scope = null;
4653
+ for (let attributeName of slotNode.getAttributeNames()) {
4654
+ const value = slotNode.getAttribute(attributeName);
4655
+ if (attributeName === "t-slot-scope") {
4656
+ scope = value;
4657
+ continue;
4658
+ }
4659
+ else if (attributeName.startsWith("t-on-")) {
4660
+ on = on || {};
4661
+ on[attributeName.slice(5)] = value;
4450
4662
  }
4451
- if (Object.keys(attrs).length) {
4452
- slotInfo.attrs = attrs;
4663
+ else {
4664
+ attrs = attrs || {};
4665
+ attrs[attributeName] = value;
4453
4666
  }
4454
- slots[name] = slotInfo;
4455
4667
  }
4668
+ slots = slots || {};
4669
+ slots[name] = { content: slotAst, on, attrs, scope };
4456
4670
  }
4457
4671
  // default slot
4458
4672
  const defaultContent = parseChildNodes(clone, ctx);
4459
4673
  if (defaultContent) {
4460
- slots.default = { content: defaultContent };
4461
- if (defaultSlotScope) {
4462
- slots.default.scope = defaultSlotScope;
4463
- }
4674
+ slots = slots || {};
4675
+ slots.default = { content: defaultContent, on, attrs: null, scope: defaultSlotScope };
4464
4676
  }
4465
4677
  }
4466
- return { type: 11 /* TComponent */, name, isDynamic, dynamicProps, props, slots };
4678
+ return { type: 11 /* TComponent */, name, isDynamic, dynamicProps, props, slots, on };
4467
4679
  }
4468
4680
  // -----------------------------------------------------------------------------
4469
4681
  // Slots
@@ -4474,15 +4686,24 @@
4474
4686
  }
4475
4687
  const name = node.getAttribute("t-slot");
4476
4688
  node.removeAttribute("t-slot");
4477
- const attrs = {};
4689
+ let attrs = null;
4690
+ let on = null;
4478
4691
  for (let attributeName of node.getAttributeNames()) {
4479
4692
  const value = node.getAttribute(attributeName);
4480
- attrs[attributeName] = value;
4693
+ if (attributeName.startsWith("t-on-")) {
4694
+ on = on || {};
4695
+ on[attributeName.slice(5)] = value;
4696
+ }
4697
+ else {
4698
+ attrs = attrs || {};
4699
+ attrs[attributeName] = value;
4700
+ }
4481
4701
  }
4482
4702
  return {
4483
4703
  type: 14 /* TSlot */,
4484
4704
  name,
4485
4705
  attrs,
4706
+ on,
4486
4707
  defaultContent: parseChildNodes(node, ctx),
4487
4708
  };
4488
4709
  }
@@ -4616,68 +4837,423 @@
4616
4837
  el.appendChild(t);
4617
4838
  }
4618
4839
  }
4619
- /**
4620
- * Normalizes the tree inside a given element and do some preliminary validation
4621
- * on it. This function modifies the Element in place.
4622
- *
4623
- * @param el the element containing the tree that should be normalized
4624
- */
4625
- function normalizeXML(el) {
4626
- normalizeTIf(el);
4627
- normalizeTEsc(el);
4840
+ /**
4841
+ * Normalizes the tree inside a given element and do some preliminary validation
4842
+ * on it. This function modifies the Element in place.
4843
+ *
4844
+ * @param el the element containing the tree that should be normalized
4845
+ */
4846
+ function normalizeXML(el) {
4847
+ normalizeTIf(el);
4848
+ normalizeTEsc(el);
4849
+ }
4850
+ /**
4851
+ * Parses an XML string into an XML document, throwing errors on parser errors
4852
+ * instead of returning an XML document containing the parseerror.
4853
+ *
4854
+ * @param xml the string to parse
4855
+ * @returns an XML document corresponding to the content of the string
4856
+ */
4857
+ function parseXML$1(xml) {
4858
+ const parser = new DOMParser();
4859
+ const doc = parser.parseFromString(xml, "text/xml");
4860
+ if (doc.getElementsByTagName("parsererror").length) {
4861
+ let msg = "Invalid XML in template.";
4862
+ const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
4863
+ if (parsererrorText) {
4864
+ msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
4865
+ const re = /\d+/g;
4866
+ const firstMatch = re.exec(parsererrorText);
4867
+ if (firstMatch) {
4868
+ const lineNumber = Number(firstMatch[0]);
4869
+ const line = xml.split("\n")[lineNumber - 1];
4870
+ const secondMatch = re.exec(parsererrorText);
4871
+ if (line && secondMatch) {
4872
+ const columnIndex = Number(secondMatch[0]) - 1;
4873
+ if (line[columnIndex]) {
4874
+ msg +=
4875
+ `\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
4876
+ `${line}\n${"-".repeat(columnIndex - 1)}^`;
4877
+ }
4878
+ }
4879
+ }
4880
+ }
4881
+ throw new Error(msg);
4882
+ }
4883
+ return doc;
4884
+ }
4885
+
4886
+ function compile(template, options = {}) {
4887
+ // parsing
4888
+ const ast = parse(template);
4889
+ // some work
4890
+ const hasSafeContext = template instanceof Node
4891
+ ? !(template instanceof Element) || template.querySelector("[t-set], [t-call]") === null
4892
+ : !template.includes("t-set") && !template.includes("t-call");
4893
+ // code generation
4894
+ const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
4895
+ const code = codeGenerator.generateCode();
4896
+ // template function
4897
+ return new Function("bdom, helpers", code);
4898
+ }
4899
+
4900
+ const TIMEOUT = Symbol("timeout");
4901
+ function wrapError(fn, hookName) {
4902
+ const error = new Error(`The following error occurred in ${hookName}: `);
4903
+ const timeoutError = new Error(`${hookName}'s promise hasn't resolved after 3 seconds`);
4904
+ const node = getCurrent();
4905
+ return (...args) => {
4906
+ try {
4907
+ const result = fn(...args);
4908
+ if (result instanceof Promise) {
4909
+ if (hookName === "onWillStart" || hookName === "onWillUpdateProps") {
4910
+ const fiber = node.fiber;
4911
+ Promise.race([
4912
+ result,
4913
+ new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), 3000)),
4914
+ ]).then((res) => {
4915
+ if (res === TIMEOUT && node.fiber === fiber) {
4916
+ console.warn(timeoutError);
4917
+ }
4918
+ });
4919
+ }
4920
+ return result.catch((cause) => {
4921
+ error.cause = cause;
4922
+ if (cause instanceof Error) {
4923
+ error.message += `"${cause.message}"`;
4924
+ }
4925
+ throw error;
4926
+ });
4927
+ }
4928
+ return result;
4929
+ }
4930
+ catch (cause) {
4931
+ if (cause instanceof Error) {
4932
+ error.message += `"${cause.message}"`;
4933
+ }
4934
+ throw error;
4935
+ }
4936
+ };
4937
+ }
4938
+ // -----------------------------------------------------------------------------
4939
+ // hooks
4940
+ // -----------------------------------------------------------------------------
4941
+ function onWillStart(fn) {
4942
+ const node = getCurrent();
4943
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4944
+ node.willStart.push(decorate(fn.bind(node.component), "onWillStart"));
4945
+ }
4946
+ function onWillUpdateProps(fn) {
4947
+ const node = getCurrent();
4948
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4949
+ node.willUpdateProps.push(decorate(fn.bind(node.component), "onWillUpdateProps"));
4950
+ }
4951
+ function onMounted(fn) {
4952
+ const node = getCurrent();
4953
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4954
+ node.mounted.push(decorate(fn.bind(node.component), "onMounted"));
4955
+ }
4956
+ function onWillPatch(fn) {
4957
+ const node = getCurrent();
4958
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4959
+ node.willPatch.unshift(decorate(fn.bind(node.component), "onWillPatch"));
4960
+ }
4961
+ function onPatched(fn) {
4962
+ const node = getCurrent();
4963
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4964
+ node.patched.push(decorate(fn.bind(node.component), "onPatched"));
4965
+ }
4966
+ function onWillUnmount(fn) {
4967
+ const node = getCurrent();
4968
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4969
+ node.willUnmount.unshift(decorate(fn.bind(node.component), "onWillUnmount"));
4970
+ }
4971
+ function onWillDestroy(fn) {
4972
+ const node = getCurrent();
4973
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4974
+ node.willDestroy.push(decorate(fn.bind(node.component), "onWillDestroy"));
4975
+ }
4976
+ function onWillRender(fn) {
4977
+ const node = getCurrent();
4978
+ const renderFn = node.renderFn;
4979
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4980
+ fn = decorate(fn.bind(node.component), "onWillRender");
4981
+ node.renderFn = () => {
4982
+ fn();
4983
+ return renderFn();
4984
+ };
4985
+ }
4986
+ function onRendered(fn) {
4987
+ const node = getCurrent();
4988
+ const renderFn = node.renderFn;
4989
+ const decorate = node.app.dev ? wrapError : (fn) => fn;
4990
+ fn = decorate(fn.bind(node.component), "onRendered");
4991
+ node.renderFn = () => {
4992
+ const result = renderFn();
4993
+ fn();
4994
+ return result;
4995
+ };
4996
+ }
4997
+ function onError(callback) {
4998
+ const node = getCurrent();
4999
+ let handlers = nodeErrorHandlers.get(node);
5000
+ if (!handlers) {
5001
+ handlers = [];
5002
+ nodeErrorHandlers.set(node, handlers);
5003
+ }
5004
+ handlers.push(callback.bind(node.component));
5005
+ }
5006
+
5007
+ class Component {
5008
+ constructor(props, env, node) {
5009
+ this.props = props;
5010
+ this.env = env;
5011
+ this.__owl__ = node;
5012
+ }
5013
+ setup() { }
5014
+ render(deep = false) {
5015
+ this.__owl__.render(deep === true);
5016
+ }
5017
+ }
5018
+ Component.template = "";
5019
+
5020
+ const VText = text("").constructor;
5021
+ class VPortal extends VText {
5022
+ constructor(selector, realBDom) {
5023
+ super("");
5024
+ this.target = null;
5025
+ this.selector = selector;
5026
+ this.realBDom = realBDom;
5027
+ }
5028
+ mount(parent, anchor) {
5029
+ super.mount(parent, anchor);
5030
+ this.target = document.querySelector(this.selector);
5031
+ if (!this.target) {
5032
+ let el = this.el;
5033
+ while (el && el.parentElement instanceof HTMLElement) {
5034
+ el = el.parentElement;
5035
+ }
5036
+ this.target = el && el.querySelector(this.selector);
5037
+ if (!this.target) {
5038
+ throw new Error("invalid portal target");
5039
+ }
5040
+ }
5041
+ this.realBDom.mount(this.target, null);
5042
+ }
5043
+ beforeRemove() {
5044
+ this.realBDom.beforeRemove();
5045
+ }
5046
+ remove() {
5047
+ if (this.realBDom) {
5048
+ super.remove();
5049
+ this.realBDom.remove();
5050
+ this.realBDom = null;
5051
+ }
5052
+ }
5053
+ patch(other) {
5054
+ super.patch(other);
5055
+ if (this.realBDom) {
5056
+ this.realBDom.patch(other.realBDom, true);
5057
+ }
5058
+ else {
5059
+ this.realBDom = other.realBDom;
5060
+ this.realBDom.mount(this.target, null);
5061
+ }
5062
+ }
5063
+ }
5064
+ class Portal extends Component {
5065
+ setup() {
5066
+ const node = this.__owl__;
5067
+ const renderFn = node.renderFn;
5068
+ node.renderFn = () => new VPortal(this.props.target, renderFn());
5069
+ onWillUnmount(() => {
5070
+ if (node.bdom) {
5071
+ node.bdom.remove();
5072
+ }
5073
+ });
5074
+ }
5075
+ }
5076
+ Portal.template = xml `<t t-slot="default"/>`;
5077
+ Portal.props = {
5078
+ target: {
5079
+ type: String,
5080
+ },
5081
+ slots: true,
5082
+ };
5083
+
5084
+ /**
5085
+ * This file contains utility functions that will be injected in each template,
5086
+ * to perform various useful tasks in the compiled code.
5087
+ */
5088
+ function withDefault(value, defaultValue) {
5089
+ return value === undefined || value === null || value === false ? defaultValue : value;
5090
+ }
5091
+ function callSlot(ctx, parent, key, name, dynamic, extra, defaultContent) {
5092
+ key = key + "__slot_" + name;
5093
+ const slots = ctx.props[TARGET].slots || {};
5094
+ const { __render, __ctx, __scope } = slots[name] || {};
5095
+ const slotScope = Object.create(__ctx || {});
5096
+ if (__scope) {
5097
+ slotScope[__scope] = extra;
5098
+ }
5099
+ const slotBDom = __render ? __render.call(__ctx.__owl__.component, slotScope, parent, key) : null;
5100
+ if (defaultContent) {
5101
+ let child1 = undefined;
5102
+ let child2 = undefined;
5103
+ if (slotBDom) {
5104
+ child1 = dynamic ? toggler(name, slotBDom) : slotBDom;
5105
+ }
5106
+ else {
5107
+ child2 = defaultContent.call(ctx.__owl__.component, ctx, parent, key);
5108
+ }
5109
+ return multi([child1, child2]);
5110
+ }
5111
+ return slotBDom || text("");
5112
+ }
5113
+ function capture(ctx) {
5114
+ const component = ctx.__owl__.component;
5115
+ const result = Object.create(component);
5116
+ for (let k in ctx) {
5117
+ result[k] = ctx[k];
5118
+ }
5119
+ return result;
5120
+ }
5121
+ function withKey(elem, k) {
5122
+ elem.key = k;
5123
+ return elem;
5124
+ }
5125
+ function prepareList(collection) {
5126
+ let keys;
5127
+ let values;
5128
+ if (Array.isArray(collection)) {
5129
+ keys = collection;
5130
+ values = collection;
5131
+ }
5132
+ else if (collection) {
5133
+ values = Object.keys(collection);
5134
+ keys = Object.values(collection);
5135
+ }
5136
+ else {
5137
+ throw new Error("Invalid loop expression");
5138
+ }
5139
+ const n = values.length;
5140
+ return [keys, values, n, new Array(n)];
5141
+ }
5142
+ const isBoundary = Symbol("isBoundary");
5143
+ function setContextValue(ctx, key, value) {
5144
+ const ctx0 = ctx;
5145
+ while (!ctx.hasOwnProperty(key) && !ctx.hasOwnProperty(isBoundary)) {
5146
+ const newCtx = ctx.__proto__;
5147
+ if (!newCtx) {
5148
+ ctx = ctx0;
5149
+ break;
5150
+ }
5151
+ ctx = newCtx;
5152
+ }
5153
+ ctx[key] = value;
5154
+ }
5155
+ function toNumber(val) {
5156
+ const n = parseFloat(val);
5157
+ return isNaN(n) ? val : n;
5158
+ }
5159
+ function shallowEqual(l1, l2) {
5160
+ for (let i = 0, l = l1.length; i < l; i++) {
5161
+ if (l1[i] !== l2[i]) {
5162
+ return false;
5163
+ }
5164
+ }
5165
+ return true;
5166
+ }
5167
+ class LazyValue {
5168
+ constructor(fn, ctx, node) {
5169
+ this.fn = fn;
5170
+ this.ctx = capture(ctx);
5171
+ this.node = node;
5172
+ }
5173
+ evaluate() {
5174
+ return this.fn(this.ctx, this.node);
5175
+ }
5176
+ toString() {
5177
+ return this.evaluate().toString();
5178
+ }
5179
+ }
5180
+ /*
5181
+ * Safely outputs `value` as a block depending on the nature of `value`
5182
+ */
5183
+ function safeOutput(value) {
5184
+ if (!value) {
5185
+ return value;
5186
+ }
5187
+ let safeKey;
5188
+ let block;
5189
+ if (value instanceof Markup) {
5190
+ safeKey = `string_safe`;
5191
+ block = html(value);
5192
+ }
5193
+ else if (value instanceof LazyValue) {
5194
+ safeKey = `lazy_value`;
5195
+ block = value.evaluate();
5196
+ }
5197
+ else if (value instanceof String || typeof value === "string") {
5198
+ safeKey = "string_unsafe";
5199
+ block = text(value);
5200
+ }
5201
+ else {
5202
+ // Assuming it is a block
5203
+ safeKey = "block_safe";
5204
+ block = value;
5205
+ }
5206
+ return toggler(safeKey, block);
5207
+ }
5208
+ let boundFunctions = new WeakMap();
5209
+ function bind(ctx, fn) {
5210
+ let component = ctx.__owl__.component;
5211
+ let boundFnMap = boundFunctions.get(component);
5212
+ if (!boundFnMap) {
5213
+ boundFnMap = new WeakMap();
5214
+ boundFunctions.set(component, boundFnMap);
5215
+ }
5216
+ let boundFn = boundFnMap.get(fn);
5217
+ if (!boundFn) {
5218
+ boundFn = fn.bind(component);
5219
+ boundFnMap.set(fn, boundFn);
5220
+ }
5221
+ return boundFn;
4628
5222
  }
4629
- /**
4630
- * Parses an XML string into an XML document, throwing errors on parser errors
4631
- * instead of returning an XML document containing the parseerror.
4632
- *
4633
- * @param xml the string to parse
4634
- * @returns an XML document corresponding to the content of the string
4635
- */
4636
- function parseXML$1(xml) {
4637
- const parser = new DOMParser();
4638
- const doc = parser.parseFromString(xml, "text/xml");
4639
- if (doc.getElementsByTagName("parsererror").length) {
4640
- let msg = "Invalid XML in template.";
4641
- const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
4642
- if (parsererrorText) {
4643
- msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
4644
- const re = /\d+/g;
4645
- const firstMatch = re.exec(parsererrorText);
4646
- if (firstMatch) {
4647
- const lineNumber = Number(firstMatch[0]);
4648
- const line = xml.split("\n")[lineNumber - 1];
4649
- const secondMatch = re.exec(parsererrorText);
4650
- if (line && secondMatch) {
4651
- const columnIndex = Number(secondMatch[0]) - 1;
4652
- if (line[columnIndex]) {
4653
- msg +=
4654
- `\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
4655
- `${line}\n${"-".repeat(columnIndex - 1)}^`;
4656
- }
4657
- }
5223
+ function multiRefSetter(refs, name) {
5224
+ let count = 0;
5225
+ return (el) => {
5226
+ if (el) {
5227
+ count++;
5228
+ if (count > 1) {
5229
+ throw new Error("Cannot have 2 elements with same ref name at the same time");
4658
5230
  }
4659
5231
  }
4660
- throw new Error(msg);
4661
- }
4662
- return doc;
4663
- }
4664
-
4665
- function compile(template, options = {}) {
4666
- // parsing
4667
- const ast = parse(template);
4668
- // some work
4669
- const hasSafeContext = template instanceof Node
4670
- ? !(template instanceof Element) || template.querySelector("[t-set], [t-call]") === null
4671
- : !template.includes("t-set") && !template.includes("t-call");
4672
- // code generation
4673
- const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
4674
- const code = codeGenerator.generateCode();
4675
- // template function
4676
- return new Function("bdom, helpers", code);
4677
- }
5232
+ if (count === 0 || el) {
5233
+ refs[name] = el;
5234
+ }
5235
+ };
5236
+ }
5237
+ const helpers = {
5238
+ withDefault,
5239
+ zero: Symbol("zero"),
5240
+ isBoundary,
5241
+ callSlot,
5242
+ capture,
5243
+ withKey,
5244
+ prepareList,
5245
+ setContextValue,
5246
+ multiRefSetter,
5247
+ shallowEqual,
5248
+ toNumber,
5249
+ validateProps,
5250
+ LazyValue,
5251
+ safeOutput,
5252
+ bind,
5253
+ createCatcher,
5254
+ };
4678
5255
 
4679
5256
  const bdom = { text, createBlock, list, multi, html, toggler, component, comment };
4680
- const globalTemplates = {};
4681
5257
  function parseXML(xml) {
4682
5258
  const parser = new DOMParser();
4683
5259
  const doc = parser.parseFromString(xml, "text/xml");
@@ -4706,23 +5282,32 @@
4706
5282
  }
4707
5283
  return doc;
4708
5284
  }
5285
+ /**
5286
+ * Returns the helpers object that will be injected in each template closure
5287
+ * function
5288
+ */
5289
+ function makeHelpers(getTemplate) {
5290
+ return Object.assign({}, helpers, {
5291
+ Portal,
5292
+ markRaw,
5293
+ getTemplate,
5294
+ call: (owner, subTemplate, ctx, parent, key) => {
5295
+ const template = getTemplate(subTemplate);
5296
+ return toggler(subTemplate, template.call(owner, ctx, parent, key));
5297
+ },
5298
+ });
5299
+ }
4709
5300
  class TemplateSet {
4710
5301
  constructor(config = {}) {
4711
5302
  this.rawTemplates = Object.create(globalTemplates);
4712
5303
  this.templates = {};
4713
- this.utils = Object.assign({}, UTILS, {
4714
- call: (owner, subTemplate, ctx, parent, key) => {
4715
- const template = this.getTemplate(subTemplate);
4716
- return toggler(subTemplate, template.call(owner, ctx, parent, key));
4717
- },
4718
- getTemplate: (name) => this.getTemplate(name),
4719
- });
4720
5304
  this.dev = config.dev || false;
4721
5305
  this.translateFn = config.translateFn;
4722
5306
  this.translatableAttributes = config.translatableAttributes;
4723
5307
  if (config.templates) {
4724
5308
  this.addTemplates(config.templates);
4725
5309
  }
5310
+ this.helpers = makeHelpers(this.getTemplate.bind(this));
4726
5311
  }
4727
5312
  addTemplate(name, template, options = {}) {
4728
5313
  if (name in this.rawTemplates && !options.allowDuplicate) {
@@ -4760,7 +5345,7 @@
4760
5345
  this.templates[name] = function (context, parent) {
4761
5346
  return templates[name].call(this, context, parent);
4762
5347
  };
4763
- const template = templateFn(bdom, this.utils);
5348
+ const template = templateFn(bdom, this.helpers);
4764
5349
  this.templates[name] = template;
4765
5350
  }
4766
5351
  return this.templates[name];
@@ -4773,160 +5358,9 @@
4773
5358
  translatableAttributes: this.translatableAttributes,
4774
5359
  });
4775
5360
  }
4776
- }
4777
- // -----------------------------------------------------------------------------
4778
- // xml tag helper
4779
- // -----------------------------------------------------------------------------
4780
- function xml(...args) {
4781
- const name = `__template__${xml.nextId++}`;
4782
- const value = String.raw(...args);
4783
- globalTemplates[name] = value;
4784
- return name;
4785
- }
4786
- xml.nextId = 1;
4787
-
4788
- class Component {
4789
- constructor(props, env, node) {
4790
- this.props = props;
4791
- this.env = env;
4792
- this.__owl__ = node;
4793
- }
4794
- setup() { }
4795
- render(deep = false) {
4796
- this.__owl__.render(deep);
4797
- }
4798
- }
4799
- Component.template = "";
4800
-
4801
- const VText = text("").constructor;
4802
- class VPortal extends VText {
4803
- constructor(selector, realBDom) {
4804
- super("");
4805
- this.target = null;
4806
- this.selector = selector;
4807
- this.realBDom = realBDom;
4808
- }
4809
- mount(parent, anchor) {
4810
- super.mount(parent, anchor);
4811
- this.target = document.querySelector(this.selector);
4812
- if (!this.target) {
4813
- let el = this.el;
4814
- while (el && el.parentElement instanceof HTMLElement) {
4815
- el = el.parentElement;
4816
- }
4817
- this.target = el && el.querySelector(this.selector);
4818
- if (!this.target) {
4819
- throw new Error("invalid portal target");
4820
- }
4821
- }
4822
- this.realBDom.mount(this.target, null);
4823
- }
4824
- beforeRemove() {
4825
- this.realBDom.beforeRemove();
4826
- }
4827
- remove() {
4828
- if (this.realBDom) {
4829
- super.remove();
4830
- this.realBDom.remove();
4831
- this.realBDom = null;
4832
- }
4833
- }
4834
- patch(other) {
4835
- super.patch(other);
4836
- if (this.realBDom) {
4837
- this.realBDom.patch(other.realBDom, true);
4838
- }
4839
- else {
4840
- this.realBDom = other.realBDom;
4841
- this.realBDom.mount(this.target, null);
4842
- }
4843
- }
4844
- }
4845
- class Portal extends Component {
4846
- setup() {
4847
- const node = this.__owl__;
4848
- const renderFn = node.renderFn;
4849
- node.renderFn = () => new VPortal(this.props.target, renderFn());
4850
- onWillUnmount(() => {
4851
- if (node.bdom) {
4852
- node.bdom.remove();
4853
- }
4854
- });
4855
- }
4856
- }
4857
- Portal.template = xml `<t t-slot="default"/>`;
4858
- Portal.props = {
4859
- target: {
4860
- type: String,
4861
- },
4862
- slots: true,
4863
- };
4864
-
4865
- // -----------------------------------------------------------------------------
4866
- // Scheduler
4867
- // -----------------------------------------------------------------------------
4868
- class Scheduler {
4869
- constructor() {
4870
- this.tasks = new Set();
4871
- this.isRunning = false;
4872
- this.requestAnimationFrame = Scheduler.requestAnimationFrame;
4873
- }
4874
- start() {
4875
- this.isRunning = true;
4876
- this.scheduleTasks();
4877
- }
4878
- stop() {
4879
- this.isRunning = false;
4880
- }
4881
- addFiber(fiber) {
4882
- this.tasks.add(fiber.root);
4883
- if (!this.isRunning) {
4884
- this.start();
4885
- }
4886
- }
4887
- /**
4888
- * Process all current tasks. This only applies to the fibers that are ready.
4889
- * Other tasks are left unchanged.
4890
- */
4891
- flush() {
4892
- this.tasks.forEach((fiber) => {
4893
- if (fiber.root !== fiber) {
4894
- this.tasks.delete(fiber);
4895
- return;
4896
- }
4897
- const hasError = fibersInError.has(fiber);
4898
- if (hasError && fiber.counter !== 0) {
4899
- this.tasks.delete(fiber);
4900
- return;
4901
- }
4902
- if (fiber.node.status === 2 /* DESTROYED */) {
4903
- this.tasks.delete(fiber);
4904
- return;
4905
- }
4906
- if (fiber.counter === 0) {
4907
- if (!hasError) {
4908
- fiber.complete();
4909
- }
4910
- this.tasks.delete(fiber);
4911
- }
4912
- });
4913
- if (this.tasks.size === 0) {
4914
- this.stop();
4915
- }
4916
- }
4917
- scheduleTasks() {
4918
- this.requestAnimationFrame(() => {
4919
- this.flush();
4920
- if (this.isRunning) {
4921
- this.scheduleTasks();
4922
- }
4923
- });
4924
- }
4925
- }
4926
- // capture the value of requestAnimationFrame as soon as possible, to avoid
4927
- // interactions with other code, such as test frameworks that override them
4928
- Scheduler.requestAnimationFrame = window.requestAnimationFrame.bind(window);
5361
+ }
4929
5362
 
5363
+ let hasBeenLogged = false;
4930
5364
  const DEV_MSG = () => {
4931
5365
  const hash = window.owl ? window.owl.__info__.hash : "master";
4932
5366
  return `Owl is running in 'dev' mode.
@@ -4943,11 +5377,13 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
4943
5377
  if (config.test) {
4944
5378
  this.dev = true;
4945
5379
  }
4946
- if (this.dev && !config.test) {
5380
+ if (this.dev && !config.test && !hasBeenLogged) {
4947
5381
  console.info(DEV_MSG());
5382
+ hasBeenLogged = true;
4948
5383
  }
4949
- const descrs = Object.getOwnPropertyDescriptors(config.env || {});
4950
- this.env = Object.freeze(Object.defineProperties({}, descrs));
5384
+ const env = config.env || {};
5385
+ const descrs = Object.getOwnPropertyDescriptors(env);
5386
+ this.env = Object.freeze(Object.create(Object.getPrototypeOf(env), descrs));
4951
5387
  this.props = config.props || {};
4952
5388
  }
4953
5389
  mount(target, options) {
@@ -4958,7 +5394,7 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
4958
5394
  return prom;
4959
5395
  }
4960
5396
  makeNode(Component, props) {
4961
- return new ComponentNode(Component, props, this);
5397
+ return new ComponentNode(Component, props, this, null, null);
4962
5398
  }
4963
5399
  mountNode(node, target, options) {
4964
5400
  const promise = new Promise((resolve, reject) => {
@@ -4990,6 +5426,7 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
4990
5426
  }
4991
5427
  destroy() {
4992
5428
  if (this.root) {
5429
+ this.scheduler.flush();
4993
5430
  this.root.destroy();
4994
5431
  }
4995
5432
  }
@@ -5010,45 +5447,6 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5010
5447
  }
5011
5448
  }
5012
5449
 
5013
- class Memo extends Component {
5014
- constructor(props, env, node) {
5015
- super(props, env, node);
5016
- // prevent patching process conditionally
5017
- let applyPatch = false;
5018
- const patchFn = node.patch;
5019
- node.patch = () => {
5020
- if (applyPatch) {
5021
- patchFn.call(node);
5022
- applyPatch = false;
5023
- }
5024
- };
5025
- // check props change, and render/apply patch if it changed
5026
- let prevProps = props;
5027
- const updateAndRender = node.updateAndRender;
5028
- node.updateAndRender = function (props, parentFiber) {
5029
- const shouldUpdate = !shallowEqual(prevProps, props);
5030
- if (shouldUpdate) {
5031
- prevProps = props;
5032
- updateAndRender.call(node, props, parentFiber);
5033
- applyPatch = true;
5034
- }
5035
- return Promise.resolve();
5036
- };
5037
- }
5038
- }
5039
- Memo.template = xml `<t t-slot="default"/>`;
5040
- /**
5041
- * we assume that each object have the same set of keys
5042
- */
5043
- function shallowEqual(p1, p2) {
5044
- for (let k in p1) {
5045
- if (k !== "slots" && p1[k] !== p2[k]) {
5046
- return false;
5047
- }
5048
- }
5049
- return true;
5050
- }
5051
-
5052
5450
  // -----------------------------------------------------------------------------
5053
5451
  // useRef
5054
5452
  // -----------------------------------------------------------------------------
@@ -5094,10 +5492,6 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5094
5492
  const node = getCurrent();
5095
5493
  node.childEnv = extendEnv(node.childEnv, envExtension);
5096
5494
  }
5097
- // -----------------------------------------------------------------------------
5098
- // useEffect
5099
- // -----------------------------------------------------------------------------
5100
- const NO_OP = () => { };
5101
5495
  /**
5102
5496
  * This hook will run a callback when a component is mounted and patched, and
5103
5497
  * will run a cleanup function before patching and before unmounting the
@@ -5115,18 +5509,20 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5115
5509
  let dependencies;
5116
5510
  onMounted(() => {
5117
5511
  dependencies = computeDependencies();
5118
- cleanup = effect(...dependencies) || NO_OP;
5512
+ cleanup = effect(...dependencies);
5119
5513
  });
5120
5514
  onPatched(() => {
5121
5515
  const newDeps = computeDependencies();
5122
5516
  const shouldReapply = newDeps.some((val, i) => val !== dependencies[i]);
5123
5517
  if (shouldReapply) {
5124
5518
  dependencies = newDeps;
5125
- cleanup();
5126
- cleanup = effect(...dependencies) || NO_OP;
5519
+ if (cleanup) {
5520
+ cleanup();
5521
+ }
5522
+ cleanup = effect(...dependencies);
5127
5523
  }
5128
5524
  });
5129
- onWillUnmount(() => cleanup());
5525
+ onWillUnmount(() => cleanup && cleanup());
5130
5526
  }
5131
5527
  // -----------------------------------------------------------------------------
5132
5528
  // useExternalListener
@@ -5153,8 +5549,6 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5153
5549
 
5154
5550
  config.shouldNormalizeDom = false;
5155
5551
  config.mainEventHandler = mainEventHandler;
5156
- UTILS.Portal = Portal;
5157
- UTILS.markRaw = markRaw;
5158
5552
  const blockDom = {
5159
5553
  config,
5160
5554
  // bdom entry points
@@ -5175,7 +5569,6 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5175
5569
  exports.App = App;
5176
5570
  exports.Component = Component;
5177
5571
  exports.EventBus = EventBus;
5178
- exports.Memo = Memo;
5179
5572
  exports.__info__ = __info__;
5180
5573
  exports.blockDom = blockDom;
5181
5574
  exports.loadFile = loadFile;
@@ -5209,9 +5602,9 @@ See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration
5209
5602
  Object.defineProperty(exports, '__esModule', { value: true });
5210
5603
 
5211
5604
 
5212
- __info__.version = '2.0.0-alpha.3';
5213
- __info__.date = '2022-02-25T09:57:37.893Z';
5214
- __info__.hash = '076b0d7';
5605
+ __info__.version = '2.0.0-beta-6';
5606
+ __info__.date = '2022-04-11T09:01:42.605Z';
5607
+ __info__.hash = '41344ef';
5215
5608
  __info__.url = 'https://github.com/odoo/owl';
5216
5609
 
5217
5610