@odoo/owl 3.0.0-alpha.2 → 3.0.0-alpha.20

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