@odoo/owl 2.8.1 → 3.0.0-alpha.10

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.
Files changed (73) hide show
  1. package/dist/compile_templates.mjs +92 -189
  2. package/dist/compiler.js +2378 -0
  3. package/dist/owl-devtools.zip +0 -0
  4. package/dist/owl.cjs.js +1371 -1261
  5. package/dist/owl.cjs.runtime.js +4094 -0
  6. package/dist/owl.es.js +1358 -1252
  7. package/dist/owl.es.runtime.js +4050 -0
  8. package/dist/owl.iife.js +1371 -1261
  9. package/dist/owl.iife.min.js +1 -1
  10. package/dist/owl.iife.runtime.js +4098 -0
  11. package/dist/owl.iife.runtime.min.js +1 -0
  12. package/dist/types/compiler/code_generator.d.ts +3 -5
  13. package/dist/types/compiler/index.d.ts +4 -4
  14. package/dist/types/compiler/inline_expressions.d.ts +1 -1
  15. package/dist/types/compiler/parser.d.ts +21 -28
  16. package/dist/types/owl.d.ts +299 -205
  17. package/dist/types/runtime/app.d.ts +29 -31
  18. package/dist/types/runtime/blockdom/block_compiler.d.ts +3 -3
  19. package/dist/types/runtime/blockdom/config.d.ts +1 -1
  20. package/dist/types/runtime/blockdom/event_catcher.d.ts +2 -2
  21. package/dist/types/runtime/blockdom/events.d.ts +1 -1
  22. package/dist/types/runtime/blockdom/index.d.ts +1 -1
  23. package/dist/types/runtime/cancellableContext.d.ts +15 -0
  24. package/dist/types/runtime/cancellablePromise.d.ts +15 -0
  25. package/dist/types/runtime/component.d.ts +5 -13
  26. package/dist/types/runtime/component_node.d.ts +15 -35
  27. package/dist/types/runtime/event_handling.d.ts +1 -1
  28. package/dist/types/runtime/executionContext.d.ts +0 -0
  29. package/dist/types/runtime/hooks.d.ts +7 -33
  30. package/dist/types/runtime/index.d.ts +15 -5
  31. package/dist/types/runtime/lifecycle_hooks.d.ts +1 -3
  32. package/dist/types/runtime/listOperation.d.ts +1 -0
  33. package/dist/types/runtime/plugins.d.ts +23 -0
  34. package/dist/types/runtime/portal.d.ts +4 -6
  35. package/dist/types/runtime/props.d.ts +65 -0
  36. package/dist/types/runtime/reactivity/computations.d.ts +31 -0
  37. package/dist/types/runtime/reactivity/computed.d.ts +7 -0
  38. package/dist/types/runtime/reactivity/derived.d.ts +7 -0
  39. package/dist/types/runtime/reactivity/effect.d.ts +2 -0
  40. package/dist/types/runtime/reactivity/proxy.d.ts +46 -0
  41. package/dist/types/runtime/reactivity/reactivity.d.ts +46 -0
  42. package/dist/types/runtime/reactivity/signal.d.ts +17 -0
  43. package/dist/types/runtime/reactivity/signals.d.ts +30 -0
  44. package/dist/types/runtime/registry.d.ts +19 -0
  45. package/dist/types/runtime/relationalModel/discussModel.d.ts +19 -0
  46. package/dist/types/runtime/relationalModel/discussModelTypes.d.ts +22 -0
  47. package/dist/types/runtime/relationalModel/field.d.ts +20 -0
  48. package/dist/types/runtime/relationalModel/model.d.ts +59 -0
  49. package/dist/types/runtime/relationalModel/modelData.d.ts +18 -0
  50. package/dist/types/runtime/relationalModel/modelRegistry.d.ts +3 -0
  51. package/dist/types/runtime/relationalModel/modelUtils.d.ts +4 -0
  52. package/dist/types/runtime/relationalModel/store.d.ts +16 -0
  53. package/dist/types/runtime/relationalModel/types.d.ts +83 -0
  54. package/dist/types/runtime/relationalModel/util.d.ts +1 -0
  55. package/dist/types/runtime/relationalModel/web/WebDataPoint.d.ts +25 -0
  56. package/dist/types/runtime/relationalModel/web/WebRecord.d.ts +131 -0
  57. package/dist/types/runtime/relationalModel/web/WebStaticList.d.ts +63 -0
  58. package/dist/types/runtime/relationalModel/web/webModel.d.ts +5 -0
  59. package/dist/types/runtime/relationalModel/web/webModelTypes.d.ts +139 -0
  60. package/dist/types/runtime/rendering/error_handling.d.ts +13 -0
  61. package/dist/types/runtime/rendering/fibers.d.ts +37 -0
  62. package/dist/types/runtime/rendering/scheduler.d.ts +21 -0
  63. package/dist/types/runtime/rendering/template_helpers.d.ts +50 -0
  64. package/dist/types/runtime/resource.d.ts +12 -0
  65. package/dist/types/runtime/signals.d.ts +19 -0
  66. package/dist/types/runtime/status.d.ts +2 -3
  67. package/dist/types/runtime/task.d.ts +12 -0
  68. package/dist/types/runtime/template_set.d.ts +3 -4
  69. package/dist/types/runtime/utils.d.ts +1 -2
  70. package/dist/types/runtime/validation.d.ts +6 -6
  71. package/dist/types/utils/registry.d.ts +15 -0
  72. package/dist/types/version.d.ts +1 -1
  73. package/package.json +9 -9
