@microsoft/fast-element 1.10.2 → 2.0.0-beta.1

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 (95) hide show
  1. package/.eslintrc.json +1 -12
  2. package/CHANGELOG.json +321 -1
  3. package/CHANGELOG.md +52 -2
  4. package/README.md +2 -2
  5. package/dist/dts/components/attributes.d.ts +4 -1
  6. package/dist/dts/components/controller.d.ts +12 -11
  7. package/dist/dts/components/fast-definitions.d.ts +8 -2
  8. package/dist/dts/components/fast-element.d.ts +5 -4
  9. package/dist/dts/debug.d.ts +1 -0
  10. package/dist/dts/hooks.d.ts +20 -0
  11. package/dist/dts/index.d.ts +16 -15
  12. package/dist/dts/index.debug.d.ts +2 -0
  13. package/dist/dts/index.rollup.d.ts +2 -0
  14. package/dist/dts/index.rollup.debug.d.ts +3 -0
  15. package/dist/dts/interfaces.d.ts +144 -0
  16. package/dist/dts/observation/arrays.d.ts +207 -0
  17. package/dist/dts/observation/behavior.d.ts +5 -5
  18. package/dist/dts/observation/notifier.d.ts +18 -18
  19. package/dist/dts/observation/observable.d.ts +86 -29
  20. package/dist/dts/observation/splice-strategies.d.ts +13 -0
  21. package/dist/dts/observation/update-queue.d.ts +40 -0
  22. package/dist/dts/platform.d.ts +18 -67
  23. package/dist/dts/polyfills.d.ts +8 -0
  24. package/dist/dts/styles/css-directive.d.ts +43 -5
  25. package/dist/dts/styles/css.d.ts +19 -3
  26. package/dist/dts/styles/element-styles.d.ts +42 -62
  27. package/dist/dts/templating/binding.d.ts +320 -64
  28. package/dist/dts/templating/children.d.ts +18 -15
  29. package/dist/dts/templating/compiler.d.ts +47 -28
  30. package/dist/dts/templating/dom.d.ts +41 -0
  31. package/dist/dts/templating/html-directive.d.ts +179 -43
  32. package/dist/dts/templating/markup.d.ts +48 -0
  33. package/dist/dts/templating/node-observation.d.ts +45 -29
  34. package/dist/dts/templating/ref.d.ts +6 -12
  35. package/dist/dts/templating/repeat.d.ts +72 -14
  36. package/dist/dts/templating/slotted.d.ts +13 -14
  37. package/dist/dts/templating/template.d.ts +78 -23
  38. package/dist/dts/templating/view.d.ts +16 -23
  39. package/dist/dts/utilities.d.ts +40 -0
  40. package/dist/esm/components/attributes.js +25 -24
  41. package/dist/esm/components/controller.js +77 -57
  42. package/dist/esm/components/fast-definitions.js +14 -22
  43. package/dist/esm/debug.js +29 -0
  44. package/dist/esm/hooks.js +32 -0
  45. package/dist/esm/index.debug.js +2 -0
  46. package/dist/esm/index.js +19 -14
  47. package/dist/esm/index.rollup.debug.js +3 -0
  48. package/dist/esm/index.rollup.js +2 -0
  49. package/dist/esm/interfaces.js +8 -1
  50. package/dist/esm/observation/arrays.js +269 -0
  51. package/dist/esm/observation/notifier.js +27 -35
  52. package/dist/esm/observation/observable.js +80 -107
  53. package/dist/esm/observation/{array-change-records.js → splice-strategies.js} +136 -62
  54. package/dist/esm/observation/update-queue.js +67 -0
  55. package/dist/esm/platform.js +36 -42
  56. package/dist/esm/polyfills.js +85 -0
  57. package/dist/esm/styles/css-directive.js +29 -13
  58. package/dist/esm/styles/css.js +27 -40
  59. package/dist/esm/styles/element-styles.js +65 -104
  60. package/dist/esm/templating/binding.js +465 -155
  61. package/dist/esm/templating/children.js +33 -23
  62. package/dist/esm/templating/compiler.js +235 -152
  63. package/dist/esm/templating/dom.js +49 -0
  64. package/dist/esm/templating/html-directive.js +125 -40
  65. package/dist/esm/templating/markup.js +75 -0
  66. package/dist/esm/templating/node-observation.js +50 -45
  67. package/dist/esm/templating/ref.js +7 -16
  68. package/dist/esm/templating/repeat.js +38 -43
  69. package/dist/esm/templating/slotted.js +23 -20
  70. package/dist/esm/templating/template.js +71 -95
  71. package/dist/esm/templating/view.js +44 -43
  72. package/dist/esm/templating/when.js +2 -1
  73. package/dist/esm/utilities.js +139 -0
  74. package/dist/fast-element.api.json +13633 -5266
  75. package/dist/fast-element.d.ts +1434 -578
  76. package/dist/fast-element.debug.js +3824 -0
  77. package/dist/fast-element.debug.min.js +1 -0
  78. package/dist/fast-element.js +3574 -4020
  79. package/dist/fast-element.min.js +1 -1
  80. package/dist/fast-element.untrimmed.d.ts +2908 -0
  81. package/dist/tsdoc-metadata.json +1 -1
  82. package/docs/api-report.md +590 -231
  83. package/docs/fast-element-2-changes.md +15 -0
  84. package/docs/guide/declaring-templates.md +4 -4
  85. package/docs/guide/defining-elements.md +2 -2
  86. package/docs/guide/next-steps.md +2 -2
  87. package/docs/guide/observables-and-state.md +1 -1
  88. package/docs/guide/using-directives.md +1 -1
  89. package/karma.conf.cjs +6 -17
  90. package/package.json +46 -14
  91. package/dist/dts/dom.d.ts +0 -112
  92. package/dist/dts/observation/array-change-records.d.ts +0 -48
  93. package/dist/dts/observation/array-observer.d.ts +0 -9
  94. package/dist/esm/dom.js +0 -207
  95. package/dist/esm/observation/array-observer.js +0 -177
