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

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