@@ -0,0 +1,4098 @@
1
+ (function (exports) {
2
+ 'use strict';
3
+
4
+ // Custom error class that wraps error that happen in the owl lifecycle
5
+ class OwlError extends Error {
6
+ }
7
+
8
+ // do not modify manually. This file is generated by the release script.
9
+ const version = "3.0.0-alpha";
10
+
11
+ class Component {
12
+ constructor(node) {
13
+ this.__owl__ = node;
14
+ }
15
+ setup() { }
16
+ render(deep = false) {
17
+ this.__owl__.render(deep === true);
18
+ }
19
+ }
20
+ Component.template = "";
21
+
22
+ /**
23
+ * Creates a batched version of a callback so that all calls to it in the same
24
+ * microtick will only call the original callback once.
25
+ *
26
+ * @param callback the callback to batch
27
+ * @returns a batched version of the original callback
28
+ */
29
+ function batched(callback) {
30
+ let scheduled = false;
31
+ return async (...args) => {
32
+ if (!scheduled) {
33
+ scheduled = true;
34
+ await Promise.resolve();
35
+ scheduled = false;
36
+ callback(...args);
37
+ }
38
+ };
39
+ }
40
+ /**
41
+ * Determine whether the given element is contained in its ownerDocument:
42
+ * either directly or with a shadow root in between.
43
+ */
44
+ function inOwnerDocument(el) {
45
+ if (!el) {
46
+ return false;
47
+ }
48
+ if (el.ownerDocument.contains(el)) {
49
+ return true;
50
+ }
51
+ const rootNode = el.getRootNode();
52
+ return rootNode instanceof ShadowRoot && el.ownerDocument.contains(rootNode.host);
53
+ }
54
+ /**
55
+ * Determine whether the given element is contained in a specific root documnet:
56
+ * either directly or with a shadow root in between or in an iframe.
57
+ */
58
+ function isAttachedToDocument(element, documentElement) {
59
+ let current = element;
60
+ const shadowRoot = documentElement.defaultView.ShadowRoot;
61
+ while (current) {
62
+ if (current === documentElement) {
63
+ return true;
64
+ }
65
+ if (current.parentNode) {
66
+ current = current.parentNode;
67
+ }
68
+ else if (current instanceof shadowRoot && current.host) {
69
+ current = current.host;
70
+ }
71
+ else {
72
+ return false;
73
+ }
74
+ }
75
+ return false;
76
+ }
77
+ function validateTarget(target) {
78
+ // Get the document and HTMLElement corresponding to the target to allow mounting in iframes
79
+ const document = target && target.ownerDocument;
80
+ if (document) {
81
+ if (!document.defaultView) {
82
+ throw new OwlError("Cannot mount a component: the target document is not attached to a window (defaultView is missing)");
83
+ }
84
+ const HTMLElement = document.defaultView.HTMLElement;
85
+ if (target instanceof HTMLElement || target instanceof ShadowRoot) {
86
+ if (!isAttachedToDocument(target, document)) {
87
+ throw new OwlError("Cannot mount a component on a detached dom node");
88
+ }
89
+ return;
90
+ }
91
+ }
92
+ throw new OwlError("Cannot mount component: the target is not a valid DOM element");
93
+ }
94
+ class EventBus extends EventTarget {
95
+ trigger(name, payload) {
96
+ this.dispatchEvent(new CustomEvent(name, { detail: payload }));
97
+ }
98
+ }
99
+ function whenReady(fn) {
100
+ return new Promise(function (resolve) {
101
+ if (document.readyState !== "loading") {
102
+ resolve(true);
103
+ }
104
+ else {
105
+ document.addEventListener("DOMContentLoaded", resolve, false);
106
+ }
107
+ }).then(fn || function () { });
108
+ }
109
+ /*
110
+ * This class just transports the fact that a string is safe
111
+ * to be injected as HTML. Overriding a JS primitive is quite painful though
112
+ * so we need to redfine toString and valueOf.
113
+ */
114
+ class Markup extends String {
115
+ }
116
+ function htmlEscape(str) {
117
+ if (str instanceof Markup) {
118
+ return str;
119
+ }
120
+ if (str === undefined) {
121
+ return markup("");
122
+ }
123
+ if (typeof str === "number") {
124
+ return markup(String(str));
125
+ }
126
+ [
127
+ ["&", "&"],
128
+ ["<", "&lt;"],
129
+ [">", "&gt;"],
130
+ ["'", "&#x27;"],
131
+ ['"', "&quot;"],
132
+ ["`", "&#x60;"],
133
+ ].forEach((pairs) => {
134
+ str = String(str).replace(new RegExp(pairs[0], "g"), pairs[1]);
135
+ });
136
+ return markup(str);
137
+ }
138
+ function markup(valueOrStrings, ...placeholders) {
139
+ if (!Array.isArray(valueOrStrings)) {
140
+ return new Markup(valueOrStrings);
141
+ }
142
+ const strings = valueOrStrings;
143
+ let acc = "";
144
+ let i = 0;
145
+ for (; i < placeholders.length; ++i) {
146
+ acc += strings[i] + htmlEscape(placeholders[i]);
147
+ }
148
+ acc += strings[i];
149
+ return new Markup(acc);
150
+ }
151
+
152
+ var ComputationState;
153
+ (function (ComputationState) {
154
+ ComputationState[ComputationState["EXECUTED"] = 0] = "EXECUTED";
155
+ ComputationState[ComputationState["STALE"] = 1] = "STALE";
156
+ ComputationState[ComputationState["PENDING"] = 2] = "PENDING";
157
+ })(ComputationState || (ComputationState = {}));
158
+ let Effects;
159
+ let CurrentComputation;
160
+ // export function computed<T>(fn: () => T, opts?: Opts) {
161
+ // // todo: handle cleanup
162
+ // let computedComputation: Computation = {
163
+ // state: ComputationState.STALE,
164
+ // sources: new Set(),
165
+ // isEager: true,
166
+ // compute: () => {
167
+ // return fn();
168
+ // },
169
+ // value: undefined,
170
+ // name: opts?.name,
171
+ // };
172
+ // updateComputation(computedComputation);
173
+ // }
174
+ function onReadAtom(atom) {
175
+ if (!CurrentComputation)
176
+ return;
177
+ CurrentComputation.sources.add(atom);
178
+ atom.observers.add(CurrentComputation);
179
+ }
180
+ function onWriteAtom(atom) {
181
+ collectEffects(() => {
182
+ for (const ctx of atom.observers) {
183
+ if (ctx.state === ComputationState.EXECUTED) {
184
+ if (ctx.isDerived)
185
+ markDownstream(ctx);
186
+ else
187
+ Effects.push(ctx);
188
+ }
189
+ ctx.state = ComputationState.STALE;
190
+ }
191
+ });
192
+ batchProcessEffects();
193
+ }
194
+ function collectEffects(fn) {
195
+ if (Effects)
196
+ return fn();
197
+ Effects = [];
198
+ try {
199
+ return fn();
200
+ }
201
+ finally {
202
+ }
203
+ }
204
+ const batchProcessEffects = batched(processEffects);
205
+ function processEffects() {
206
+ if (!Effects)
207
+ return;
208
+ for (const computation of Effects) {
209
+ updateComputation(computation);
210
+ }
211
+ Effects = undefined;
212
+ }
213
+ function untrack(fn) {
214
+ return runWithComputation(undefined, fn);
215
+ }
216
+ function getCurrentComputation() {
217
+ return CurrentComputation;
218
+ }
219
+ function setComputation(computation) {
220
+ CurrentComputation = computation;
221
+ }
222
+ // todo: should probably use updateComputation instead.
223
+ function runWithComputation(computation, fn) {
224
+ const previousComputation = CurrentComputation;
225
+ CurrentComputation = computation;
226
+ let result;
227
+ try {
228
+ result = fn();
229
+ }
230
+ finally {
231
+ CurrentComputation = previousComputation;
232
+ }
233
+ return result;
234
+ }
235
+ function updateComputation(computation) {
236
+ var _a;
237
+ const state = computation.state;
238
+ if (computation.isDerived)
239
+ onReadAtom(computation);
240
+ if (state === ComputationState.EXECUTED)
241
+ return;
242
+ if (state === ComputationState.PENDING) {
243
+ computeSources(computation);
244
+ // If the state is still not stale after processing the sources, it means
245
+ // none of the dependencies have changed.
246
+ // todo: test it
247
+ if (computation.state !== ComputationState.STALE) {
248
+ computation.state = ComputationState.EXECUTED;
249
+ return;
250
+ }
251
+ }
252
+ // todo: test performance. We might want to avoid removing the atoms to
253
+ // directly re-add them at compute. Especially as we are making them stale.
254
+ removeSources(computation);
255
+ const previousComputation = CurrentComputation;
256
+ CurrentComputation = computation;
257
+ computation.value = (_a = computation.compute) === null || _a === void 0 ? void 0 : _a.call(computation);
258
+ computation.state = ComputationState.EXECUTED;
259
+ CurrentComputation = previousComputation;
260
+ }
261
+ function removeSources(computation) {
262
+ const sources = computation.sources;
263
+ for (const source of sources) {
264
+ const observers = source.observers;
265
+ observers.delete(computation);
266
+ // todo: if source has no effect observer anymore, remove its sources too
267
+ // todo: test it
268
+ }
269
+ sources.clear();
270
+ }
271
+ function markDownstream(derived) {
272
+ for (const observer of derived.observers) {
273
+ // if the state has already been marked, skip it
274
+ if (observer.state)
275
+ continue;
276
+ observer.state = ComputationState.PENDING;
277
+ if (observer.isDerived)
278
+ markDownstream(observer);
279
+ else
280
+ Effects.push(observer);
281
+ }
282
+ }
283
+ function computeSources(derived) {
284
+ for (const source of derived.sources) {
285
+ if (!("compute" in source))
286
+ continue;
287
+ updateComputation(source);
288
+ }
289
+ }
290
+
291
+ // Maps fibers to thrown errors
292
+ const fibersInError = new WeakMap();
293
+ const nodeErrorHandlers = new WeakMap();
294
+ function destroyApp(app, error) {
295
+ try {
296
+ app.destroy();
297
+ }
298
+ catch (e) {
299
+ // mute all errors here because we are in a corrupted state anyway
300
+ }
301
+ const e = Object.assign(new OwlError(`[Owl] Unhandled error. Destroying the root component`), {
302
+ cause: error,
303
+ });
304
+ return e;
305
+ }
306
+ function _handleError(node, error) {
307
+ if (!node) {
308
+ return false;
309
+ }
310
+ const fiber = node.fiber;
311
+ if (fiber) {
312
+ fibersInError.set(fiber, error);
313
+ }
314
+ const errorHandlers = nodeErrorHandlers.get(node);
315
+ if (errorHandlers) {
316
+ let handled = false;
317
+ // execute in the opposite order
318
+ const finalize = () => destroyApp(node.app, error);
319
+ for (let i = errorHandlers.length - 1; i >= 0; i--) {
320
+ try {
321
+ errorHandlers[i](error, finalize);
322
+ handled = true;
323
+ break;
324
+ }
325
+ catch (e) {
326
+ error = e;
327
+ }
328
+ }
329
+ if (handled) {
330
+ return true;
331
+ }
332
+ }
333
+ return _handleError(node.parent, error);
334
+ }
335
+ function handleError(params) {
336
+ let { error } = params;
337
+ const node = "node" in params ? params.node : params.fiber.node;
338
+ const fiber = "fiber" in params ? params.fiber : node.fiber;
339
+ if (fiber) {
340
+ // resets the fibers on components if possible. This is important so that
341
+ // new renderings can be properly included in the initial one, if any.
342
+ let current = fiber;
343
+ do {
344
+ current.node.fiber = current;
345
+ current = current.parent;
346
+ } while (current);
347
+ fibersInError.set(fiber.root, error);
348
+ }
349
+ const handled = _handleError(node, error);
350
+ if (!handled) {
351
+ throw destroyApp(node.app, error);
352
+ }
353
+ }
354
+
355
+ function filterOutModifiersFromData(dataList) {
356
+ dataList = dataList.slice();
357
+ const modifiers = [];
358
+ let elm;
359
+ while ((elm = dataList[0]) && typeof elm === "string") {
360
+ modifiers.push(dataList.shift());
361
+ }
362
+ return { modifiers, data: dataList };
363
+ }
364
+ const config = {
365
+ // whether or not blockdom should normalize DOM whenever a block is created.
366
+ // Normalizing dom mean removing empty text nodes (or containing only spaces)
367
+ shouldNormalizeDom: true,
368
+ // this is the main event handler. Every event handler registered with blockdom
369
+ // will go through this function, giving it the data registered in the block
370
+ // and the event
371
+ mainEventHandler: (data, ev, currentTarget) => {
372
+ if (typeof data === "function") {
373
+ data(ev);
374
+ }
375
+ else if (Array.isArray(data)) {
376
+ data = filterOutModifiersFromData(data).data;
377
+ data[0](data[1], ev);
378
+ }
379
+ return false;
380
+ },
381
+ };
382
+
383
+ // -----------------------------------------------------------------------------
384
+ // Toggler node
385
+ // -----------------------------------------------------------------------------
386
+ const txt = document.createTextNode("");
387
+ class VToggler {
388
+ constructor(key, child) {
389
+ this.key = key;
390
+ this.child = child;
391
+ }
392
+ mount(parent, afterNode) {
393
+ this.parentEl = parent;
394
+ this.child.mount(parent, afterNode);
395
+ }
396
+ moveBeforeDOMNode(node, parent) {
397
+ this.child.moveBeforeDOMNode(node, parent);
398
+ }
399
+ moveBeforeVNode(other, afterNode) {
400
+ this.moveBeforeDOMNode((other && other.firstNode()) || afterNode);
401
+ }
402
+ patch(other, withBeforeRemove) {
403
+ if (this === other) {
404
+ return;
405
+ }
406
+ let child1 = this.child;
407
+ let child2 = other.child;
408
+ if (this.key === other.key) {
409
+ child1.patch(child2, withBeforeRemove);
410
+ }
411
+ else {
412
+ const firstNode = child1.firstNode();
413
+ firstNode.parentElement.insertBefore(txt, firstNode);
414
+ if (withBeforeRemove) {
415
+ child1.beforeRemove();
416
+ }
417
+ child1.remove();
418
+ child2.mount(this.parentEl, txt);
419
+ this.child = child2;
420
+ this.key = other.key;
421
+ }
422
+ }
423
+ beforeRemove() {
424
+ this.child.beforeRemove();
425
+ }
426
+ remove() {
427
+ this.child.remove();
428
+ }
429
+ firstNode() {
430
+ return this.child.firstNode();
431
+ }
432
+ toString() {
433
+ return this.child.toString();
434
+ }
435
+ }
436
+ function toggler(key, child) {
437
+ return new VToggler(key, child);
438
+ }
439
+
440
+ const { setAttribute: elemSetAttribute, removeAttribute } = Element.prototype;
441
+ const tokenList = DOMTokenList.prototype;
442
+ const tokenListAdd = tokenList.add;
443
+ const tokenListRemove = tokenList.remove;
444
+ const isArray = Array.isArray;
445
+ const { split, trim } = String.prototype;
446
+ const wordRegexp = /\s+/;
447
+ /**
448
+ * We regroup here all code related to updating attributes in a very loose sense:
449
+ * attributes, properties and classs are all managed by the functions in this
450
+ * file.
451
+ */
452
+ function setAttribute(key, value) {
453
+ switch (value) {
454
+ case false:
455
+ case undefined:
456
+ removeAttribute.call(this, key);
457
+ break;
458
+ case true:
459
+ elemSetAttribute.call(this, key, "");
460
+ break;
461
+ default:
462
+ elemSetAttribute.call(this, key, value);
463
+ }
464
+ }
465
+ function createAttrUpdater(attr) {
466
+ return function (value) {
467
+ setAttribute.call(this, attr, value);
468
+ };
469
+ }
470
+ function attrsSetter(attrs) {
471
+ if (isArray(attrs)) {
472
+ if (attrs[0] === "class") {
473
+ setClass.call(this, attrs[1]);
474
+ }
475
+ else {
476
+ setAttribute.call(this, attrs[0], attrs[1]);
477
+ }
478
+ }
479
+ else {
480
+ for (let k in attrs) {
481
+ if (k === "class") {
482
+ setClass.call(this, attrs[k]);
483
+ }
484
+ else {
485
+ setAttribute.call(this, k, attrs[k]);
486
+ }
487
+ }
488
+ }
489
+ }
490
+ function attrsUpdater(attrs, oldAttrs) {
491
+ if (isArray(attrs)) {
492
+ const name = attrs[0];
493
+ const val = attrs[1];
494
+ if (name === oldAttrs[0]) {
495
+ if (val === oldAttrs[1]) {
496
+ return;
497
+ }
498
+ if (name === "class") {
499
+ updateClass.call(this, val, oldAttrs[1]);
500
+ }
501
+ else {
502
+ setAttribute.call(this, name, val);
503
+ }
504
+ }
505
+ else {
506
+ removeAttribute.call(this, oldAttrs[0]);
507
+ setAttribute.call(this, name, val);
508
+ }
509
+ }
510
+ else {
511
+ for (let k in oldAttrs) {
512
+ if (!(k in attrs)) {
513
+ if (k === "class") {
514
+ updateClass.call(this, "", oldAttrs[k]);
515
+ }
516
+ else {
517
+ removeAttribute.call(this, k);
518
+ }
519
+ }
520
+ }
521
+ for (let k in attrs) {
522
+ const val = attrs[k];
523
+ if (val !== oldAttrs[k]) {
524
+ if (k === "class") {
525
+ updateClass.call(this, val, oldAttrs[k]);
526
+ }
527
+ else {
528
+ setAttribute.call(this, k, val);
529
+ }
530
+ }
531
+ }
532
+ }
533
+ }
534
+ function toClassObj(expr) {
535
+ const result = {};
536
+ switch (typeof expr) {
537
+ case "string":
538
+ // we transform here a list of classes into an object:
539
+ // 'hey you' becomes {hey: true, you: true}
540
+ const str = trim.call(expr);
541
+ if (!str) {
542
+ return {};
543
+ }
544
+ let words = split.call(str, wordRegexp);
545
+ for (let i = 0, l = words.length; i < l; i++) {
546
+ result[words[i]] = true;
547
+ }
548
+ return result;
549
+ case "object":
550
+ // this is already an object but we may need to split keys:
551
+ // {'a': true, 'b c': true} should become {a: true, b: true, c: true}
552
+ for (let key in expr) {
553
+ const value = expr[key];
554
+ if (value) {
555
+ key = trim.call(key);
556
+ if (!key) {
557
+ continue;
558
+ }
559
+ const words = split.call(key, wordRegexp);
560
+ for (let word of words) {
561
+ result[word] = value;
562
+ }
563
+ }
564
+ }
565
+ return result;
566
+ case "undefined":
567
+ return {};
568
+ case "number":
569
+ return { [expr]: true };
570
+ default:
571
+ return { [expr]: true };
572
+ }
573
+ }
574
+ function setClass(val) {
575
+ val = val === "" ? {} : toClassObj(val);
576
+ // add classes
577
+ const cl = this.classList;
578
+ for (let c in val) {
579
+ tokenListAdd.call(cl, c);
580
+ }
581
+ }
582
+ function updateClass(val, oldVal) {
583
+ oldVal = oldVal === "" ? {} : toClassObj(oldVal);
584
+ val = val === "" ? {} : toClassObj(val);
585
+ const cl = this.classList;
586
+ // remove classes
587
+ for (let c in oldVal) {
588
+ if (!(c in val)) {
589
+ tokenListRemove.call(cl, c);
590
+ }
591
+ }
592
+ // add classes
593
+ for (let c in val) {
594
+ if (!(c in oldVal)) {
595
+ tokenListAdd.call(cl, c);
596
+ }
597
+ }
598
+ }
599
+
600
+ function createEventHandler(rawEvent) {
601
+ const eventName = rawEvent.split(".")[0];
602
+ const capture = rawEvent.includes(".capture");
603
+ if (rawEvent.includes(".synthetic")) {
604
+ return createSyntheticHandler(eventName, capture);
605
+ }
606
+ else {
607
+ return createElementHandler(eventName, capture);
608
+ }
609
+ }
610
+ // Native listener
611
+ let nextNativeEventId = 1;
612
+ function createElementHandler(evName, capture = false) {
613
+ let eventKey = `__event__${evName}_${nextNativeEventId++}`;
614
+ if (capture) {
615
+ eventKey = `${eventKey}_capture`;
616
+ }
617
+ function listener(ev) {
618
+ const currentTarget = ev.currentTarget;
619
+ if (!currentTarget || !inOwnerDocument(currentTarget))
620
+ return;
621
+ const data = currentTarget[eventKey];
622
+ if (!data)
623
+ return;
624
+ config.mainEventHandler(data, ev, currentTarget);
625
+ }
626
+ function setup(data) {
627
+ this[eventKey] = data;
628
+ this.addEventListener(evName, listener, { capture });
629
+ }
630
+ function remove() {
631
+ delete this[eventKey];
632
+ this.removeEventListener(evName, listener, { capture });
633
+ }
634
+ function update(data) {
635
+ this[eventKey] = data;
636
+ }
637
+ return { setup, update, remove };
638
+ }
639
+ // Synthetic handler: a form of event delegation that allows placing only one
640
+ // listener per event type.
641
+ let nextSyntheticEventId = 1;
642
+ function createSyntheticHandler(evName, capture = false) {
643
+ let eventKey = `__event__synthetic_${evName}`;
644
+ if (capture) {
645
+ eventKey = `${eventKey}_capture`;
646
+ }
647
+ setupSyntheticEvent(evName, eventKey, capture);
648
+ const currentId = nextSyntheticEventId++;
649
+ function setup(data) {
650
+ const _data = this[eventKey] || {};
651
+ _data[currentId] = data;
652
+ this[eventKey] = _data;
653
+ }
654
+ function remove() {
655
+ delete this[eventKey];
656
+ }
657
+ return { setup, update: setup, remove };
658
+ }
659
+ function nativeToSyntheticEvent(eventKey, event) {
660
+ let dom = event.target;
661
+ while (dom !== null) {
662
+ const _data = dom[eventKey];
663
+ if (_data) {
664
+ for (const data of Object.values(_data)) {
665
+ const stopped = config.mainEventHandler(data, event, dom);
666
+ if (stopped)
667
+ return;
668
+ }
669
+ }
670
+ dom = dom.parentNode;
671
+ }
672
+ }
673
+ const CONFIGURED_SYNTHETIC_EVENTS = {};
674
+ function setupSyntheticEvent(evName, eventKey, capture = false) {
675
+ if (CONFIGURED_SYNTHETIC_EVENTS[eventKey]) {
676
+ return;
677
+ }
678
+ document.addEventListener(evName, (event) => nativeToSyntheticEvent(eventKey, event), {
679
+ capture,
680
+ });
681
+ CONFIGURED_SYNTHETIC_EVENTS[eventKey] = true;
682
+ }
683
+
684
+ const getDescriptor$3 = (o, p) => Object.getOwnPropertyDescriptor(o, p);
685
+ const nodeProto$4 = Node.prototype;
686
+ const nodeInsertBefore$3 = nodeProto$4.insertBefore;
687
+ const nodeSetTextContent$1 = getDescriptor$3(nodeProto$4, "textContent").set;
688
+ const nodeRemoveChild$3 = nodeProto$4.removeChild;
689
+ // -----------------------------------------------------------------------------
690
+ // Multi NODE
691
+ // -----------------------------------------------------------------------------
692
+ class VMulti {
693
+ constructor(children) {
694
+ this.children = children;
695
+ }
696
+ mount(parent, afterNode) {
697
+ const children = this.children;
698
+ const l = children.length;
699
+ const anchors = new Array(l);
700
+ for (let i = 0; i < l; i++) {
701
+ let child = children[i];
702
+ if (child) {
703
+ child.mount(parent, afterNode);
704
+ }
705
+ else {
706
+ const childAnchor = document.createTextNode("");
707
+ anchors[i] = childAnchor;
708
+ nodeInsertBefore$3.call(parent, childAnchor, afterNode);
709
+ }
710
+ }
711
+ this.anchors = anchors;
712
+ this.parentEl = parent;
713
+ }
714
+ moveBeforeDOMNode(node, parent = this.parentEl) {
715
+ this.parentEl = parent;
716
+ const children = this.children;
717
+ const anchors = this.anchors;
718
+ for (let i = 0, l = children.length; i < l; i++) {
719
+ let child = children[i];
720
+ if (child) {
721
+ child.moveBeforeDOMNode(node, parent);
722
+ }
723
+ else {
724
+ const anchor = anchors[i];
725
+ nodeInsertBefore$3.call(parent, anchor, node);
726
+ }
727
+ }
728
+ }
729
+ moveBeforeVNode(other, afterNode) {
730
+ if (other) {
731
+ const next = other.children[0];
732
+ afterNode = (next ? next.firstNode() : other.anchors[0]) || null;
733
+ }
734
+ const children = this.children;
735
+ const parent = this.parentEl;
736
+ const anchors = this.anchors;
737
+ for (let i = 0, l = children.length; i < l; i++) {
738
+ let child = children[i];
739
+ if (child) {
740
+ child.moveBeforeVNode(null, afterNode);
741
+ }
742
+ else {
743
+ const anchor = anchors[i];
744
+ nodeInsertBefore$3.call(parent, anchor, afterNode);
745
+ }
746
+ }
747
+ }
748
+ patch(other, withBeforeRemove) {
749
+ if (this === other) {
750
+ return;
751
+ }
752
+ const children1 = this.children;
753
+ const children2 = other.children;
754
+ const anchors = this.anchors;
755
+ const parentEl = this.parentEl;
756
+ for (let i = 0, l = children1.length; i < l; i++) {
757
+ const vn1 = children1[i];
758
+ const vn2 = children2[i];
759
+ if (vn1) {
760
+ if (vn2) {
761
+ vn1.patch(vn2, withBeforeRemove);
762
+ }
763
+ else {
764
+ const afterNode = vn1.firstNode();
765
+ const anchor = document.createTextNode("");
766
+ anchors[i] = anchor;
767
+ nodeInsertBefore$3.call(parentEl, anchor, afterNode);
768
+ if (withBeforeRemove) {
769
+ vn1.beforeRemove();
770
+ }
771
+ vn1.remove();
772
+ children1[i] = undefined;
773
+ }
774
+ }
775
+ else if (vn2) {
776
+ children1[i] = vn2;
777
+ const anchor = anchors[i];
778
+ vn2.mount(parentEl, anchor);
779
+ nodeRemoveChild$3.call(parentEl, anchor);
780
+ }
781
+ }
782
+ }
783
+ beforeRemove() {
784
+ const children = this.children;
785
+ for (let i = 0, l = children.length; i < l; i++) {
786
+ const child = children[i];
787
+ if (child) {
788
+ child.beforeRemove();
789
+ }
790
+ }
791
+ }
792
+ remove() {
793
+ const parentEl = this.parentEl;
794
+ if (this.isOnlyChild) {
795
+ nodeSetTextContent$1.call(parentEl, "");
796
+ }
797
+ else {
798
+ const children = this.children;
799
+ const anchors = this.anchors;
800
+ for (let i = 0, l = children.length; i < l; i++) {
801
+ const child = children[i];
802
+ if (child) {
803
+ child.remove();
804
+ }
805
+ else {
806
+ nodeRemoveChild$3.call(parentEl, anchors[i]);
807
+ }
808
+ }
809
+ }
810
+ }
811
+ firstNode() {
812
+ const child = this.children[0];
813
+ return child ? child.firstNode() : this.anchors[0];
814
+ }
815
+ toString() {
816
+ return this.children.map((c) => (c ? c.toString() : "")).join("");
817
+ }
818
+ }
819
+ function multi(children) {
820
+ return new VMulti(children);
821
+ }
822
+
823
+ const getDescriptor$2 = (o, p) => Object.getOwnPropertyDescriptor(o, p);
824
+ const nodeProto$3 = Node.prototype;
825
+ const characterDataProto$1 = CharacterData.prototype;
826
+ const nodeInsertBefore$2 = nodeProto$3.insertBefore;
827
+ const characterDataSetData$1 = getDescriptor$2(characterDataProto$1, "data").set;
828
+ const nodeRemoveChild$2 = nodeProto$3.removeChild;
829
+ class VSimpleNode {
830
+ constructor(text) {
831
+ this.text = text;
832
+ }
833
+ mountNode(node, parent, afterNode) {
834
+ this.parentEl = parent;
835
+ nodeInsertBefore$2.call(parent, node, afterNode);
836
+ this.el = node;
837
+ }
838
+ moveBeforeDOMNode(node, parent = this.parentEl) {
839
+ this.parentEl = parent;
840
+ nodeInsertBefore$2.call(parent, this.el, node);
841
+ }
842
+ moveBeforeVNode(other, afterNode) {
843
+ nodeInsertBefore$2.call(this.parentEl, this.el, other ? other.el : afterNode);
844
+ }
845
+ beforeRemove() { }
846
+ remove() {
847
+ nodeRemoveChild$2.call(this.parentEl, this.el);
848
+ }
849
+ firstNode() {
850
+ return this.el;
851
+ }
852
+ toString() {
853
+ return this.text;
854
+ }
855
+ }
856
+ class VText$1 extends VSimpleNode {
857
+ mount(parent, afterNode) {
858
+ this.mountNode(document.createTextNode(toText(this.text)), parent, afterNode);
859
+ }
860
+ patch(other) {
861
+ const text2 = other.text;
862
+ if (this.text !== text2) {
863
+ characterDataSetData$1.call(this.el, toText(text2));
864
+ this.text = text2;
865
+ }
866
+ }
867
+ }
868
+ class VComment extends VSimpleNode {
869
+ mount(parent, afterNode) {
870
+ this.mountNode(document.createComment(toText(this.text)), parent, afterNode);
871
+ }
872
+ patch() { }
873
+ }
874
+ function text(str) {
875
+ return new VText$1(str);
876
+ }
877
+ function comment(str) {
878
+ return new VComment(str);
879
+ }
880
+ function toText(value) {
881
+ switch (typeof value) {
882
+ case "string":
883
+ return value;
884
+ case "number":
885
+ return String(value);
886
+ case "boolean":
887
+ return value ? "true" : "false";
888
+ default:
889
+ return value || "";
890
+ }
891
+ }
892
+
893
+ const getDescriptor$1 = (o, p) => Object.getOwnPropertyDescriptor(o, p);
894
+ const nodeProto$2 = Node.prototype;
895
+ const elementProto = Element.prototype;
896
+ const characterDataProto = CharacterData.prototype;
897
+ const characterDataSetData = getDescriptor$1(characterDataProto, "data").set;
898
+ const nodeGetFirstChild = getDescriptor$1(nodeProto$2, "firstChild").get;
899
+ const nodeGetNextSibling = getDescriptor$1(nodeProto$2, "nextSibling").get;
900
+ const NO_OP = () => { };
901
+ function makePropSetter(name) {
902
+ return function setProp(value) {
903
+ // support 0, fallback to empty string for other falsy values
904
+ this[name] = value === 0 ? 0 : value ? value.valueOf() : "";
905
+ };
906
+ }
907
+ const cache = {};
908
+ /**
909
+ * Compiling blocks is a multi-step process:
910
+ *
911
+ * 1. build an IntermediateTree from the HTML element. This intermediate tree
912
+ * is a binary tree structure that encode dynamic info sub nodes, and the
913
+ * path required to reach them
914
+ * 2. process the tree to build a block context, which is an object that aggregate
915
+ * all dynamic info in a list, and also, all ref indexes.
916
+ * 3. process the context to build appropriate builder/setter functions
917
+ * 4. make a dynamic block class, which will efficiently collect references and
918
+ * create/update dynamic locations/children
919
+ *
920
+ * @param str
921
+ * @returns a new block type, that can build concrete blocks
922
+ */
923
+ function createBlock(str) {
924
+ if (str in cache) {
925
+ return cache[str];
926
+ }
927
+ // step 0: prepare html base element
928
+ const doc = new DOMParser().parseFromString(`<t>${str}</t>`, "text/xml");
929
+ const node = doc.firstChild.firstChild;
930
+ if (config.shouldNormalizeDom) {
931
+ normalizeNode(node);
932
+ }
933
+ // step 1: prepare intermediate tree
934
+ const tree = buildTree(node);
935
+ // step 2: prepare block context
936
+ const context = buildContext(tree);
937
+ // step 3: build the final block class
938
+ const template = tree.el;
939
+ const Block = buildBlock(template, context);
940
+ cache[str] = Block;
941
+ return Block;
942
+ }
943
+ // -----------------------------------------------------------------------------
944
+ // Helper
945
+ // -----------------------------------------------------------------------------
946
+ function normalizeNode(node) {
947
+ if (node.nodeType === Node.TEXT_NODE) {
948
+ if (!/\S/.test(node.textContent)) {
949
+ node.remove();
950
+ return;
951
+ }
952
+ }
953
+ if (node.nodeType === Node.ELEMENT_NODE) {
954
+ if (node.tagName === "pre") {
955
+ return;
956
+ }
957
+ }
958
+ for (let i = node.childNodes.length - 1; i >= 0; --i) {
959
+ normalizeNode(node.childNodes.item(i));
960
+ }
961
+ }
962
+ function buildTree(node, parent = null, domParentTree = null) {
963
+ switch (node.nodeType) {
964
+ case Node.ELEMENT_NODE: {
965
+ // HTMLElement
966
+ let currentNS = domParentTree && domParentTree.currentNS;
967
+ const tagName = node.tagName;
968
+ let el = undefined;
969
+ const info = [];
970
+ if (tagName.startsWith("block-text-")) {
971
+ const index = parseInt(tagName.slice(11), 10);
972
+ info.push({ type: "text", idx: index });
973
+ el = document.createTextNode("");
974
+ }
975
+ if (tagName.startsWith("block-child-")) {
976
+ if (!domParentTree.isRef) {
977
+ addRef(domParentTree);
978
+ }
979
+ const index = parseInt(tagName.slice(12), 10);
980
+ info.push({ type: "child", idx: index });
981
+ el = document.createTextNode("");
982
+ }
983
+ currentNS || (currentNS = node.namespaceURI);
984
+ if (!el) {
985
+ el = currentNS
986
+ ? document.createElementNS(currentNS, tagName)
987
+ : document.createElement(tagName);
988
+ }
989
+ if (el instanceof Element) {
990
+ if (!domParentTree) {
991
+ // some html elements may have side effects when setting their attributes.
992
+ // For example, setting the src attribute of an <img/> will trigger a
993
+ // request to get the corresponding image. This is something that we
994
+ // don't want at compile time. We avoid that by putting the content of
995
+ // the block in a <template/> element
996
+ const fragment = document.createElement("template").content;
997
+ fragment.appendChild(el);
998
+ }
999
+ const attrs = node.attributes;
1000
+ for (let i = 0; i < attrs.length; i++) {
1001
+ const attrName = attrs[i].name;
1002
+ const attrValue = attrs[i].value;
1003
+ if (attrName.startsWith("block-handler-")) {
1004
+ const idx = parseInt(attrName.slice(14), 10);
1005
+ info.push({
1006
+ type: "handler",
1007
+ idx,
1008
+ event: attrValue,
1009
+ });
1010
+ }
1011
+ else if (attrName.startsWith("block-attribute-")) {
1012
+ const idx = parseInt(attrName.slice(16), 10);
1013
+ info.push({
1014
+ type: "attribute",
1015
+ idx,
1016
+ name: attrValue,
1017
+ tag: tagName,
1018
+ });
1019
+ }
1020
+ else if (attrName.startsWith("block-property-")) {
1021
+ const idx = parseInt(attrName.slice(15), 10);
1022
+ info.push({
1023
+ type: "property",
1024
+ idx,
1025
+ name: attrValue,
1026
+ tag: tagName,
1027
+ });
1028
+ }
1029
+ else if (attrName === "block-attributes") {
1030
+ info.push({
1031
+ type: "attributes",
1032
+ idx: parseInt(attrValue, 10),
1033
+ });
1034
+ }
1035
+ else if (attrName === "block-ref") {
1036
+ info.push({
1037
+ type: "ref",
1038
+ idx: parseInt(attrValue, 10),
1039
+ });
1040
+ }
1041
+ else {
1042
+ el.setAttribute(attrs[i].name, attrValue);
1043
+ }
1044
+ }
1045
+ }
1046
+ const tree = {
1047
+ parent,
1048
+ firstChild: null,
1049
+ nextSibling: null,
1050
+ el,
1051
+ info,
1052
+ refN: 0,
1053
+ currentNS,
1054
+ };
1055
+ if (node.firstChild) {
1056
+ const childNode = node.childNodes[0];
1057
+ if (node.childNodes.length === 1 &&
1058
+ childNode.nodeType === Node.ELEMENT_NODE &&
1059
+ childNode.tagName.startsWith("block-child-")) {
1060
+ const tagName = childNode.tagName;
1061
+ const index = parseInt(tagName.slice(12), 10);
1062
+ info.push({ idx: index, type: "child", isOnlyChild: true });
1063
+ }
1064
+ else {
1065
+ tree.firstChild = buildTree(node.firstChild, tree, tree);
1066
+ el.appendChild(tree.firstChild.el);
1067
+ let curNode = node.firstChild;
1068
+ let curTree = tree.firstChild;
1069
+ while ((curNode = curNode.nextSibling)) {
1070
+ curTree.nextSibling = buildTree(curNode, curTree, tree);
1071
+ el.appendChild(curTree.nextSibling.el);
1072
+ curTree = curTree.nextSibling;
1073
+ }
1074
+ }
1075
+ }
1076
+ if (tree.info.length) {
1077
+ addRef(tree);
1078
+ }
1079
+ return tree;
1080
+ }
1081
+ case Node.TEXT_NODE:
1082
+ case Node.COMMENT_NODE: {
1083
+ // text node or comment node
1084
+ const el = node.nodeType === Node.TEXT_NODE
1085
+ ? document.createTextNode(node.textContent)
1086
+ : document.createComment(node.textContent);
1087
+ return {
1088
+ parent: parent,
1089
+ firstChild: null,
1090
+ nextSibling: null,
1091
+ el,
1092
+ info: [],
1093
+ refN: 0,
1094
+ currentNS: null,
1095
+ };
1096
+ }
1097
+ }
1098
+ throw new OwlError("boom");
1099
+ }
1100
+ function addRef(tree) {
1101
+ tree.isRef = true;
1102
+ do {
1103
+ tree.refN++;
1104
+ } while ((tree = tree.parent));
1105
+ }
1106
+ function parentTree(tree) {
1107
+ let parent = tree.parent;
1108
+ while (parent && parent.nextSibling === tree) {
1109
+ tree = parent;
1110
+ parent = parent.parent;
1111
+ }
1112
+ return parent;
1113
+ }
1114
+ function buildContext(tree, ctx, fromIdx) {
1115
+ if (!ctx) {
1116
+ const children = new Array(tree.info.filter((v) => v.type === "child").length);
1117
+ ctx = { collectors: [], locations: [], children, cbRefs: [], refN: tree.refN };
1118
+ fromIdx = 0;
1119
+ }
1120
+ if (tree.refN) {
1121
+ const initialIdx = fromIdx;
1122
+ const isRef = tree.isRef;
1123
+ const firstChild = tree.firstChild ? tree.firstChild.refN : 0;
1124
+ const nextSibling = tree.nextSibling ? tree.nextSibling.refN : 0;
1125
+ //node
1126
+ if (isRef) {
1127
+ for (let info of tree.info) {
1128
+ info.refIdx = initialIdx;
1129
+ }
1130
+ tree.refIdx = initialIdx;
1131
+ updateCtx(ctx, tree);
1132
+ fromIdx++;
1133
+ }
1134
+ // right
1135
+ if (nextSibling) {
1136
+ const idx = fromIdx + firstChild;
1137
+ ctx.collectors.push({ idx, prevIdx: initialIdx, getVal: nodeGetNextSibling });
1138
+ buildContext(tree.nextSibling, ctx, idx);
1139
+ }
1140
+ // left
1141
+ if (firstChild) {
1142
+ ctx.collectors.push({ idx: fromIdx, prevIdx: initialIdx, getVal: nodeGetFirstChild });
1143
+ buildContext(tree.firstChild, ctx, fromIdx);
1144
+ }
1145
+ }
1146
+ return ctx;
1147
+ }
1148
+ function updateCtx(ctx, tree) {
1149
+ for (let info of tree.info) {
1150
+ switch (info.type) {
1151
+ case "text":
1152
+ ctx.locations.push({
1153
+ idx: info.idx,
1154
+ refIdx: info.refIdx,
1155
+ setData: setText,
1156
+ updateData: setText,
1157
+ });
1158
+ break;
1159
+ case "child":
1160
+ if (info.isOnlyChild) {
1161
+ // tree is the parentnode here
1162
+ ctx.children[info.idx] = {
1163
+ parentRefIdx: info.refIdx,
1164
+ isOnlyChild: true,
1165
+ };
1166
+ }
1167
+ else {
1168
+ // tree is the anchor text node
1169
+ ctx.children[info.idx] = {
1170
+ parentRefIdx: parentTree(tree).refIdx,
1171
+ afterRefIdx: info.refIdx,
1172
+ };
1173
+ }
1174
+ break;
1175
+ case "property": {
1176
+ const refIdx = info.refIdx;
1177
+ const setProp = makePropSetter(info.name);
1178
+ ctx.locations.push({
1179
+ idx: info.idx,
1180
+ refIdx,
1181
+ setData: setProp,
1182
+ updateData: setProp,
1183
+ });
1184
+ break;
1185
+ }
1186
+ case "attribute": {
1187
+ const refIdx = info.refIdx;
1188
+ let updater;
1189
+ let setter;
1190
+ if (info.name === "class") {
1191
+ setter = setClass;
1192
+ updater = updateClass;
1193
+ }
1194
+ else {
1195
+ setter = createAttrUpdater(info.name);
1196
+ updater = setter;
1197
+ }
1198
+ ctx.locations.push({
1199
+ idx: info.idx,
1200
+ refIdx,
1201
+ setData: setter,
1202
+ updateData: updater,
1203
+ });
1204
+ break;
1205
+ }
1206
+ case "attributes":
1207
+ ctx.locations.push({
1208
+ idx: info.idx,
1209
+ refIdx: info.refIdx,
1210
+ setData: attrsSetter,
1211
+ updateData: attrsUpdater,
1212
+ });
1213
+ break;
1214
+ case "handler": {
1215
+ const { setup, update } = createEventHandler(info.event);
1216
+ ctx.locations.push({
1217
+ idx: info.idx,
1218
+ refIdx: info.refIdx,
1219
+ setData: setup,
1220
+ updateData: update,
1221
+ });
1222
+ break;
1223
+ }
1224
+ case "ref": {
1225
+ ctx.locations.push({
1226
+ idx: info.idx,
1227
+ refIdx: info.refIdx,
1228
+ setData: NO_OP,
1229
+ updateData: NO_OP,
1230
+ });
1231
+ ctx.cbRefs.push(info.idx);
1232
+ break;
1233
+ }
1234
+ }
1235
+ }
1236
+ }
1237
+ // -----------------------------------------------------------------------------
1238
+ // building the concrete block class
1239
+ // -----------------------------------------------------------------------------
1240
+ function buildBlock(template, ctx) {
1241
+ let B = createBlockClass(template, ctx);
1242
+ if (ctx.children.length) {
1243
+ B = class extends B {
1244
+ constructor(data, children) {
1245
+ super(data);
1246
+ this.children = children;
1247
+ }
1248
+ };
1249
+ B.prototype.beforeRemove = VMulti.prototype.beforeRemove;
1250
+ return (data, children = []) => new B(data, children);
1251
+ }
1252
+ return (data) => new B(data);
1253
+ }
1254
+ function createBlockClass(template, ctx) {
1255
+ const { refN, collectors, children, locations, cbRefs } = ctx;
1256
+ const colN = collectors.length;
1257
+ locations.sort((a, b) => a.idx - b.idx);
1258
+ const locN = locations.length;
1259
+ const childN = children.length;
1260
+ const childrenLocs = children;
1261
+ const isDynamic = refN > 0;
1262
+ // these values are defined here to make them faster to lookup in the class
1263
+ // block scope
1264
+ const nodeCloneNode = nodeProto$2.cloneNode;
1265
+ const nodeInsertBefore = nodeProto$2.insertBefore;
1266
+ const elementRemove = elementProto.remove;
1267
+ class Block {
1268
+ constructor(data) {
1269
+ this.data = data;
1270
+ }
1271
+ beforeRemove() { }
1272
+ remove() {
1273
+ elementRemove.call(this.el);
1274
+ }
1275
+ firstNode() {
1276
+ return this.el;
1277
+ }
1278
+ moveBeforeDOMNode(node, parent = this.parentEl) {
1279
+ this.parentEl = parent;
1280
+ nodeInsertBefore.call(parent, this.el, node);
1281
+ }
1282
+ moveBeforeVNode(other, afterNode) {
1283
+ nodeInsertBefore.call(this.parentEl, this.el, other ? other.el : afterNode);
1284
+ }
1285
+ toString() {
1286
+ const div = document.createElement("div");
1287
+ this.mount(div, null);
1288
+ return div.innerHTML;
1289
+ }
1290
+ mount(parent, afterNode) {
1291
+ const el = nodeCloneNode.call(template, true);
1292
+ nodeInsertBefore.call(parent, el, afterNode);
1293
+ this.el = el;
1294
+ this.parentEl = parent;
1295
+ }
1296
+ patch(other, withBeforeRemove) { }
1297
+ }
1298
+ if (isDynamic) {
1299
+ Block.prototype.mount = function mount(parent, afterNode) {
1300
+ const el = nodeCloneNode.call(template, true);
1301
+ // collecting references
1302
+ const refs = new Array(refN);
1303
+ this.refs = refs;
1304
+ refs[0] = el;
1305
+ for (let i = 0; i < colN; i++) {
1306
+ const w = collectors[i];
1307
+ refs[w.idx] = w.getVal.call(refs[w.prevIdx]);
1308
+ }
1309
+ // applying data to all update points
1310
+ if (locN) {
1311
+ const data = this.data;
1312
+ for (let i = 0; i < locN; i++) {
1313
+ const loc = locations[i];
1314
+ loc.setData.call(refs[loc.refIdx], data[i]);
1315
+ }
1316
+ }
1317
+ nodeInsertBefore.call(parent, el, afterNode);
1318
+ // preparing all children
1319
+ if (childN) {
1320
+ const children = this.children;
1321
+ for (let i = 0; i < childN; i++) {
1322
+ const child = children[i];
1323
+ if (child) {
1324
+ const loc = childrenLocs[i];
1325
+ const afterNode = loc.afterRefIdx ? refs[loc.afterRefIdx] : null;
1326
+ child.isOnlyChild = loc.isOnlyChild;
1327
+ child.mount(refs[loc.parentRefIdx], afterNode);
1328
+ }
1329
+ }
1330
+ }
1331
+ this.el = el;
1332
+ this.parentEl = parent;
1333
+ if (cbRefs.length) {
1334
+ const data = this.data;
1335
+ const refs = this.refs;
1336
+ for (let cbRef of cbRefs) {
1337
+ const { idx, refIdx } = locations[cbRef];
1338
+ const fn = data[idx];
1339
+ fn(refs[refIdx], null);
1340
+ }
1341
+ }
1342
+ };
1343
+ Block.prototype.patch = function patch(other, withBeforeRemove) {
1344
+ if (this === other) {
1345
+ return;
1346
+ }
1347
+ const refs = this.refs;
1348
+ // update texts/attributes/
1349
+ if (locN) {
1350
+ const data1 = this.data;
1351
+ const data2 = other.data;
1352
+ for (let i = 0; i < locN; i++) {
1353
+ const val1 = data1[i];
1354
+ const val2 = data2[i];
1355
+ if (val1 !== val2) {
1356
+ const loc = locations[i];
1357
+ loc.updateData.call(refs[loc.refIdx], val2, val1);
1358
+ }
1359
+ }
1360
+ this.data = data2;
1361
+ }
1362
+ // update children
1363
+ if (childN) {
1364
+ let children1 = this.children;
1365
+ const children2 = other.children;
1366
+ for (let i = 0; i < childN; i++) {
1367
+ const child1 = children1[i];
1368
+ const child2 = children2[i];
1369
+ if (child1) {
1370
+ if (child2) {
1371
+ child1.patch(child2, withBeforeRemove);
1372
+ }
1373
+ else {
1374
+ if (withBeforeRemove) {
1375
+ child1.beforeRemove();
1376
+ }
1377
+ child1.remove();
1378
+ children1[i] = undefined;
1379
+ }
1380
+ }
1381
+ else if (child2) {
1382
+ const loc = childrenLocs[i];
1383
+ const afterNode = loc.afterRefIdx ? refs[loc.afterRefIdx] : null;
1384
+ child2.mount(refs[loc.parentRefIdx], afterNode);
1385
+ children1[i] = child2;
1386
+ }
1387
+ }
1388
+ }
1389
+ };
1390
+ Block.prototype.remove = function remove() {
1391
+ if (cbRefs.length) {
1392
+ const data = this.data;
1393
+ const refs = this.refs;
1394
+ for (let cbRef of cbRefs) {
1395
+ const { idx, refIdx } = locations[cbRef];
1396
+ const fn = data[idx];
1397
+ fn(null, refs[refIdx]);
1398
+ }
1399
+ }
1400
+ elementRemove.call(this.el);
1401
+ };
1402
+ }
1403
+ return Block;
1404
+ }
1405
+ function setText(value) {
1406
+ characterDataSetData.call(this, toText(value));
1407
+ }
1408
+
1409
+ const getDescriptor = (o, p) => Object.getOwnPropertyDescriptor(o, p);
1410
+ const nodeProto$1 = Node.prototype;
1411
+ const nodeInsertBefore$1 = nodeProto$1.insertBefore;
1412
+ const nodeAppendChild = nodeProto$1.appendChild;
1413
+ const nodeRemoveChild$1 = nodeProto$1.removeChild;
1414
+ const nodeSetTextContent = getDescriptor(nodeProto$1, "textContent").set;
1415
+ // -----------------------------------------------------------------------------
1416
+ // List Node
1417
+ // -----------------------------------------------------------------------------
1418
+ class VList {
1419
+ constructor(children) {
1420
+ this.children = children;
1421
+ }
1422
+ mount(parent, afterNode) {
1423
+ const children = this.children;
1424
+ const _anchor = document.createTextNode("");
1425
+ this.anchor = _anchor;
1426
+ nodeInsertBefore$1.call(parent, _anchor, afterNode);
1427
+ const l = children.length;
1428
+ if (l) {
1429
+ const mount = children[0].mount;
1430
+ for (let i = 0; i < l; i++) {
1431
+ mount.call(children[i], parent, _anchor);
1432
+ }
1433
+ }
1434
+ this.parentEl = parent;
1435
+ }
1436
+ moveBeforeDOMNode(node, parent = this.parentEl) {
1437
+ this.parentEl = parent;
1438
+ const children = this.children;
1439
+ for (let i = 0, l = children.length; i < l; i++) {
1440
+ children[i].moveBeforeDOMNode(node, parent);
1441
+ }
1442
+ parent.insertBefore(this.anchor, node);
1443
+ }
1444
+ moveBeforeVNode(other, afterNode) {
1445
+ if (other) {
1446
+ const next = other.children[0];
1447
+ afterNode = (next ? next.firstNode() : other.anchor) || null;
1448
+ }
1449
+ const children = this.children;
1450
+ for (let i = 0, l = children.length; i < l; i++) {
1451
+ children[i].moveBeforeVNode(null, afterNode);
1452
+ }
1453
+ this.parentEl.insertBefore(this.anchor, afterNode);
1454
+ }
1455
+ patch(other, withBeforeRemove) {
1456
+ if (this === other) {
1457
+ return;
1458
+ }
1459
+ const ch1 = this.children;
1460
+ const ch2 = other.children;
1461
+ if (ch2.length === 0 && ch1.length === 0) {
1462
+ return;
1463
+ }
1464
+ this.children = ch2;
1465
+ const proto = ch2[0] || ch1[0];
1466
+ const { mount: cMount, patch: cPatch, remove: cRemove, beforeRemove, moveBeforeVNode: cMoveBefore, firstNode: cFirstNode, } = proto;
1467
+ const _anchor = this.anchor;
1468
+ const isOnlyChild = this.isOnlyChild;
1469
+ const parent = this.parentEl;
1470
+ // fast path: no new child => only remove
1471
+ if (ch2.length === 0 && isOnlyChild) {
1472
+ if (withBeforeRemove) {
1473
+ for (let i = 0, l = ch1.length; i < l; i++) {
1474
+ beforeRemove.call(ch1[i]);
1475
+ }
1476
+ }
1477
+ nodeSetTextContent.call(parent, "");
1478
+ nodeAppendChild.call(parent, _anchor);
1479
+ return;
1480
+ }
1481
+ let startIdx1 = 0;
1482
+ let startIdx2 = 0;
1483
+ let startVn1 = ch1[0];
1484
+ let startVn2 = ch2[0];
1485
+ let endIdx1 = ch1.length - 1;
1486
+ let endIdx2 = ch2.length - 1;
1487
+ let endVn1 = ch1[endIdx1];
1488
+ let endVn2 = ch2[endIdx2];
1489
+ let mapping = undefined;
1490
+ while (startIdx1 <= endIdx1 && startIdx2 <= endIdx2) {
1491
+ // -------------------------------------------------------------------
1492
+ if (startVn1 === null) {
1493
+ startVn1 = ch1[++startIdx1];
1494
+ continue;
1495
+ }
1496
+ // -------------------------------------------------------------------
1497
+ if (endVn1 === null) {
1498
+ endVn1 = ch1[--endIdx1];
1499
+ continue;
1500
+ }
1501
+ // -------------------------------------------------------------------
1502
+ let startKey1 = startVn1.key;
1503
+ let startKey2 = startVn2.key;
1504
+ if (startKey1 === startKey2) {
1505
+ cPatch.call(startVn1, startVn2, withBeforeRemove);
1506
+ ch2[startIdx2] = startVn1;
1507
+ startVn1 = ch1[++startIdx1];
1508
+ startVn2 = ch2[++startIdx2];
1509
+ continue;
1510
+ }
1511
+ // -------------------------------------------------------------------
1512
+ let endKey1 = endVn1.key;
1513
+ let endKey2 = endVn2.key;
1514
+ if (endKey1 === endKey2) {
1515
+ cPatch.call(endVn1, endVn2, withBeforeRemove);
1516
+ ch2[endIdx2] = endVn1;
1517
+ endVn1 = ch1[--endIdx1];
1518
+ endVn2 = ch2[--endIdx2];
1519
+ continue;
1520
+ }
1521
+ // -------------------------------------------------------------------
1522
+ if (startKey1 === endKey2) {
1523
+ // bnode moved right
1524
+ cPatch.call(startVn1, endVn2, withBeforeRemove);
1525
+ ch2[endIdx2] = startVn1;
1526
+ const nextChild = ch2[endIdx2 + 1];
1527
+ cMoveBefore.call(startVn1, nextChild, _anchor);
1528
+ startVn1 = ch1[++startIdx1];
1529
+ endVn2 = ch2[--endIdx2];
1530
+ continue;
1531
+ }
1532
+ // -------------------------------------------------------------------
1533
+ if (endKey1 === startKey2) {
1534
+ // bnode moved left
1535
+ cPatch.call(endVn1, startVn2, withBeforeRemove);
1536
+ ch2[startIdx2] = endVn1;
1537
+ const nextChild = ch1[startIdx1];
1538
+ cMoveBefore.call(endVn1, nextChild, _anchor);
1539
+ endVn1 = ch1[--endIdx1];
1540
+ startVn2 = ch2[++startIdx2];
1541
+ continue;
1542
+ }
1543
+ // -------------------------------------------------------------------
1544
+ mapping = mapping || createMapping(ch1, startIdx1, endIdx1);
1545
+ let idxInOld = mapping[startKey2];
1546
+ if (idxInOld === undefined) {
1547
+ cMount.call(startVn2, parent, cFirstNode.call(startVn1) || null);
1548
+ }
1549
+ else {
1550
+ const elmToMove = ch1[idxInOld];
1551
+ cMoveBefore.call(elmToMove, startVn1, null);
1552
+ cPatch.call(elmToMove, startVn2, withBeforeRemove);
1553
+ ch2[startIdx2] = elmToMove;
1554
+ ch1[idxInOld] = null;
1555
+ }
1556
+ startVn2 = ch2[++startIdx2];
1557
+ }
1558
+ // ---------------------------------------------------------------------
1559
+ if (startIdx1 <= endIdx1 || startIdx2 <= endIdx2) {
1560
+ if (startIdx1 > endIdx1) {
1561
+ const nextChild = ch2[endIdx2 + 1];
1562
+ const anchor = nextChild ? cFirstNode.call(nextChild) || null : _anchor;
1563
+ for (let i = startIdx2; i <= endIdx2; i++) {
1564
+ cMount.call(ch2[i], parent, anchor);
1565
+ }
1566
+ }
1567
+ else {
1568
+ for (let i = startIdx1; i <= endIdx1; i++) {
1569
+ let ch = ch1[i];
1570
+ if (ch) {
1571
+ if (withBeforeRemove) {
1572
+ beforeRemove.call(ch);
1573
+ }
1574
+ cRemove.call(ch);
1575
+ }
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ beforeRemove() {
1581
+ const children = this.children;
1582
+ const l = children.length;
1583
+ if (l) {
1584
+ const beforeRemove = children[0].beforeRemove;
1585
+ for (let i = 0; i < l; i++) {
1586
+ beforeRemove.call(children[i]);
1587
+ }
1588
+ }
1589
+ }
1590
+ remove() {
1591
+ const { parentEl, anchor } = this;
1592
+ if (this.isOnlyChild) {
1593
+ nodeSetTextContent.call(parentEl, "");
1594
+ }
1595
+ else {
1596
+ const children = this.children;
1597
+ const l = children.length;
1598
+ if (l) {
1599
+ const remove = children[0].remove;
1600
+ for (let i = 0; i < l; i++) {
1601
+ remove.call(children[i]);
1602
+ }
1603
+ }
1604
+ nodeRemoveChild$1.call(parentEl, anchor);
1605
+ }
1606
+ }
1607
+ firstNode() {
1608
+ const child = this.children[0];
1609
+ return child ? child.firstNode() : undefined;
1610
+ }
1611
+ toString() {
1612
+ return this.children.map((c) => c.toString()).join("");
1613
+ }
1614
+ }
1615
+ function list(children) {
1616
+ return new VList(children);
1617
+ }
1618
+ function createMapping(ch1, startIdx1, endIdx2) {
1619
+ let mapping = {};
1620
+ for (let i = startIdx1; i <= endIdx2; i++) {
1621
+ mapping[ch1[i].key] = i;
1622
+ }
1623
+ return mapping;
1624
+ }
1625
+
1626
+ const nodeProto = Node.prototype;
1627
+ const nodeInsertBefore = nodeProto.insertBefore;
1628
+ const nodeRemoveChild = nodeProto.removeChild;
1629
+ class VHtml {
1630
+ constructor(html) {
1631
+ this.content = [];
1632
+ this.html = html;
1633
+ }
1634
+ mount(parent, afterNode) {
1635
+ this.parentEl = parent;
1636
+ const template = document.createElement("template");
1637
+ template.innerHTML = this.html;
1638
+ this.content = [...template.content.childNodes];
1639
+ for (let elem of this.content) {
1640
+ nodeInsertBefore.call(parent, elem, afterNode);
1641
+ }
1642
+ if (!this.content.length) {
1643
+ const textNode = document.createTextNode("");
1644
+ this.content.push(textNode);
1645
+ nodeInsertBefore.call(parent, textNode, afterNode);
1646
+ }
1647
+ }
1648
+ moveBeforeDOMNode(node, parent = this.parentEl) {
1649
+ this.parentEl = parent;
1650
+ for (let elem of this.content) {
1651
+ nodeInsertBefore.call(parent, elem, node);
1652
+ }
1653
+ }
1654
+ moveBeforeVNode(other, afterNode) {
1655
+ const target = other ? other.content[0] : afterNode;
1656
+ this.moveBeforeDOMNode(target);
1657
+ }
1658
+ patch(other) {
1659
+ if (this === other) {
1660
+ return;
1661
+ }
1662
+ const html2 = other.html;
1663
+ if (this.html !== html2) {
1664
+ const parent = this.parentEl;
1665
+ // insert new html in front of current
1666
+ const afterNode = this.content[0];
1667
+ const template = document.createElement("template");
1668
+ template.innerHTML = html2;
1669
+ const content = [...template.content.childNodes];
1670
+ for (let elem of content) {
1671
+ nodeInsertBefore.call(parent, elem, afterNode);
1672
+ }
1673
+ if (!content.length) {
1674
+ const textNode = document.createTextNode("");
1675
+ content.push(textNode);
1676
+ nodeInsertBefore.call(parent, textNode, afterNode);
1677
+ }
1678
+ // remove current content
1679
+ this.remove();
1680
+ this.content = content;
1681
+ this.html = other.html;
1682
+ }
1683
+ }
1684
+ beforeRemove() { }
1685
+ remove() {
1686
+ const parent = this.parentEl;
1687
+ for (let elem of this.content) {
1688
+ nodeRemoveChild.call(parent, elem);
1689
+ }
1690
+ }
1691
+ firstNode() {
1692
+ return this.content[0];
1693
+ }
1694
+ toString() {
1695
+ return this.html;
1696
+ }
1697
+ }
1698
+ function html(str) {
1699
+ return new VHtml(str);
1700
+ }
1701
+
1702
+ function createCatcher(eventsSpec) {
1703
+ const n = Object.keys(eventsSpec).length;
1704
+ class VCatcher {
1705
+ constructor(child, handlers) {
1706
+ this.handlerFns = [];
1707
+ this.afterNode = null;
1708
+ this.child = child;
1709
+ this.handlerData = handlers;
1710
+ }
1711
+ mount(parent, afterNode) {
1712
+ this.parentEl = parent;
1713
+ this.child.mount(parent, afterNode);
1714
+ this.afterNode = document.createTextNode("");
1715
+ parent.insertBefore(this.afterNode, afterNode);
1716
+ this.wrapHandlerData();
1717
+ for (let name in eventsSpec) {
1718
+ const index = eventsSpec[name];
1719
+ const handler = createEventHandler(name);
1720
+ this.handlerFns[index] = handler;
1721
+ handler.setup.call(parent, this.handlerData[index]);
1722
+ }
1723
+ }
1724
+ wrapHandlerData() {
1725
+ for (let i = 0; i < n; i++) {
1726
+ let handler = this.handlerData[i];
1727
+ // handler = [...mods, fn, comp], so we need to replace second to last elem
1728
+ let idx = handler.length - 2;
1729
+ let origFn = handler[idx];
1730
+ const self = this;
1731
+ handler[idx] = function (ev) {
1732
+ const target = ev.target;
1733
+ let currentNode = self.child.firstNode();
1734
+ const afterNode = self.afterNode;
1735
+ while (currentNode && currentNode !== afterNode) {
1736
+ if (currentNode.contains(target)) {
1737
+ return origFn.call(this, ev);
1738
+ }
1739
+ currentNode = currentNode.nextSibling;
1740
+ }
1741
+ };
1742
+ }
1743
+ }
1744
+ moveBeforeDOMNode(node, parent = this.parentEl) {
1745
+ this.parentEl = parent;
1746
+ this.child.moveBeforeDOMNode(node, parent);
1747
+ parent.insertBefore(this.afterNode, node);
1748
+ }
1749
+ moveBeforeVNode(other, afterNode) {
1750
+ if (other) {
1751
+ // check this with @ged-odoo for use in foreach
1752
+ afterNode = other.firstNode() || afterNode;
1753
+ }
1754
+ this.child.moveBeforeVNode(other ? other.child : null, afterNode);
1755
+ this.parentEl.insertBefore(this.afterNode, afterNode);
1756
+ }
1757
+ patch(other, withBeforeRemove) {
1758
+ if (this === other) {
1759
+ return;
1760
+ }
1761
+ this.handlerData = other.handlerData;
1762
+ this.wrapHandlerData();
1763
+ for (let i = 0; i < n; i++) {
1764
+ this.handlerFns[i].update.call(this.parentEl, this.handlerData[i]);
1765
+ }
1766
+ this.child.patch(other.child, withBeforeRemove);
1767
+ }
1768
+ beforeRemove() {
1769
+ this.child.beforeRemove();
1770
+ }
1771
+ remove() {
1772
+ for (let i = 0; i < n; i++) {
1773
+ this.handlerFns[i].remove.call(this.parentEl);
1774
+ }
1775
+ this.child.remove();
1776
+ this.afterNode.remove();
1777
+ }
1778
+ firstNode() {
1779
+ return this.child.firstNode();
1780
+ }
1781
+ toString() {
1782
+ return this.child.toString();
1783
+ }
1784
+ }
1785
+ return function (child, handlers) {
1786
+ return new VCatcher(child, handlers);
1787
+ };
1788
+ }
1789
+
1790
+ function mount$1(vnode, fixture, afterNode = null) {
1791
+ vnode.mount(fixture, afterNode);
1792
+ }
1793
+ function patch(vnode1, vnode2, withBeforeRemove = false) {
1794
+ vnode1.patch(vnode2, withBeforeRemove);
1795
+ }
1796
+ function remove(vnode, withBeforeRemove = false) {
1797
+ if (withBeforeRemove) {
1798
+ vnode.beforeRemove();
1799
+ }
1800
+ vnode.remove();
1801
+ }
1802
+
1803
+ function makeChildFiber(node, parent) {
1804
+ let current = node.fiber;
1805
+ if (current) {
1806
+ cancelFibers(current.children);
1807
+ current.root = null;
1808
+ }
1809
+ return new Fiber(node, parent);
1810
+ }
1811
+ function makeRootFiber(node) {
1812
+ let current = node.fiber;
1813
+ if (current) {
1814
+ let root = current.root;
1815
+ // lock root fiber because canceling children fibers may destroy components,
1816
+ // which means any arbitrary code can be run in onWillDestroy, which may
1817
+ // trigger new renderings
1818
+ root.locked = true;
1819
+ root.setCounter(root.counter + 1 - cancelFibers(current.children));
1820
+ root.locked = false;
1821
+ current.children = [];
1822
+ current.childrenMap = {};
1823
+ current.bdom = null;
1824
+ if (fibersInError.has(current)) {
1825
+ fibersInError.delete(current);
1826
+ fibersInError.delete(root);
1827
+ current.appliedToDom = false;
1828
+ if (current instanceof RootFiber) {
1829
+ // it is possible that this fiber is a fiber that crashed while being
1830
+ // mounted, so the mounted list is possibly corrupted. We restore it to
1831
+ // its normal initial state (which is empty list or a list with a mount
1832
+ // fiber.
1833
+ current.mounted = current instanceof MountFiber ? [current] : [];
1834
+ }
1835
+ }
1836
+ return current;
1837
+ }
1838
+ const fiber = new RootFiber(node, null);
1839
+ if (node.willPatch.length) {
1840
+ fiber.willPatch.push(fiber);
1841
+ }
1842
+ if (node.patched.length) {
1843
+ fiber.patched.push(fiber);
1844
+ }
1845
+ return fiber;
1846
+ }
1847
+ function throwOnRender() {
1848
+ throw new OwlError("Attempted to render cancelled fiber");
1849
+ }
1850
+ /**
1851
+ * @returns number of not-yet rendered fibers cancelled
1852
+ */
1853
+ function cancelFibers(fibers) {
1854
+ let result = 0;
1855
+ for (let fiber of fibers) {
1856
+ let node = fiber.node;
1857
+ fiber.render = throwOnRender;
1858
+ if (node.status === 0 /* STATUS.NEW */) {
1859
+ node.cancel();
1860
+ }
1861
+ node.fiber = null;
1862
+ if (fiber.bdom) {
1863
+ // if fiber has been rendered, this means that the component props have
1864
+ // been updated. however, this fiber will not be patched to the dom, so
1865
+ // it could happen that the next render compare the current props with
1866
+ // the same props, and skip the render completely. With the next line,
1867
+ // we kindly request the component code to force a render, so it works as
1868
+ // expected.
1869
+ node.forceNextRender = true;
1870
+ }
1871
+ else {
1872
+ result++;
1873
+ }
1874
+ result += cancelFibers(fiber.children);
1875
+ }
1876
+ return result;
1877
+ }
1878
+ class Fiber {
1879
+ constructor(node, parent) {
1880
+ this.bdom = null;
1881
+ this.children = [];
1882
+ this.appliedToDom = false;
1883
+ this.deep = false;
1884
+ this.childrenMap = {};
1885
+ this.node = node;
1886
+ this.parent = parent;
1887
+ if (parent) {
1888
+ this.deep = parent.deep;
1889
+ const root = parent.root;
1890
+ root.setCounter(root.counter + 1);
1891
+ this.root = root;
1892
+ parent.children.push(this);
1893
+ }
1894
+ else {
1895
+ this.root = this;
1896
+ }
1897
+ }
1898
+ render() {
1899
+ // if some parent has a fiber => register in followup
1900
+ let prev = this.root.node;
1901
+ let scheduler = prev.app.scheduler;
1902
+ let current = prev.parent;
1903
+ while (current) {
1904
+ if (current.fiber) {
1905
+ let root = current.fiber.root;
1906
+ if (root.counter === 0 && prev.parentKey in current.fiber.childrenMap) {
1907
+ current = root.node;
1908
+ }
1909
+ else {
1910
+ scheduler.delayedRenders.push(this);
1911
+ return;
1912
+ }
1913
+ }
1914
+ prev = current;
1915
+ current = current.parent;
1916
+ }
1917
+ // there are no current rendering from above => we can render
1918
+ this._render();
1919
+ }
1920
+ _render() {
1921
+ const node = this.node;
1922
+ const root = this.root;
1923
+ if (root) {
1924
+ // todo: should use updateComputation somewhere else.
1925
+ runWithComputation(node.signalComputation, () => {
1926
+ try {
1927
+ this.bdom = true;
1928
+ this.bdom = node.renderFn();
1929
+ }
1930
+ catch (e) {
1931
+ node.app.handleError({ node, error: e });
1932
+ }
1933
+ });
1934
+ root.setCounter(root.counter - 1);
1935
+ }
1936
+ }
1937
+ }
1938
+ class RootFiber extends Fiber {
1939
+ constructor() {
1940
+ super(...arguments);
1941
+ this.counter = 1;
1942
+ // only add stuff in this if they have registered some hooks
1943
+ this.willPatch = [];
1944
+ this.patched = [];
1945
+ this.mounted = [];
1946
+ // A fiber is typically locked when it is completing and the patch has not, or is being applied.
1947
+ // i.e.: render triggered in onWillUnmount or in willPatch will be delayed
1948
+ this.locked = false;
1949
+ }
1950
+ complete() {
1951
+ const node = this.node;
1952
+ this.locked = true;
1953
+ let current = undefined;
1954
+ let mountedFibers = this.mounted;
1955
+ try {
1956
+ // Step 1: calling all willPatch lifecycle hooks
1957
+ for (current of this.willPatch) {
1958
+ // because of the asynchronous nature of the rendering, some parts of the
1959
+ // UI may have been rendered, then deleted in a followup rendering, and we
1960
+ // do not want to call onWillPatch in that case.
1961
+ let node = current.node;
1962
+ if (node.fiber === current) {
1963
+ const component = node.component;
1964
+ for (let cb of node.willPatch) {
1965
+ cb.call(component);
1966
+ }
1967
+ }
1968
+ }
1969
+ current = undefined;
1970
+ // Step 2: patching the dom
1971
+ node._patch();
1972
+ this.locked = false;
1973
+ // Step 4: calling all mounted lifecycle hooks
1974
+ while ((current = mountedFibers.pop())) {
1975
+ current = current;
1976
+ if (current.appliedToDom) {
1977
+ for (let cb of current.node.mounted) {
1978
+ cb();
1979
+ }
1980
+ }
1981
+ }
1982
+ // Step 5: calling all patched hooks
1983
+ let patchedFibers = this.patched;
1984
+ while ((current = patchedFibers.pop())) {
1985
+ current = current;
1986
+ if (current.appliedToDom) {
1987
+ for (let cb of current.node.patched) {
1988
+ cb();
1989
+ }
1990
+ }
1991
+ }
1992
+ }
1993
+ catch (e) {
1994
+ // if mountedFibers is not empty, this means that a crash occured while
1995
+ // calling the mounted hooks of some component. So, there may still be
1996
+ // some component that have been mounted, but for which the mounted hooks
1997
+ // have not been called. Here, we remove the willUnmount hooks for these
1998
+ // specific component to prevent a worse situation (willUnmount being
1999
+ // called even though mounted has not been called)
2000
+ for (let fiber of mountedFibers) {
2001
+ fiber.node.willUnmount = [];
2002
+ }
2003
+ this.locked = false;
2004
+ node.app.handleError({ fiber: current || this, error: e });
2005
+ }
2006
+ }
2007
+ setCounter(newValue) {
2008
+ this.counter = newValue;
2009
+ if (newValue === 0) {
2010
+ this.node.app.scheduler.flush();
2011
+ }
2012
+ }
2013
+ }
2014
+ class MountFiber extends RootFiber {
2015
+ constructor(node, target, options = {}) {
2016
+ super(node, null);
2017
+ this.target = target;
2018
+ this.position = options.position || "last-child";
2019
+ }
2020
+ complete() {
2021
+ let current = this;
2022
+ try {
2023
+ const node = this.node;
2024
+ node.children = this.childrenMap;
2025
+ node.app.constructor.validateTarget(this.target);
2026
+ if (node.bdom) {
2027
+ // this is a complicated situation: if we mount a fiber with an existing
2028
+ // bdom, this means that this same fiber was already completed, mounted,
2029
+ // but a crash occurred in some mounted hook. Then, it was handled and
2030
+ // the new rendering is being applied.
2031
+ node.updateDom();
2032
+ }
2033
+ else {
2034
+ node.bdom = this.bdom;
2035
+ if (this.position === "last-child" || this.target.childNodes.length === 0) {
2036
+ mount$1(node.bdom, this.target);
2037
+ }
2038
+ else {
2039
+ const firstChild = this.target.childNodes[0];
2040
+ mount$1(node.bdom, this.target, firstChild);
2041
+ }
2042
+ }
2043
+ // unregistering the fiber before mounted since it can do another render
2044
+ // and that the current rendering is obviously completed
2045
+ node.fiber = null;
2046
+ node.status = 1 /* STATUS.MOUNTED */;
2047
+ this.appliedToDom = true;
2048
+ let mountedFibers = this.mounted;
2049
+ while ((current = mountedFibers.pop())) {
2050
+ if (current.appliedToDom) {
2051
+ for (let cb of current.node.mounted) {
2052
+ cb();
2053
+ }
2054
+ }
2055
+ }
2056
+ }
2057
+ catch (e) {
2058
+ this.node.app.handleError({ fiber: current, error: e });
2059
+ }
2060
+ }
2061
+ }
2062
+
2063
+ let currentNode = null;
2064
+ function saveCurrent() {
2065
+ let n = currentNode;
2066
+ return () => {
2067
+ currentNode = n;
2068
+ };
2069
+ }
2070
+ function getCurrent() {
2071
+ if (!currentNode) {
2072
+ throw new OwlError("No active component (a hook function should only be called in 'setup')");
2073
+ }
2074
+ return currentNode;
2075
+ }
2076
+ function useComponent() {
2077
+ return currentNode.component;
2078
+ }
2079
+ class ComponentNode {
2080
+ constructor(C, props, app, parent, parentKey) {
2081
+ this.fiber = null;
2082
+ this.bdom = null;
2083
+ this.status = 0 /* STATUS.NEW */;
2084
+ this.forceNextRender = false;
2085
+ this.children = Object.create(null);
2086
+ this.willStart = [];
2087
+ this.willUpdateProps = [];
2088
+ this.willUnmount = [];
2089
+ this.mounted = [];
2090
+ this.willPatch = [];
2091
+ this.patched = [];
2092
+ this.willDestroy = [];
2093
+ this.name = C.name;
2094
+ currentNode = this;
2095
+ this.app = app;
2096
+ this.parent = parent;
2097
+ this.parentKey = parentKey;
2098
+ this.pluginManager = parent ? parent.pluginManager : app.pluginManager;
2099
+ this.signalComputation = {
2100
+ value: undefined,
2101
+ compute: () => this.render(false),
2102
+ sources: new Set(),
2103
+ state: ComputationState.EXECUTED,
2104
+ };
2105
+ this.props = Object.assign({}, props);
2106
+ const previousComputation = getCurrentComputation();
2107
+ setComputation(this.signalComputation);
2108
+ this.component = new C(this);
2109
+ const ctx = { this: this.component, __owl__: this };
2110
+ this.renderFn = app.getTemplate(C.template).bind(this.component, ctx, this);
2111
+ this.component.setup();
2112
+ setComputation(previousComputation);
2113
+ currentNode = null;
2114
+ }
2115
+ mountComponent(target, options) {
2116
+ const fiber = new MountFiber(this, target, options);
2117
+ this.app.scheduler.addFiber(fiber);
2118
+ this.initiateRender(fiber);
2119
+ }
2120
+ async initiateRender(fiber) {
2121
+ this.fiber = fiber;
2122
+ if (this.mounted.length) {
2123
+ fiber.root.mounted.push(fiber);
2124
+ }
2125
+ const component = this.component;
2126
+ try {
2127
+ let promises;
2128
+ runWithComputation(undefined, () => {
2129
+ promises = this.willStart.map((f) => f.call(component));
2130
+ });
2131
+ await Promise.all(promises);
2132
+ }
2133
+ catch (e) {
2134
+ this.app.handleError({ node: this, error: e });
2135
+ return;
2136
+ }
2137
+ if (this.status === 0 /* STATUS.NEW */ && this.fiber === fiber) {
2138
+ fiber.render();
2139
+ }
2140
+ }
2141
+ async render(deep) {
2142
+ if (this.status >= 2 /* STATUS.CANCELLED */) {
2143
+ return;
2144
+ }
2145
+ let current = this.fiber;
2146
+ if (current && (current.root.locked || current.bdom === true)) {
2147
+ await Promise.resolve();
2148
+ // situation may have changed after the microtask tick
2149
+ current = this.fiber;
2150
+ }
2151
+ if (current) {
2152
+ if (!current.bdom && !fibersInError.has(current)) {
2153
+ if (deep) {
2154
+ // we want the render from this point on to be with deep=true
2155
+ current.deep = deep;
2156
+ }
2157
+ return;
2158
+ }
2159
+ // if current rendering was with deep=true, we want this one to be the same
2160
+ deep = deep || current.deep;
2161
+ }
2162
+ else if (!this.bdom) {
2163
+ return;
2164
+ }
2165
+ const fiber = makeRootFiber(this);
2166
+ fiber.deep = deep;
2167
+ this.fiber = fiber;
2168
+ this.app.scheduler.addFiber(fiber);
2169
+ await Promise.resolve();
2170
+ if (this.status >= 2 /* STATUS.CANCELLED */) {
2171
+ return;
2172
+ }
2173
+ // We only want to actually render the component if the following two
2174
+ // conditions are true:
2175
+ // * this.fiber: it could be null, in which case the render has been cancelled
2176
+ // * (current || !fiber.parent): if current is not null, this means that the
2177
+ // render function was called when a render was already occurring. In this
2178
+ // case, the pending rendering was cancelled, and the fiber needs to be
2179
+ // rendered to complete the work. If current is null, we check that the
2180
+ // fiber has no parent. If that is the case, the fiber was downgraded from
2181
+ // a root fiber to a child fiber in the previous microtick, because it was
2182
+ // embedded in a rendering coming from above, so the fiber will be rendered
2183
+ // in the next microtick anyway, so we should not render it again.
2184
+ if (this.fiber === fiber && (current || !fiber.parent)) {
2185
+ fiber.render();
2186
+ }
2187
+ }
2188
+ cancel() {
2189
+ this._cancel();
2190
+ delete this.parent.children[this.parentKey];
2191
+ this.app.scheduler.scheduleDestroy(this);
2192
+ }
2193
+ _cancel() {
2194
+ this.status = 2 /* STATUS.CANCELLED */;
2195
+ const children = this.children;
2196
+ for (let childKey in children) {
2197
+ children[childKey]._cancel();
2198
+ }
2199
+ }
2200
+ destroy() {
2201
+ let shouldRemove = this.status === 1 /* STATUS.MOUNTED */;
2202
+ this._destroy();
2203
+ if (shouldRemove) {
2204
+ this.bdom.remove();
2205
+ }
2206
+ }
2207
+ _destroy() {
2208
+ const component = this.component;
2209
+ if (this.status === 1 /* STATUS.MOUNTED */) {
2210
+ for (let cb of this.willUnmount) {
2211
+ cb.call(component);
2212
+ }
2213
+ }
2214
+ for (let child of Object.values(this.children)) {
2215
+ child._destroy();
2216
+ }
2217
+ if (this.willDestroy.length) {
2218
+ try {
2219
+ for (let cb of this.willDestroy) {
2220
+ cb.call(component);
2221
+ }
2222
+ }
2223
+ catch (e) {
2224
+ this.app.handleError({ error: e, node: this });
2225
+ }
2226
+ }
2227
+ this.status = 3 /* STATUS.DESTROYED */;
2228
+ }
2229
+ async updateAndRender(props, parentFiber) {
2230
+ props = Object.assign({}, props);
2231
+ // update
2232
+ const fiber = makeChildFiber(this, parentFiber);
2233
+ this.fiber = fiber;
2234
+ const component = this.component;
2235
+ let prom;
2236
+ untrack(() => {
2237
+ prom = Promise.all(this.willUpdateProps.map((f) => f.call(component, props)));
2238
+ });
2239
+ await prom;
2240
+ if (fiber !== this.fiber) {
2241
+ return;
2242
+ }
2243
+ this.props = props;
2244
+ fiber.render();
2245
+ const parentRoot = parentFiber.root;
2246
+ if (this.willPatch.length) {
2247
+ parentRoot.willPatch.push(fiber);
2248
+ }
2249
+ if (this.patched.length) {
2250
+ parentRoot.patched.push(fiber);
2251
+ }
2252
+ }
2253
+ /**
2254
+ * Finds a child that has dom that is not yet updated, and update it. This
2255
+ * method is meant to be used only in the context of repatching the dom after
2256
+ * a mounted hook failed and was handled.
2257
+ */
2258
+ updateDom() {
2259
+ if (!this.fiber) {
2260
+ return;
2261
+ }
2262
+ if (this.bdom === this.fiber.bdom) {
2263
+ // If the error was handled by some child component, we need to find it to
2264
+ // apply its change
2265
+ for (let k in this.children) {
2266
+ const child = this.children[k];
2267
+ child.updateDom();
2268
+ }
2269
+ }
2270
+ else {
2271
+ // if we get here, this is the component that handled the error and rerendered
2272
+ // itself, so we can simply patch the dom
2273
+ this.bdom.patch(this.fiber.bdom, false);
2274
+ this.fiber.appliedToDom = true;
2275
+ this.fiber = null;
2276
+ }
2277
+ }
2278
+ // ---------------------------------------------------------------------------
2279
+ // Block DOM methods
2280
+ // ---------------------------------------------------------------------------
2281
+ firstNode() {
2282
+ const bdom = this.bdom;
2283
+ return bdom ? bdom.firstNode() : undefined;
2284
+ }
2285
+ mount(parent, anchor) {
2286
+ const bdom = this.fiber.bdom;
2287
+ this.bdom = bdom;
2288
+ bdom.mount(parent, anchor);
2289
+ this.status = 1 /* STATUS.MOUNTED */;
2290
+ this.fiber.appliedToDom = true;
2291
+ this.children = this.fiber.childrenMap;
2292
+ this.fiber = null;
2293
+ }
2294
+ moveBeforeDOMNode(node, parent) {
2295
+ this.bdom.moveBeforeDOMNode(node, parent);
2296
+ }
2297
+ moveBeforeVNode(other, afterNode) {
2298
+ this.bdom.moveBeforeVNode(other ? other.bdom : null, afterNode);
2299
+ }
2300
+ patch() {
2301
+ if (this.fiber && this.fiber.parent) {
2302
+ // we only patch here renderings coming from above. renderings initiated
2303
+ // by the component will be patched independently in the appropriate
2304
+ // fiber.complete
2305
+ this._patch();
2306
+ }
2307
+ }
2308
+ _patch() {
2309
+ let hasChildren = false;
2310
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
2311
+ for (let _k in this.children) {
2312
+ hasChildren = true;
2313
+ break;
2314
+ }
2315
+ const fiber = this.fiber;
2316
+ this.children = fiber.childrenMap;
2317
+ this.bdom.patch(fiber.bdom, hasChildren);
2318
+ fiber.appliedToDom = true;
2319
+ this.fiber = null;
2320
+ }
2321
+ beforeRemove() {
2322
+ this._destroy();
2323
+ }
2324
+ remove() {
2325
+ this.bdom.remove();
2326
+ }
2327
+ }
2328
+
2329
+ let currentPluginManager = null;
2330
+ const _getCurrentPluginManager = () => currentPluginManager;
2331
+ class Plugin {
2332
+ setup() { }
2333
+ }
2334
+ Plugin.id = "";
2335
+ class PluginManager {
2336
+ constructor(parent) {
2337
+ var _a;
2338
+ this.children = [];
2339
+ this.onDestroyCb = [];
2340
+ this.status = 0 /* STATUS.NEW */;
2341
+ this.parent = parent;
2342
+ (_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.push(this);
2343
+ this.plugins = this.parent ? Object.create(this.parent.plugins) : {};
2344
+ }
2345
+ destroy() {
2346
+ for (let children of this.children) {
2347
+ children.destroy();
2348
+ }
2349
+ const cbs = this.onDestroyCb;
2350
+ while (cbs.length) {
2351
+ cbs.pop()();
2352
+ }
2353
+ this.status = 3 /* STATUS.DESTROYED */;
2354
+ }
2355
+ getPluginById(id) {
2356
+ return this.plugins[id] || null;
2357
+ }
2358
+ getPlugin(pluginType) {
2359
+ return this.getPluginById(pluginType.id);
2360
+ }
2361
+ startPlugins(pluginTypes) {
2362
+ const previousManager = currentPluginManager;
2363
+ currentPluginManager = this;
2364
+ const plugins = [];
2365
+ // instantiate plugins
2366
+ for (const pluginType of pluginTypes) {
2367
+ if (!pluginType.id) {
2368
+ currentPluginManager = previousManager;
2369
+ throw new OwlError(`Plugin "${pluginType.name}" has no id`);
2370
+ }
2371
+ if (this.plugins.hasOwnProperty(pluginType.id)) {
2372
+ continue;
2373
+ }
2374
+ const plugin = new pluginType();
2375
+ this.plugins[pluginType.id] = plugin;
2376
+ plugins.push(plugin);
2377
+ }
2378
+ // setup phase
2379
+ for (let p of plugins) {
2380
+ p.setup();
2381
+ }
2382
+ currentPluginManager = previousManager;
2383
+ if (!currentPluginManager) {
2384
+ this.status = 1 /* STATUS.MOUNTED */;
2385
+ }
2386
+ return plugins;
2387
+ }
2388
+ }
2389
+ function plugin(pluginType) {
2390
+ // getCurrent will throw if we're not in a component
2391
+ const manager = currentPluginManager || getCurrent().pluginManager;
2392
+ let plugin = manager.getPluginById(pluginType.id);
2393
+ if (!plugin) {
2394
+ if (manager === currentPluginManager) {
2395
+ manager.startPlugins([pluginType]);
2396
+ plugin = manager.getPluginById(pluginType.id);
2397
+ }
2398
+ else {
2399
+ throw new OwlError(`Unknown plugin "${pluginType.id}"`);
2400
+ }
2401
+ }
2402
+ return plugin;
2403
+ }
2404
+
2405
+ // Special key to subscribe to, to be notified of key creation/deletion
2406
+ const KEYCHANGES = Symbol("Key changes");
2407
+ const objectToString = Object.prototype.toString;
2408
+ const objectHasOwnProperty = Object.prototype.hasOwnProperty;
2409
+ // Use arrays because Array.includes is faster than Set.has for small arrays
2410
+ const SUPPORTED_RAW_TYPES = ["Object", "Array", "Set", "Map", "WeakMap"];
2411
+ const COLLECTION_RAW_TYPES = ["Set", "Map", "WeakMap"];
2412
+ /**
2413
+ * extract "RawType" from strings like "[object RawType]" => this lets us ignore
2414
+ * many native objects such as Promise (whose toString is [object Promise])
2415
+ * or Date ([object Date]), while also supporting collections without using
2416
+ * instanceof in a loop
2417
+ *
2418
+ * @param obj the object to check
2419
+ * @returns the raw type of the object
2420
+ */
2421
+ function rawType(obj) {
2422
+ return objectToString.call(toRaw(obj)).slice(8, -1);
2423
+ }
2424
+ /**
2425
+ * Checks whether a given value can be made into a proxy object.
2426
+ *
2427
+ * @param value the value to check
2428
+ * @returns whether the value can be made proxy
2429
+ */
2430
+ function canBeMadeReactive(value) {
2431
+ if (typeof value !== "object") {
2432
+ return false;
2433
+ }
2434
+ return SUPPORTED_RAW_TYPES.includes(rawType(value));
2435
+ }
2436
+ /**
2437
+ * Creates a proxy from the given object/callback if possible and returns it,
2438
+ * returns the original object otherwise.
2439
+ *
2440
+ * @param value the value make proxy
2441
+ * @returns a proxy for the given object when possible, the original otherwise
2442
+ */
2443
+ function possiblyReactive(val) {
2444
+ return canBeMadeReactive(val) ? proxy(val) : val;
2445
+ }
2446
+ const skipped = new WeakSet();
2447
+ /**
2448
+ * Mark an object or array so that it is ignored by the reactivity system
2449
+ *
2450
+ * @param value the value to mark
2451
+ * @returns the object itself
2452
+ */
2453
+ function markRaw(value) {
2454
+ skipped.add(value);
2455
+ return value;
2456
+ }
2457
+ /**
2458
+ * Given a proxy objet, return the raw (non proxy) underlying object
2459
+ *
2460
+ * @param value a proxy value
2461
+ * @returns the underlying value
2462
+ */
2463
+ function toRaw(value) {
2464
+ return targets.has(value) ? targets.get(value) : value;
2465
+ }
2466
+ const targetToKeysToAtomItem = new WeakMap();
2467
+ function getTargetKeyAtom(target, key) {
2468
+ let keyToAtomItem = targetToKeysToAtomItem.get(target);
2469
+ if (!keyToAtomItem) {
2470
+ keyToAtomItem = new Map();
2471
+ targetToKeysToAtomItem.set(target, keyToAtomItem);
2472
+ }
2473
+ let atom = keyToAtomItem.get(key);
2474
+ if (!atom) {
2475
+ atom = {
2476
+ value: undefined,
2477
+ observers: new Set(),
2478
+ };
2479
+ keyToAtomItem.set(key, atom);
2480
+ }
2481
+ return atom;
2482
+ }
2483
+ /**
2484
+ * Observes a given key on a target with an callback. The callback will be
2485
+ * called when the given key changes on the target.
2486
+ *
2487
+ * @param target the target whose key should be observed
2488
+ * @param key the key to observe (or Symbol(KEYCHANGES) for key creation
2489
+ * or deletion)
2490
+ * @param callback the function to call when the key changes
2491
+ */
2492
+ function onReadTargetKey(target, key) {
2493
+ onReadAtom(getTargetKeyAtom(target, key));
2494
+ }
2495
+ /**
2496
+ * Notify Reactives that are observing a given target that a key has changed on
2497
+ * the target.
2498
+ *
2499
+ * @param target target whose Reactives should be notified that the target was
2500
+ * changed.
2501
+ * @param key the key that changed (or Symbol `KEYCHANGES` if a key was created
2502
+ * or deleted)
2503
+ */
2504
+ function onWriteTargetKey(target, key) {
2505
+ const keyToAtomItem = targetToKeysToAtomItem.get(target);
2506
+ if (!keyToAtomItem) {
2507
+ return;
2508
+ }
2509
+ const atom = keyToAtomItem.get(key);
2510
+ if (!atom) {
2511
+ return;
2512
+ }
2513
+ onWriteAtom(atom);
2514
+ }
2515
+ // Maps proxy objects to the underlying target
2516
+ const targets = new WeakMap();
2517
+ const proxyCache = new WeakMap();
2518
+ /**
2519
+ * Creates a reactive proxy for an object. Reading data on the proxy object
2520
+ * subscribes to changes to the data. Writing data on the object will cause the
2521
+ * notify callback to be called if there are suscriptions to that data. Nested
2522
+ * objects and arrays are automatically made reactive as well.
2523
+ *
2524
+ * Whenever you are notified of a change, all subscriptions are cleared, and if
2525
+ * you would like to be notified of any further changes, you should go read
2526
+ * the underlying data again. We assume that if you don't go read it again after
2527
+ * being notified, it means that you are no longer interested in that data.
2528
+ *
2529
+ * Subscriptions:
2530
+ * + Reading a property on an object will subscribe you to changes in the value
2531
+ * of that property.
2532
+ * + Accessing an object's keys (eg with Object.keys or with `for..in`) will
2533
+ * subscribe you to the creation/deletion of keys. Checking the presence of a
2534
+ * key on the object with 'in' has the same effect.
2535
+ * - getOwnPropertyDescriptor does not currently subscribe you to the property.
2536
+ * This is a choice that was made because changing a key's value will trigger
2537
+ * this trap and we do not want to subscribe by writes. This also means that
2538
+ * Object.hasOwnProperty doesn't subscribe as it goes through this trap.
2539
+ *
2540
+ * @param target the object for which to create a proxy proxy
2541
+ * @param callback the function to call when an observed property of the
2542
+ * proxy has changed
2543
+ * @returns a proxy that tracks changes to it
2544
+ */
2545
+ function proxy(target) {
2546
+ if (!canBeMadeReactive(target)) {
2547
+ throw new OwlError(`Cannot make the given value reactive`);
2548
+ }
2549
+ if (skipped.has(target)) {
2550
+ return target;
2551
+ }
2552
+ if (targets.has(target)) {
2553
+ // target is reactive, create a reactive on the underlying object instead
2554
+ return target;
2555
+ }
2556
+ const reactive = proxyCache.get(target);
2557
+ if (reactive)
2558
+ return reactive;
2559
+ const targetRawType = rawType(target);
2560
+ const handler = COLLECTION_RAW_TYPES.includes(targetRawType)
2561
+ ? collectionsProxyHandler(target, targetRawType)
2562
+ : basicProxyHandler();
2563
+ const proxy = new Proxy(target, handler);
2564
+ proxyCache.set(target, proxy);
2565
+ targets.set(proxy, target);
2566
+ return proxy;
2567
+ }
2568
+ /**
2569
+ * Creates a basic proxy handler for regular objects and arrays.
2570
+ *
2571
+ * @param callback @see proxy
2572
+ * @returns a proxy handler object
2573
+ */
2574
+ function basicProxyHandler() {
2575
+ return {
2576
+ get(target, key, receiver) {
2577
+ // non-writable non-configurable properties cannot be made proxy
2578
+ const desc = Object.getOwnPropertyDescriptor(target, key);
2579
+ if (desc && !desc.writable && !desc.configurable) {
2580
+ return Reflect.get(target, key, receiver);
2581
+ }
2582
+ onReadTargetKey(target, key);
2583
+ return possiblyReactive(Reflect.get(target, key, receiver));
2584
+ },
2585
+ set(target, key, value, receiver) {
2586
+ const hadKey = objectHasOwnProperty.call(target, key);
2587
+ const originalValue = Reflect.get(target, key, receiver);
2588
+ const ret = Reflect.set(target, key, toRaw(value), receiver);
2589
+ if (!hadKey && objectHasOwnProperty.call(target, key)) {
2590
+ onWriteTargetKey(target, KEYCHANGES);
2591
+ }
2592
+ // While Array length may trigger the set trap, it's not actually set by this
2593
+ // method but is updated behind the scenes, and the trap is not called with the
2594
+ // new value. We disable the "same-value-optimization" for it because of that.
2595
+ if (originalValue !== Reflect.get(target, key, receiver) ||
2596
+ (key === "length" && Array.isArray(target))) {
2597
+ onWriteTargetKey(target, key);
2598
+ }
2599
+ return ret;
2600
+ },
2601
+ deleteProperty(target, key) {
2602
+ const ret = Reflect.deleteProperty(target, key);
2603
+ // TODO: only notify when something was actually deleted
2604
+ onWriteTargetKey(target, KEYCHANGES);
2605
+ onWriteTargetKey(target, key);
2606
+ return ret;
2607
+ },
2608
+ ownKeys(target) {
2609
+ onReadTargetKey(target, KEYCHANGES);
2610
+ return Reflect.ownKeys(target);
2611
+ },
2612
+ has(target, key) {
2613
+ // TODO: this observes all key changes instead of only the presence of the argument key
2614
+ // observing the key itself would observe value changes instead of presence changes
2615
+ // so we may need a finer grained system to distinguish observing value vs presence.
2616
+ onReadTargetKey(target, KEYCHANGES);
2617
+ return Reflect.has(target, key);
2618
+ },
2619
+ };
2620
+ }
2621
+ /**
2622
+ * Creates a function that will observe the key that is passed to it when called
2623
+ * and delegates to the underlying method.
2624
+ *
2625
+ * @param methodName name of the method to delegate to
2626
+ * @param target @see proxy
2627
+ * @param callback @see proxy
2628
+ */
2629
+ function makeKeyObserver(methodName, target) {
2630
+ return (key) => {
2631
+ key = toRaw(key);
2632
+ onReadTargetKey(target, key);
2633
+ return possiblyReactive(target[methodName](key));
2634
+ };
2635
+ }
2636
+ /**
2637
+ * Creates an iterable that will delegate to the underlying iteration method and
2638
+ * observe keys as necessary.
2639
+ *
2640
+ * @param methodName name of the method to delegate to
2641
+ * @param target @see proxy
2642
+ * @param callback @see proxy
2643
+ */
2644
+ function makeIteratorObserver(methodName, target) {
2645
+ return function* () {
2646
+ onReadTargetKey(target, KEYCHANGES);
2647
+ const keys = target.keys();
2648
+ for (const item of target[methodName]()) {
2649
+ const key = keys.next().value;
2650
+ onReadTargetKey(target, key);
2651
+ yield possiblyReactive(item);
2652
+ }
2653
+ };
2654
+ }
2655
+ /**
2656
+ * Creates a forEach function that will delegate to forEach on the underlying
2657
+ * collection while observing key changes, and keys as they're iterated over,
2658
+ * and making the passed keys/values proxy.
2659
+ *
2660
+ * @param target @see proxy
2661
+ * @param callback @see proxy
2662
+ */
2663
+ function makeForEachObserver(target) {
2664
+ return function forEach(forEachCb, thisArg) {
2665
+ onReadTargetKey(target, KEYCHANGES);
2666
+ target.forEach(function (val, key, targetObj) {
2667
+ onReadTargetKey(target, key);
2668
+ forEachCb.call(thisArg, possiblyReactive(val), possiblyReactive(key), possiblyReactive(targetObj));
2669
+ }, thisArg);
2670
+ };
2671
+ }
2672
+ /**
2673
+ * Creates a function that will delegate to an underlying method, and check if
2674
+ * that method has modified the presence or value of a key, and notify the
2675
+ * proxys appropriately.
2676
+ *
2677
+ * @param setterName name of the method to delegate to
2678
+ * @param getterName name of the method which should be used to retrieve the
2679
+ * value before calling the delegate method for comparison purposes
2680
+ * @param target @see proxy
2681
+ */
2682
+ function delegateAndNotify(setterName, getterName, target) {
2683
+ return (key, value) => {
2684
+ key = toRaw(key);
2685
+ const hadKey = target.has(key);
2686
+ const originalValue = target[getterName](key);
2687
+ const ret = target[setterName](key, value);
2688
+ const hasKey = target.has(key);
2689
+ if (hadKey !== hasKey) {
2690
+ onWriteTargetKey(target, KEYCHANGES);
2691
+ }
2692
+ if (originalValue !== target[getterName](key)) {
2693
+ onWriteTargetKey(target, key);
2694
+ }
2695
+ return ret;
2696
+ };
2697
+ }
2698
+ /**
2699
+ * Creates a function that will clear the underlying collection and notify that
2700
+ * the keys of the collection have changed.
2701
+ *
2702
+ * @param target @see proxy
2703
+ */
2704
+ function makeClearNotifier(target) {
2705
+ return () => {
2706
+ const allKeys = [...target.keys()];
2707
+ target.clear();
2708
+ onWriteTargetKey(target, KEYCHANGES);
2709
+ for (const key of allKeys) {
2710
+ onWriteTargetKey(target, key);
2711
+ }
2712
+ };
2713
+ }
2714
+ /**
2715
+ * Maps raw type of an object to an object containing functions that can be used
2716
+ * to build an appropritate proxy handler for that raw type. Eg: when making a
2717
+ * proxy set, calling the has method should mark the key that is being
2718
+ * retrieved as observed, and calling the add or delete method should notify the
2719
+ * proxys that the key which is being added or deleted has been modified.
2720
+ */
2721
+ const rawTypeToFuncHandlers = {
2722
+ Set: (target) => ({
2723
+ has: makeKeyObserver("has", target),
2724
+ add: delegateAndNotify("add", "has", target),
2725
+ delete: delegateAndNotify("delete", "has", target),
2726
+ keys: makeIteratorObserver("keys", target),
2727
+ values: makeIteratorObserver("values", target),
2728
+ entries: makeIteratorObserver("entries", target),
2729
+ [Symbol.iterator]: makeIteratorObserver(Symbol.iterator, target),
2730
+ forEach: makeForEachObserver(target),
2731
+ clear: makeClearNotifier(target),
2732
+ get size() {
2733
+ onReadTargetKey(target, KEYCHANGES);
2734
+ return target.size;
2735
+ },
2736
+ }),
2737
+ Map: (target) => ({
2738
+ has: makeKeyObserver("has", target),
2739
+ get: makeKeyObserver("get", target),
2740
+ set: delegateAndNotify("set", "get", target),
2741
+ delete: delegateAndNotify("delete", "has", target),
2742
+ keys: makeIteratorObserver("keys", target),
2743
+ values: makeIteratorObserver("values", target),
2744
+ entries: makeIteratorObserver("entries", target),
2745
+ [Symbol.iterator]: makeIteratorObserver(Symbol.iterator, target),
2746
+ forEach: makeForEachObserver(target),
2747
+ clear: makeClearNotifier(target),
2748
+ get size() {
2749
+ onReadTargetKey(target, KEYCHANGES);
2750
+ return target.size;
2751
+ },
2752
+ }),
2753
+ WeakMap: (target) => ({
2754
+ has: makeKeyObserver("has", target),
2755
+ get: makeKeyObserver("get", target),
2756
+ set: delegateAndNotify("set", "get", target),
2757
+ delete: delegateAndNotify("delete", "has", target),
2758
+ }),
2759
+ };
2760
+ /**
2761
+ * Creates a proxy handler for collections (Set/Map/WeakMap)
2762
+ *
2763
+ * @param callback @see proxy
2764
+ * @param target @see proxy
2765
+ * @returns a proxy handler object
2766
+ */
2767
+ function collectionsProxyHandler(target, targetRawType) {
2768
+ // TODO: if performance is an issue we can create the special handlers lazily when each
2769
+ // property is read.
2770
+ const specialHandlers = rawTypeToFuncHandlers[targetRawType](target);
2771
+ return Object.assign(basicProxyHandler(), {
2772
+ // FIXME: probably broken when part of prototype chain since we ignore the receiver
2773
+ get(target, key) {
2774
+ if (objectHasOwnProperty.call(specialHandlers, key)) {
2775
+ return specialHandlers[key];
2776
+ }
2777
+ onReadTargetKey(target, key);
2778
+ return possiblyReactive(target[key]);
2779
+ },
2780
+ });
2781
+ }
2782
+
2783
+ // -----------------------------------------------------------------------------
2784
+ // Scheduler
2785
+ // -----------------------------------------------------------------------------
2786
+ class Scheduler {
2787
+ constructor() {
2788
+ this.tasks = new Set();
2789
+ this.frame = 0;
2790
+ this.delayedRenders = [];
2791
+ this.cancelledNodes = new Set();
2792
+ this.processing = false;
2793
+ this.requestAnimationFrame = Scheduler.requestAnimationFrame;
2794
+ }
2795
+ addFiber(fiber) {
2796
+ this.tasks.add(fiber.root);
2797
+ }
2798
+ scheduleDestroy(node) {
2799
+ this.cancelledNodes.add(node);
2800
+ if (this.frame === 0) {
2801
+ this.frame = this.requestAnimationFrame(() => this.processTasks());
2802
+ }
2803
+ }
2804
+ /**
2805
+ * Process all current tasks. This only applies to the fibers that are ready.
2806
+ * Other tasks are left unchanged.
2807
+ */
2808
+ flush() {
2809
+ if (this.delayedRenders.length) {
2810
+ let renders = this.delayedRenders;
2811
+ this.delayedRenders = [];
2812
+ for (let f of renders) {
2813
+ if (f.root && f.node.status !== 3 /* STATUS.DESTROYED */ && f.node.fiber === f) {
2814
+ f.render();
2815
+ }
2816
+ }
2817
+ }
2818
+ if (this.frame === 0) {
2819
+ this.frame = this.requestAnimationFrame(() => this.processTasks());
2820
+ }
2821
+ }
2822
+ processTasks() {
2823
+ if (this.processing) {
2824
+ return;
2825
+ }
2826
+ this.processing = true;
2827
+ this.frame = 0;
2828
+ for (let node of this.cancelledNodes) {
2829
+ node._destroy();
2830
+ }
2831
+ this.cancelledNodes.clear();
2832
+ for (let task of this.tasks) {
2833
+ this.processFiber(task);
2834
+ }
2835
+ for (let task of this.tasks) {
2836
+ if (task.node.status === 3 /* STATUS.DESTROYED */) {
2837
+ this.tasks.delete(task);
2838
+ }
2839
+ }
2840
+ this.processing = false;
2841
+ }
2842
+ processFiber(fiber) {
2843
+ if (fiber.root !== fiber) {
2844
+ this.tasks.delete(fiber);
2845
+ return;
2846
+ }
2847
+ const hasError = fibersInError.has(fiber);
2848
+ if (hasError && fiber.counter !== 0) {
2849
+ this.tasks.delete(fiber);
2850
+ return;
2851
+ }
2852
+ if (fiber.node.status === 3 /* STATUS.DESTROYED */) {
2853
+ this.tasks.delete(fiber);
2854
+ return;
2855
+ }
2856
+ if (fiber.counter === 0) {
2857
+ if (!hasError) {
2858
+ fiber.complete();
2859
+ }
2860
+ // at this point, the fiber should have been applied to the DOM, so we can
2861
+ // remove it from the task list. If it is not the case, it means that there
2862
+ // was an error and an error handler triggered a new rendering that recycled
2863
+ // the fiber, so in that case, we actually want to keep the fiber around,
2864
+ // otherwise it will just be ignored.
2865
+ if (fiber.appliedToDom) {
2866
+ this.tasks.delete(fiber);
2867
+ }
2868
+ }
2869
+ }
2870
+ }
2871
+ // capture the value of requestAnimationFrame as soon as possible, to avoid
2872
+ // interactions with other code, such as test frameworks that override them
2873
+ Scheduler.requestAnimationFrame = window.requestAnimationFrame.bind(window);
2874
+
2875
+ // -----------------------------------------------------------------------------
2876
+ // hooks
2877
+ // -----------------------------------------------------------------------------
2878
+ function decorate(node, f, hookName) {
2879
+ const result = f.bind(node.component);
2880
+ if (node.app.dev) {
2881
+ const suffix = f.name ? ` <${f.name}>` : "";
2882
+ Reflect.defineProperty(result, "name", {
2883
+ value: hookName + suffix,
2884
+ });
2885
+ }
2886
+ return result;
2887
+ }
2888
+ function onWillStart(fn) {
2889
+ const node = getCurrent();
2890
+ node.willStart.push(decorate(node, fn, "onWillStart"));
2891
+ }
2892
+ function onWillUpdateProps(fn) {
2893
+ const node = getCurrent();
2894
+ node.willUpdateProps.push(decorate(node, fn, "onWillUpdateProps"));
2895
+ }
2896
+ function onMounted(fn) {
2897
+ const node = getCurrent();
2898
+ node.mounted.push(decorate(node, fn, "onMounted"));
2899
+ }
2900
+ function onWillPatch(fn) {
2901
+ const node = getCurrent();
2902
+ node.willPatch.unshift(decorate(node, fn, "onWillPatch"));
2903
+ }
2904
+ function onPatched(fn) {
2905
+ const node = getCurrent();
2906
+ node.patched.push(decorate(node, fn, "onPatched"));
2907
+ }
2908
+ function onWillUnmount(fn) {
2909
+ const node = getCurrent();
2910
+ node.willUnmount.unshift(decorate(node, fn, "onWillUnmount"));
2911
+ }
2912
+ function onWillDestroy(fn) {
2913
+ const pm = _getCurrentPluginManager();
2914
+ if (pm) {
2915
+ pm.onDestroyCb.push(fn);
2916
+ }
2917
+ else {
2918
+ const node = getCurrent();
2919
+ node.willDestroy.unshift(decorate(node, fn, "onWillDestroy"));
2920
+ }
2921
+ }
2922
+ function onError(callback) {
2923
+ const node = getCurrent();
2924
+ let handlers = nodeErrorHandlers.get(node);
2925
+ if (!handlers) {
2926
+ handlers = [];
2927
+ nodeErrorHandlers.set(node, handlers);
2928
+ }
2929
+ handlers.push(callback.bind(node.component));
2930
+ }
2931
+
2932
+ // -----------------------------------------------------------------------------
2933
+ // helpers
2934
+ // -----------------------------------------------------------------------------
2935
+ const isUnionType = (t) => Array.isArray(t);
2936
+ const isBaseType = (t) => typeof t !== "object";
2937
+ const isValueType = (t) => typeof t === "object" && t && "value" in t;
2938
+ function isOptional(t) {
2939
+ return typeof t === "object" && "optional" in t ? t.optional || false : false;
2940
+ }
2941
+ function describeType(type) {
2942
+ return type === "*" || type === true ? "value" : type.name.toLowerCase();
2943
+ }
2944
+ function describe(info) {
2945
+ if (isBaseType(info)) {
2946
+ return describeType(info);
2947
+ }
2948
+ else if (isUnionType(info)) {
2949
+ return info.map(describe).join(" or ");
2950
+ }
2951
+ else if (isValueType(info)) {
2952
+ return String(info.value);
2953
+ }
2954
+ if ("element" in info) {
2955
+ return `list of ${describe({ type: info.element, optional: false })}s`;
2956
+ }
2957
+ if ("shape" in info) {
2958
+ return `object`;
2959
+ }
2960
+ return describe(info.type || "*");
2961
+ }
2962
+ function toSchema(spec) {
2963
+ return Object.fromEntries(spec.map((e) => e.endsWith("?") ? [e.slice(0, -1), { optional: true }] : [e, { type: "*", optional: false }]));
2964
+ }
2965
+ /**
2966
+ * Main validate function
2967
+ */
2968
+ function validate(obj, spec) {
2969
+ let errors = validateSchema(obj, spec);
2970
+ if (errors.length) {
2971
+ throw new OwlError("Invalid object: " + errors.join(", "));
2972
+ }
2973
+ }
2974
+ /**
2975
+ * Helper validate function, to get the list of errors. useful if one want to
2976
+ * manipulate the errors without parsing an error object
2977
+ */
2978
+ function validateSchema(obj, schema) {
2979
+ if (Array.isArray(schema)) {
2980
+ schema = toSchema(schema);
2981
+ }
2982
+ // obj = toRaw(obj);
2983
+ let errors = [];
2984
+ // check if each value in obj has correct shape
2985
+ for (let key in obj) {
2986
+ if (key in schema) {
2987
+ let result = validateType(key, obj[key], schema[key]);
2988
+ if (result) {
2989
+ errors.push(result);
2990
+ }
2991
+ }
2992
+ else if (!("*" in schema)) {
2993
+ errors.push(`unknown key '${key}'`);
2994
+ }
2995
+ }
2996
+ // check that all specified keys are defined in obj
2997
+ for (let key in schema) {
2998
+ const spec = schema[key];
2999
+ if (key !== "*" && !isOptional(spec) && !(key in obj)) {
3000
+ const isObj = typeof spec === "object" && !Array.isArray(spec);
3001
+ const isAny = spec === "*" || (isObj && "type" in spec ? spec.type === "*" : isObj);
3002
+ let detail = isAny ? "" : ` (should be a ${describe(spec)})`;
3003
+ errors.push(`'${key}' is missing${detail}`);
3004
+ }
3005
+ }
3006
+ return errors;
3007
+ }
3008
+ function validateBaseType(key, value, type) {
3009
+ if (typeof type === "function") {
3010
+ if (typeof value === "object") {
3011
+ if (!(value instanceof type)) {
3012
+ return `'${key}' is not a ${describeType(type)}`;
3013
+ }
3014
+ }
3015
+ else if (typeof value !== type.name.toLowerCase()) {
3016
+ return `'${key}' is not a ${describeType(type)}`;
3017
+ }
3018
+ }
3019
+ return null;
3020
+ }
3021
+ function validateArrayType(key, value, descr) {
3022
+ if (!Array.isArray(value)) {
3023
+ return `'${key}' is not a list of ${describe(descr)}s`;
3024
+ }
3025
+ for (let i = 0; i < value.length; i++) {
3026
+ const error = validateType(`${key}[${i}]`, value[i], descr);
3027
+ if (error) {
3028
+ return error;
3029
+ }
3030
+ }
3031
+ return null;
3032
+ }
3033
+ function validateType(key, value, descr) {
3034
+ if (value === undefined) {
3035
+ return isOptional(descr) ? null : `'${key}' is undefined (should be a ${describe(descr)})`;
3036
+ }
3037
+ else if (isBaseType(descr)) {
3038
+ return validateBaseType(key, value, descr);
3039
+ }
3040
+ else if (isValueType(descr)) {
3041
+ return value === descr.value ? null : `'${key}' is not equal to '${descr.value}'`;
3042
+ }
3043
+ else if (isUnionType(descr)) {
3044
+ let validDescr = descr.find((p) => !validateType(key, value, p));
3045
+ return validDescr ? null : `'${key}' is not a ${describe(descr)}`;
3046
+ }
3047
+ let result = null;
3048
+ if ("element" in descr) {
3049
+ result = validateArrayType(key, value, descr.element);
3050
+ }
3051
+ else if ("shape" in descr) {
3052
+ if (typeof value !== "object" || Array.isArray(value)) {
3053
+ result = `'${key}' is not an object`;
3054
+ }
3055
+ else {
3056
+ const errors = validateSchema(value, descr.shape);
3057
+ if (errors.length) {
3058
+ result = `'${key}' doesn't have the correct shape (${errors.join(", ")})`;
3059
+ }
3060
+ }
3061
+ }
3062
+ else if ("values" in descr) {
3063
+ if (typeof value !== "object" || Array.isArray(value)) {
3064
+ result = `'${key}' is not an object`;
3065
+ }
3066
+ else {
3067
+ const errors = Object.entries(value)
3068
+ .map(([key, value]) => validateType(key, value, descr.values))
3069
+ .filter(Boolean);
3070
+ if (errors.length) {
3071
+ result = `some of the values in '${key}' are invalid (${errors.join(", ")})`;
3072
+ }
3073
+ }
3074
+ }
3075
+ if ("type" in descr && !result) {
3076
+ result = validateType(key, value, descr.type);
3077
+ }
3078
+ if ("validate" in descr && !result) {
3079
+ result = !descr.validate(value) ? `'${key}' is not valid` : null;
3080
+ }
3081
+ return result;
3082
+ }
3083
+
3084
+ function validateProps(componentName, props, validation, keys) {
3085
+ const propsToValidate = Object.create(null);
3086
+ const errors = [];
3087
+ for (const key of keys) {
3088
+ if (key in props) {
3089
+ propsToValidate[key] = props[key];
3090
+ }
3091
+ if (propsToValidate[key] === undefined &&
3092
+ !Array.isArray(validation) &&
3093
+ validation[key].defaultValue !== undefined) {
3094
+ if (!validation[key].optional) {
3095
+ errors.push(`A default value cannot be defined for the mandatory prop '${key}'`);
3096
+ continue;
3097
+ }
3098
+ propsToValidate[key] = validation[key].defaultValue;
3099
+ }
3100
+ }
3101
+ errors.push(...validateSchema(propsToValidate, validation));
3102
+ if (errors.length) {
3103
+ throw new OwlError(`Invalid props for component '${componentName}': ` + errors.join(", "));
3104
+ // node.app.handleError({
3105
+ // error: new OwlError(`Invalid props for component '${componentName}': ` + errors.join(", ")),
3106
+ // node,
3107
+ // });
3108
+ }
3109
+ }
3110
+ function props(validation) {
3111
+ const node = getCurrent();
3112
+ const isSchemaValidated = validation && !Array.isArray(validation);
3113
+ function getProp(key) {
3114
+ if (isSchemaValidated && node.props[key] === undefined) {
3115
+ return validation[key].defaultValue;
3116
+ }
3117
+ return node.props[key];
3118
+ }
3119
+ const result = Object.create(null);
3120
+ function applyPropGetters(keys) {
3121
+ for (const key of keys) {
3122
+ Reflect.defineProperty(result, key, {
3123
+ enumerable: true,
3124
+ get: getProp.bind(null, key),
3125
+ });
3126
+ }
3127
+ }
3128
+ if (validation) {
3129
+ const keys = (isSchemaValidated ? Object.keys(validation) : validation).map((key) => key.endsWith("?") ? key.slice(0, -1) : key);
3130
+ applyPropGetters(keys);
3131
+ if (node.app.dev) {
3132
+ validateProps(node.name, node.props, validation, keys);
3133
+ node.willUpdateProps.push((np) => {
3134
+ validateProps(node.name, np, validation, keys);
3135
+ });
3136
+ }
3137
+ }
3138
+ else {
3139
+ applyPropGetters(Object.keys(node.props));
3140
+ node.willUpdateProps.push((np) => {
3141
+ for (let key in result) {
3142
+ Reflect.deleteProperty(result, key);
3143
+ }
3144
+ applyPropGetters(Object.keys(np));
3145
+ });
3146
+ }
3147
+ return result;
3148
+ }
3149
+
3150
+ const VText = text("").constructor;
3151
+ class VPortal extends VText {
3152
+ constructor(selector, content) {
3153
+ super("");
3154
+ this.target = null;
3155
+ this.selector = selector;
3156
+ this.content = content;
3157
+ }
3158
+ mount(parent, anchor) {
3159
+ super.mount(parent, anchor);
3160
+ this.target = document.querySelector(this.selector);
3161
+ if (this.target) {
3162
+ this.content.mount(this.target, null);
3163
+ }
3164
+ else {
3165
+ this.content.mount(parent, anchor);
3166
+ }
3167
+ }
3168
+ beforeRemove() {
3169
+ this.content.beforeRemove();
3170
+ }
3171
+ remove() {
3172
+ if (this.content) {
3173
+ super.remove();
3174
+ this.content.remove();
3175
+ this.content = null;
3176
+ }
3177
+ }
3178
+ patch(other) {
3179
+ super.patch(other);
3180
+ if (this.content) {
3181
+ this.content.patch(other.content, true);
3182
+ }
3183
+ else {
3184
+ this.content = other.content;
3185
+ this.content.mount(this.target, null);
3186
+ }
3187
+ }
3188
+ }
3189
+ /**
3190
+ * kind of similar to <t t-slot="default"/>, but it wraps it around a VPortal
3191
+ */
3192
+ function portalTemplate(app, bdom, helpers) {
3193
+ let { callSlot } = helpers;
3194
+ return function template(ctx, node, key = "") {
3195
+ return new VPortal(ctx.this.props.target, callSlot(ctx, node, key, "default", false, null));
3196
+ };
3197
+ }
3198
+ class Portal extends Component {
3199
+ constructor() {
3200
+ super(...arguments);
3201
+ this.props = props({
3202
+ target: String,
3203
+ slots: true,
3204
+ });
3205
+ }
3206
+ setup() {
3207
+ const node = this.__owl__;
3208
+ onMounted(() => {
3209
+ const portal = node.bdom;
3210
+ if (!portal.target) {
3211
+ const target = document.querySelector(node.props.target);
3212
+ if (target) {
3213
+ portal.content.moveBeforeDOMNode(target.firstChild, target);
3214
+ }
3215
+ else {
3216
+ throw new OwlError("invalid portal target");
3217
+ }
3218
+ }
3219
+ });
3220
+ onWillUnmount(() => {
3221
+ const portal = node.bdom;
3222
+ portal.remove();
3223
+ });
3224
+ }
3225
+ }
3226
+ Portal.template = "__portal__";
3227
+
3228
+ const ObjectCreate = Object.create;
3229
+ /**
3230
+ * This file contains utility functions that will be injected in each template,
3231
+ * to perform various useful tasks in the compiled code.
3232
+ */
3233
+ function withDefault(value, defaultValue) {
3234
+ return value === undefined || value === null || value === false ? defaultValue : value;
3235
+ }
3236
+ function callSlot(ctx, parent, key, name, dynamic, extra, defaultContent) {
3237
+ key = key + "__slot_" + name;
3238
+ const slots = ctx.__owl__.props.slots || {};
3239
+ const { __render, __ctx, __scope } = slots[name] || {};
3240
+ const slotScope = ObjectCreate(__ctx || {});
3241
+ if (__scope) {
3242
+ slotScope[__scope] = extra;
3243
+ }
3244
+ const slotBDom = __render ? __render(slotScope, parent, key) : null;
3245
+ if (defaultContent) {
3246
+ let child1 = undefined;
3247
+ let child2 = undefined;
3248
+ if (slotBDom) {
3249
+ child1 = dynamic ? toggler(name, slotBDom) : slotBDom;
3250
+ }
3251
+ else {
3252
+ child2 = defaultContent(ctx, parent, key);
3253
+ }
3254
+ return multi([child1, child2]);
3255
+ }
3256
+ return slotBDom || text("");
3257
+ }
3258
+ function capture(ctx) {
3259
+ const result = ObjectCreate(ctx);
3260
+ for (let k in ctx) {
3261
+ result[k] = ctx[k];
3262
+ }
3263
+ return result;
3264
+ }
3265
+ function withKey(elem, k) {
3266
+ elem.key = k;
3267
+ return elem;
3268
+ }
3269
+ function prepareList(collection) {
3270
+ let keys;
3271
+ let values;
3272
+ if (Array.isArray(collection)) {
3273
+ keys = collection;
3274
+ values = collection;
3275
+ }
3276
+ else if (collection instanceof Map) {
3277
+ keys = [...collection.keys()];
3278
+ values = [...collection.values()];
3279
+ }
3280
+ else if (Symbol.iterator in Object(collection)) {
3281
+ keys = [...collection];
3282
+ values = keys;
3283
+ }
3284
+ else if (collection && typeof collection === "object") {
3285
+ values = Object.values(collection);
3286
+ keys = Object.keys(collection);
3287
+ }
3288
+ else {
3289
+ throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
3290
+ }
3291
+ const n = values.length;
3292
+ return [keys, values, n, new Array(n)];
3293
+ }
3294
+ const isBoundary = Symbol("isBoundary");
3295
+ function setContextValue(ctx, key, value) {
3296
+ const ctx0 = ctx;
3297
+ while (!ctx.hasOwnProperty(key) && !ctx.hasOwnProperty(isBoundary)) {
3298
+ const newCtx = ctx.__proto__;
3299
+ if (!newCtx) {
3300
+ ctx = ctx0;
3301
+ break;
3302
+ }
3303
+ ctx = newCtx;
3304
+ }
3305
+ ctx[key] = value;
3306
+ }
3307
+ function toNumber(val) {
3308
+ const n = parseFloat(val);
3309
+ return isNaN(n) ? val : n;
3310
+ }
3311
+ function shallowEqual(l1, l2) {
3312
+ for (let i = 0, l = l1.length; i < l; i++) {
3313
+ if (l1[i] !== l2[i]) {
3314
+ return false;
3315
+ }
3316
+ }
3317
+ return true;
3318
+ }
3319
+ class LazyValue {
3320
+ constructor(fn, ctx, component, node, key) {
3321
+ this.fn = fn;
3322
+ this.ctx = capture(ctx);
3323
+ this.component = component;
3324
+ this.node = node;
3325
+ this.key = key;
3326
+ }
3327
+ evaluate() {
3328
+ return this.fn.call(this.component, this.ctx, this.node, this.key);
3329
+ }
3330
+ toString() {
3331
+ return this.evaluate().toString();
3332
+ }
3333
+ }
3334
+ /*
3335
+ * Safely outputs `value` as a block depending on the nature of `value`
3336
+ */
3337
+ function safeOutput(value, defaultValue) {
3338
+ if (value === undefined || value === null) {
3339
+ return defaultValue ? toggler("default", defaultValue) : toggler("undefined", text(""));
3340
+ }
3341
+ let safeKey;
3342
+ let block;
3343
+ if (value instanceof Markup) {
3344
+ safeKey = `string_safe`;
3345
+ block = html(value);
3346
+ }
3347
+ else if (value instanceof LazyValue) {
3348
+ safeKey = `lazy_value`;
3349
+ block = value.evaluate();
3350
+ }
3351
+ else {
3352
+ safeKey = "string_unsafe";
3353
+ block = text(value);
3354
+ }
3355
+ return toggler(safeKey, block);
3356
+ }
3357
+ function createRef(ref) {
3358
+ if (!ref) {
3359
+ throw new OwlError(`Ref is undefined or null`);
3360
+ }
3361
+ let add;
3362
+ let remove;
3363
+ if (ref.add && ref.remove) {
3364
+ add = ref.add.bind(ref);
3365
+ remove = ref.remove.bind(ref);
3366
+ }
3367
+ else if (ref.set) {
3368
+ add = ref.set.bind(ref);
3369
+ remove = () => ref.set(null);
3370
+ }
3371
+ else {
3372
+ throw new OwlError(`Ref should implement either a 'set' function or 'add' and 'remove' functions`);
3373
+ }
3374
+ return (el, previousEl) => {
3375
+ if (previousEl) {
3376
+ remove(previousEl);
3377
+ }
3378
+ if (el) {
3379
+ add(el);
3380
+ }
3381
+ };
3382
+ }
3383
+ function modelExpr(value) {
3384
+ if (!value.set || typeof value !== "function") {
3385
+ throw new OwlError(`Invalid t-model expression: expression should evaluate to a function with a 'set' method defined on it`);
3386
+ }
3387
+ return value;
3388
+ }
3389
+ const helpers = {
3390
+ withDefault,
3391
+ zero: Symbol("zero"),
3392
+ isBoundary,
3393
+ callSlot,
3394
+ capture,
3395
+ withKey,
3396
+ prepareList,
3397
+ setContextValue,
3398
+ shallowEqual,
3399
+ toNumber,
3400
+ LazyValue,
3401
+ safeOutput,
3402
+ createCatcher,
3403
+ markRaw,
3404
+ OwlError,
3405
+ createRef,
3406
+ modelExpr,
3407
+ };
3408
+
3409
+ /**
3410
+ * Parses an XML string into an XML document, throwing errors on parser errors
3411
+ * instead of returning an XML document containing the parseerror.
3412
+ *
3413
+ * @param xml the string to parse
3414
+ * @returns an XML document corresponding to the content of the string
3415
+ */
3416
+ function parseXML(xml) {
3417
+ const parser = new DOMParser();
3418
+ const doc = parser.parseFromString(xml, "text/xml");
3419
+ if (doc.getElementsByTagName("parsererror").length) {
3420
+ let msg = "Invalid XML in template.";
3421
+ const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
3422
+ if (parsererrorText) {
3423
+ msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
3424
+ const re = /\d+/g;
3425
+ const firstMatch = re.exec(parsererrorText);
3426
+ if (firstMatch) {
3427
+ const lineNumber = Number(firstMatch[0]);
3428
+ const line = xml.split("\n")[lineNumber - 1];
3429
+ const secondMatch = re.exec(parsererrorText);
3430
+ if (line && secondMatch) {
3431
+ const columnIndex = Number(secondMatch[0]) - 1;
3432
+ if (line[columnIndex]) {
3433
+ msg +=
3434
+ `\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
3435
+ `${line}\n${"-".repeat(columnIndex - 1)}^`;
3436
+ }
3437
+ }
3438
+ }
3439
+ }
3440
+ throw new OwlError(msg);
3441
+ }
3442
+ return doc;
3443
+ }
3444
+
3445
+ const bdom = { text, createBlock, list, multi, html, toggler, comment };
3446
+ class TemplateSet {
3447
+ static registerTemplate(name, fn) {
3448
+ globalTemplates[name] = fn;
3449
+ }
3450
+ constructor(config = {}) {
3451
+ this.rawTemplates = Object.create(globalTemplates);
3452
+ this.templates = {};
3453
+ this.Portal = Portal;
3454
+ this.dev = config.dev || false;
3455
+ this.translateFn = config.translateFn;
3456
+ this.translatableAttributes = config.translatableAttributes;
3457
+ if (config.templates) {
3458
+ if (config.templates instanceof Document || typeof config.templates === "string") {
3459
+ this.addTemplates(config.templates);
3460
+ }
3461
+ else {
3462
+ for (const name in config.templates) {
3463
+ this.addTemplate(name, config.templates[name]);
3464
+ }
3465
+ }
3466
+ }
3467
+ this.getRawTemplate = config.getTemplate;
3468
+ this.customDirectives = config.customDirectives || {};
3469
+ this.runtimeUtils = { ...helpers, __globals__: config.globalValues || {} };
3470
+ this.hasGlobalValues = Boolean(config.globalValues && Object.keys(config.globalValues).length);
3471
+ }
3472
+ addTemplate(name, template) {
3473
+ if (name in this.rawTemplates) {
3474
+ // this check can be expensive, just silently ignore double definitions outside dev mode
3475
+ if (!this.dev) {
3476
+ return;
3477
+ }
3478
+ const rawTemplate = this.rawTemplates[name];
3479
+ const currentAsString = typeof rawTemplate === "string"
3480
+ ? rawTemplate
3481
+ : rawTemplate instanceof Element
3482
+ ? rawTemplate.outerHTML
3483
+ : rawTemplate.toString();
3484
+ const newAsString = typeof template === "string" ? template : template.outerHTML;
3485
+ if (currentAsString === newAsString) {
3486
+ return;
3487
+ }
3488
+ throw new OwlError(`Template ${name} already defined with different content`);
3489
+ }
3490
+ this.rawTemplates[name] = template;
3491
+ }
3492
+ addTemplates(xml) {
3493
+ if (!xml) {
3494
+ // empty string
3495
+ return;
3496
+ }
3497
+ xml = xml instanceof Document ? xml : parseXML(xml);
3498
+ for (const template of xml.querySelectorAll("[t-name]")) {
3499
+ const name = template.getAttribute("t-name");
3500
+ this.addTemplate(name, template);
3501
+ }
3502
+ }
3503
+ getTemplate(name) {
3504
+ var _a;
3505
+ if (!(name in this.templates)) {
3506
+ const rawTemplate = ((_a = this.getRawTemplate) === null || _a === void 0 ? void 0 : _a.call(this, name)) || this.rawTemplates[name];
3507
+ if (rawTemplate === undefined) {
3508
+ let extraInfo = "";
3509
+ try {
3510
+ const componentName = getCurrent().component.constructor.name;
3511
+ extraInfo = ` (for component "${componentName}")`;
3512
+ }
3513
+ catch { }
3514
+ throw new OwlError(`Missing template: "${name}"${extraInfo}`);
3515
+ }
3516
+ const isFn = typeof rawTemplate === "function" && !(rawTemplate instanceof Element);
3517
+ const templateFn = isFn ? rawTemplate : this._compileTemplate(name, rawTemplate);
3518
+ // first add a function to lazily get the template, in case there is a
3519
+ // recursive call to the template name
3520
+ const templates = this.templates;
3521
+ this.templates[name] = function (context, parent) {
3522
+ return templates[name].call(this, context, parent);
3523
+ };
3524
+ const template = templateFn(this, bdom, this.runtimeUtils);
3525
+ this.templates[name] = template;
3526
+ }
3527
+ return this.templates[name];
3528
+ }
3529
+ _compileTemplate(name, template) {
3530
+ throw new OwlError(`Unable to compile a template. Please use owl full build instead`);
3531
+ }
3532
+ callTemplate(owner, subTemplate, ctx, parent, key) {
3533
+ const template = this.getTemplate(subTemplate);
3534
+ return toggler(subTemplate, template.call(owner, ctx, parent, key + subTemplate));
3535
+ }
3536
+ }
3537
+ // -----------------------------------------------------------------------------
3538
+ // xml tag helper
3539
+ // -----------------------------------------------------------------------------
3540
+ const globalTemplates = {};
3541
+ function xml(...args) {
3542
+ const name = `__template__${xml.nextId++}`;
3543
+ const value = String.raw(...args);
3544
+ globalTemplates[name] = value;
3545
+ return name;
3546
+ }
3547
+ xml.nextId = 1;
3548
+ TemplateSet.registerTemplate("__portal__", portalTemplate);
3549
+
3550
+ let hasBeenLogged = false;
3551
+ const apps = new Set();
3552
+ window.__OWL_DEVTOOLS__ || (window.__OWL_DEVTOOLS__ = { apps, Fiber, RootFiber, toRaw, proxy });
3553
+ class App extends TemplateSet {
3554
+ constructor(config = {}) {
3555
+ super(config);
3556
+ this.scheduler = new Scheduler();
3557
+ this.roots = new Set();
3558
+ this.name = config.name || "";
3559
+ apps.add(this);
3560
+ this.pluginManager = config.pluginManager || new PluginManager(null);
3561
+ if (config.test) {
3562
+ this.dev = true;
3563
+ }
3564
+ if (this.dev && !config.test && !hasBeenLogged) {
3565
+ console.info(`Owl is running in 'dev' mode.`);
3566
+ hasBeenLogged = true;
3567
+ }
3568
+ }
3569
+ createRoot(Root, config = {}) {
3570
+ const props = config.props || {};
3571
+ let resolve;
3572
+ let reject;
3573
+ const promise = new Promise((res, rej) => {
3574
+ resolve = res;
3575
+ reject = rej;
3576
+ });
3577
+ const restore = saveCurrent();
3578
+ let node;
3579
+ let error = null;
3580
+ try {
3581
+ node = this.makeNode(Root, props);
3582
+ }
3583
+ catch (e) {
3584
+ error = e;
3585
+ reject(e);
3586
+ }
3587
+ finally {
3588
+ restore();
3589
+ }
3590
+ const root = {
3591
+ node: node,
3592
+ promise,
3593
+ mount: (target, options) => {
3594
+ if (error) {
3595
+ return promise;
3596
+ }
3597
+ App.validateTarget(target);
3598
+ this.mountNode(node, target, resolve, reject, options);
3599
+ return promise;
3600
+ },
3601
+ destroy: () => {
3602
+ this.roots.delete(root);
3603
+ node.destroy();
3604
+ this.scheduler.processTasks();
3605
+ },
3606
+ };
3607
+ this.roots.add(root);
3608
+ return root;
3609
+ }
3610
+ makeNode(Component, props) {
3611
+ return new ComponentNode(Component, props, this, null, null);
3612
+ }
3613
+ mountNode(node, target, resolve, reject, options) {
3614
+ // Manually add the last resort error handler on the node
3615
+ let handlers = nodeErrorHandlers.get(node);
3616
+ if (!handlers) {
3617
+ handlers = [];
3618
+ nodeErrorHandlers.set(node, handlers);
3619
+ }
3620
+ handlers.unshift((e, finalize) => {
3621
+ const finalError = finalize();
3622
+ reject(finalError);
3623
+ });
3624
+ // manually set a onMounted callback.
3625
+ // that way, we are independant from the current node.
3626
+ node.mounted.push(() => {
3627
+ resolve(node.component);
3628
+ handlers.shift();
3629
+ });
3630
+ node.mountComponent(target, options);
3631
+ }
3632
+ destroy() {
3633
+ for (let root of this.roots) {
3634
+ root.destroy();
3635
+ }
3636
+ this.scheduler.processTasks();
3637
+ apps.delete(this);
3638
+ }
3639
+ createComponent(name, isStatic, hasSlotsProp, hasDynamicPropList, propList) {
3640
+ const isDynamic = !isStatic;
3641
+ let arePropsDifferent;
3642
+ const hasNoProp = propList.length === 0;
3643
+ if (hasSlotsProp) {
3644
+ arePropsDifferent = (_1, _2) => true;
3645
+ }
3646
+ else if (hasDynamicPropList) {
3647
+ arePropsDifferent = function (props1, props2) {
3648
+ for (let k in props1) {
3649
+ if (props1[k] !== props2[k]) {
3650
+ return true;
3651
+ }
3652
+ }
3653
+ return Object.keys(props1).length !== Object.keys(props2).length;
3654
+ };
3655
+ }
3656
+ else if (hasNoProp) {
3657
+ arePropsDifferent = (_1, _2) => false;
3658
+ }
3659
+ else {
3660
+ arePropsDifferent = function (props1, props2) {
3661
+ for (let p of propList) {
3662
+ if (props1[p] !== props2[p]) {
3663
+ return true;
3664
+ }
3665
+ }
3666
+ return false;
3667
+ };
3668
+ }
3669
+ const updateAndRender = ComponentNode.prototype.updateAndRender;
3670
+ const initiateRender = ComponentNode.prototype.initiateRender;
3671
+ return (props, key, ctx, parent, C) => {
3672
+ let children = ctx.children;
3673
+ let node = children[key];
3674
+ if (isDynamic && node && node.component.constructor !== C) {
3675
+ node = undefined;
3676
+ }
3677
+ const parentFiber = ctx.fiber;
3678
+ if (node) {
3679
+ if (arePropsDifferent(node.props, props) || parentFiber.deep || node.forceNextRender) {
3680
+ node.forceNextRender = false;
3681
+ updateAndRender.call(node, props, parentFiber);
3682
+ }
3683
+ }
3684
+ else {
3685
+ // new component
3686
+ if (isStatic) {
3687
+ const components = parent.constructor.components;
3688
+ if (!components) {
3689
+ throw new OwlError(`Cannot find the definition of component "${name}", missing static components key in parent`);
3690
+ }
3691
+ C = components[name];
3692
+ if (!C) {
3693
+ throw new OwlError(`Cannot find the definition of component "${name}"`);
3694
+ }
3695
+ else if (!(C.prototype instanceof Component)) {
3696
+ throw new OwlError(`"${name}" is not a Component. It must inherit from the Component class`);
3697
+ }
3698
+ }
3699
+ node = new ComponentNode(C, props, this, ctx, key);
3700
+ children[key] = node;
3701
+ initiateRender.call(node, new Fiber(node, parentFiber));
3702
+ }
3703
+ parentFiber.childrenMap[key] = node;
3704
+ return node;
3705
+ };
3706
+ }
3707
+ handleError(...args) {
3708
+ return handleError(...args);
3709
+ }
3710
+ }
3711
+ App.validateTarget = validateTarget;
3712
+ App.apps = apps;
3713
+ App.version = version;
3714
+ async function mount(C, target, config = {}) {
3715
+ const app = new App(config);
3716
+ const root = app.createRoot(C, config);
3717
+ return root.mount(target, config);
3718
+ }
3719
+
3720
+ const mainEventHandler = (data, ev, currentTarget) => {
3721
+ const { data: _data, modifiers } = filterOutModifiersFromData(data);
3722
+ data = _data;
3723
+ let stopped = false;
3724
+ if (modifiers.length) {
3725
+ let selfMode = false;
3726
+ const isSelf = ev.target === currentTarget;
3727
+ for (const mod of modifiers) {
3728
+ switch (mod) {
3729
+ case "self":
3730
+ selfMode = true;
3731
+ if (isSelf) {
3732
+ continue;
3733
+ }
3734
+ else {
3735
+ return stopped;
3736
+ }
3737
+ case "prevent":
3738
+ if ((selfMode && isSelf) || !selfMode)
3739
+ ev.preventDefault();
3740
+ continue;
3741
+ case "stop":
3742
+ if ((selfMode && isSelf) || !selfMode)
3743
+ ev.stopPropagation();
3744
+ stopped = true;
3745
+ continue;
3746
+ }
3747
+ }
3748
+ }
3749
+ // If handler is empty, the array slot 0 will also be empty, and data will not have the property 0
3750
+ // We check this rather than data[0] being truthy (or typeof function) so that it crashes
3751
+ // as expected when there is a handler expression that evaluates to a falsy value
3752
+ if (Object.hasOwnProperty.call(data, 0)) {
3753
+ const handler = data[0];
3754
+ if (typeof handler !== "function") {
3755
+ throw new OwlError(`Invalid handler (expected a function, received: '${handler}')`);
3756
+ }
3757
+ let node = data[1] ? data[1].__owl__ : null;
3758
+ if (node ? node.status === 1 /* STATUS.MOUNTED */ : true) {
3759
+ handler.call(node ? node.component : null, ev);
3760
+ }
3761
+ }
3762
+ return stopped;
3763
+ };
3764
+
3765
+ function computed(fn, opts) {
3766
+ // todo: handle cleanup
3767
+ let derivedComputation;
3768
+ return () => {
3769
+ derivedComputation !== null && derivedComputation !== void 0 ? derivedComputation : (derivedComputation = {
3770
+ state: ComputationState.STALE,
3771
+ sources: new Set(),
3772
+ compute: () => {
3773
+ onWriteAtom(derivedComputation);
3774
+ return fn();
3775
+ },
3776
+ isDerived: true,
3777
+ value: undefined,
3778
+ observers: new Set(),
3779
+ name: opts === null || opts === void 0 ? void 0 : opts.name,
3780
+ });
3781
+ updateComputation(derivedComputation);
3782
+ return derivedComputation.value;
3783
+ };
3784
+ }
3785
+
3786
+ function signal(value, opts) {
3787
+ const atom = {
3788
+ value,
3789
+ observers: new Set(),
3790
+ name: opts === null || opts === void 0 ? void 0 : opts.name,
3791
+ };
3792
+ const read = () => {
3793
+ onReadAtom(atom);
3794
+ return atom.value;
3795
+ };
3796
+ const write = (newValue) => {
3797
+ if (typeof newValue === "function") {
3798
+ newValue = newValue(atom.value);
3799
+ }
3800
+ if (Object.is(atom.value, newValue))
3801
+ return;
3802
+ atom.value = newValue;
3803
+ onWriteAtom(atom);
3804
+ };
3805
+ read.set = write;
3806
+ read.update = (updater) => {
3807
+ if (updater) {
3808
+ write(updater(atom.value));
3809
+ }
3810
+ else {
3811
+ onWriteAtom(atom);
3812
+ }
3813
+ };
3814
+ return read;
3815
+ }
3816
+
3817
+ class Resource {
3818
+ constructor(name, type) {
3819
+ this._items = signal([]);
3820
+ this.items = computed(() => {
3821
+ return this._items()
3822
+ .sort((el1, el2) => el1[0] - el2[0])
3823
+ .map((elem) => elem[1]);
3824
+ });
3825
+ this._name = name || "resource";
3826
+ this._type = type;
3827
+ }
3828
+ add(item, sequence = 50) {
3829
+ if (this._type) {
3830
+ const error = validateType("item", item, this._type);
3831
+ if (error) {
3832
+ throw new Error(`Invalid type: ${error} (resource '${this._name}')`);
3833
+ }
3834
+ }
3835
+ this._items().push([sequence, item]);
3836
+ this._items.update();
3837
+ return this;
3838
+ }
3839
+ remove(item) {
3840
+ const items = this._items().filter(([seq, val]) => val !== item);
3841
+ this._items.set(items);
3842
+ return this;
3843
+ }
3844
+ }
3845
+ function useResource(r, elements) {
3846
+ for (let elem of elements) {
3847
+ r.add(elem);
3848
+ }
3849
+ onWillDestroy(() => {
3850
+ for (let elem of elements) {
3851
+ r.remove(elem);
3852
+ }
3853
+ });
3854
+ }
3855
+
3856
+ class Registry {
3857
+ constructor(name, type) {
3858
+ this._map = signal(Object.create(null));
3859
+ this.entries = computed(() => {
3860
+ const entries = Object.entries(this._map())
3861
+ .sort((el1, el2) => el1[1][0] - el2[1][0])
3862
+ .map(([str, elem]) => [str, elem[1]]);
3863
+ return entries;
3864
+ });
3865
+ this.items = computed(() => this.entries().map((e) => e[1]));
3866
+ this._name = name || "registry";
3867
+ this._type = type;
3868
+ }
3869
+ addById(item, sequence = 50) {
3870
+ if (!item.id) {
3871
+ throw new Error(`Item should have an id key`);
3872
+ }
3873
+ return this.add(item.id, item, sequence);
3874
+ }
3875
+ add(key, value, sequence = 50) {
3876
+ if (this._type) {
3877
+ const error = validateType(key, value, this._type);
3878
+ // todo: move error handling in validation.js
3879
+ if (error) {
3880
+ throw new Error("Invalid type: " + error);
3881
+ }
3882
+ }
3883
+ this._map()[key] = [sequence, value];
3884
+ this._map.update();
3885
+ return this;
3886
+ }
3887
+ get(key, defaultValue) {
3888
+ const hasKey = key in this._map();
3889
+ if (!hasKey && arguments.length < 2) {
3890
+ throw new Error(`KeyNotFoundError: Cannot find key "${key}" in this registry`);
3891
+ }
3892
+ return hasKey ? this._map()[key][1] : defaultValue;
3893
+ }
3894
+ remove(key) {
3895
+ delete this._map()[key];
3896
+ this._map.update();
3897
+ }
3898
+ }
3899
+
3900
+ function status() {
3901
+ const pm = _getCurrentPluginManager();
3902
+ const node = pm || getCurrent();
3903
+ return () => {
3904
+ switch (node.status) {
3905
+ case 0 /* STATUS.NEW */:
3906
+ return "new";
3907
+ case 2 /* STATUS.CANCELLED */:
3908
+ return "cancelled";
3909
+ case 1 /* STATUS.MOUNTED */:
3910
+ return pm ? "started" : "mounted";
3911
+ case 3 /* STATUS.DESTROYED */:
3912
+ return "destroyed";
3913
+ }
3914
+ };
3915
+ }
3916
+
3917
+ function effect(fn, opts) {
3918
+ var _a, _b, _c;
3919
+ const effectComputation = {
3920
+ state: ComputationState.STALE,
3921
+ value: undefined,
3922
+ compute() {
3923
+ // In case the cleanup read an atom.
3924
+ // todo: test it
3925
+ setComputation(undefined);
3926
+ // CurrentComputation = undefined!;
3927
+ // `removeSources` is made by `runComputation`.
3928
+ unsubscribeEffect(effectComputation);
3929
+ setComputation(effectComputation);
3930
+ // CurrentComputation = effectComputation;
3931
+ return fn();
3932
+ },
3933
+ sources: new Set(),
3934
+ childrenEffect: [],
3935
+ name: opts === null || opts === void 0 ? void 0 : opts.name,
3936
+ };
3937
+ (_c = (_b = (_a = getCurrentComputation()) === null || _a === void 0 ? void 0 : _a.childrenEffect) === null || _b === void 0 ? void 0 : _b.push) === null || _c === void 0 ? void 0 : _c.call(_b, effectComputation);
3938
+ updateComputation(effectComputation);
3939
+ // Remove sources and unsubscribe
3940
+ return () => {
3941
+ // In case the cleanup read an atom.
3942
+ // todo: test it
3943
+ const previousComputation = getCurrentComputation();
3944
+ setComputation(undefined);
3945
+ unsubscribeEffect(effectComputation);
3946
+ setComputation(previousComputation);
3947
+ };
3948
+ }
3949
+ function unsubscribeEffect(effectComputation) {
3950
+ removeSources(effectComputation);
3951
+ cleanupEffect(effectComputation);
3952
+ for (const children of effectComputation.childrenEffect) {
3953
+ // Consider it executed to avoid it's re-execution
3954
+ // todo: make a test for it
3955
+ children.state = ComputationState.EXECUTED;
3956
+ removeSources(children);
3957
+ unsubscribeEffect(children);
3958
+ }
3959
+ effectComputation.childrenEffect.length = 0;
3960
+ }
3961
+ function cleanupEffect(computation) {
3962
+ // the computation.value of an effect is a cleanup function
3963
+ const cleanupFn = computation.value;
3964
+ if (cleanupFn && typeof cleanupFn === "function") {
3965
+ cleanupFn();
3966
+ computation.value = undefined;
3967
+ }
3968
+ }
3969
+
3970
+ // -----------------------------------------------------------------------------
3971
+ // useEffect
3972
+ // -----------------------------------------------------------------------------
3973
+ /**
3974
+ * This hook will run a callback when a component is mounted and patched, and
3975
+ * will run a cleanup function before patching and before unmounting the
3976
+ * the component.
3977
+ *
3978
+ * @template T
3979
+ * @param {Effect<T>} effect the effect to run on component mount and/or patch
3980
+ * @param {()=>[...T]} [computeDependencies=()=>[NaN]] a callback to compute
3981
+ * dependencies that will decide if the effect needs to be cleaned up and
3982
+ * run again. If the dependencies did not change, the effect will not run
3983
+ * again. The default value returns an array containing only NaN because
3984
+ * NaN !== NaN, which will cause the effect to rerun on every patch.
3985
+ */
3986
+ function useEffect(fn) {
3987
+ let cleanup = null;
3988
+ let effectCleanup = effect(() => {
3989
+ cleanup === null || cleanup === void 0 ? void 0 : cleanup();
3990
+ cleanup = fn();
3991
+ });
3992
+ onWillDestroy(() => {
3993
+ cleanup === null || cleanup === void 0 ? void 0 : cleanup();
3994
+ effectCleanup();
3995
+ });
3996
+ }
3997
+ // -----------------------------------------------------------------------------
3998
+ // useListener
3999
+ // -----------------------------------------------------------------------------
4000
+ /**
4001
+ * When a component needs to listen to DOM Events on element(s) that are not
4002
+ * part of his hierarchy, we can use the `useListener` hook.
4003
+ * It will correctly add and remove the event listener, whenever the
4004
+ * component is mounted and unmounted.
4005
+ *
4006
+ * Example:
4007
+ * a menu needs to listen to the click on window to be closed automatically
4008
+ *
4009
+ * Usage:
4010
+ * in the constructor of the OWL component that needs to be notified,
4011
+ * `useListener(window, 'click', this._doSomething);`
4012
+ * */
4013
+ function useListener(target, eventName, handler, eventParams) {
4014
+ const node = getCurrent();
4015
+ const boundHandler = handler.bind(node.component);
4016
+ onMounted(() => target.addEventListener(eventName, boundHandler, eventParams));
4017
+ onWillUnmount(() => target.removeEventListener(eventName, boundHandler, eventParams));
4018
+ }
4019
+ function usePlugins(Plugins) {
4020
+ const node = getCurrent();
4021
+ const manager = new PluginManager(node.pluginManager);
4022
+ node.pluginManager = manager;
4023
+ onWillDestroy(() => manager.destroy());
4024
+ return manager.startPlugins(Plugins);
4025
+ }
4026
+
4027
+ config.shouldNormalizeDom = false;
4028
+ config.mainEventHandler = mainEventHandler;
4029
+ const blockDom = {
4030
+ config,
4031
+ // bdom entry points
4032
+ mount: mount$1,
4033
+ patch,
4034
+ remove,
4035
+ // bdom block types
4036
+ list,
4037
+ multi,
4038
+ text,
4039
+ toggler,
4040
+ createBlock,
4041
+ html,
4042
+ comment,
4043
+ };
4044
+ const __info__ = {
4045
+ version: App.version,
4046
+ };
4047
+
4048
+ exports.App = App;
4049
+ exports.Component = Component;
4050
+ exports.EventBus = EventBus;
4051
+ exports.OwlError = OwlError;
4052
+ exports.Plugin = Plugin;
4053
+ exports.PluginManager = PluginManager;
4054
+ exports.Registry = Registry;
4055
+ exports.Resource = Resource;
4056
+ exports.__info__ = __info__;
4057
+ exports.batched = batched;
4058
+ exports.blockDom = blockDom;
4059
+ exports.computed = computed;
4060
+ exports.effect = effect;
4061
+ exports.htmlEscape = htmlEscape;
4062
+ exports.markRaw = markRaw;
4063
+ exports.markup = markup;
4064
+ exports.mount = mount;
4065
+ exports.onError = onError;
4066
+ exports.onMounted = onMounted;
4067
+ exports.onPatched = onPatched;
4068
+ exports.onWillDestroy = onWillDestroy;
4069
+ exports.onWillPatch = onWillPatch;
4070
+ exports.onWillStart = onWillStart;
4071
+ exports.onWillUnmount = onWillUnmount;
4072
+ exports.onWillUpdateProps = onWillUpdateProps;
4073
+ exports.plugin = plugin;
4074
+ exports.props = props;
4075
+ exports.proxy = proxy;
4076
+ exports.signal = signal;
4077
+ exports.status = status;
4078
+ exports.toRaw = toRaw;
4079
+ exports.untrack = untrack;
4080
+ exports.useComponent = useComponent;
4081
+ exports.useEffect = useEffect;
4082
+ exports.useListener = useListener;
4083
+ exports.usePlugins = usePlugins;
4084
+ exports.useResource = useResource;
4085
+ exports.validate = validate;
4086
+ exports.validateType = validateType;
4087
+ exports.whenReady = whenReady;
4088
+ exports.xml = xml;
4089
+
4090
+ Object.defineProperty(exports, '__esModule', { value: true });
4091
+
4092
+
4093
+ __info__.date = '2025-12-15T09:45:48.537Z';
4094
+ __info__.hash = '4af29e6';
4095
+ __info__.url = 'https://github.com/odoo/owl';
4096
+
4097
+
4098
+ })(this.owl = this.owl || {});