@@ -0,0 +1,3824 @@
1
+ (function ensureGlobalThis() {
2
+ if (typeof globalThis !== "undefined") {
3
+ // We're running in a modern environment.
4
+ return;
5
+ }
6
+ if (typeof global !== "undefined") {
7
+ // We're running in NodeJS
8
+ global.globalThis = global;
9
+ }
10
+ else if (typeof self !== "undefined") {
11
+ self.globalThis = self;
12
+ }
13
+ else if (typeof window !== "undefined") {
14
+ // We're running in the browser's main thread.
15
+ window.globalThis = window;
16
+ }
17
+ else {
18
+ // Hopefully we never get here...
19
+ // Not all environments allow eval and Function. Use only as a last resort:
20
+ // eslint-disable-next-line no-new-func
21
+ const result = new Function("return this")();
22
+ result.globalThis = result;
23
+ }
24
+ })();
25
+ // API-only Polyfill for trustedTypes
26
+ if (!globalThis.trustedTypes) {
27
+ globalThis.trustedTypes = {
28
+ createPolicy: (n, r) => r,
29
+ };
30
+ }
31
+ // ensure FAST global - duplicated in platform.ts
32
+ const propConfig$1 = {
33
+ configurable: false,
34
+ enumerable: false,
35
+ writable: false,
36
+ };
37
+ if (globalThis.FAST === void 0) {
38
+ Reflect.defineProperty(globalThis, "FAST", Object.assign({ value: Object.create(null) }, propConfig$1));
39
+ }
40
+ const FAST$2 = globalThis.FAST;
41
+ if (FAST$2.getById === void 0) {
42
+ const storage = Object.create(null);
43
+ Reflect.defineProperty(FAST$2, "getById", Object.assign({ value(id, initialize) {
44
+ let found = storage[id];
45
+ if (found === void 0) {
46
+ found = initialize ? (storage[id] = initialize()) : null;
47
+ }
48
+ return found;
49
+ } }, propConfig$1));
50
+ }
51
+ // duplicated from DOM
52
+ const supportsAdoptedStyleSheets = Array.isArray(document.adoptedStyleSheets) &&
53
+ "replace" in CSSStyleSheet.prototype;
54
+ function usableStyleTarget(target) {
55
+ return target === document ? document.body : target;
56
+ }
57
+ let id$1 = 0;
58
+ const nextStyleId = () => `fast-${++id$1}`;
59
+ class StyleElementStrategy {
60
+ constructor(styles) {
61
+ this.styles = styles;
62
+ this.styleClass = nextStyleId();
63
+ }
64
+ addStylesTo(target) {
65
+ target = usableStyleTarget(target);
66
+ const styles = this.styles;
67
+ const styleClass = this.styleClass;
68
+ for (let i = 0; i < styles.length; i++) {
69
+ const element = document.createElement("style");
70
+ element.innerHTML = styles[i];
71
+ element.className = styleClass;
72
+ target.append(element);
73
+ }
74
+ }
75
+ removeStylesFrom(target) {
76
+ const styles = target.querySelectorAll(`.${this.styleClass}`);
77
+ target = usableStyleTarget(target);
78
+ for (let i = 0, ii = styles.length; i < ii; ++i) {
79
+ target.removeChild(styles[i]);
80
+ }
81
+ }
82
+ }
83
+ if (!supportsAdoptedStyleSheets) {
84
+ FAST$2.getById(/* KernelServiceId.styleSheetStrategy */ 5, () => StyleElementStrategy);
85
+ }
86
+
87
+ if (globalThis.FAST === void 0) {
88
+ Reflect.defineProperty(globalThis, "FAST", {
89
+ value: Object.create(null),
90
+ configurable: false,
91
+ enumerable: false,
92
+ writable: false,
93
+ });
94
+ }
95
+ const FAST$1 = globalThis.FAST;
96
+ const debugMessages = {
97
+ [1101 /* needsArrayObservation */]: "Must call enableArrayObservation before observing arrays.",
98
+ [1201 /* onlySetHTMLPolicyOnce */]: "The HTML policy can only be set once.",
99
+ [1202 /* bindingInnerHTMLRequiresTrustedTypes */]: "To bind innerHTML, you must use a TrustedTypesPolicy.",
100
+ [1401 /* missingElementDefinition */]: "Missing FASTElement definition.",
101
+ };
102
+ Object.assign(FAST$1, {
103
+ addMessages(messages) {
104
+ Object.assign(debugMessages, messages);
105
+ },
106
+ warn(code, ...args) {
107
+ var _a;
108
+ console.warn((_a = debugMessages[code]) !== null && _a !== void 0 ? _a : "Unknown Warning");
109
+ },
110
+ error(code, ...args) {
111
+ var _a;
112
+ return new Error((_a = debugMessages[code]) !== null && _a !== void 0 ? _a : "Unknown Error");
113
+ },
114
+ });
115
+
116
+ // ensure FAST global - duplicated in polyfills.ts and debug.ts
117
+ const propConfig = {
118
+ configurable: false,
119
+ enumerable: false,
120
+ writable: false,
121
+ };
122
+ if (globalThis.FAST === void 0) {
123
+ Reflect.defineProperty(globalThis, "FAST", Object.assign({ value: Object.create(null) }, propConfig));
124
+ }
125
+ /**
126
+ * The FAST global.
127
+ * @internal
128
+ */
129
+ const FAST = globalThis.FAST;
130
+ if (FAST.getById === void 0) {
131
+ const storage = Object.create(null);
132
+ Reflect.defineProperty(FAST, "getById", Object.assign({ value(id, initialize) {
133
+ let found = storage[id];
134
+ if (found === void 0) {
135
+ found = initialize ? (storage[id] = initialize()) : null;
136
+ }
137
+ return found;
138
+ } }, propConfig));
139
+ }
140
+ if (FAST.error === void 0) {
141
+ Object.assign(FAST, {
142
+ warn() { },
143
+ error(code) {
144
+ return new Error(`Code ${code}`);
145
+ },
146
+ addMessages() { },
147
+ });
148
+ }
149
+ /**
150
+ * A readonly, empty array.
151
+ * @remarks
152
+ * Typically returned by APIs that return arrays when there are
153
+ * no actual items to return.
154
+ * @public
155
+ */
156
+ const emptyArray = Object.freeze([]);
157
+ /**
158
+ * Do not change. Part of shared kernel contract.
159
+ * @internal
160
+ */
161
+ function createTypeRegistry() {
162
+ const typeToDefinition = new Map();
163
+ return Object.freeze({
164
+ register(definition) {
165
+ if (typeToDefinition.has(definition.type)) {
166
+ return false;
167
+ }
168
+ typeToDefinition.set(definition.type, definition);
169
+ return true;
170
+ },
171
+ getByType(key) {
172
+ return typeToDefinition.get(key);
173
+ },
174
+ getForInstance(object) {
175
+ return typeToDefinition.get(object.constructor);
176
+ },
177
+ });
178
+ }
179
+
180
+ /**
181
+ * @internal
182
+ */
183
+ const isFunction = (object) => typeof object === "function";
184
+ /**
185
+ * @internal
186
+ */
187
+ const isString = (object) => typeof object === "string";
188
+
189
+ /**
190
+ * The default UpdateQueue.
191
+ * @public
192
+ */
193
+ const Updates = FAST.getById(1 /* KernelServiceId.updateQueue */, () => {
194
+ const tasks = [];
195
+ const pendingErrors = [];
196
+ const rAF = globalThis.requestAnimationFrame;
197
+ let updateAsync = true;
198
+ function throwFirstError() {
199
+ if (pendingErrors.length) {
200
+ throw pendingErrors.shift();
201
+ }
202
+ }
203
+ function tryRunTask(task) {
204
+ try {
205
+ task.call();
206
+ }
207
+ catch (error) {
208
+ if (updateAsync) {
209
+ pendingErrors.push(error);
210
+ setTimeout(throwFirstError, 0);
211
+ }
212
+ else {
213
+ tasks.length = 0;
214
+ throw error;
215
+ }
216
+ }
217
+ }
218
+ function process() {
219
+ const capacity = 1024;
220
+ let index = 0;
221
+ while (index < tasks.length) {
222
+ tryRunTask(tasks[index]);
223
+ index++;
224
+ // Prevent leaking memory for long chains of recursive calls to `enqueue`.
225
+ // If we call `enqueue` within a task scheduled by `enqueue`, the queue will
226
+ // grow, but to avoid an O(n) walk for every task we execute, we don't
227
+ // shift tasks off the queue after they have been executed.
228
+ // Instead, we periodically shift 1024 tasks off the queue.
229
+ if (index > capacity) {
230
+ // Manually shift all values starting at the index back to the
231
+ // beginning of the queue.
232
+ for (let scan = 0, newLength = tasks.length - index; scan < newLength; scan++) {
233
+ tasks[scan] = tasks[scan + index];
234
+ }
235
+ tasks.length -= index;
236
+ index = 0;
237
+ }
238
+ }
239
+ tasks.length = 0;
240
+ }
241
+ function enqueue(callable) {
242
+ tasks.push(callable);
243
+ if (tasks.length < 2) {
244
+ updateAsync ? rAF(process) : process();
245
+ }
246
+ }
247
+ return Object.freeze({
248
+ enqueue,
249
+ next: () => new Promise(enqueue),
250
+ process,
251
+ setMode: (isAsync) => (updateAsync = isAsync),
252
+ });
253
+ });
254
+
255
+ /**
256
+ * An implementation of {@link Notifier} that efficiently keeps track of
257
+ * subscribers interested in a specific change notification on an
258
+ * observable subject.
259
+ *
260
+ * @remarks
261
+ * This set is optimized for the most common scenario of 1 or 2 subscribers.
262
+ * With this in mind, it can store a subscriber in an internal field, allowing it to avoid Array#push operations.
263
+ * If the set ever exceeds two subscribers, it upgrades to an array automatically.
264
+ * @public
265
+ */
266
+ class SubscriberSet {
267
+ /**
268
+ * Creates an instance of SubscriberSet for the specified subject.
269
+ * @param subject - The subject that subscribers will receive notifications from.
270
+ * @param initialSubscriber - An initial subscriber to changes.
271
+ */
272
+ constructor(subject, initialSubscriber) {
273
+ this.sub1 = void 0;
274
+ this.sub2 = void 0;
275
+ this.spillover = void 0;
276
+ this.subject = subject;
277
+ this.sub1 = initialSubscriber;
278
+ }
279
+ /**
280
+ * Checks whether the provided subscriber has been added to this set.
281
+ * @param subscriber - The subscriber to test for inclusion in this set.
282
+ */
283
+ has(subscriber) {
284
+ return this.spillover === void 0
285
+ ? this.sub1 === subscriber || this.sub2 === subscriber
286
+ : this.spillover.indexOf(subscriber) !== -1;
287
+ }
288
+ /**
289
+ * Subscribes to notification of changes in an object's state.
290
+ * @param subscriber - The object that is subscribing for change notification.
291
+ */
292
+ subscribe(subscriber) {
293
+ const spillover = this.spillover;
294
+ if (spillover === void 0) {
295
+ if (this.has(subscriber)) {
296
+ return;
297
+ }
298
+ if (this.sub1 === void 0) {
299
+ this.sub1 = subscriber;
300
+ return;
301
+ }
302
+ if (this.sub2 === void 0) {
303
+ this.sub2 = subscriber;
304
+ return;
305
+ }
306
+ this.spillover = [this.sub1, this.sub2, subscriber];
307
+ this.sub1 = void 0;
308
+ this.sub2 = void 0;
309
+ }
310
+ else {
311
+ const index = spillover.indexOf(subscriber);
312
+ if (index === -1) {
313
+ spillover.push(subscriber);
314
+ }
315
+ }
316
+ }
317
+ /**
318
+ * Unsubscribes from notification of changes in an object's state.
319
+ * @param subscriber - The object that is unsubscribing from change notification.
320
+ */
321
+ unsubscribe(subscriber) {
322
+ const spillover = this.spillover;
323
+ if (spillover === void 0) {
324
+ if (this.sub1 === subscriber) {
325
+ this.sub1 = void 0;
326
+ }
327
+ else if (this.sub2 === subscriber) {
328
+ this.sub2 = void 0;
329
+ }
330
+ }
331
+ else {
332
+ const index = spillover.indexOf(subscriber);
333
+ if (index !== -1) {
334
+ spillover.splice(index, 1);
335
+ }
336
+ }
337
+ }
338
+ /**
339
+ * Notifies all subscribers.
340
+ * @param args - Data passed along to subscribers during notification.
341
+ */
342
+ notify(args) {
343
+ const spillover = this.spillover;
344
+ const subject = this.subject;
345
+ if (spillover === void 0) {
346
+ const sub1 = this.sub1;
347
+ const sub2 = this.sub2;
348
+ if (sub1 !== void 0) {
349
+ sub1.handleChange(subject, args);
350
+ }
351
+ if (sub2 !== void 0) {
352
+ sub2.handleChange(subject, args);
353
+ }
354
+ }
355
+ else {
356
+ for (let i = 0, ii = spillover.length; i < ii; ++i) {
357
+ spillover[i].handleChange(subject, args);
358
+ }
359
+ }
360
+ }
361
+ }
362
+ /**
363
+ * An implementation of Notifier that allows subscribers to be notified
364
+ * of individual property changes on an object.
365
+ * @public
366
+ */
367
+ class PropertyChangeNotifier {
368
+ /**
369
+ * Creates an instance of PropertyChangeNotifier for the specified subject.
370
+ * @param subject - The object that subscribers will receive notifications for.
371
+ */
372
+ constructor(subject) {
373
+ this.subscribers = {};
374
+ this.subjectSubscribers = null;
375
+ this.subject = subject;
376
+ }
377
+ /**
378
+ * Notifies all subscribers, based on the specified property.
379
+ * @param propertyName - The property name, passed along to subscribers during notification.
380
+ */
381
+ notify(propertyName) {
382
+ var _a, _b;
383
+ (_a = this.subscribers[propertyName]) === null || _a === void 0 ? void 0 : _a.notify(propertyName);
384
+ (_b = this.subjectSubscribers) === null || _b === void 0 ? void 0 : _b.notify(propertyName);
385
+ }
386
+ /**
387
+ * Subscribes to notification of changes in an object's state.
388
+ * @param subscriber - The object that is subscribing for change notification.
389
+ * @param propertyToWatch - The name of the property that the subscriber is interested in watching for changes.
390
+ */
391
+ subscribe(subscriber, propertyToWatch) {
392
+ var _a, _b;
393
+ let subscribers;
394
+ if (propertyToWatch) {
395
+ subscribers =
396
+ (_a = this.subscribers[propertyToWatch]) !== null && _a !== void 0 ? _a : (this.subscribers[propertyToWatch] = new SubscriberSet(this.subject));
397
+ }
398
+ else {
399
+ subscribers =
400
+ (_b = this.subjectSubscribers) !== null && _b !== void 0 ? _b : (this.subjectSubscribers = new SubscriberSet(this.subject));
401
+ }
402
+ subscribers.subscribe(subscriber);
403
+ }
404
+ /**
405
+ * Unsubscribes from notification of changes in an object's state.
406
+ * @param subscriber - The object that is unsubscribing from change notification.
407
+ * @param propertyToUnwatch - The name of the property that the subscriber is no longer interested in watching.
408
+ */
409
+ unsubscribe(subscriber, propertyToUnwatch) {
410
+ var _a, _b;
411
+ if (propertyToUnwatch) {
412
+ (_a = this.subscribers[propertyToUnwatch]) === null || _a === void 0 ? void 0 : _a.unsubscribe(subscriber);
413
+ }
414
+ else {
415
+ (_b = this.subjectSubscribers) === null || _b === void 0 ? void 0 : _b.unsubscribe(subscriber);
416
+ }
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Common Observable APIs.
422
+ * @public
423
+ */
424
+ const Observable = FAST.getById(2 /* KernelServiceId.observable */, () => {
425
+ const queueUpdate = Updates.enqueue;
426
+ const volatileRegex = /(:|&&|\|\||if)/;
427
+ const notifierLookup = new WeakMap();
428
+ const accessorLookup = new WeakMap();
429
+ let watcher = void 0;
430
+ let createArrayObserver = (array) => {
431
+ throw FAST.error(1101 /* Message.needsArrayObservation */);
432
+ };
433
+ function getNotifier(source) {
434
+ var _a;
435
+ let found = (_a = source.$fastController) !== null && _a !== void 0 ? _a : notifierLookup.get(source);
436
+ if (found === void 0) {
437
+ Array.isArray(source)
438
+ ? (found = createArrayObserver(source))
439
+ : notifierLookup.set(source, (found = new PropertyChangeNotifier(source)));
440
+ }
441
+ return found;
442
+ }
443
+ function getAccessors(target) {
444
+ let accessors = accessorLookup.get(target);
445
+ if (accessors === void 0) {
446
+ let currentTarget = Reflect.getPrototypeOf(target);
447
+ while (accessors === void 0 && currentTarget !== null) {
448
+ accessors = accessorLookup.get(currentTarget);
449
+ currentTarget = Reflect.getPrototypeOf(currentTarget);
450
+ }
451
+ accessors = accessors === void 0 ? [] : accessors.slice(0);
452
+ accessorLookup.set(target, accessors);
453
+ }
454
+ return accessors;
455
+ }
456
+ class DefaultObservableAccessor {
457
+ constructor(name) {
458
+ this.name = name;
459
+ this.field = `_${name}`;
460
+ this.callback = `${name}Changed`;
461
+ }
462
+ getValue(source) {
463
+ if (watcher !== void 0) {
464
+ watcher.watch(source, this.name);
465
+ }
466
+ return source[this.field];
467
+ }
468
+ setValue(source, newValue) {
469
+ const field = this.field;
470
+ const oldValue = source[field];
471
+ if (oldValue !== newValue) {
472
+ source[field] = newValue;
473
+ const callback = source[this.callback];
474
+ if (isFunction(callback)) {
475
+ callback.call(source, oldValue, newValue);
476
+ }
477
+ getNotifier(source).notify(this.name);
478
+ }
479
+ }
480
+ }
481
+ class BindingObserverImplementation extends SubscriberSet {
482
+ constructor(binding, initialSubscriber, isVolatileBinding = false) {
483
+ super(binding, initialSubscriber);
484
+ this.binding = binding;
485
+ this.isVolatileBinding = isVolatileBinding;
486
+ this.needsRefresh = true;
487
+ this.needsQueue = true;
488
+ this.isAsync = true;
489
+ this.first = this;
490
+ this.last = null;
491
+ this.propertySource = void 0;
492
+ this.propertyName = void 0;
493
+ this.notifier = void 0;
494
+ this.next = void 0;
495
+ }
496
+ setMode(isAsync) {
497
+ this.isAsync = this.needsQueue = isAsync;
498
+ }
499
+ observe(source, context) {
500
+ if (this.needsRefresh && this.last !== null) {
501
+ this.dispose();
502
+ }
503
+ const previousWatcher = watcher;
504
+ watcher = this.needsRefresh ? this : void 0;
505
+ this.needsRefresh = this.isVolatileBinding;
506
+ const result = this.binding(source, context !== null && context !== void 0 ? context : ExecutionContext.default);
507
+ watcher = previousWatcher;
508
+ return result;
509
+ }
510
+ dispose() {
511
+ if (this.last !== null) {
512
+ let current = this.first;
513
+ while (current !== void 0) {
514
+ current.notifier.unsubscribe(this, current.propertyName);
515
+ current = current.next;
516
+ }
517
+ this.last = null;
518
+ this.needsRefresh = this.needsQueue = this.isAsync;
519
+ }
520
+ }
521
+ watch(propertySource, propertyName) {
522
+ const prev = this.last;
523
+ const notifier = getNotifier(propertySource);
524
+ const current = prev === null ? this.first : {};
525
+ current.propertySource = propertySource;
526
+ current.propertyName = propertyName;
527
+ current.notifier = notifier;
528
+ notifier.subscribe(this, propertyName);
529
+ if (prev !== null) {
530
+ if (!this.needsRefresh) {
531
+ // Declaring the variable prior to assignment below circumvents
532
+ // a bug in Angular's optimization process causing infinite recursion
533
+ // of this watch() method. Details https://github.com/microsoft/fast/issues/4969
534
+ let prevValue;
535
+ watcher = void 0;
536
+ /* eslint-disable-next-line */
537
+ prevValue = prev.propertySource[prev.propertyName];
538
+ /* eslint-disable-next-line */
539
+ watcher = this;
540
+ if (propertySource === prevValue) {
541
+ this.needsRefresh = true;
542
+ }
543
+ }
544
+ prev.next = current;
545
+ }
546
+ this.last = current;
547
+ }
548
+ handleChange() {
549
+ if (this.needsQueue) {
550
+ this.needsQueue = false;
551
+ queueUpdate(this);
552
+ }
553
+ else if (!this.isAsync) {
554
+ this.call();
555
+ }
556
+ }
557
+ call() {
558
+ if (this.last !== null) {
559
+ this.needsQueue = this.isAsync;
560
+ this.notify(this);
561
+ }
562
+ }
563
+ *records() {
564
+ let next = this.first;
565
+ while (next !== void 0) {
566
+ yield next;
567
+ next = next.next;
568
+ }
569
+ }
570
+ }
571
+ return Object.freeze({
572
+ /**
573
+ * @internal
574
+ * @param factory - The factory used to create array observers.
575
+ */
576
+ setArrayObserverFactory(factory) {
577
+ createArrayObserver = factory;
578
+ },
579
+ /**
580
+ * Gets a notifier for an object or Array.
581
+ * @param source - The object or Array to get the notifier for.
582
+ */
583
+ getNotifier,
584
+ /**
585
+ * Records a property change for a source object.
586
+ * @param source - The object to record the change against.
587
+ * @param propertyName - The property to track as changed.
588
+ */
589
+ track(source, propertyName) {
590
+ watcher && watcher.watch(source, propertyName);
591
+ },
592
+ /**
593
+ * Notifies watchers that the currently executing property getter or function is volatile
594
+ * with respect to its observable dependencies.
595
+ */
596
+ trackVolatile() {
597
+ watcher && (watcher.needsRefresh = true);
598
+ },
599
+ /**
600
+ * Notifies subscribers of a source object of changes.
601
+ * @param source - the object to notify of changes.
602
+ * @param args - The change args to pass to subscribers.
603
+ */
604
+ notify(source, args) {
605
+ /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
606
+ getNotifier(source).notify(args);
607
+ },
608
+ /**
609
+ * Defines an observable property on an object or prototype.
610
+ * @param target - The target object to define the observable on.
611
+ * @param nameOrAccessor - The name of the property to define as observable;
612
+ * or a custom accessor that specifies the property name and accessor implementation.
613
+ */
614
+ defineProperty(target, nameOrAccessor) {
615
+ if (isString(nameOrAccessor)) {
616
+ nameOrAccessor = new DefaultObservableAccessor(nameOrAccessor);
617
+ }
618
+ getAccessors(target).push(nameOrAccessor);
619
+ Reflect.defineProperty(target, nameOrAccessor.name, {
620
+ enumerable: true,
621
+ get() {
622
+ return nameOrAccessor.getValue(this);
623
+ },
624
+ set(newValue) {
625
+ nameOrAccessor.setValue(this, newValue);
626
+ },
627
+ });
628
+ },
629
+ /**
630
+ * Finds all the observable accessors defined on the target,
631
+ * including its prototype chain.
632
+ * @param target - The target object to search for accessor on.
633
+ */
634
+ getAccessors,
635
+ /**
636
+ * Creates a {@link BindingObserver} that can watch the
637
+ * provided {@link Binding} for changes.
638
+ * @param binding - The binding to observe.
639
+ * @param initialSubscriber - An initial subscriber to changes in the binding value.
640
+ * @param isVolatileBinding - Indicates whether the binding's dependency list must be re-evaluated on every value evaluation.
641
+ */
642
+ binding(binding, initialSubscriber, isVolatileBinding = this.isVolatileBinding(binding)) {
643
+ return new BindingObserverImplementation(binding, initialSubscriber, isVolatileBinding);
644
+ },
645
+ /**
646
+ * Determines whether a binding expression is volatile and needs to have its dependency list re-evaluated
647
+ * on every evaluation of the value.
648
+ * @param binding - The binding to inspect.
649
+ */
650
+ isVolatileBinding(binding) {
651
+ return volatileRegex.test(binding.toString());
652
+ },
653
+ });
654
+ });
655
+ /**
656
+ * Decorator: Defines an observable property on the target.
657
+ * @param target - The target to define the observable on.
658
+ * @param nameOrAccessor - The property name or accessor to define the observable as.
659
+ * @public
660
+ */
661
+ function observable(target, nameOrAccessor) {
662
+ Observable.defineProperty(target, nameOrAccessor);
663
+ }
664
+ /**
665
+ * Decorator: Marks a property getter as having volatile observable dependencies.
666
+ * @param target - The target that the property is defined on.
667
+ * @param name - The property name.
668
+ * @param name - The existing descriptor.
669
+ * @public
670
+ */
671
+ function volatile(target, name, descriptor) {
672
+ return Object.assign({}, descriptor, {
673
+ get() {
674
+ Observable.trackVolatile();
675
+ return descriptor.get.apply(this);
676
+ },
677
+ });
678
+ }
679
+ const contextEvent = FAST.getById(3 /* KernelServiceId.contextEvent */, () => {
680
+ let current = null;
681
+ return {
682
+ get() {
683
+ return current;
684
+ },
685
+ set(event) {
686
+ current = event;
687
+ },
688
+ };
689
+ });
690
+ class DefaultExecutionContext {
691
+ constructor(parentSource = null, parentContext = null) {
692
+ this.index = 0;
693
+ this.length = 0;
694
+ this.parent = parentSource;
695
+ this.parentContext = parentContext;
696
+ }
697
+ get event() {
698
+ return contextEvent.get();
699
+ }
700
+ get isEven() {
701
+ return this.index % 2 === 0;
702
+ }
703
+ get isOdd() {
704
+ return this.index % 2 !== 0;
705
+ }
706
+ get isFirst() {
707
+ return this.index === 0;
708
+ }
709
+ get isInMiddle() {
710
+ return !this.isFirst && !this.isLast;
711
+ }
712
+ get isLast() {
713
+ return this.index === this.length - 1;
714
+ }
715
+ eventDetail() {
716
+ return this.event.detail;
717
+ }
718
+ eventTarget() {
719
+ return this.event.target;
720
+ }
721
+ updatePosition(index, length) {
722
+ this.index = index;
723
+ this.length = length;
724
+ }
725
+ createChildContext(parentSource) {
726
+ return new DefaultExecutionContext(parentSource, this);
727
+ }
728
+ createItemContext(index, length) {
729
+ const childContext = Object.create(this);
730
+ childContext.index = index;
731
+ childContext.length = length;
732
+ return childContext;
733
+ }
734
+ }
735
+ Observable.defineProperty(DefaultExecutionContext.prototype, "index");
736
+ Observable.defineProperty(DefaultExecutionContext.prototype, "length");
737
+ /**
738
+ * The common execution context APIs.
739
+ * @public
740
+ */
741
+ const ExecutionContext = Object.freeze({
742
+ default: new DefaultExecutionContext(),
743
+ /**
744
+ * Sets the event for the current execution context.
745
+ * @param event - The event to set.
746
+ * @internal
747
+ */
748
+ setEvent(event) {
749
+ contextEvent.set(event);
750
+ },
751
+ /**
752
+ * Creates a new root execution context.
753
+ * @returns A new execution context.
754
+ */
755
+ create() {
756
+ return new DefaultExecutionContext();
757
+ },
758
+ });
759
+
760
+ /**
761
+ * A splice map is a representation of how a previous array of items
762
+ * was transformed into a new array of items. Conceptually it is a list of
763
+ * tuples of
764
+ *
765
+ * (index, removed, addedCount)
766
+ *
767
+ * which are kept in ascending index order of. The tuple represents that at
768
+ * the |index|, |removed| sequence of items were removed, and counting forward
769
+ * from |index|, |addedCount| items were added.
770
+ * @public
771
+ */
772
+ class Splice {
773
+ /**
774
+ * Creates a splice.
775
+ * @param index - The index that the splice occurs at.
776
+ * @param removed - The items that were removed.
777
+ * @param addedCount - The number of items that were added.
778
+ */
779
+ constructor(index, removed, addedCount) {
780
+ this.index = index;
781
+ this.removed = removed;
782
+ this.addedCount = addedCount;
783
+ }
784
+ /**
785
+ * Adjusts the splice index based on the provided array.
786
+ * @param array - The array to adjust to.
787
+ * @returns The same splice, mutated based on the reference array.
788
+ */
789
+ adjustTo(array) {
790
+ let index = this.index;
791
+ const arrayLength = array.length;
792
+ if (index > arrayLength) {
793
+ index = arrayLength - this.addedCount;
794
+ }
795
+ else if (index < 0) {
796
+ index = arrayLength + this.removed.length + index - this.addedCount;
797
+ }
798
+ this.index = index < 0 ? 0 : index;
799
+ return this;
800
+ }
801
+ }
802
+ /**
803
+ * Indicates what level of feature support the splice
804
+ * strategy provides.
805
+ * @public
806
+ */
807
+ const SpliceStrategySupport = Object.freeze({
808
+ /**
809
+ * Only supports resets.
810
+ */
811
+ reset: 1,
812
+ /**
813
+ * Supports tracking splices and resets.
814
+ */
815
+ splice: 2,
816
+ /**
817
+ * Supports tracking splices and resets, while applying some form
818
+ * of optimization, such as merging, to the splices.
819
+ */
820
+ optimized: 3,
821
+ });
822
+ const reset = new Splice(0, emptyArray, 0);
823
+ reset.reset = true;
824
+ const resetSplices = [reset];
825
+ let defaultSpliceStrategy = Object.freeze({
826
+ support: SpliceStrategySupport.splice,
827
+ normalize(previous, current, changes) {
828
+ return previous === void 0 ? changes !== null && changes !== void 0 ? changes : emptyArray : resetSplices;
829
+ },
830
+ pop(array, observer, pop, args) {
831
+ const notEmpty = array.length > 0;
832
+ const result = pop.apply(array, args);
833
+ if (notEmpty) {
834
+ observer.addSplice(new Splice(array.length, [result], 0));
835
+ }
836
+ return result;
837
+ },
838
+ push(array, observer, push, args) {
839
+ const result = push.apply(array, args);
840
+ observer.addSplice(new Splice(array.length - args.length, [], args.length).adjustTo(array));
841
+ return result;
842
+ },
843
+ reverse(array, observer, reverse, args) {
844
+ const result = reverse.apply(array, args);
845
+ observer.reset(array);
846
+ return result;
847
+ },
848
+ shift(array, observer, shift, args) {
849
+ const notEmpty = array.length > 0;
850
+ const result = shift.apply(array, args);
851
+ if (notEmpty) {
852
+ observer.addSplice(new Splice(0, [result], 0));
853
+ }
854
+ return result;
855
+ },
856
+ sort(array, observer, sort, args) {
857
+ const result = sort.apply(array, args);
858
+ observer.reset(array);
859
+ return result;
860
+ },
861
+ splice(array, observer, splice, args) {
862
+ const result = splice.apply(array, args);
863
+ observer.addSplice(new Splice(+args[0], result, args.length > 2 ? args.length - 2 : 0).adjustTo(array));
864
+ return result;
865
+ },
866
+ unshift(array, observer, unshift, args) {
867
+ const result = unshift.apply(array, args);
868
+ observer.addSplice(new Splice(0, [], args.length).adjustTo(array));
869
+ return result;
870
+ },
871
+ });
872
+ /**
873
+ * Functionality related to tracking changes in arrays.
874
+ * @public
875
+ */
876
+ const SpliceStrategy = Object.freeze({
877
+ /**
878
+ * A set of changes that represent a full array reset.
879
+ */
880
+ reset: resetSplices,
881
+ /**
882
+ * Sets the default strategy to use for array observers.
883
+ * @param strategy - The splice strategy to use.
884
+ */
885
+ setDefaultStrategy(strategy) {
886
+ defaultSpliceStrategy = strategy;
887
+ },
888
+ });
889
+ function setNonEnumerable(target, property, value) {
890
+ Reflect.defineProperty(target, property, {
891
+ value,
892
+ enumerable: false,
893
+ });
894
+ }
895
+ class DefaultArrayObserver extends SubscriberSet {
896
+ constructor(subject) {
897
+ super(subject);
898
+ this.oldCollection = void 0;
899
+ this.splices = void 0;
900
+ this.needsQueue = true;
901
+ this._strategy = null;
902
+ this._lengthObserver = void 0;
903
+ this.call = this.flush;
904
+ setNonEnumerable(subject, "$fastController", this);
905
+ }
906
+ get strategy() {
907
+ return this._strategy;
908
+ }
909
+ set strategy(value) {
910
+ this._strategy = value;
911
+ }
912
+ get lengthObserver() {
913
+ let observer = this._lengthObserver;
914
+ if (observer === void 0) {
915
+ const array = this.subject;
916
+ this._lengthObserver = observer = {
917
+ length: array.length,
918
+ handleChange() {
919
+ if (this.length !== array.length) {
920
+ this.length = array.length;
921
+ Observable.notify(observer, "length");
922
+ }
923
+ },
924
+ };
925
+ this.subscribe(observer);
926
+ }
927
+ return observer;
928
+ }
929
+ subscribe(subscriber) {
930
+ this.flush();
931
+ super.subscribe(subscriber);
932
+ }
933
+ addSplice(splice) {
934
+ if (this.splices === void 0) {
935
+ this.splices = [splice];
936
+ }
937
+ else {
938
+ this.splices.push(splice);
939
+ }
940
+ this.enqueue();
941
+ }
942
+ reset(oldCollection) {
943
+ this.oldCollection = oldCollection;
944
+ this.enqueue();
945
+ }
946
+ flush() {
947
+ var _a;
948
+ const splices = this.splices;
949
+ const oldCollection = this.oldCollection;
950
+ if (splices === void 0 && oldCollection === void 0) {
951
+ return;
952
+ }
953
+ this.needsQueue = true;
954
+ this.splices = void 0;
955
+ this.oldCollection = void 0;
956
+ this.notify(((_a = this._strategy) !== null && _a !== void 0 ? _a : defaultSpliceStrategy).normalize(oldCollection, this.subject, splices));
957
+ }
958
+ enqueue() {
959
+ if (this.needsQueue) {
960
+ this.needsQueue = false;
961
+ Updates.enqueue(this);
962
+ }
963
+ }
964
+ }
965
+ let enabled = false;
966
+ /**
967
+ * An observer for arrays.
968
+ * @public
969
+ */
970
+ const ArrayObserver = Object.freeze({
971
+ /**
972
+ * Enables the array observation mechanism.
973
+ * @remarks
974
+ * Array observation is enabled automatically when using the
975
+ * {@link RepeatDirective}, so calling this API manually is
976
+ * not typically necessary.
977
+ */
978
+ enable() {
979
+ if (enabled) {
980
+ return;
981
+ }
982
+ enabled = true;
983
+ Observable.setArrayObserverFactory((collection) => new DefaultArrayObserver(collection));
984
+ const proto = Array.prototype;
985
+ if (!proto.$fastPatch) {
986
+ setNonEnumerable(proto, "$fastPatch", 1);
987
+ [
988
+ proto.pop,
989
+ proto.push,
990
+ proto.reverse,
991
+ proto.shift,
992
+ proto.sort,
993
+ proto.splice,
994
+ proto.unshift,
995
+ ].forEach(method => {
996
+ proto[method.name] = function (...args) {
997
+ var _a;
998
+ const o = this.$fastController;
999
+ return o === void 0
1000
+ ? method.apply(this, args)
1001
+ : ((_a = o.strategy) !== null && _a !== void 0 ? _a : defaultSpliceStrategy)[method.name](this, o, method, args);
1002
+ };
1003
+ });
1004
+ }
1005
+ },
1006
+ });
1007
+ /**
1008
+ * Enables observing the length of an array.
1009
+ * @param array - The array to observe the length of.
1010
+ * @returns The length of the array.
1011
+ * @public
1012
+ */
1013
+ function length(array) {
1014
+ if (!array) {
1015
+ return 0;
1016
+ }
1017
+ let arrayObserver = array.$fastController;
1018
+ if (arrayObserver === void 0) {
1019
+ ArrayObserver.enable();
1020
+ arrayObserver = Observable.getNotifier(array);
1021
+ }
1022
+ Observable.track(arrayObserver.lengthObserver, "length");
1023
+ return array.length;
1024
+ }
1025
+
1026
+ const styleSheetCache = new Map();
1027
+ let DefaultStyleStrategy;
1028
+ function reduceStyles(styles) {
1029
+ return styles
1030
+ .map((x) => x instanceof ElementStyles ? reduceStyles(x.styles) : [x])
1031
+ .reduce((prev, curr) => prev.concat(curr), []);
1032
+ }
1033
+ /**
1034
+ * Represents styles that can be applied to a custom element.
1035
+ * @public
1036
+ */
1037
+ class ElementStyles {
1038
+ /**
1039
+ * Creates an instance of ElementStyles.
1040
+ * @param styles - The styles that will be associated with elements.
1041
+ */
1042
+ constructor(styles) {
1043
+ this.styles = styles;
1044
+ this.targets = new WeakSet();
1045
+ this._strategy = null;
1046
+ this.behaviors = styles
1047
+ .map((x) => x instanceof ElementStyles ? x.behaviors : null)
1048
+ .reduce((prev, curr) => (curr === null ? prev : prev === null ? curr : prev.concat(curr)), null);
1049
+ }
1050
+ /**
1051
+ * Gets the StyleStrategy associated with these element styles.
1052
+ */
1053
+ get strategy() {
1054
+ if (this._strategy === null) {
1055
+ this.withStrategy(DefaultStyleStrategy);
1056
+ }
1057
+ return this._strategy;
1058
+ }
1059
+ /** @internal */
1060
+ addStylesTo(target) {
1061
+ this.strategy.addStylesTo(target);
1062
+ this.targets.add(target);
1063
+ }
1064
+ /** @internal */
1065
+ removeStylesFrom(target) {
1066
+ this.strategy.removeStylesFrom(target);
1067
+ this.targets.delete(target);
1068
+ }
1069
+ /** @internal */
1070
+ isAttachedTo(target) {
1071
+ return this.targets.has(target);
1072
+ }
1073
+ /**
1074
+ * Associates behaviors with this set of styles.
1075
+ * @param behaviors - The behaviors to associate.
1076
+ */
1077
+ withBehaviors(...behaviors) {
1078
+ this.behaviors =
1079
+ this.behaviors === null ? behaviors : this.behaviors.concat(behaviors);
1080
+ return this;
1081
+ }
1082
+ /**
1083
+ * Sets the strategy that handles adding/removing these styles for an element.
1084
+ * @param strategy - The strategy to use.
1085
+ */
1086
+ withStrategy(Strategy) {
1087
+ this._strategy = new Strategy(reduceStyles(this.styles));
1088
+ return this;
1089
+ }
1090
+ /**
1091
+ * Sets the default strategy type to use when creating style strategies.
1092
+ * @param Strategy - The strategy type to construct.
1093
+ */
1094
+ static setDefaultStrategy(Strategy) {
1095
+ DefaultStyleStrategy = Strategy;
1096
+ }
1097
+ }
1098
+ /**
1099
+ * Indicates whether the DOM supports the adoptedStyleSheets feature.
1100
+ */
1101
+ ElementStyles.supportsAdoptedStyleSheets = Array.isArray(document.adoptedStyleSheets) &&
1102
+ "replace" in CSSStyleSheet.prototype;
1103
+ /**
1104
+ * https://wicg.github.io/construct-stylesheets/
1105
+ * https://developers.google.com/web/updates/2019/02/constructable-stylesheets
1106
+ *
1107
+ * @internal
1108
+ */
1109
+ class AdoptedStyleSheetsStrategy {
1110
+ constructor(styles) {
1111
+ this.sheets = styles.map((x) => {
1112
+ if (x instanceof CSSStyleSheet) {
1113
+ return x;
1114
+ }
1115
+ let sheet = styleSheetCache.get(x);
1116
+ if (sheet === void 0) {
1117
+ sheet = new CSSStyleSheet();
1118
+ sheet.replaceSync(x);
1119
+ styleSheetCache.set(x, sheet);
1120
+ }
1121
+ return sheet;
1122
+ });
1123
+ }
1124
+ addStylesTo(target) {
1125
+ target.adoptedStyleSheets = [...target.adoptedStyleSheets, ...this.sheets];
1126
+ }
1127
+ removeStylesFrom(target) {
1128
+ const sheets = this.sheets;
1129
+ target.adoptedStyleSheets = target.adoptedStyleSheets.filter((x) => sheets.indexOf(x) === -1);
1130
+ }
1131
+ }
1132
+ ElementStyles.setDefaultStrategy(FAST.getById(5 /* KernelServiceId.styleSheetStrategy */, () => AdoptedStyleSheetsStrategy));
1133
+
1134
+ const registry$1 = createTypeRegistry();
1135
+ /**
1136
+ * Instructs the css engine to provide dynamic styles or
1137
+ * associate behaviors with styles.
1138
+ * @public
1139
+ */
1140
+ const CSSDirective = Object.freeze({
1141
+ /**
1142
+ * Gets the directive definition associated with the instance.
1143
+ * @param instance - The directive instance to retrieve the definition for.
1144
+ */
1145
+ getForInstance: registry$1.getForInstance,
1146
+ /**
1147
+ * Gets the directive definition associated with the specified type.
1148
+ * @param type - The directive type to retrieve the definition for.
1149
+ */
1150
+ getByType: registry$1.getByType,
1151
+ /**
1152
+ * Defines a CSSDirective.
1153
+ * @param type - The type to define as a directive.
1154
+ */
1155
+ define(type) {
1156
+ registry$1.register({ type });
1157
+ return type;
1158
+ },
1159
+ });
1160
+ /**
1161
+ * Decorator: Defines a CSSDirective.
1162
+ * @public
1163
+ */
1164
+ function cssDirective() {
1165
+ /* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
1166
+ return function (type) {
1167
+ CSSDirective.define(type);
1168
+ };
1169
+ }
1170
+
1171
+ function collectStyles(strings, values) {
1172
+ const styles = [];
1173
+ let cssString = "";
1174
+ const behaviors = [];
1175
+ const add = (behavior) => {
1176
+ behaviors.push(behavior);
1177
+ };
1178
+ for (let i = 0, ii = strings.length - 1; i < ii; ++i) {
1179
+ cssString += strings[i];
1180
+ let value = values[i];
1181
+ if (CSSDirective.getForInstance(value) !== void 0) {
1182
+ value = value.createCSS(add);
1183
+ }
1184
+ if (value instanceof ElementStyles || value instanceof CSSStyleSheet) {
1185
+ if (cssString.trim() !== "") {
1186
+ styles.push(cssString);
1187
+ cssString = "";
1188
+ }
1189
+ styles.push(value);
1190
+ }
1191
+ else {
1192
+ cssString += value;
1193
+ }
1194
+ }
1195
+ cssString += strings[strings.length - 1];
1196
+ if (cssString.trim() !== "") {
1197
+ styles.push(cssString);
1198
+ }
1199
+ return {
1200
+ styles,
1201
+ behaviors,
1202
+ };
1203
+ }
1204
+ /**
1205
+ * Transforms a template literal string into styles.
1206
+ * @param strings - The string fragments that are interpolated with the values.
1207
+ * @param values - The values that are interpolated with the string fragments.
1208
+ * @remarks
1209
+ * The css helper supports interpolation of strings and ElementStyle instances.
1210
+ * @public
1211
+ */
1212
+ const css = ((strings, ...values) => {
1213
+ const { styles, behaviors } = collectStyles(strings, values);
1214
+ const elementStyles = new ElementStyles(styles);
1215
+ return behaviors.length ? elementStyles.withBehaviors(...behaviors) : elementStyles;
1216
+ });
1217
+ class CSSPartial {
1218
+ constructor(styles, behaviors) {
1219
+ this.behaviors = behaviors;
1220
+ this.css = "";
1221
+ const stylesheets = styles.reduce((accumulated, current) => {
1222
+ if (isString(current)) {
1223
+ this.css += current;
1224
+ }
1225
+ else {
1226
+ accumulated.push(current);
1227
+ }
1228
+ return accumulated;
1229
+ }, []);
1230
+ if (stylesheets.length) {
1231
+ this.styles = new ElementStyles(stylesheets);
1232
+ }
1233
+ }
1234
+ createCSS(add) {
1235
+ this.behaviors.forEach(add);
1236
+ if (this.styles) {
1237
+ add(this);
1238
+ }
1239
+ return this.css;
1240
+ }
1241
+ bind(el) {
1242
+ el.$fastController.addStyles(this.styles);
1243
+ }
1244
+ unbind(el) {
1245
+ el.$fastController.removeStyles(this.styles);
1246
+ }
1247
+ }
1248
+ CSSDirective.define(CSSPartial);
1249
+ css.partial = (strings, ...values) => {
1250
+ const { styles, behaviors } = collectStyles(strings, values);
1251
+ return new CSSPartial(styles, behaviors);
1252
+ };
1253
+ /**
1254
+ * @deprecated Use css.partial instead.
1255
+ * @public
1256
+ */
1257
+ const cssPartial = css.partial;
1258
+
1259
+ /**
1260
+ * Common DOM APIs.
1261
+ * @public
1262
+ */
1263
+ const DOM = Object.freeze({
1264
+ /**
1265
+ * @deprecated
1266
+ * Use Updates.enqueue().
1267
+ */
1268
+ queueUpdate: Updates.enqueue,
1269
+ /**
1270
+ * @deprecated
1271
+ * Use Updates.next()
1272
+ */
1273
+ nextUpdate: Updates.next,
1274
+ /**
1275
+ * @deprecated
1276
+ * Use Updates.process()
1277
+ */
1278
+ processUpdates: Updates.process,
1279
+ /**
1280
+ * Sets an attribute value on an element.
1281
+ * @param element - The element to set the attribute value on.
1282
+ * @param attributeName - The attribute name to set.
1283
+ * @param value - The value of the attribute to set.
1284
+ * @remarks
1285
+ * If the value is `null` or `undefined`, the attribute is removed, otherwise
1286
+ * it is set to the provided value using the standard `setAttribute` API.
1287
+ */
1288
+ setAttribute(element, attributeName, value) {
1289
+ value === null || value === undefined
1290
+ ? element.removeAttribute(attributeName)
1291
+ : element.setAttribute(attributeName, value);
1292
+ },
1293
+ /**
1294
+ * Sets a boolean attribute value.
1295
+ * @param element - The element to set the boolean attribute value on.
1296
+ * @param attributeName - The attribute name to set.
1297
+ * @param value - The value of the attribute to set.
1298
+ * @remarks
1299
+ * If the value is true, the attribute is added; otherwise it is removed.
1300
+ */
1301
+ setBooleanAttribute(element, attributeName, value) {
1302
+ value
1303
+ ? element.setAttribute(attributeName, "")
1304
+ : element.removeAttribute(attributeName);
1305
+ },
1306
+ });
1307
+
1308
+ const marker = `fast-${Math.random().toString(36).substring(2, 8)}`;
1309
+ const interpolationStart = `${marker}{`;
1310
+ const interpolationEnd = `}${marker}`;
1311
+ const interpolationEndLength = interpolationEnd.length;
1312
+ let id = 0;
1313
+ /** @internal */
1314
+ const nextId = () => `${marker}-${++id}`;
1315
+ /**
1316
+ * Common APIs related to markup generation.
1317
+ * @public
1318
+ */
1319
+ const Markup = Object.freeze({
1320
+ /**
1321
+ * Creates a placeholder string suitable for marking out a location *within*
1322
+ * an attribute value or HTML content.
1323
+ * @param index - The directive index to create the placeholder for.
1324
+ * @remarks
1325
+ * Used internally by binding directives.
1326
+ */
1327
+ interpolation: (id) => `${interpolationStart}${id}${interpolationEnd}`,
1328
+ /**
1329
+ * Creates a placeholder that manifests itself as an attribute on an
1330
+ * element.
1331
+ * @param attributeName - The name of the custom attribute.
1332
+ * @param index - The directive index to create the placeholder for.
1333
+ * @remarks
1334
+ * Used internally by attribute directives such as `ref`, `slotted`, and `children`.
1335
+ */
1336
+ attribute: (id) => `${nextId()}="${interpolationStart}${id}${interpolationEnd}"`,
1337
+ /**
1338
+ * Creates a placeholder that manifests itself as a marker within the DOM structure.
1339
+ * @param index - The directive index to create the placeholder for.
1340
+ * @remarks
1341
+ * Used internally by structural directives such as `repeat`.
1342
+ */
1343
+ comment: (id) => `<!--${interpolationStart}${id}${interpolationEnd}-->`,
1344
+ });
1345
+ /**
1346
+ * Common APIs related to content parsing.
1347
+ * @public
1348
+ */
1349
+ const Parser = Object.freeze({
1350
+ /**
1351
+ * Parses text content or HTML attribute content, separating out the static strings
1352
+ * from the directives.
1353
+ * @param value - The content or attribute string to parse.
1354
+ * @param factories - A list of directives to search for in the string.
1355
+ * @returns A heterogeneous array of static strings interspersed with
1356
+ * directives or null if no directives are found in the string.
1357
+ */
1358
+ parse(value, factories) {
1359
+ const parts = value.split(interpolationStart);
1360
+ if (parts.length === 1) {
1361
+ return null;
1362
+ }
1363
+ const result = [];
1364
+ for (let i = 0, ii = parts.length; i < ii; ++i) {
1365
+ const current = parts[i];
1366
+ const index = current.indexOf(interpolationEnd);
1367
+ let literal;
1368
+ if (index === -1) {
1369
+ literal = current;
1370
+ }
1371
+ else {
1372
+ const factoryId = current.substring(0, index);
1373
+ result.push(factories[factoryId]);
1374
+ literal = current.substring(index + interpolationEndLength);
1375
+ }
1376
+ if (literal !== "") {
1377
+ result.push(literal);
1378
+ }
1379
+ }
1380
+ return result;
1381
+ },
1382
+ });
1383
+
1384
+ const registry = createTypeRegistry();
1385
+ /**
1386
+ * Instructs the template engine to apply behavior to a node.
1387
+ * @public
1388
+ */
1389
+ const HTMLDirective = Object.freeze({
1390
+ /**
1391
+ * Gets the directive definition associated with the instance.
1392
+ * @param instance - The directive instance to retrieve the definition for.
1393
+ */
1394
+ getForInstance: registry.getForInstance,
1395
+ /**
1396
+ * Gets the directive definition associated with the specified type.
1397
+ * @param type - The directive type to retrieve the definition for.
1398
+ */
1399
+ getByType: registry.getByType,
1400
+ /**
1401
+ * Defines an HTMLDirective based on the options.
1402
+ * @param type - The type to define as a directive.
1403
+ * @param options - Options that specify the directive's application.
1404
+ */
1405
+ define(type, options) {
1406
+ options = options || {};
1407
+ options.type = type;
1408
+ registry.register(options);
1409
+ return type;
1410
+ },
1411
+ });
1412
+ /**
1413
+ * Decorator: Defines an HTMLDirective.
1414
+ * @param options - Provides options that specify the directive's application.
1415
+ * @public
1416
+ */
1417
+ function htmlDirective(options) {
1418
+ /* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
1419
+ return function (type) {
1420
+ HTMLDirective.define(type, options);
1421
+ };
1422
+ }
1423
+ /**
1424
+ * The type of HTML aspect to target.
1425
+ * @public
1426
+ */
1427
+ const Aspect = Object.freeze({
1428
+ /**
1429
+ * Not aspected.
1430
+ */
1431
+ none: 0,
1432
+ /**
1433
+ * An attribute.
1434
+ */
1435
+ attribute: 1,
1436
+ /**
1437
+ * A boolean attribute.
1438
+ */
1439
+ booleanAttribute: 2,
1440
+ /**
1441
+ * A property.
1442
+ */
1443
+ property: 3,
1444
+ /**
1445
+ * Content
1446
+ */
1447
+ content: 4,
1448
+ /**
1449
+ * A token list.
1450
+ */
1451
+ tokenList: 5,
1452
+ /**
1453
+ * An event.
1454
+ */
1455
+ event: 6,
1456
+ /**
1457
+ *
1458
+ * @param directive - The directive to assign the aspect to.
1459
+ * @param value - The value to base the aspect determination on.
1460
+ */
1461
+ assign(directive, value) {
1462
+ directive.sourceAspect = value;
1463
+ if (!value) {
1464
+ return;
1465
+ }
1466
+ switch (value[0]) {
1467
+ case ":":
1468
+ directive.targetAspect = value.substring(1);
1469
+ switch (directive.targetAspect) {
1470
+ case "innerHTML":
1471
+ directive.aspectType = Aspect.property;
1472
+ break;
1473
+ case "classList":
1474
+ directive.aspectType = Aspect.tokenList;
1475
+ break;
1476
+ default:
1477
+ directive.aspectType = Aspect.property;
1478
+ break;
1479
+ }
1480
+ break;
1481
+ case "?":
1482
+ directive.targetAspect = value.substring(1);
1483
+ directive.aspectType = Aspect.booleanAttribute;
1484
+ break;
1485
+ case "@":
1486
+ directive.targetAspect = value.substring(1);
1487
+ directive.aspectType = Aspect.event;
1488
+ break;
1489
+ default:
1490
+ if (value === "class") {
1491
+ directive.targetAspect = "className";
1492
+ directive.aspectType = Aspect.property;
1493
+ }
1494
+ else {
1495
+ directive.targetAspect = value;
1496
+ directive.aspectType = Aspect.attribute;
1497
+ }
1498
+ break;
1499
+ }
1500
+ },
1501
+ });
1502
+ /**
1503
+ * A base class used for attribute directives that don't need internal state.
1504
+ * @public
1505
+ */
1506
+ class StatelessAttachedAttributeDirective {
1507
+ /**
1508
+ * Creates an instance of RefDirective.
1509
+ * @param options - The options to use in configuring the directive.
1510
+ */
1511
+ constructor(options) {
1512
+ this.options = options;
1513
+ }
1514
+ /**
1515
+ * Creates a behavior.
1516
+ * @param targets - The targets available for behaviors to be attached to.
1517
+ */
1518
+ createBehavior(targets) {
1519
+ return this;
1520
+ }
1521
+ /**
1522
+ * Creates a placeholder string based on the directive's index within the template.
1523
+ * @param index - The index of the directive within the template.
1524
+ * @remarks
1525
+ * Creates a custom attribute placeholder.
1526
+ */
1527
+ createHTML(add) {
1528
+ return Markup.attribute(add(this));
1529
+ }
1530
+ }
1531
+
1532
+ const createInnerHTMLBinding = globalThis.TrustedHTML
1533
+ ? (binding) => (s, c) => {
1534
+ const value = binding(s, c);
1535
+ if (value instanceof TrustedHTML) {
1536
+ return value;
1537
+ }
1538
+ throw FAST.error(1202 /* Message.bindingInnerHTMLRequiresTrustedTypes */);
1539
+ }
1540
+ : (binding) => binding;
1541
+ /**
1542
+ * Describes how aspects of an HTML element will be affected by bindings.
1543
+ * @public
1544
+ */
1545
+ const BindingMode = Object.freeze({
1546
+ /**
1547
+ * Creates a binding mode based on the supplied behavior types.
1548
+ * @param UpdateType - The base behavior type used to update aspects.
1549
+ * @param EventType - The base behavior type used to respond to events.
1550
+ * @returns A new binding mode.
1551
+ */
1552
+ define(UpdateType, EventType = EventBinding) {
1553
+ return Object.freeze({
1554
+ [1]: d => new UpdateType(d, DOM.setAttribute),
1555
+ [2]: d => new UpdateType(d, DOM.setBooleanAttribute),
1556
+ [3]: d => new UpdateType(d, (t, a, v) => (t[a] = v)),
1557
+ [4]: d => new (createContentBinding(UpdateType))(d, updateContentTarget),
1558
+ [5]: d => new UpdateType(d, updateTokenListTarget),
1559
+ [6]: d => new EventType(d),
1560
+ });
1561
+ },
1562
+ });
1563
+ /**
1564
+ * Describes the configuration for a binding expression.
1565
+ * @public
1566
+ */
1567
+ const BindingConfig = Object.freeze({
1568
+ /**
1569
+ * Creates a binding configuration based on the provided mode and options.
1570
+ * @param mode - The mode to use for the configuration.
1571
+ * @param defaultOptions - The default options to use for the configuration.
1572
+ * @returns A new binding configuration.
1573
+ */
1574
+ define(mode, defaultOptions) {
1575
+ const config = (options) => {
1576
+ return {
1577
+ mode: config.mode,
1578
+ options: Object.assign({}, defaultOptions, options),
1579
+ };
1580
+ };
1581
+ config.options = defaultOptions;
1582
+ config.mode = mode;
1583
+ return config;
1584
+ },
1585
+ });
1586
+ /**
1587
+ * A base binding behavior for DOM updates.
1588
+ * @public
1589
+ */
1590
+ class UpdateBinding {
1591
+ /**
1592
+ * Creates an instance of UpdateBinding.
1593
+ * @param directive - The directive that has the configuration for this behavior.
1594
+ * @param updateTarget - The function used to update the target with the latest value.
1595
+ */
1596
+ constructor(directive, updateTarget) {
1597
+ this.directive = directive;
1598
+ this.updateTarget = updateTarget;
1599
+ }
1600
+ /**
1601
+ * Bind this behavior to the source.
1602
+ * @param source - The source to bind to.
1603
+ * @param context - The execution context that the binding is operating within.
1604
+ * @param targets - The targets that behaviors in a view can attach to.
1605
+ */
1606
+ bind(source, context, targets) { }
1607
+ /**
1608
+ * Unbinds this behavior from the source.
1609
+ * @param source - The source to unbind from.
1610
+ * @param context - The execution context that the binding is operating within.
1611
+ * @param targets - The targets that behaviors in a view can attach to.
1612
+ */
1613
+ unbind(source, context, targets) { }
1614
+ /**
1615
+ * Creates a behavior.
1616
+ * @param targets - The targets available for behaviors to be attached to.
1617
+ */
1618
+ createBehavior(targets) {
1619
+ return this;
1620
+ }
1621
+ }
1622
+ function createContentBinding(Type) {
1623
+ return class extends Type {
1624
+ unbind(source, context, targets) {
1625
+ super.unbind(source, context, targets);
1626
+ const target = targets[this.directive.nodeId];
1627
+ const view = target.$fastView;
1628
+ if (view !== void 0 && view.isComposed) {
1629
+ view.unbind();
1630
+ view.needsBindOnly = true;
1631
+ }
1632
+ }
1633
+ };
1634
+ }
1635
+ function updateContentTarget(target, aspect, value, source, context) {
1636
+ // If there's no actual value, then this equates to the
1637
+ // empty string for the purposes of content bindings.
1638
+ if (value === null || value === undefined) {
1639
+ value = "";
1640
+ }
1641
+ // If the value has a "create" method, then it's a template-like.
1642
+ if (value.create) {
1643
+ target.textContent = "";
1644
+ let view = target.$fastView;
1645
+ // If there's no previous view that we might be able to
1646
+ // reuse then create a new view from the template.
1647
+ if (view === void 0) {
1648
+ view = value.create();
1649
+ }
1650
+ else {
1651
+ // If there is a previous view, but it wasn't created
1652
+ // from the same template as the new value, then we
1653
+ // need to remove the old view if it's still in the DOM
1654
+ // and create a new view from the template.
1655
+ if (target.$fastTemplate !== value) {
1656
+ if (view.isComposed) {
1657
+ view.remove();
1658
+ view.unbind();
1659
+ }
1660
+ view = value.create();
1661
+ }
1662
+ }
1663
+ // It's possible that the value is the same as the previous template
1664
+ // and that there's actually no need to compose it.
1665
+ if (!view.isComposed) {
1666
+ view.isComposed = true;
1667
+ view.bind(source, context);
1668
+ view.insertBefore(target);
1669
+ target.$fastView = view;
1670
+ target.$fastTemplate = value;
1671
+ }
1672
+ else if (view.needsBindOnly) {
1673
+ view.needsBindOnly = false;
1674
+ view.bind(source, context);
1675
+ }
1676
+ }
1677
+ else {
1678
+ const view = target.$fastView;
1679
+ // If there is a view and it's currently composed into
1680
+ // the DOM, then we need to remove it.
1681
+ if (view !== void 0 && view.isComposed) {
1682
+ view.isComposed = false;
1683
+ view.remove();
1684
+ if (view.needsBindOnly) {
1685
+ view.needsBindOnly = false;
1686
+ }
1687
+ else {
1688
+ view.unbind();
1689
+ }
1690
+ }
1691
+ target.textContent = value;
1692
+ }
1693
+ }
1694
+ function updateTokenListTarget(target, aspect, value) {
1695
+ var _a;
1696
+ const directive = this.directive;
1697
+ const lookup = `${directive.id}-t`;
1698
+ const state = (_a = target[lookup]) !== null && _a !== void 0 ? _a : (target[lookup] = { c: 0, v: Object.create(null) });
1699
+ const versions = state.v;
1700
+ let currentVersion = state.c;
1701
+ const tokenList = target[aspect];
1702
+ // Add the classes, tracking the version at which they were added.
1703
+ if (value !== null && value !== undefined && value.length) {
1704
+ const names = value.split(/\s+/);
1705
+ for (let i = 0, ii = names.length; i < ii; ++i) {
1706
+ const currentName = names[i];
1707
+ if (currentName === "") {
1708
+ continue;
1709
+ }
1710
+ versions[currentName] = currentVersion;
1711
+ tokenList.add(currentName);
1712
+ }
1713
+ }
1714
+ state.v = currentVersion + 1;
1715
+ // If this is the first call to add classes, there's no need to remove old ones.
1716
+ if (currentVersion === 0) {
1717
+ return;
1718
+ }
1719
+ // Remove classes from the previous version.
1720
+ currentVersion -= 1;
1721
+ for (const name in versions) {
1722
+ if (versions[name] === currentVersion) {
1723
+ tokenList.remove(name);
1724
+ }
1725
+ }
1726
+ }
1727
+ /**
1728
+ * A binding behavior for one-time bindings.
1729
+ * @public
1730
+ */
1731
+ class OneTimeBinding extends UpdateBinding {
1732
+ /**
1733
+ * Bind this behavior to the source.
1734
+ * @param source - The source to bind to.
1735
+ * @param context - The execution context that the binding is operating within.
1736
+ * @param targets - The targets that behaviors in a view can attach to.
1737
+ */
1738
+ bind(source, context, targets) {
1739
+ const directive = this.directive;
1740
+ this.updateTarget(targets[directive.nodeId], directive.targetAspect, directive.binding(source, context), source, context);
1741
+ }
1742
+ }
1743
+ const signals = Object.create(null);
1744
+ /**
1745
+ * A binding behavior for signal bindings.
1746
+ * @public
1747
+ */
1748
+ class SignalBinding extends UpdateBinding {
1749
+ constructor() {
1750
+ super(...arguments);
1751
+ this.handlerProperty = `${this.directive.id}-h`;
1752
+ }
1753
+ /**
1754
+ * Bind this behavior to the source.
1755
+ * @param source - The source to bind to.
1756
+ * @param context - The execution context that the binding is operating within.
1757
+ * @param targets - The targets that behaviors in a view can attach to.
1758
+ */
1759
+ bind(source, context, targets) {
1760
+ const directive = this.directive;
1761
+ const target = targets[directive.nodeId];
1762
+ const signal = this.getSignal(source, context);
1763
+ const handler = (target[this.handlerProperty] = () => {
1764
+ this.updateTarget(target, directive.targetAspect, directive.binding(source, context), source, context);
1765
+ });
1766
+ handler();
1767
+ const found = signals[signal];
1768
+ if (found) {
1769
+ Array.isArray(found)
1770
+ ? found.push(handler)
1771
+ : (signals[signal] = [found, handler]);
1772
+ }
1773
+ else {
1774
+ signals[signal] = handler;
1775
+ }
1776
+ }
1777
+ /**
1778
+ * Unbinds this behavior from the source.
1779
+ * @param source - The source to unbind from.
1780
+ * @param context - The execution context that the binding is operating within.
1781
+ * @param targets - The targets that behaviors in a view can attach to.
1782
+ */
1783
+ unbind(source, context, targets) {
1784
+ const signal = this.getSignal(source, context);
1785
+ const found = signals[signal];
1786
+ if (found && Array.isArray(found)) {
1787
+ const directive = this.directive;
1788
+ const target = targets[directive.nodeId];
1789
+ const handler = target[this.handlerProperty];
1790
+ const index = found.indexOf(handler);
1791
+ if (index !== -1) {
1792
+ found.splice(index, 1);
1793
+ }
1794
+ }
1795
+ else {
1796
+ signals[signal] = void 0;
1797
+ }
1798
+ }
1799
+ getSignal(source, context) {
1800
+ const options = this.directive.options;
1801
+ return isString(options) ? options : options(source, context);
1802
+ }
1803
+ /**
1804
+ * Sends the specified signal to signaled bindings.
1805
+ * @param signal - The signal to send.
1806
+ * @public
1807
+ */
1808
+ static send(signal) {
1809
+ const found = signals[signal];
1810
+ if (found) {
1811
+ Array.isArray(found) ? found.forEach(x => x()) : found();
1812
+ }
1813
+ }
1814
+ }
1815
+ /**
1816
+ * A binding behavior for bindings that change.
1817
+ * @public
1818
+ */
1819
+ class ChangeBinding extends UpdateBinding {
1820
+ /**
1821
+ * Creates an instance of ChangeBinding.
1822
+ * @param directive - The directive that has the configuration for this behavior.
1823
+ * @param updateTarget - The function used to update the target with the latest value.
1824
+ */
1825
+ constructor(directive, updateTarget) {
1826
+ super(directive, updateTarget);
1827
+ this.isBindingVolatile = Observable.isVolatileBinding(directive.binding);
1828
+ this.observerProperty = `${directive.id}-o`;
1829
+ }
1830
+ /**
1831
+ * Returns the binding observer used to update the node.
1832
+ * @param target - The target node.
1833
+ * @returns A BindingObserver.
1834
+ */
1835
+ getObserver(target) {
1836
+ var _a;
1837
+ return ((_a = target[this.observerProperty]) !== null && _a !== void 0 ? _a : (target[this.observerProperty] = Observable.binding(this.directive.binding, this, this.isBindingVolatile)));
1838
+ }
1839
+ /**
1840
+ * Bind this behavior to the source.
1841
+ * @param source - The source to bind to.
1842
+ * @param context - The execution context that the binding is operating within.
1843
+ * @param targets - The targets that behaviors in a view can attach to.
1844
+ */
1845
+ bind(source, context, targets) {
1846
+ const directive = this.directive;
1847
+ const target = targets[directive.nodeId];
1848
+ const observer = this.getObserver(target);
1849
+ observer.target = target;
1850
+ observer.source = source;
1851
+ observer.context = context;
1852
+ this.updateTarget(target, directive.targetAspect, observer.observe(source, context), source, context);
1853
+ }
1854
+ /**
1855
+ * Unbinds this behavior from the source.
1856
+ * @param source - The source to unbind from.
1857
+ * @param context - The execution context that the binding is operating within.
1858
+ * @param targets - The targets that behaviors in a view can attach to.
1859
+ */
1860
+ unbind(source, context, targets) {
1861
+ const target = targets[this.directive.nodeId];
1862
+ const observer = this.getObserver(target);
1863
+ observer.dispose();
1864
+ observer.target = null;
1865
+ observer.source = null;
1866
+ observer.context = null;
1867
+ }
1868
+ /** @internal */
1869
+ handleChange(binding, observer) {
1870
+ const target = observer.target;
1871
+ const source = observer.source;
1872
+ const context = observer.context;
1873
+ this.updateTarget(target, this.directive.targetAspect, observer.observe(source, context), source, context);
1874
+ }
1875
+ }
1876
+ /**
1877
+ * A binding behavior for handling events.
1878
+ * @public
1879
+ */
1880
+ class EventBinding {
1881
+ /**
1882
+ * Creates an instance of EventBinding.
1883
+ * @param directive - The directive that has the configuration for this behavior.
1884
+ */
1885
+ constructor(directive) {
1886
+ this.directive = directive;
1887
+ this.sourceProperty = `${directive.id}-s`;
1888
+ this.contextProperty = `${directive.id}-c`;
1889
+ }
1890
+ /**
1891
+ * Bind this behavior to the source.
1892
+ * @param source - The source to bind to.
1893
+ * @param context - The execution context that the binding is operating within.
1894
+ * @param targets - The targets that behaviors in a view can attach to.
1895
+ */
1896
+ bind(source, context, targets) {
1897
+ const directive = this.directive;
1898
+ const target = targets[directive.nodeId];
1899
+ target[this.sourceProperty] = source;
1900
+ target[this.contextProperty] = context;
1901
+ target.addEventListener(directive.targetAspect, this, directive.options);
1902
+ }
1903
+ /**
1904
+ * Unbinds this behavior from the source.
1905
+ * @param source - The source to unbind from.
1906
+ * @param context - The execution context that the binding is operating within.
1907
+ * @param targets - The targets that behaviors in a view can attach to.
1908
+ */
1909
+ unbind(source, context, targets) {
1910
+ const directive = this.directive;
1911
+ const target = targets[directive.nodeId];
1912
+ target[this.sourceProperty] = target[this.contextProperty] = null;
1913
+ target.removeEventListener(directive.targetAspect, this, directive.options);
1914
+ }
1915
+ /**
1916
+ * Creates a behavior.
1917
+ * @param targets - The targets available for behaviors to be attached to.
1918
+ */
1919
+ createBehavior(targets) {
1920
+ return this;
1921
+ }
1922
+ /**
1923
+ * @internal
1924
+ */
1925
+ handleEvent(event) {
1926
+ const target = event.currentTarget;
1927
+ ExecutionContext.setEvent(event);
1928
+ const result = this.directive.binding(target[this.sourceProperty], target[this.contextProperty]);
1929
+ ExecutionContext.setEvent(null);
1930
+ if (result !== true) {
1931
+ event.preventDefault();
1932
+ }
1933
+ }
1934
+ }
1935
+ let twoWaySettings = {
1936
+ determineChangeEvent() {
1937
+ return "change";
1938
+ },
1939
+ };
1940
+ /**
1941
+ * A binding behavior for bindings that update in two directions.
1942
+ * @public
1943
+ */
1944
+ class TwoWayBinding extends ChangeBinding {
1945
+ /**
1946
+ * Bind this behavior to the source.
1947
+ * @param source - The source to bind to.
1948
+ * @param context - The execution context that the binding is operating within.
1949
+ * @param targets - The targets that behaviors in a view can attach to.
1950
+ */
1951
+ bind(source, context, targets) {
1952
+ var _a;
1953
+ super.bind(source, context, targets);
1954
+ const directive = this.directive;
1955
+ const target = targets[directive.nodeId];
1956
+ if (!this.changeEvent) {
1957
+ this.changeEvent =
1958
+ (_a = directive.options.changeEvent) !== null && _a !== void 0 ? _a : twoWaySettings.determineChangeEvent(directive, target);
1959
+ }
1960
+ target.addEventListener(this.changeEvent, this);
1961
+ }
1962
+ /**
1963
+ * Unbinds this behavior from the source.
1964
+ * @param source - The source to unbind from.
1965
+ * @param context - The execution context that the binding is operating within.
1966
+ * @param targets - The targets that behaviors in a view can attach to.
1967
+ */
1968
+ unbind(source, context, targets) {
1969
+ super.unbind(source, context, targets);
1970
+ targets[this.directive.nodeId].removeEventListener(this.changeEvent, this);
1971
+ }
1972
+ /** @internal */
1973
+ handleEvent(event) {
1974
+ const directive = this.directive;
1975
+ const target = event.currentTarget;
1976
+ let value;
1977
+ switch (directive.aspectType) {
1978
+ case 1:
1979
+ value = target.getAttribute(directive.targetAspect);
1980
+ break;
1981
+ case 2:
1982
+ value = target.hasAttribute(directive.targetAspect);
1983
+ break;
1984
+ case 4:
1985
+ value = target.innerText;
1986
+ break;
1987
+ default:
1988
+ value = target[directive.targetAspect];
1989
+ break;
1990
+ }
1991
+ const observer = this.getObserver(target);
1992
+ const last = observer.last; // using internal API!!!
1993
+ last.propertySource[last.propertyName] = directive.options.fromView(value);
1994
+ }
1995
+ /**
1996
+ * Configures two-way binding.
1997
+ * @param settings - The settings to use for the two-way binding system.
1998
+ */
1999
+ static configure(settings) {
2000
+ twoWaySettings = settings;
2001
+ }
2002
+ }
2003
+ /**
2004
+ * The default onChange binding configuration.
2005
+ * @public
2006
+ */
2007
+ const onChange = BindingConfig.define(BindingMode.define(ChangeBinding), {});
2008
+ /**
2009
+ * The default twoWay binding configuration.
2010
+ * @public
2011
+ */
2012
+ const twoWay = BindingConfig.define(BindingMode.define(TwoWayBinding), {
2013
+ fromView: v => v,
2014
+ });
2015
+ /**
2016
+ * The default onTime binding configuration.
2017
+ * @public
2018
+ */
2019
+ const oneTime = BindingConfig.define(BindingMode.define(OneTimeBinding), {
2020
+ once: true,
2021
+ });
2022
+ const signalMode = BindingMode.define(SignalBinding);
2023
+ /**
2024
+ * Creates a signal binding configuration with the supplied options.
2025
+ * @param options - The signal name or a binding to use to retrieve the signal name.
2026
+ * @returns A binding configuration.
2027
+ * @public
2028
+ */
2029
+ const signal = (options) => {
2030
+ return { mode: signalMode, options };
2031
+ };
2032
+ /**
2033
+ * A directive that applies bindings.
2034
+ * @public
2035
+ */
2036
+ class HTMLBindingDirective {
2037
+ /**
2038
+ * Creates an instance of HTMLBindingDirective.
2039
+ * @param binding - The binding to apply.
2040
+ * @param mode - The binding mode to use when applying the binding.
2041
+ * @param options - The options to configure the binding with.
2042
+ */
2043
+ constructor(binding, mode, options) {
2044
+ this.binding = binding;
2045
+ this.mode = mode;
2046
+ this.options = options;
2047
+ this.factory = null;
2048
+ /**
2049
+ * The type of aspect to target.
2050
+ */
2051
+ this.aspectType = Aspect.content;
2052
+ }
2053
+ /**
2054
+ * Creates HTML to be used within a template.
2055
+ * @param add - Can be used to add behavior factories to a template.
2056
+ */
2057
+ createHTML(add) {
2058
+ return Markup.interpolation(add(this));
2059
+ }
2060
+ /**
2061
+ * Creates a behavior.
2062
+ * @param targets - The targets available for behaviors to be attached to.
2063
+ */
2064
+ createBehavior(targets) {
2065
+ if (this.factory == null) {
2066
+ if (this.targetAspect === "innerHTML") {
2067
+ this.binding = createInnerHTMLBinding(this.binding);
2068
+ }
2069
+ this.factory = this.mode[this.aspectType](this);
2070
+ }
2071
+ return this.factory.createBehavior(targets);
2072
+ }
2073
+ }
2074
+ HTMLDirective.define(HTMLBindingDirective, { aspected: true });
2075
+ /**
2076
+ * Creates a binding directive with the specified configuration.
2077
+ * @param binding - The binding expression.
2078
+ * @param config - The binding configuration.
2079
+ * @returns A binding directive.
2080
+ * @public
2081
+ */
2082
+ function bind(binding, config = onChange) {
2083
+ if (!("mode" in config)) {
2084
+ config = onChange(config);
2085
+ }
2086
+ return new HTMLBindingDirective(binding, config.mode, config.options);
2087
+ }
2088
+
2089
+ function removeNodeSequence(firstNode, lastNode) {
2090
+ const parent = firstNode.parentNode;
2091
+ let current = firstNode;
2092
+ let next;
2093
+ while (current !== lastNode) {
2094
+ next = current.nextSibling;
2095
+ parent.removeChild(current);
2096
+ current = next;
2097
+ }
2098
+ parent.removeChild(lastNode);
2099
+ }
2100
+ /**
2101
+ * The standard View implementation, which also implements ElementView and SyntheticView.
2102
+ * @public
2103
+ */
2104
+ class HTMLView {
2105
+ /**
2106
+ * Constructs an instance of HTMLView.
2107
+ * @param fragment - The html fragment that contains the nodes for this view.
2108
+ * @param behaviors - The behaviors to be applied to this view.
2109
+ */
2110
+ constructor(fragment, factories, targets) {
2111
+ this.fragment = fragment;
2112
+ this.factories = factories;
2113
+ this.targets = targets;
2114
+ this.behaviors = null;
2115
+ /**
2116
+ * The data that the view is bound to.
2117
+ */
2118
+ this.source = null;
2119
+ /**
2120
+ * The execution context the view is running within.
2121
+ */
2122
+ this.context = null;
2123
+ this.firstChild = fragment.firstChild;
2124
+ this.lastChild = fragment.lastChild;
2125
+ }
2126
+ /**
2127
+ * Appends the view's DOM nodes to the referenced node.
2128
+ * @param node - The parent node to append the view's DOM nodes to.
2129
+ */
2130
+ appendTo(node) {
2131
+ node.appendChild(this.fragment);
2132
+ }
2133
+ /**
2134
+ * Inserts the view's DOM nodes before the referenced node.
2135
+ * @param node - The node to insert the view's DOM before.
2136
+ */
2137
+ insertBefore(node) {
2138
+ if (this.fragment.hasChildNodes()) {
2139
+ node.parentNode.insertBefore(this.fragment, node);
2140
+ }
2141
+ else {
2142
+ const parentNode = node.parentNode;
2143
+ const end = this.lastChild;
2144
+ let current = this.firstChild;
2145
+ let next;
2146
+ while (current !== end) {
2147
+ next = current.nextSibling;
2148
+ parentNode.insertBefore(current, node);
2149
+ current = next;
2150
+ }
2151
+ parentNode.insertBefore(end, node);
2152
+ }
2153
+ }
2154
+ /**
2155
+ * Removes the view's DOM nodes.
2156
+ * The nodes are not disposed and the view can later be re-inserted.
2157
+ */
2158
+ remove() {
2159
+ const fragment = this.fragment;
2160
+ const end = this.lastChild;
2161
+ let current = this.firstChild;
2162
+ let next;
2163
+ while (current !== end) {
2164
+ next = current.nextSibling;
2165
+ fragment.appendChild(current);
2166
+ current = next;
2167
+ }
2168
+ fragment.appendChild(end);
2169
+ }
2170
+ /**
2171
+ * Removes the view and unbinds its behaviors, disposing of DOM nodes afterward.
2172
+ * Once a view has been disposed, it cannot be inserted or bound again.
2173
+ */
2174
+ dispose() {
2175
+ removeNodeSequence(this.firstChild, this.lastChild);
2176
+ this.unbind();
2177
+ }
2178
+ /**
2179
+ * Binds a view's behaviors to its binding source.
2180
+ * @param source - The binding source for the view's binding behaviors.
2181
+ * @param context - The execution context to run the behaviors within.
2182
+ */
2183
+ bind(source, context) {
2184
+ let behaviors = this.behaviors;
2185
+ const oldSource = this.source;
2186
+ if (oldSource === source) {
2187
+ return;
2188
+ }
2189
+ this.source = source;
2190
+ this.context = context;
2191
+ const targets = this.targets;
2192
+ if (oldSource !== null) {
2193
+ for (let i = 0, ii = behaviors.length; i < ii; ++i) {
2194
+ const current = behaviors[i];
2195
+ current.unbind(oldSource, context, targets);
2196
+ current.bind(source, context, targets);
2197
+ }
2198
+ }
2199
+ else if (behaviors === null) {
2200
+ this.behaviors = behaviors = new Array(this.factories.length);
2201
+ const factories = this.factories;
2202
+ for (let i = 0, ii = factories.length; i < ii; ++i) {
2203
+ const behavior = factories[i].createBehavior(targets);
2204
+ behavior.bind(source, context, targets);
2205
+ behaviors[i] = behavior;
2206
+ }
2207
+ }
2208
+ else {
2209
+ for (let i = 0, ii = behaviors.length; i < ii; ++i) {
2210
+ behaviors[i].bind(source, context, targets);
2211
+ }
2212
+ }
2213
+ }
2214
+ /**
2215
+ * Unbinds a view's behaviors from its binding source.
2216
+ */
2217
+ unbind() {
2218
+ const oldSource = this.source;
2219
+ if (oldSource === null) {
2220
+ return;
2221
+ }
2222
+ const targets = this.targets;
2223
+ const context = this.context;
2224
+ const behaviors = this.behaviors;
2225
+ for (let i = 0, ii = behaviors.length; i < ii; ++i) {
2226
+ behaviors[i].unbind(oldSource, context, targets);
2227
+ }
2228
+ this.source = null;
2229
+ this.context = null;
2230
+ }
2231
+ /**
2232
+ * Efficiently disposes of a contiguous range of synthetic view instances.
2233
+ * @param views - A contiguous range of views to be disposed.
2234
+ */
2235
+ static disposeContiguousBatch(views) {
2236
+ if (views.length === 0) {
2237
+ return;
2238
+ }
2239
+ removeNodeSequence(views[0].firstChild, views[views.length - 1].lastChild);
2240
+ for (let i = 0, ii = views.length; i < ii; ++i) {
2241
+ views[i].unbind();
2242
+ }
2243
+ }
2244
+ }
2245
+
2246
+ const targetIdFrom = (parentId, nodeIndex) => `${parentId}.${nodeIndex}`;
2247
+ const descriptorCache = {};
2248
+ // used to prevent creating lots of objects just to track node and index while compiling
2249
+ const next = {
2250
+ index: 0,
2251
+ node: null,
2252
+ };
2253
+ class CompilationContext {
2254
+ constructor(fragment, directives) {
2255
+ this.fragment = fragment;
2256
+ this.directives = directives;
2257
+ this.proto = null;
2258
+ this.nodeIds = new Set();
2259
+ this.descriptors = {};
2260
+ this.factories = [];
2261
+ }
2262
+ addFactory(factory, parentId, nodeId, targetIndex) {
2263
+ if (!this.nodeIds.has(nodeId)) {
2264
+ this.nodeIds.add(nodeId);
2265
+ this.addTargetDescriptor(parentId, nodeId, targetIndex);
2266
+ }
2267
+ factory.nodeId = nodeId;
2268
+ this.factories.push(factory);
2269
+ }
2270
+ freeze() {
2271
+ this.proto = Object.create(null, this.descriptors);
2272
+ return this;
2273
+ }
2274
+ addTargetDescriptor(parentId, targetId, targetIndex) {
2275
+ const descriptors = this.descriptors;
2276
+ if (targetId === "r" || // root
2277
+ targetId === "h" || // host
2278
+ descriptors[targetId]) {
2279
+ return;
2280
+ }
2281
+ if (!descriptors[parentId]) {
2282
+ const index = parentId.lastIndexOf(".");
2283
+ const grandparentId = parentId.substring(0, index);
2284
+ const childIndex = parseInt(parentId.substring(index + 1));
2285
+ this.addTargetDescriptor(grandparentId, parentId, childIndex);
2286
+ }
2287
+ let descriptor = descriptorCache[targetId];
2288
+ if (!descriptor) {
2289
+ const field = `_${targetId}`;
2290
+ descriptorCache[targetId] = descriptor = {
2291
+ get() {
2292
+ var _a;
2293
+ return ((_a = this[field]) !== null && _a !== void 0 ? _a : (this[field] = this[parentId].childNodes[targetIndex]));
2294
+ },
2295
+ };
2296
+ }
2297
+ descriptors[targetId] = descriptor;
2298
+ }
2299
+ createView(hostBindingTarget) {
2300
+ const fragment = this.fragment.cloneNode(true);
2301
+ const targets = Object.create(this.proto);
2302
+ targets.r = fragment;
2303
+ targets.h = hostBindingTarget !== null && hostBindingTarget !== void 0 ? hostBindingTarget : fragment;
2304
+ for (const id of this.nodeIds) {
2305
+ targets[id]; // trigger locator
2306
+ }
2307
+ return new HTMLView(fragment, this.factories, targets);
2308
+ }
2309
+ }
2310
+ function compileAttributes(context, parentId, node, nodeId, nodeIndex, includeBasicValues = false) {
2311
+ const attributes = node.attributes;
2312
+ const directives = context.directives;
2313
+ for (let i = 0, ii = attributes.length; i < ii; ++i) {
2314
+ const attr = attributes[i];
2315
+ const attrValue = attr.value;
2316
+ const parseResult = Parser.parse(attrValue, directives);
2317
+ let result = null;
2318
+ if (parseResult === null) {
2319
+ if (includeBasicValues) {
2320
+ result = bind(() => attrValue, oneTime);
2321
+ Aspect.assign(result, attr.name);
2322
+ }
2323
+ }
2324
+ else {
2325
+ /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
2326
+ result = Compiler.aggregate(parseResult);
2327
+ }
2328
+ if (result !== null) {
2329
+ node.removeAttributeNode(attr);
2330
+ i--;
2331
+ ii--;
2332
+ context.addFactory(result, parentId, nodeId, nodeIndex);
2333
+ }
2334
+ }
2335
+ }
2336
+ function compileContent(context, node, parentId, nodeId, nodeIndex) {
2337
+ const parseResult = Parser.parse(node.textContent, context.directives);
2338
+ if (parseResult === null) {
2339
+ next.node = node.nextSibling;
2340
+ next.index = nodeIndex + 1;
2341
+ return next;
2342
+ }
2343
+ let currentNode;
2344
+ let lastNode = (currentNode = node);
2345
+ for (let i = 0, ii = parseResult.length; i < ii; ++i) {
2346
+ const currentPart = parseResult[i];
2347
+ if (i !== 0) {
2348
+ nodeIndex++;
2349
+ nodeId = targetIdFrom(parentId, nodeIndex);
2350
+ currentNode = lastNode.parentNode.insertBefore(document.createTextNode(""), lastNode.nextSibling);
2351
+ }
2352
+ if (isString(currentPart)) {
2353
+ currentNode.textContent = currentPart;
2354
+ }
2355
+ else {
2356
+ currentNode.textContent = " ";
2357
+ context.addFactory(currentPart, parentId, nodeId, nodeIndex);
2358
+ }
2359
+ lastNode = currentNode;
2360
+ }
2361
+ next.index = nodeIndex + 1;
2362
+ next.node = lastNode.nextSibling;
2363
+ return next;
2364
+ }
2365
+ function compileChildren(context, parent, parentId) {
2366
+ let nodeIndex = 0;
2367
+ let childNode = parent.firstChild;
2368
+ while (childNode) {
2369
+ /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
2370
+ const result = compileNode(context, parentId, childNode, nodeIndex);
2371
+ childNode = result.node;
2372
+ nodeIndex = result.index;
2373
+ }
2374
+ }
2375
+ function compileNode(context, parentId, node, nodeIndex) {
2376
+ const nodeId = targetIdFrom(parentId, nodeIndex);
2377
+ switch (node.nodeType) {
2378
+ case 1: // element node
2379
+ compileAttributes(context, parentId, node, nodeId, nodeIndex);
2380
+ compileChildren(context, node, nodeId);
2381
+ break;
2382
+ case 3: // text node
2383
+ return compileContent(context, node, parentId, nodeId, nodeIndex);
2384
+ case 8: // comment
2385
+ const parts = Parser.parse(node.data, context.directives);
2386
+ if (parts !== null) {
2387
+ context.addFactory(
2388
+ /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
2389
+ Compiler.aggregate(parts), parentId, nodeId, nodeIndex);
2390
+ }
2391
+ break;
2392
+ }
2393
+ next.index = nodeIndex + 1;
2394
+ next.node = node.nextSibling;
2395
+ return next;
2396
+ }
2397
+ function isMarker(node, directives) {
2398
+ return (node &&
2399
+ node.nodeType == 8 &&
2400
+ Parser.parse(node.data, directives) !== null);
2401
+ }
2402
+ const templateTag = "TEMPLATE";
2403
+ const policyOptions = { createHTML: html => html };
2404
+ let htmlPolicy = globalThis.trustedTypes
2405
+ ? globalThis.trustedTypes.createPolicy("fast-html", policyOptions)
2406
+ : policyOptions;
2407
+ const fastHTMLPolicy = htmlPolicy;
2408
+ /**
2409
+ * Common APIs related to compilation.
2410
+ * @public
2411
+ */
2412
+ const Compiler = {
2413
+ /**
2414
+ * Sets the HTML trusted types policy used by the compiler.
2415
+ * @param policy - The policy to set for HTML.
2416
+ * @remarks
2417
+ * This API can only be called once, for security reasons. It should be
2418
+ * called by the application developer at the start of their program.
2419
+ */
2420
+ setHTMLPolicy(policy) {
2421
+ if (htmlPolicy !== fastHTMLPolicy) {
2422
+ throw FAST.error(1201 /* Message.onlySetHTMLPolicyOnce */);
2423
+ }
2424
+ htmlPolicy = policy;
2425
+ },
2426
+ /**
2427
+ * Compiles a template and associated directives into a compilation
2428
+ * result which can be used to create views.
2429
+ * @param html - The html string or template element to compile.
2430
+ * @param directives - The directives referenced by the template.
2431
+ * @remarks
2432
+ * The template that is provided for compilation is altered in-place
2433
+ * and cannot be compiled again. If the original template must be preserved,
2434
+ * it is recommended that you clone the original and pass the clone to this API.
2435
+ * @public
2436
+ */
2437
+ compile(html, directives) {
2438
+ let template;
2439
+ if (isString(html)) {
2440
+ template = document.createElement(templateTag);
2441
+ template.innerHTML = htmlPolicy.createHTML(html);
2442
+ const fec = template.content.firstElementChild;
2443
+ if (fec !== null && fec.tagName === templateTag) {
2444
+ template = fec;
2445
+ }
2446
+ }
2447
+ else {
2448
+ template = html;
2449
+ }
2450
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=1111864
2451
+ const fragment = document.adoptNode(template.content);
2452
+ const context = new CompilationContext(fragment, directives);
2453
+ compileAttributes(context, "", template, /* host */ "h", 0, true);
2454
+ if (
2455
+ // If the first node in a fragment is a marker, that means it's an unstable first node,
2456
+ // because something like a when, repeat, etc. could add nodes before the marker.
2457
+ // To mitigate this, we insert a stable first node. However, if we insert a node,
2458
+ // that will alter the result of the TreeWalker. So, we also need to offset the target index.
2459
+ isMarker(fragment.firstChild, directives) ||
2460
+ // Or if there is only one node and a directive, it means the template's content
2461
+ // is *only* the directive. In that case, HTMLView.dispose() misses any nodes inserted by
2462
+ // the directive. Inserting a new node ensures proper disposal of nodes added by the directive.
2463
+ (fragment.childNodes.length === 1 && Object.keys(directives).length > 0)) {
2464
+ fragment.insertBefore(document.createComment(""), fragment.firstChild);
2465
+ }
2466
+ compileChildren(context, fragment, /* root */ "r");
2467
+ next.node = null; // prevent leaks
2468
+ return context.freeze();
2469
+ },
2470
+ /**
2471
+ * Sets the default compilation strategy that will be used by the ViewTemplate whenever
2472
+ * it needs to compile a view preprocessed with the html template function.
2473
+ * @param strategy - The compilation strategy to use when compiling templates.
2474
+ */
2475
+ setDefaultStrategy(strategy) {
2476
+ this.compile = strategy;
2477
+ },
2478
+ /**
2479
+ * Aggregates an array of strings and directives into a single directive.
2480
+ * @param parts - A heterogeneous array of static strings interspersed with
2481
+ * directives.
2482
+ * @returns A single inline directive that aggregates the behavior of all the parts.
2483
+ */
2484
+ aggregate(parts) {
2485
+ if (parts.length === 1) {
2486
+ return parts[0];
2487
+ }
2488
+ let sourceAspect;
2489
+ const partCount = parts.length;
2490
+ const finalParts = parts.map((x) => {
2491
+ if (isString(x)) {
2492
+ return () => x;
2493
+ }
2494
+ sourceAspect = x.sourceAspect || sourceAspect;
2495
+ return x.binding;
2496
+ });
2497
+ const binding = (scope, context) => {
2498
+ let output = "";
2499
+ for (let i = 0; i < partCount; ++i) {
2500
+ output += finalParts[i](scope, context);
2501
+ }
2502
+ return output;
2503
+ };
2504
+ const directive = bind(binding);
2505
+ Aspect.assign(directive, sourceAspect);
2506
+ return directive;
2507
+ },
2508
+ };
2509
+
2510
+ /**
2511
+ * A template capable of creating HTMLView instances or rendering directly to DOM.
2512
+ * @public
2513
+ */
2514
+ class ViewTemplate {
2515
+ /**
2516
+ * Creates an instance of ViewTemplate.
2517
+ * @param html - The html representing what this template will instantiate, including placeholders for directives.
2518
+ * @param factories - The directives that will be connected to placeholders in the html.
2519
+ */
2520
+ constructor(html, factories) {
2521
+ this.result = null;
2522
+ this.html = html;
2523
+ this.factories = factories;
2524
+ }
2525
+ /**
2526
+ * Creates an HTMLView instance based on this template definition.
2527
+ * @param hostBindingTarget - The element that host behaviors will be bound to.
2528
+ */
2529
+ create(hostBindingTarget) {
2530
+ if (this.result === null) {
2531
+ this.result = Compiler.compile(this.html, this.factories);
2532
+ }
2533
+ return this.result.createView(hostBindingTarget);
2534
+ }
2535
+ /**
2536
+ * Creates an HTMLView from this template, binds it to the source, and then appends it to the host.
2537
+ * @param source - The data source to bind the template to.
2538
+ * @param host - The Element where the template will be rendered.
2539
+ * @param hostBindingTarget - An HTML element to target the host bindings at if different from the
2540
+ * host that the template is being attached to.
2541
+ */
2542
+ render(source, host, hostBindingTarget, context) {
2543
+ const view = this.create(hostBindingTarget !== null && hostBindingTarget !== void 0 ? hostBindingTarget : host);
2544
+ view.bind(source, context !== null && context !== void 0 ? context : ExecutionContext.default);
2545
+ view.appendTo(host);
2546
+ return view;
2547
+ }
2548
+ }
2549
+ // Much thanks to LitHTML for working this out!
2550
+ const lastAttributeNameRegex =
2551
+ /* eslint-disable-next-line no-control-regex */
2552
+ /([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;
2553
+ function createAspectedHTML(value, prevString, add) {
2554
+ const match = lastAttributeNameRegex.exec(prevString);
2555
+ if (match !== null) {
2556
+ Aspect.assign(value, match[2]);
2557
+ }
2558
+ return value.createHTML(add);
2559
+ }
2560
+ /**
2561
+ * Transforms a template literal string into a ViewTemplate.
2562
+ * @param strings - The string fragments that are interpolated with the values.
2563
+ * @param values - The values that are interpolated with the string fragments.
2564
+ * @remarks
2565
+ * The html helper supports interpolation of strings, numbers, binding expressions,
2566
+ * other template instances, and Directive instances.
2567
+ * @public
2568
+ */
2569
+ function html(strings, ...values) {
2570
+ let html = "";
2571
+ const factories = Object.create(null);
2572
+ const add = (factory) => {
2573
+ var _a;
2574
+ const id = (_a = factory.id) !== null && _a !== void 0 ? _a : (factory.id = nextId());
2575
+ factories[id] = factory;
2576
+ return id;
2577
+ };
2578
+ for (let i = 0, ii = strings.length - 1; i < ii; ++i) {
2579
+ const currentString = strings[i];
2580
+ const currentValue = values[i];
2581
+ let definition;
2582
+ html += currentString;
2583
+ if (isFunction(currentValue)) {
2584
+ html += createAspectedHTML(bind(currentValue), currentString, add);
2585
+ }
2586
+ else if (isString(currentValue)) {
2587
+ const match = lastAttributeNameRegex.exec(currentString);
2588
+ if (match !== null) {
2589
+ const directive = bind(() => currentValue, oneTime);
2590
+ Aspect.assign(directive, match[2]);
2591
+ html += directive.createHTML(add);
2592
+ }
2593
+ else {
2594
+ html += currentValue;
2595
+ }
2596
+ }
2597
+ else if ((definition = HTMLDirective.getForInstance(currentValue)) === void 0) {
2598
+ html += createAspectedHTML(bind(() => currentValue, oneTime), currentString, add);
2599
+ }
2600
+ else {
2601
+ if (definition.aspected) {
2602
+ html += createAspectedHTML(currentValue, currentString, add);
2603
+ }
2604
+ else {
2605
+ html += currentValue.createHTML(add);
2606
+ }
2607
+ }
2608
+ }
2609
+ return new ViewTemplate(html + strings[strings.length - 1], factories);
2610
+ }
2611
+ /**
2612
+ * Transforms a template literal string into a ChildViewTemplate.
2613
+ * @param strings - The string fragments that are interpolated with the values.
2614
+ * @param values - The values that are interpolated with the string fragments.
2615
+ * @remarks
2616
+ * The html helper supports interpolation of strings, numbers, binding expressions,
2617
+ * other template instances, and Directive instances.
2618
+ * @public
2619
+ */
2620
+ const child = html;
2621
+ /**
2622
+ * Transforms a template literal string into an ItemViewTemplate.
2623
+ * @param strings - The string fragments that are interpolated with the values.
2624
+ * @param values - The values that are interpolated with the string fragments.
2625
+ * @remarks
2626
+ * The html helper supports interpolation of strings, numbers, binding expressions,
2627
+ * other template instances, and Directive instances.
2628
+ * @public
2629
+ */
2630
+ const item = html;
2631
+
2632
+ /**
2633
+ * The runtime behavior for template references.
2634
+ * @public
2635
+ */
2636
+ class RefDirective extends StatelessAttachedAttributeDirective {
2637
+ /**
2638
+ * Bind this behavior to the source.
2639
+ * @param source - The source to bind to.
2640
+ * @param context - The execution context that the binding is operating within.
2641
+ * @param targets - The targets that behaviors in a view can attach to.
2642
+ */
2643
+ bind(source, context, targets) {
2644
+ source[this.options] = targets[this.nodeId];
2645
+ }
2646
+ /**
2647
+ * Unbinds this behavior from the source.
2648
+ * @param source - The source to unbind from.
2649
+ */
2650
+ /* eslint-disable-next-line @typescript-eslint/no-empty-function */
2651
+ unbind() { }
2652
+ }
2653
+ HTMLDirective.define(RefDirective);
2654
+ /**
2655
+ * A directive that observes the updates a property with a reference to the element.
2656
+ * @param propertyName - The name of the property to assign the reference to.
2657
+ * @public
2658
+ */
2659
+ const ref = (propertyName) => new RefDirective(propertyName);
2660
+
2661
+ /**
2662
+ * A directive that enables basic conditional rendering in a template.
2663
+ * @param binding - The condition to test for rendering.
2664
+ * @param templateOrTemplateBinding - The template or a binding that gets
2665
+ * the template to render when the condition is true.
2666
+ * @public
2667
+ */
2668
+ function when(binding, templateOrTemplateBinding) {
2669
+ const getTemplate = isFunction(templateOrTemplateBinding)
2670
+ ? templateOrTemplateBinding
2671
+ : () => templateOrTemplateBinding;
2672
+ return (source, context) => binding(source, context) ? getTemplate(source, context) : null;
2673
+ }
2674
+
2675
+ const defaultRepeatOptions = Object.freeze({
2676
+ positioning: false,
2677
+ recycle: true,
2678
+ });
2679
+ function bindWithoutPositioning(view, items, index, context) {
2680
+ view.bind(items[index], context);
2681
+ }
2682
+ function bindWithPositioning(view, items, index, context) {
2683
+ view.bind(items[index], context.createItemContext(index, items.length));
2684
+ }
2685
+ /**
2686
+ * A behavior that renders a template for each item in an array.
2687
+ * @public
2688
+ */
2689
+ class RepeatBehavior {
2690
+ /**
2691
+ * Creates an instance of RepeatBehavior.
2692
+ * @param location - The location in the DOM to render the repeat.
2693
+ * @param itemsBinding - The array to render.
2694
+ * @param isItemsBindingVolatile - Indicates whether the items binding has volatile dependencies.
2695
+ * @param templateBinding - The template to render for each item.
2696
+ * @param isTemplateBindingVolatile - Indicates whether the template binding has volatile dependencies.
2697
+ * @param options - Options used to turn on special repeat features.
2698
+ */
2699
+ constructor(location, itemsBinding, isItemsBindingVolatile, templateBinding, isTemplateBindingVolatile, options) {
2700
+ this.location = location;
2701
+ this.itemsBinding = itemsBinding;
2702
+ this.templateBinding = templateBinding;
2703
+ this.options = options;
2704
+ this.source = null;
2705
+ this.views = [];
2706
+ this.items = null;
2707
+ this.itemsObserver = null;
2708
+ this.context = void 0;
2709
+ this.childContext = void 0;
2710
+ this.bindView = bindWithoutPositioning;
2711
+ this.itemsBindingObserver = Observable.binding(itemsBinding, this, isItemsBindingVolatile);
2712
+ this.templateBindingObserver = Observable.binding(templateBinding, this, isTemplateBindingVolatile);
2713
+ if (options.positioning) {
2714
+ this.bindView = bindWithPositioning;
2715
+ }
2716
+ }
2717
+ /**
2718
+ * Bind this behavior to the source.
2719
+ * @param source - The source to bind to.
2720
+ * @param context - The execution context that the binding is operating within.
2721
+ */
2722
+ bind(source, context) {
2723
+ this.source = source;
2724
+ this.context = context;
2725
+ this.childContext = context.createChildContext(source);
2726
+ this.items = this.itemsBindingObserver.observe(source, this.context);
2727
+ this.template = this.templateBindingObserver.observe(source, this.context);
2728
+ this.observeItems(true);
2729
+ this.refreshAllViews();
2730
+ }
2731
+ /**
2732
+ * Unbinds this behavior from the source.
2733
+ * @param source - The source to unbind from.
2734
+ */
2735
+ unbind() {
2736
+ this.source = null;
2737
+ this.items = null;
2738
+ if (this.itemsObserver !== null) {
2739
+ this.itemsObserver.unsubscribe(this);
2740
+ }
2741
+ this.unbindAllViews();
2742
+ this.itemsBindingObserver.dispose();
2743
+ this.templateBindingObserver.dispose();
2744
+ }
2745
+ /**
2746
+ * Handles changes in the array, its items, and the repeat template.
2747
+ * @param source - The source of the change.
2748
+ * @param args - The details about what was changed.
2749
+ */
2750
+ handleChange(source, args) {
2751
+ if (source === this.itemsBinding) {
2752
+ this.items = this.itemsBindingObserver.observe(this.source, this.context);
2753
+ this.observeItems();
2754
+ this.refreshAllViews();
2755
+ }
2756
+ else if (source === this.templateBinding) {
2757
+ this.template = this.templateBindingObserver.observe(this.source, this.context);
2758
+ this.refreshAllViews(true);
2759
+ }
2760
+ else if (args[0].reset) {
2761
+ this.refreshAllViews();
2762
+ }
2763
+ else {
2764
+ this.updateViews(args);
2765
+ }
2766
+ }
2767
+ observeItems(force = false) {
2768
+ if (!this.items) {
2769
+ this.items = emptyArray;
2770
+ return;
2771
+ }
2772
+ const oldObserver = this.itemsObserver;
2773
+ const newObserver = (this.itemsObserver = Observable.getNotifier(this.items));
2774
+ const hasNewObserver = oldObserver !== newObserver;
2775
+ if (hasNewObserver && oldObserver !== null) {
2776
+ oldObserver.unsubscribe(this);
2777
+ }
2778
+ if (hasNewObserver || force) {
2779
+ newObserver.subscribe(this);
2780
+ }
2781
+ }
2782
+ updateViews(splices) {
2783
+ const views = this.views;
2784
+ const childContext = this.childContext;
2785
+ const totalRemoved = [];
2786
+ const bindView = this.bindView;
2787
+ let removeDelta = 0;
2788
+ for (let i = 0, ii = splices.length; i < ii; ++i) {
2789
+ const splice = splices[i];
2790
+ const removed = splice.removed;
2791
+ totalRemoved.push(...views.splice(splice.index + removeDelta, removed.length));
2792
+ removeDelta -= splice.addedCount;
2793
+ }
2794
+ const items = this.items;
2795
+ const template = this.template;
2796
+ for (let i = 0, ii = splices.length; i < ii; ++i) {
2797
+ const splice = splices[i];
2798
+ let addIndex = splice.index;
2799
+ const end = addIndex + splice.addedCount;
2800
+ for (; addIndex < end; ++addIndex) {
2801
+ const neighbor = views[addIndex];
2802
+ const location = neighbor ? neighbor.firstChild : this.location;
2803
+ const view = this.options.recycle && totalRemoved.length > 0
2804
+ ? totalRemoved.shift()
2805
+ : template.create();
2806
+ views.splice(addIndex, 0, view);
2807
+ bindView(view, items, addIndex, childContext);
2808
+ view.insertBefore(location);
2809
+ }
2810
+ }
2811
+ for (let i = 0, ii = totalRemoved.length; i < ii; ++i) {
2812
+ totalRemoved[i].dispose();
2813
+ }
2814
+ if (this.options.positioning) {
2815
+ for (let i = 0, ii = views.length; i < ii; ++i) {
2816
+ views[i].context.updatePosition(i, ii);
2817
+ }
2818
+ }
2819
+ }
2820
+ refreshAllViews(templateChanged = false) {
2821
+ const items = this.items;
2822
+ const template = this.template;
2823
+ const location = this.location;
2824
+ const bindView = this.bindView;
2825
+ const childContext = this.childContext;
2826
+ let itemsLength = items.length;
2827
+ let views = this.views;
2828
+ let viewsLength = views.length;
2829
+ if (itemsLength === 0 || templateChanged) {
2830
+ // all views need to be removed
2831
+ HTMLView.disposeContiguousBatch(views);
2832
+ viewsLength = 0;
2833
+ }
2834
+ if (viewsLength === 0) {
2835
+ // all views need to be created
2836
+ this.views = views = new Array(itemsLength);
2837
+ for (let i = 0; i < itemsLength; ++i) {
2838
+ const view = template.create();
2839
+ bindView(view, items, i, childContext);
2840
+ views[i] = view;
2841
+ view.insertBefore(location);
2842
+ }
2843
+ }
2844
+ else {
2845
+ // attempt to reuse existing views with new data
2846
+ let i = 0;
2847
+ for (; i < itemsLength; ++i) {
2848
+ if (i < viewsLength) {
2849
+ const view = views[i];
2850
+ bindView(view, items, i, childContext);
2851
+ }
2852
+ else {
2853
+ const view = template.create();
2854
+ bindView(view, items, i, childContext);
2855
+ views.push(view);
2856
+ view.insertBefore(location);
2857
+ }
2858
+ }
2859
+ const removed = views.splice(i, viewsLength - i);
2860
+ for (i = 0, itemsLength = removed.length; i < itemsLength; ++i) {
2861
+ removed[i].dispose();
2862
+ }
2863
+ }
2864
+ }
2865
+ unbindAllViews() {
2866
+ const views = this.views;
2867
+ for (let i = 0, ii = views.length; i < ii; ++i) {
2868
+ views[i].unbind();
2869
+ }
2870
+ }
2871
+ }
2872
+ /**
2873
+ * A directive that configures list rendering.
2874
+ * @public
2875
+ */
2876
+ class RepeatDirective {
2877
+ /**
2878
+ * Creates an instance of RepeatDirective.
2879
+ * @param itemsBinding - The binding that provides the array to render.
2880
+ * @param templateBinding - The template binding used to obtain a template to render for each item in the array.
2881
+ * @param options - Options used to turn on special repeat features.
2882
+ */
2883
+ constructor(itemsBinding, templateBinding, options) {
2884
+ this.itemsBinding = itemsBinding;
2885
+ this.templateBinding = templateBinding;
2886
+ this.options = options;
2887
+ ArrayObserver.enable();
2888
+ this.isItemsBindingVolatile = Observable.isVolatileBinding(itemsBinding);
2889
+ this.isTemplateBindingVolatile = Observable.isVolatileBinding(templateBinding);
2890
+ }
2891
+ /**
2892
+ * Creates a placeholder string based on the directive's index within the template.
2893
+ * @param index - The index of the directive within the template.
2894
+ */
2895
+ createHTML(add) {
2896
+ return Markup.comment(add(this));
2897
+ }
2898
+ /**
2899
+ * Creates a behavior for the provided target node.
2900
+ * @param target - The node instance to create the behavior for.
2901
+ */
2902
+ createBehavior(targets) {
2903
+ return new RepeatBehavior(targets[this.nodeId], this.itemsBinding, this.isItemsBindingVolatile, this.templateBinding, this.isTemplateBindingVolatile, this.options);
2904
+ }
2905
+ }
2906
+ HTMLDirective.define(RepeatDirective);
2907
+ function repeat(itemsBinding, templateOrTemplateBinding, options = defaultRepeatOptions) {
2908
+ const templateBinding = isFunction(templateOrTemplateBinding)
2909
+ ? templateOrTemplateBinding
2910
+ : () => templateOrTemplateBinding;
2911
+ return new RepeatDirective(itemsBinding, templateBinding, options);
2912
+ }
2913
+
2914
+ const selectElements = (value) => value.nodeType === 1;
2915
+ /**
2916
+ * Creates a function that can be used to filter a Node array, selecting only elements.
2917
+ * @param selector - An optional selector to restrict the filter to.
2918
+ * @public
2919
+ */
2920
+ const elements = (selector) => selector
2921
+ ? value => value.nodeType === 1 && value.matches(selector)
2922
+ : selectElements;
2923
+ /**
2924
+ * A base class for node observation.
2925
+ * @public
2926
+ * @remarks
2927
+ * Internally used by the SlottedDirective and the ChildrenDirective.
2928
+ */
2929
+ class NodeObservationDirective extends StatelessAttachedAttributeDirective {
2930
+ constructor() {
2931
+ super(...arguments);
2932
+ this.sourceProperty = `${this.id}-s`;
2933
+ }
2934
+ /**
2935
+ * Bind this behavior to the source.
2936
+ * @param source - The source to bind to.
2937
+ * @param context - The execution context that the binding is operating within.
2938
+ * @param targets - The targets that behaviors in a view can attach to.
2939
+ */
2940
+ bind(source, context, targets) {
2941
+ const target = targets[this.nodeId];
2942
+ target[this.sourceProperty] = source;
2943
+ this.updateTarget(source, this.computeNodes(target));
2944
+ this.observe(target);
2945
+ }
2946
+ /**
2947
+ * Unbinds this behavior from the source.
2948
+ * @param source - The source to unbind from.
2949
+ * @param context - The execution context that the binding is operating within.
2950
+ * @param targets - The targets that behaviors in a view can attach to.
2951
+ */
2952
+ unbind(source, context, targets) {
2953
+ const target = targets[this.nodeId];
2954
+ this.updateTarget(source, emptyArray);
2955
+ this.disconnect(target);
2956
+ target[this.sourceProperty] = null;
2957
+ }
2958
+ /**
2959
+ * Gets the data source for the target.
2960
+ * @param target - The target to get the source for.
2961
+ * @returns The source.
2962
+ */
2963
+ getSource(target) {
2964
+ return target[this.sourceProperty];
2965
+ }
2966
+ /**
2967
+ * Updates the source property with the computed nodes.
2968
+ * @param source - The source object to assign the nodes property to.
2969
+ * @param value - The nodes to assign to the source object property.
2970
+ */
2971
+ updateTarget(source, value) {
2972
+ source[this.options.property] = value;
2973
+ }
2974
+ /**
2975
+ * Computes the set of nodes that should be assigned to the source property.
2976
+ * @param target - The target to compute the nodes for.
2977
+ * @returns The computed nodes.
2978
+ * @remarks
2979
+ * Applies filters if provided.
2980
+ */
2981
+ computeNodes(target) {
2982
+ let nodes = this.getNodes(target);
2983
+ if ("filter" in this.options) {
2984
+ nodes = nodes.filter(this.options.filter);
2985
+ }
2986
+ return nodes;
2987
+ }
2988
+ }
2989
+
2990
+ const slotEvent = "slotchange";
2991
+ /**
2992
+ * The runtime behavior for slotted node observation.
2993
+ * @public
2994
+ */
2995
+ class SlottedDirective extends NodeObservationDirective {
2996
+ /**
2997
+ * Begins observation of the nodes.
2998
+ * @param target - The target to observe.
2999
+ */
3000
+ observe(target) {
3001
+ target.addEventListener(slotEvent, this);
3002
+ }
3003
+ /**
3004
+ * Disconnects observation of the nodes.
3005
+ * @param target - The target to unobserve.
3006
+ */
3007
+ disconnect(target) {
3008
+ target.removeEventListener(slotEvent, this);
3009
+ }
3010
+ /**
3011
+ * Retrieves the raw nodes that should be assigned to the source property.
3012
+ * @param target - The target to get the node to.
3013
+ */
3014
+ getNodes(target) {
3015
+ return target.assignedNodes(this.options);
3016
+ }
3017
+ /** @internal */
3018
+ handleEvent(event) {
3019
+ const target = event.currentTarget;
3020
+ this.updateTarget(this.getSource(target), this.computeNodes(target));
3021
+ }
3022
+ }
3023
+ HTMLDirective.define(SlottedDirective);
3024
+ /**
3025
+ * A directive that observes the `assignedNodes()` of a slot and updates a property
3026
+ * whenever they change.
3027
+ * @param propertyOrOptions - The options used to configure slotted node observation.
3028
+ * @public
3029
+ */
3030
+ function slotted(propertyOrOptions) {
3031
+ if (isString(propertyOrOptions)) {
3032
+ propertyOrOptions = { property: propertyOrOptions };
3033
+ }
3034
+ return new SlottedDirective(propertyOrOptions);
3035
+ }
3036
+
3037
+ /**
3038
+ * The runtime behavior for child node observation.
3039
+ * @public
3040
+ */
3041
+ class ChildrenDirective extends NodeObservationDirective {
3042
+ /**
3043
+ * Creates an instance of ChildrenDirective.
3044
+ * @param options - The options to use in configuring the child observation behavior.
3045
+ */
3046
+ constructor(options) {
3047
+ super(options);
3048
+ this.observerProperty = `${this.id}-o`;
3049
+ this.handleEvent = (mutations, observer) => {
3050
+ const target = observer.target;
3051
+ this.updateTarget(this.getSource(target), this.computeNodes(target));
3052
+ };
3053
+ options.childList = true;
3054
+ }
3055
+ /**
3056
+ * Begins observation of the nodes.
3057
+ * @param target - The target to observe.
3058
+ */
3059
+ observe(target) {
3060
+ var _a;
3061
+ const observer = (_a = target[this.observerProperty]) !== null && _a !== void 0 ? _a : (target[this.observerProperty] = new MutationObserver(this.handleEvent));
3062
+ observer.target = target;
3063
+ observer.observe(target, this.options);
3064
+ }
3065
+ /**
3066
+ * Disconnects observation of the nodes.
3067
+ * @param target - The target to unobserve.
3068
+ */
3069
+ disconnect(target) {
3070
+ const observer = target[this.observerProperty];
3071
+ observer.target = null;
3072
+ observer.disconnect();
3073
+ }
3074
+ /**
3075
+ * Retrieves the raw nodes that should be assigned to the source property.
3076
+ * @param target - The target to get the node to.
3077
+ */
3078
+ getNodes(target) {
3079
+ if ("selector" in this.options) {
3080
+ return Array.from(target.querySelectorAll(this.options.selector));
3081
+ }
3082
+ return Array.from(target.childNodes);
3083
+ }
3084
+ }
3085
+ HTMLDirective.define(ChildrenDirective);
3086
+ /**
3087
+ * A directive that observes the `childNodes` of an element and updates a property
3088
+ * whenever they change.
3089
+ * @param propertyOrOptions - The options used to configure child node observation.
3090
+ * @public
3091
+ */
3092
+ function children(propertyOrOptions) {
3093
+ if (isString(propertyOrOptions)) {
3094
+ propertyOrOptions = {
3095
+ property: propertyOrOptions,
3096
+ };
3097
+ }
3098
+ return new ChildrenDirective(propertyOrOptions);
3099
+ }
3100
+
3101
+ const booleanMode = "boolean";
3102
+ const reflectMode = "reflect";
3103
+ /**
3104
+ * A {@link ValueConverter} that converts to and from `boolean` values.
3105
+ * @remarks
3106
+ * Used automatically when the `boolean` {@link AttributeMode} is selected.
3107
+ * @public
3108
+ */
3109
+ const booleanConverter = {
3110
+ toView(value) {
3111
+ return value ? "true" : "false";
3112
+ },
3113
+ fromView(value) {
3114
+ return value === null ||
3115
+ value === void 0 ||
3116
+ value === "false" ||
3117
+ value === false ||
3118
+ value === 0
3119
+ ? false
3120
+ : true;
3121
+ },
3122
+ };
3123
+ function toNumber(value) {
3124
+ if (value === null || value === undefined) {
3125
+ return null;
3126
+ }
3127
+ const number = value * 1;
3128
+ return isNaN(number) ? null : number;
3129
+ }
3130
+ /**
3131
+ * A {@link ValueConverter} that converts to and from `number` values.
3132
+ * @remarks
3133
+ * This converter allows for nullable numbers, returning `null` if the
3134
+ * input was `null`, `undefined`, or `NaN`.
3135
+ * @public
3136
+ */
3137
+ const nullableNumberConverter = {
3138
+ toView(value) {
3139
+ const output = toNumber(value);
3140
+ return output ? output.toString() : output;
3141
+ },
3142
+ fromView: toNumber,
3143
+ };
3144
+ /**
3145
+ * An implementation of {@link Accessor} that supports reactivity,
3146
+ * change callbacks, attribute reflection, and type conversion for
3147
+ * custom elements.
3148
+ * @public
3149
+ */
3150
+ class AttributeDefinition {
3151
+ /**
3152
+ * Creates an instance of AttributeDefinition.
3153
+ * @param Owner - The class constructor that owns this attribute.
3154
+ * @param name - The name of the property associated with the attribute.
3155
+ * @param attribute - The name of the attribute in HTML.
3156
+ * @param mode - The {@link AttributeMode} that describes the behavior of this attribute.
3157
+ * @param converter - A {@link ValueConverter} that integrates with the property getter/setter
3158
+ * to convert values to and from a DOM string.
3159
+ */
3160
+ constructor(Owner, name, attribute = name.toLowerCase(), mode = reflectMode, converter) {
3161
+ this.guards = new Set();
3162
+ this.Owner = Owner;
3163
+ this.name = name;
3164
+ this.attribute = attribute;
3165
+ this.mode = mode;
3166
+ this.converter = converter;
3167
+ this.fieldName = `_${name}`;
3168
+ this.callbackName = `${name}Changed`;
3169
+ this.hasCallback = this.callbackName in Owner.prototype;
3170
+ if (mode === booleanMode && converter === void 0) {
3171
+ this.converter = booleanConverter;
3172
+ }
3173
+ }
3174
+ /**
3175
+ * Sets the value of the attribute/property on the source element.
3176
+ * @param source - The source element to access.
3177
+ * @param value - The value to set the attribute/property to.
3178
+ */
3179
+ setValue(source, newValue) {
3180
+ const oldValue = source[this.fieldName];
3181
+ const converter = this.converter;
3182
+ if (converter !== void 0) {
3183
+ newValue = converter.fromView(newValue);
3184
+ }
3185
+ if (oldValue !== newValue) {
3186
+ source[this.fieldName] = newValue;
3187
+ this.tryReflectToAttribute(source);
3188
+ if (this.hasCallback) {
3189
+ source[this.callbackName](oldValue, newValue);
3190
+ }
3191
+ source.$fastController.notify(this.name);
3192
+ }
3193
+ }
3194
+ /**
3195
+ * Gets the value of the attribute/property on the source element.
3196
+ * @param source - The source element to access.
3197
+ */
3198
+ getValue(source) {
3199
+ Observable.track(source, this.name);
3200
+ return source[this.fieldName];
3201
+ }
3202
+ /** @internal */
3203
+ onAttributeChangedCallback(element, value) {
3204
+ if (this.guards.has(element)) {
3205
+ return;
3206
+ }
3207
+ this.guards.add(element);
3208
+ this.setValue(element, value);
3209
+ this.guards.delete(element);
3210
+ }
3211
+ tryReflectToAttribute(element) {
3212
+ const mode = this.mode;
3213
+ const guards = this.guards;
3214
+ if (guards.has(element) || mode === "fromView") {
3215
+ return;
3216
+ }
3217
+ Updates.enqueue(() => {
3218
+ guards.add(element);
3219
+ const latestValue = element[this.fieldName];
3220
+ switch (mode) {
3221
+ case reflectMode:
3222
+ const converter = this.converter;
3223
+ DOM.setAttribute(element, this.attribute, converter !== void 0 ? converter.toView(latestValue) : latestValue);
3224
+ break;
3225
+ case booleanMode:
3226
+ DOM.setBooleanAttribute(element, this.attribute, latestValue);
3227
+ break;
3228
+ }
3229
+ guards.delete(element);
3230
+ });
3231
+ }
3232
+ /**
3233
+ * Collects all attribute definitions associated with the owner.
3234
+ * @param Owner - The class constructor to collect attribute for.
3235
+ * @param attributeLists - Any existing attributes to collect and merge with those associated with the owner.
3236
+ * @internal
3237
+ */
3238
+ static collect(Owner, ...attributeLists) {
3239
+ const attributes = [];
3240
+ attributeLists.push(Owner.attributes);
3241
+ for (let i = 0, ii = attributeLists.length; i < ii; ++i) {
3242
+ const list = attributeLists[i];
3243
+ if (list === void 0) {
3244
+ continue;
3245
+ }
3246
+ for (let j = 0, jj = list.length; j < jj; ++j) {
3247
+ const config = list[j];
3248
+ if (isString(config)) {
3249
+ attributes.push(new AttributeDefinition(Owner, config));
3250
+ }
3251
+ else {
3252
+ attributes.push(new AttributeDefinition(Owner, config.property, config.attribute, config.mode, config.converter));
3253
+ }
3254
+ }
3255
+ }
3256
+ return attributes;
3257
+ }
3258
+ }
3259
+ function attr(configOrTarget, prop) {
3260
+ let config;
3261
+ function decorator($target, $prop) {
3262
+ if (arguments.length > 1) {
3263
+ // Non invocation:
3264
+ // - @attr
3265
+ // Invocation with or w/o opts:
3266
+ // - @attr()
3267
+ // - @attr({...opts})
3268
+ config.property = $prop;
3269
+ }
3270
+ const attributes = $target.constructor.attributes ||
3271
+ ($target.constructor.attributes = []);
3272
+ attributes.push(config);
3273
+ }
3274
+ if (arguments.length > 1) {
3275
+ // Non invocation:
3276
+ // - @attr
3277
+ config = {};
3278
+ decorator(configOrTarget, prop);
3279
+ return;
3280
+ }
3281
+ // Invocation with or w/o opts:
3282
+ // - @attr()
3283
+ // - @attr({...opts})
3284
+ config = configOrTarget === void 0 ? {} : configOrTarget;
3285
+ return decorator;
3286
+ }
3287
+
3288
+ const defaultShadowOptions = { mode: "open" };
3289
+ const defaultElementOptions = {};
3290
+ const fastElementRegistry = FAST.getById(4 /* KernelServiceId.elementRegistry */, () => createTypeRegistry());
3291
+ /**
3292
+ * Defines metadata for a FASTElement.
3293
+ * @public
3294
+ */
3295
+ class FASTElementDefinition {
3296
+ /**
3297
+ * Creates an instance of FASTElementDefinition.
3298
+ * @param type - The type this definition is being created for.
3299
+ * @param nameOrConfig - The name of the element to define or a config object
3300
+ * that describes the element to define.
3301
+ */
3302
+ constructor(type, nameOrConfig = type.definition) {
3303
+ if (isString(nameOrConfig)) {
3304
+ nameOrConfig = { name: nameOrConfig };
3305
+ }
3306
+ this.type = type;
3307
+ this.name = nameOrConfig.name;
3308
+ this.template = nameOrConfig.template;
3309
+ const attributes = AttributeDefinition.collect(type, nameOrConfig.attributes);
3310
+ const observedAttributes = new Array(attributes.length);
3311
+ const propertyLookup = {};
3312
+ const attributeLookup = {};
3313
+ for (let i = 0, ii = attributes.length; i < ii; ++i) {
3314
+ const current = attributes[i];
3315
+ observedAttributes[i] = current.attribute;
3316
+ propertyLookup[current.name] = current;
3317
+ attributeLookup[current.attribute] = current;
3318
+ }
3319
+ this.attributes = attributes;
3320
+ this.observedAttributes = observedAttributes;
3321
+ this.propertyLookup = propertyLookup;
3322
+ this.attributeLookup = attributeLookup;
3323
+ this.shadowOptions =
3324
+ nameOrConfig.shadowOptions === void 0
3325
+ ? defaultShadowOptions
3326
+ : nameOrConfig.shadowOptions === null
3327
+ ? void 0
3328
+ : Object.assign(Object.assign({}, defaultShadowOptions), nameOrConfig.shadowOptions);
3329
+ this.elementOptions =
3330
+ nameOrConfig.elementOptions === void 0
3331
+ ? defaultElementOptions
3332
+ : Object.assign(Object.assign({}, defaultElementOptions), nameOrConfig.elementOptions);
3333
+ this.styles =
3334
+ nameOrConfig.styles === void 0
3335
+ ? void 0
3336
+ : Array.isArray(nameOrConfig.styles)
3337
+ ? new ElementStyles(nameOrConfig.styles)
3338
+ : nameOrConfig.styles instanceof ElementStyles
3339
+ ? nameOrConfig.styles
3340
+ : new ElementStyles([nameOrConfig.styles]);
3341
+ }
3342
+ /**
3343
+ * Indicates if this element has been defined in at least one registry.
3344
+ */
3345
+ get isDefined() {
3346
+ return !!fastElementRegistry.getByType(this.type);
3347
+ }
3348
+ /**
3349
+ * Defines a custom element based on this definition.
3350
+ * @param registry - The element registry to define the element in.
3351
+ */
3352
+ define(registry = customElements) {
3353
+ const type = this.type;
3354
+ if (fastElementRegistry.register(this)) {
3355
+ const attributes = this.attributes;
3356
+ const proto = type.prototype;
3357
+ for (let i = 0, ii = attributes.length; i < ii; ++i) {
3358
+ Observable.defineProperty(proto, attributes[i]);
3359
+ }
3360
+ Reflect.defineProperty(type, "observedAttributes", {
3361
+ value: this.observedAttributes,
3362
+ enumerable: true,
3363
+ });
3364
+ }
3365
+ if (!registry.get(this.name)) {
3366
+ registry.define(this.name, type, this.elementOptions);
3367
+ }
3368
+ return this;
3369
+ }
3370
+ }
3371
+ /**
3372
+ * Gets the element definition associated with the specified type.
3373
+ * @param type - The custom element type to retrieve the definition for.
3374
+ */
3375
+ FASTElementDefinition.getByType = fastElementRegistry.getByType;
3376
+ /**
3377
+ * Gets the element definition associated with the instance.
3378
+ * @param instance - The custom element instance to retrieve the definition for.
3379
+ */
3380
+ FASTElementDefinition.getForInstance = fastElementRegistry.getForInstance;
3381
+
3382
+ const shadowRoots = new WeakMap();
3383
+ const defaultEventOptions = {
3384
+ bubbles: true,
3385
+ composed: true,
3386
+ cancelable: true,
3387
+ };
3388
+ function getShadowRoot(element) {
3389
+ var _a, _b;
3390
+ return (_b = (_a = element.shadowRoot) !== null && _a !== void 0 ? _a : shadowRoots.get(element)) !== null && _b !== void 0 ? _b : null;
3391
+ }
3392
+ const isConnectedPropertyName = "isConnected";
3393
+ /**
3394
+ * Controls the lifecycle and rendering of a `FASTElement`.
3395
+ * @public
3396
+ */
3397
+ class Controller extends PropertyChangeNotifier {
3398
+ /**
3399
+ * Creates a Controller to control the specified element.
3400
+ * @param element - The element to be controlled by this controller.
3401
+ * @param definition - The element definition metadata that instructs this
3402
+ * controller in how to handle rendering and other platform integrations.
3403
+ * @internal
3404
+ */
3405
+ constructor(element, definition) {
3406
+ super(element);
3407
+ this.boundObservables = null;
3408
+ this.behaviors = null;
3409
+ this.needsInitialization = true;
3410
+ this.hasExistingShadowRoot = false;
3411
+ this._template = null;
3412
+ this._styles = null;
3413
+ this._isConnected = false;
3414
+ /**
3415
+ * This allows Observable.getNotifier(...) to return the Controller
3416
+ * when the notifier for the Controller itself is being requested. The
3417
+ * result is that the Observable system does not need to create a separate
3418
+ * instance of Notifier for observables on the Controller. The component and
3419
+ * the controller will now share the same notifier, removing one-object construct
3420
+ * per web component instance.
3421
+ */
3422
+ this.$fastController = this;
3423
+ /**
3424
+ * The view associated with the custom element.
3425
+ * @remarks
3426
+ * If `null` then the element is managing its own rendering.
3427
+ */
3428
+ this.view = null;
3429
+ this.element = element;
3430
+ this.definition = definition;
3431
+ const shadowOptions = definition.shadowOptions;
3432
+ if (shadowOptions !== void 0) {
3433
+ let shadowRoot = element.shadowRoot;
3434
+ if (shadowRoot) {
3435
+ this.hasExistingShadowRoot = true;
3436
+ }
3437
+ else {
3438
+ shadowRoot = element.attachShadow(shadowOptions);
3439
+ if (shadowOptions.mode === "closed") {
3440
+ shadowRoots.set(element, shadowRoot);
3441
+ }
3442
+ }
3443
+ }
3444
+ // Capture any observable values that were set by the binding engine before
3445
+ // the browser upgraded the element. Then delete the property since it will
3446
+ // shadow the getter/setter that is required to make the observable operate.
3447
+ // Later, in the connect callback, we'll re-apply the values.
3448
+ const accessors = Observable.getAccessors(element);
3449
+ if (accessors.length > 0) {
3450
+ const boundObservables = (this.boundObservables = Object.create(null));
3451
+ for (let i = 0, ii = accessors.length; i < ii; ++i) {
3452
+ const propertyName = accessors[i].name;
3453
+ const value = element[propertyName];
3454
+ if (value !== void 0) {
3455
+ delete element[propertyName];
3456
+ boundObservables[propertyName] = value;
3457
+ }
3458
+ }
3459
+ }
3460
+ }
3461
+ /**
3462
+ * Indicates whether or not the custom element has been
3463
+ * connected to the document.
3464
+ */
3465
+ get isConnected() {
3466
+ Observable.track(this, isConnectedPropertyName);
3467
+ return this._isConnected;
3468
+ }
3469
+ setIsConnected(value) {
3470
+ this._isConnected = value;
3471
+ Observable.notify(this, isConnectedPropertyName);
3472
+ }
3473
+ /**
3474
+ * Gets/sets the template used to render the component.
3475
+ * @remarks
3476
+ * This value can only be accurately read after connect but can be set at any time.
3477
+ */
3478
+ get template() {
3479
+ var _a;
3480
+ // 1. Template overrides take top precedence.
3481
+ if (this._template === null) {
3482
+ const definition = this.definition;
3483
+ if (this.element.resolveTemplate) {
3484
+ // 2. Allow for element instance overrides next.
3485
+ this._template = this.element.resolveTemplate();
3486
+ }
3487
+ else if (definition.template) {
3488
+ // 3. Default to the static definition.
3489
+ this._template = (_a = definition.template) !== null && _a !== void 0 ? _a : null;
3490
+ }
3491
+ }
3492
+ return this._template;
3493
+ }
3494
+ set template(value) {
3495
+ if (this._template === value) {
3496
+ return;
3497
+ }
3498
+ this._template = value;
3499
+ if (!this.needsInitialization) {
3500
+ this.renderTemplate(value);
3501
+ }
3502
+ }
3503
+ /**
3504
+ * Gets/sets the primary styles used for the component.
3505
+ * @remarks
3506
+ * This value can only be accurately read after connect but can be set at any time.
3507
+ */
3508
+ get styles() {
3509
+ var _a;
3510
+ // 1. Styles overrides take top precedence.
3511
+ if (this._styles === null) {
3512
+ const definition = this.definition;
3513
+ if (this.element.resolveStyles) {
3514
+ // 2. Allow for element instance overrides next.
3515
+ this._styles = this.element.resolveStyles();
3516
+ }
3517
+ else if (definition.styles) {
3518
+ // 3. Default to the static definition.
3519
+ this._styles = (_a = definition.styles) !== null && _a !== void 0 ? _a : null;
3520
+ }
3521
+ }
3522
+ return this._styles;
3523
+ }
3524
+ set styles(value) {
3525
+ if (this._styles === value) {
3526
+ return;
3527
+ }
3528
+ if (this._styles !== null) {
3529
+ this.removeStyles(this._styles);
3530
+ }
3531
+ this._styles = value;
3532
+ if (!this.needsInitialization) {
3533
+ this.addStyles(value);
3534
+ }
3535
+ }
3536
+ /**
3537
+ * Adds styles to this element. Providing an HTMLStyleElement will attach the element instance to the shadowRoot.
3538
+ * @param styles - The styles to add.
3539
+ */
3540
+ addStyles(styles) {
3541
+ if (!styles) {
3542
+ return;
3543
+ }
3544
+ const target = getShadowRoot(this.element) ||
3545
+ this.element.getRootNode();
3546
+ if (styles instanceof HTMLElement) {
3547
+ target.append(styles);
3548
+ }
3549
+ else if (!styles.isAttachedTo(target)) {
3550
+ const sourceBehaviors = styles.behaviors;
3551
+ styles.addStylesTo(target);
3552
+ if (sourceBehaviors !== null) {
3553
+ this.addBehaviors(sourceBehaviors);
3554
+ }
3555
+ }
3556
+ }
3557
+ /**
3558
+ * Removes styles from this element. Providing an HTMLStyleElement will detach the element instance from the shadowRoot.
3559
+ * @param styles - the styles to remove.
3560
+ */
3561
+ removeStyles(styles) {
3562
+ if (!styles) {
3563
+ return;
3564
+ }
3565
+ const target = getShadowRoot(this.element) ||
3566
+ this.element.getRootNode();
3567
+ if (styles instanceof HTMLElement) {
3568
+ target.removeChild(styles);
3569
+ }
3570
+ else if (styles.isAttachedTo(target)) {
3571
+ const sourceBehaviors = styles.behaviors;
3572
+ styles.removeStylesFrom(target);
3573
+ if (sourceBehaviors !== null) {
3574
+ this.removeBehaviors(sourceBehaviors);
3575
+ }
3576
+ }
3577
+ }
3578
+ /**
3579
+ * Adds behaviors to this element.
3580
+ * @param behaviors - The behaviors to add.
3581
+ */
3582
+ addBehaviors(behaviors) {
3583
+ var _a;
3584
+ const targetBehaviors = (_a = this.behaviors) !== null && _a !== void 0 ? _a : (this.behaviors = new Map());
3585
+ const length = behaviors.length;
3586
+ const behaviorsToBind = [];
3587
+ for (let i = 0; i < length; ++i) {
3588
+ const behavior = behaviors[i];
3589
+ if (targetBehaviors.has(behavior)) {
3590
+ targetBehaviors.set(behavior, targetBehaviors.get(behavior) + 1);
3591
+ }
3592
+ else {
3593
+ targetBehaviors.set(behavior, 1);
3594
+ behaviorsToBind.push(behavior);
3595
+ }
3596
+ }
3597
+ if (this._isConnected) {
3598
+ const element = this.element;
3599
+ const context = ExecutionContext.default;
3600
+ for (let i = 0; i < behaviorsToBind.length; ++i) {
3601
+ behaviorsToBind[i].bind(element, context);
3602
+ }
3603
+ }
3604
+ }
3605
+ /**
3606
+ * Removes behaviors from this element.
3607
+ * @param behaviors - The behaviors to remove.
3608
+ * @param force - Forces unbinding of behaviors.
3609
+ */
3610
+ removeBehaviors(behaviors, force = false) {
3611
+ const targetBehaviors = this.behaviors;
3612
+ if (targetBehaviors === null) {
3613
+ return;
3614
+ }
3615
+ const length = behaviors.length;
3616
+ const behaviorsToUnbind = [];
3617
+ for (let i = 0; i < length; ++i) {
3618
+ const behavior = behaviors[i];
3619
+ if (targetBehaviors.has(behavior)) {
3620
+ const count = targetBehaviors.get(behavior) - 1;
3621
+ count === 0 || force
3622
+ ? targetBehaviors.delete(behavior) && behaviorsToUnbind.push(behavior)
3623
+ : targetBehaviors.set(behavior, count);
3624
+ }
3625
+ }
3626
+ if (this._isConnected) {
3627
+ const element = this.element;
3628
+ const context = ExecutionContext.default;
3629
+ for (let i = 0; i < behaviorsToUnbind.length; ++i) {
3630
+ behaviorsToUnbind[i].unbind(element, context);
3631
+ }
3632
+ }
3633
+ }
3634
+ /**
3635
+ * Runs connected lifecycle behavior on the associated element.
3636
+ */
3637
+ onConnectedCallback() {
3638
+ if (this._isConnected) {
3639
+ return;
3640
+ }
3641
+ const element = this.element;
3642
+ const context = ExecutionContext.default;
3643
+ if (this.needsInitialization) {
3644
+ this.finishInitialization();
3645
+ }
3646
+ else if (this.view !== null) {
3647
+ this.view.bind(element, context);
3648
+ }
3649
+ const behaviors = this.behaviors;
3650
+ if (behaviors !== null) {
3651
+ for (const behavior of behaviors.keys()) {
3652
+ behavior.bind(element, context);
3653
+ }
3654
+ }
3655
+ this.setIsConnected(true);
3656
+ }
3657
+ /**
3658
+ * Runs disconnected lifecycle behavior on the associated element.
3659
+ */
3660
+ onDisconnectedCallback() {
3661
+ if (!this._isConnected) {
3662
+ return;
3663
+ }
3664
+ this.setIsConnected(false);
3665
+ const view = this.view;
3666
+ if (view !== null) {
3667
+ view.unbind();
3668
+ }
3669
+ const behaviors = this.behaviors;
3670
+ if (behaviors !== null) {
3671
+ const element = this.element;
3672
+ const context = ExecutionContext.default;
3673
+ for (const behavior of behaviors.keys()) {
3674
+ behavior.unbind(element, context);
3675
+ }
3676
+ }
3677
+ }
3678
+ /**
3679
+ * Runs the attribute changed callback for the associated element.
3680
+ * @param name - The name of the attribute that changed.
3681
+ * @param oldValue - The previous value of the attribute.
3682
+ * @param newValue - The new value of the attribute.
3683
+ */
3684
+ onAttributeChangedCallback(name, oldValue, newValue) {
3685
+ const attrDef = this.definition.attributeLookup[name];
3686
+ if (attrDef !== void 0) {
3687
+ attrDef.onAttributeChangedCallback(this.element, newValue);
3688
+ }
3689
+ }
3690
+ /**
3691
+ * Emits a custom HTML event.
3692
+ * @param type - The type name of the event.
3693
+ * @param detail - The event detail object to send with the event.
3694
+ * @param options - The event options. By default bubbles and composed.
3695
+ * @remarks
3696
+ * Only emits events if connected.
3697
+ */
3698
+ emit(type, detail, options) {
3699
+ if (this._isConnected) {
3700
+ return this.element.dispatchEvent(new CustomEvent(type, Object.assign(Object.assign({ detail }, defaultEventOptions), options)));
3701
+ }
3702
+ return false;
3703
+ }
3704
+ finishInitialization() {
3705
+ const element = this.element;
3706
+ const boundObservables = this.boundObservables;
3707
+ // If we have any observables that were bound, re-apply their values.
3708
+ if (boundObservables !== null) {
3709
+ const propertyNames = Object.keys(boundObservables);
3710
+ for (let i = 0, ii = propertyNames.length; i < ii; ++i) {
3711
+ const propertyName = propertyNames[i];
3712
+ element[propertyName] = boundObservables[propertyName];
3713
+ }
3714
+ this.boundObservables = null;
3715
+ }
3716
+ this.renderTemplate(this.template);
3717
+ this.addStyles(this.styles);
3718
+ this.needsInitialization = false;
3719
+ }
3720
+ renderTemplate(template) {
3721
+ var _a;
3722
+ const element = this.element;
3723
+ // When getting the host to render to, we start by looking
3724
+ // up the shadow root. If there isn't one, then that means
3725
+ // we're doing a Light DOM render to the element's direct children.
3726
+ const host = (_a = getShadowRoot(element)) !== null && _a !== void 0 ? _a : element;
3727
+ if (this.view !== null) {
3728
+ // If there's already a view, we need to unbind and remove through dispose.
3729
+ this.view.dispose();
3730
+ this.view = null;
3731
+ }
3732
+ else if (!this.needsInitialization || this.hasExistingShadowRoot) {
3733
+ this.hasExistingShadowRoot = false;
3734
+ // If there was previous custom rendering, we need to clear out the host.
3735
+ for (let child = host.firstChild; child !== null; child = host.firstChild) {
3736
+ host.removeChild(child);
3737
+ }
3738
+ }
3739
+ if (template) {
3740
+ // If a new template was provided, render it.
3741
+ this.view = template.render(element, host, element);
3742
+ }
3743
+ }
3744
+ /**
3745
+ * Locates or creates a controller for the specified element.
3746
+ * @param element - The element to return the controller for.
3747
+ * @remarks
3748
+ * The specified element must have a {@link FASTElementDefinition}
3749
+ * registered either through the use of the {@link customElement}
3750
+ * decorator or a call to `FASTElement.define`.
3751
+ */
3752
+ static forCustomElement(element) {
3753
+ const controller = element.$fastController;
3754
+ if (controller !== void 0) {
3755
+ return controller;
3756
+ }
3757
+ const definition = FASTElementDefinition.getForInstance(element);
3758
+ if (definition === void 0) {
3759
+ throw FAST.error(1401 /* Message.missingElementDefinition */);
3760
+ }
3761
+ return (element.$fastController = new Controller(element, definition));
3762
+ }
3763
+ }
3764
+
3765
+ /* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
3766
+ function createFASTElement(BaseType) {
3767
+ return class extends BaseType {
3768
+ constructor() {
3769
+ /* eslint-disable-next-line */
3770
+ super();
3771
+ Controller.forCustomElement(this);
3772
+ }
3773
+ $emit(type, detail, options) {
3774
+ return this.$fastController.emit(type, detail, options);
3775
+ }
3776
+ connectedCallback() {
3777
+ this.$fastController.onConnectedCallback();
3778
+ }
3779
+ disconnectedCallback() {
3780
+ this.$fastController.onDisconnectedCallback();
3781
+ }
3782
+ attributeChangedCallback(name, oldValue, newValue) {
3783
+ this.$fastController.onAttributeChangedCallback(name, oldValue, newValue);
3784
+ }
3785
+ };
3786
+ }
3787
+ /**
3788
+ * A minimal base class for FASTElements that also provides
3789
+ * static helpers for working with FASTElements.
3790
+ * @public
3791
+ */
3792
+ const FASTElement = Object.assign(createFASTElement(HTMLElement), {
3793
+ /**
3794
+ * Creates a new FASTElement base class inherited from the
3795
+ * provided base type.
3796
+ * @param BaseType - The base element type to inherit from.
3797
+ */
3798
+ from(BaseType) {
3799
+ return createFASTElement(BaseType);
3800
+ },
3801
+ /**
3802
+ * Defines a platform custom element based on the provided type and definition.
3803
+ * @param type - The custom element type to define.
3804
+ * @param nameOrDef - The name of the element to define or a definition object
3805
+ * that describes the element to define.
3806
+ */
3807
+ define(type, nameOrDef) {
3808
+ return new FASTElementDefinition(type, nameOrDef).define().type;
3809
+ },
3810
+ });
3811
+ /**
3812
+ * Decorator: Defines a platform custom element based on `FASTElement`.
3813
+ * @param nameOrDef - The name of the element to define or a definition object
3814
+ * that describes the element to define.
3815
+ * @public
3816
+ */
3817
+ function customElement(nameOrDef) {
3818
+ /* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
3819
+ return function (type) {
3820
+ new FASTElementDefinition(type, nameOrDef).define();
3821
+ };
3822
+ }
3823
+
3824
+ export { AdoptedStyleSheetsStrategy, ArrayObserver, Aspect, AttributeDefinition, BindingConfig, BindingMode, CSSDirective, ChangeBinding, ChildrenDirective, Compiler, Controller, DOM, ElementStyles, EventBinding, ExecutionContext, FAST, FASTElement, FASTElementDefinition, HTMLBindingDirective, HTMLDirective, HTMLView, Markup, NodeObservationDirective, Observable, OneTimeBinding, Parser, PropertyChangeNotifier, RefDirective, RepeatBehavior, RepeatDirective, SignalBinding, SlottedDirective, Splice, SpliceStrategy, SpliceStrategySupport, StatelessAttachedAttributeDirective, SubscriberSet, TwoWayBinding, UpdateBinding, Updates, ViewTemplate, attr, bind, booleanConverter, child, children, createTypeRegistry, css, cssDirective, cssPartial, customElement, elements, emptyArray, html, htmlDirective, item, length, nullableNumberConverter, observable, onChange, oneTime, ref, repeat, signal, slotted, twoWay, volatile, when };