@vonage/vivid 3.0.0-next.2 → 3.0.0-next.5

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 (88) hide show
  1. package/accordion/index.js +61 -0
  2. package/accordion-item/index.js +125 -0
  3. package/badge/index.js +19 -10
  4. package/banner/index.js +212 -0
  5. package/breadcrumb/index.js +100 -0
  6. package/breadcrumb-item/index.js +15 -8
  7. package/button/index.js +24 -15
  8. package/calendar/index.js +1521 -0
  9. package/elevation/index.js +5 -12
  10. package/focus/index.js +2 -2
  11. package/icon/index.js +33 -4
  12. package/index.d.ts +1 -0
  13. package/index.js +21 -5
  14. package/layout/index.js +1 -1
  15. package/lib/accordion/accordion.d.ts +9 -0
  16. package/lib/accordion/accordion.template.d.ts +4 -0
  17. package/lib/accordion/index.d.ts +2 -0
  18. package/lib/accordion-item/accordion-item.d.ts +13 -0
  19. package/lib/accordion-item/accordion-item.template.d.ts +4 -0
  20. package/lib/accordion-item/index.d.ts +3 -0
  21. package/lib/badge/badge.d.ts +3 -3
  22. package/lib/banner/banner.d.ts +20 -0
  23. package/lib/banner/banner.template.d.ts +6 -0
  24. package/lib/banner/index.d.ts +2 -0
  25. package/lib/breadcrumb/breadcrumb.d.ts +3 -0
  26. package/lib/breadcrumb/index.d.ts +2 -0
  27. package/lib/breadcrumb-item/breadcrumb-item.d.ts +3 -3
  28. package/lib/breadcrumb-item/breadcrumb-item.template.d.ts +0 -1
  29. package/lib/breadcrumb-item/index.d.ts +1 -0
  30. package/lib/button/button.d.ts +3 -3
  31. package/lib/calendar/calendar.d.ts +11 -0
  32. package/lib/calendar/calendar.template.d.ts +4 -0
  33. package/lib/calendar/helpers/calendar.date-functions.d.ts +2 -0
  34. package/lib/calendar/helpers/calendar.event-context.d.ts +6 -0
  35. package/lib/calendar/helpers/calendar.keyboard-interactions.d.ts +9 -0
  36. package/lib/calendar/index.d.ts +3 -0
  37. package/lib/components.d.ts +9 -0
  38. package/lib/elevation/elevation.d.ts +1 -1
  39. package/lib/enums.d.ts +3 -2
  40. package/lib/icon/icon.d.ts +1 -3
  41. package/lib/popup/index.d.ts +4 -0
  42. package/lib/popup/popup.d.ts +29 -0
  43. package/lib/popup/popup.template.d.ts +4 -0
  44. package/lib/progress/index.d.ts +2 -0
  45. package/lib/progress/progress.d.ts +9 -0
  46. package/lib/progress/progress.template.d.ts +5 -0
  47. package/lib/progress-ring/index.d.ts +2 -0
  48. package/lib/progress-ring/progress-ring.d.ts +6 -0
  49. package/lib/progress-ring/progress-ring.template.d.ts +4 -0
  50. package/lib/side-drawer/index.d.ts +2 -0
  51. package/lib/side-drawer/side-drawer.d.ts +12 -0
  52. package/lib/side-drawer/side-drawer.template.d.ts +4 -0
  53. package/lib/sidenav-item/sidenav-item.d.ts +4 -5
  54. package/lib/text/index.d.ts +2 -0
  55. package/lib/text/text.d.ts +10 -0
  56. package/lib/text/text.template.d.ts +4 -0
  57. package/lib/text-anchor/text-anchor.d.ts +3 -0
  58. package/lib/tooltip/index.d.ts +3 -0
  59. package/lib/tooltip/tooltip.d.ts +10 -0
  60. package/lib/tooltip/tooltip.template.d.ts +4 -0
  61. package/package.json +9 -5
  62. package/popup/index.js +2087 -0
  63. package/progress/index.js +98 -0
  64. package/progress-ring/index.js +76 -0
  65. package/shared/_has.js +58 -0
  66. package/shared/affix.js +10 -25
  67. package/shared/anchor.js +3 -3
  68. package/shared/aria-global.js +20 -20
  69. package/shared/base-progress.js +65 -0
  70. package/shared/breadcrumb-item.js +25 -0
  71. package/shared/es.object.assign.js +68 -0
  72. package/shared/icon.js +1393 -0
  73. package/shared/index.js +4918 -1427
  74. package/shared/index2.js +15 -4905
  75. package/shared/patterns/affix.d.ts +3 -4
  76. package/shared/slotted.js +119 -0
  77. package/shared/text-anchor.js +21 -0
  78. package/shared/text-anchor.template.js +14 -19
  79. package/shared/web.dom-collections.iterator.js +639 -639
  80. package/shared/when.js +15 -0
  81. package/side-drawer/index.js +103 -0
  82. package/sidenav-item/index.js +15 -56
  83. package/styles/themes/dark.css +4 -4
  84. package/styles/themes/light.css +4 -4
  85. package/text/index.js +45 -0
  86. package/text-anchor/index.js +6 -2
  87. package/tooltip/index.js +73 -0
  88. package/shared/index3.js +0 -21
package/shared/index2.js CHANGED
@@ -1,4911 +1,21 @@
1
- /**
2
- * A reference to globalThis, with support
3
- * for browsers that don't yet support the spec.
4
- * @public
5
- */
6
- const $global = (function () {
7
- if (typeof globalThis !== "undefined") {
8
- // We're running in a modern environment.
9
- return globalThis;
10
- }
11
- if (typeof global !== "undefined") {
12
- // We're running in NodeJS
13
- return global;
14
- }
15
- if (typeof self !== "undefined") {
16
- // We're running in a worker.
17
- return self;
18
- }
19
- if (typeof window !== "undefined") {
20
- // We're running in the browser's main thread.
21
- return window;
22
- }
23
- try {
24
- // Hopefully we never get here...
25
- // Not all environments allow eval and Function. Use only as a last resort:
26
- // eslint-disable-next-line no-new-func
27
- return new Function("return this")();
28
- }
29
- catch (_a) {
30
- // If all fails, give up and create an object.
31
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
32
- return {};
33
- }
34
- })();
35
- // API-only Polyfill for trustedTypes
36
- if ($global.trustedTypes === void 0) {
37
- $global.trustedTypes = { createPolicy: (n, r) => r };
38
- }
39
- /**
40
- * A readonly, empty array.
41
- * @remarks
42
- * Typically returned by APIs that return arrays when there are
43
- * no actual items to return.
44
- * @internal
45
- */
46
- const emptyArray = Object.freeze([]);
1
+ import { F as FoundationElement, h as html, d as designSystem } from './index.js';
2
+ import { s as styleInject } from './style-inject.es.js';
47
3
 
48
- const updateQueue = [];
49
- /* eslint-disable */
50
- const fastHTMLPolicy = $global.trustedTypes.createPolicy("fast-html", {
51
- createHTML: html => html,
52
- });
53
- /* eslint-enable */
54
- let htmlPolicy = fastHTMLPolicy;
55
- // We use a queue so we can ensure errors are thrown in order.
56
- const pendingErrors = [];
57
- function throwFirstError() {
58
- if (pendingErrors.length) {
59
- throw pendingErrors.shift();
60
- }
61
- }
62
- function tryRunTask(task) {
63
- try {
64
- task.call();
65
- }
66
- catch (error) {
67
- pendingErrors.push(error);
68
- setTimeout(throwFirstError, 0);
69
- }
70
- }
71
- const marker = `fast-${Math.random().toString(36).substring(2, 8)}`;
72
- /** @internal */
73
- const _interpolationStart = `${marker}{`;
74
- /** @internal */
75
- const _interpolationEnd = `}${marker}`;
76
- /**
77
- * Common DOM APIs.
78
- * @public
79
- */
80
- const DOM = Object.freeze({
81
- /**
82
- * Indicates whether the DOM supports the adoptedStyleSheets feature.
83
- */
84
- supportsAdoptedStyleSheets: Array.isArray(document.adoptedStyleSheets) &&
85
- "replace" in CSSStyleSheet.prototype,
86
- /**
87
- * Sets the HTML trusted types policy used by the templating engine.
88
- * @param policy - The policy to set for HTML.
89
- * @remarks
90
- * This API can only be called once, for security reasons. It should be
91
- * called by the application developer at the start of their program.
92
- */
93
- setHTMLPolicy(policy) {
94
- if (htmlPolicy !== fastHTMLPolicy) {
95
- throw new Error("The HTML policy can only be set once.");
96
- }
97
- htmlPolicy = policy;
98
- },
99
- /**
100
- * Turns a string into trusted HTML using the configured trusted types policy.
101
- * @param html - The string to turn into trusted HTML.
102
- * @remarks
103
- * Used internally by the template engine when creating templates
104
- * and setting innerHTML.
105
- */
106
- createHTML(html) {
107
- return htmlPolicy.createHTML(html);
108
- },
109
- /**
110
- * Determines if the provided node is a template marker used by the runtime.
111
- * @param node - The node to test.
112
- */
113
- isMarker(node) {
114
- return node && node.nodeType === 8 && node.data.startsWith(marker);
115
- },
116
- /**
117
- * Given a marker node, extract the {@link HTMLDirective} index from the placeholder.
118
- * @param node - The marker node to extract the index from.
119
- */
120
- extractDirectiveIndexFromMarker(node) {
121
- return parseInt(node.data.replace(`${marker}:`, ""));
122
- },
123
- /**
124
- * Creates a placeholder string suitable for marking out a location *within*
125
- * an attribute value or HTML content.
126
- * @param index - The directive index to create the placeholder for.
127
- * @remarks
128
- * Used internally by binding directives.
129
- */
130
- createInterpolationPlaceholder(index) {
131
- return `${_interpolationStart}${index}${_interpolationEnd}`;
132
- },
133
- /**
134
- * Creates a placeholder that manifests itself as an attribute on an
135
- * element.
136
- * @param attributeName - The name of the custom attribute.
137
- * @param index - The directive index to create the placeholder for.
138
- * @remarks
139
- * Used internally by attribute directives such as `ref`, `slotted`, and `children`.
140
- */
141
- createCustomAttributePlaceholder(attributeName, index) {
142
- return `${attributeName}="${this.createInterpolationPlaceholder(index)}"`;
143
- },
144
- /**
145
- * Creates a placeholder that manifests itself as a marker within the DOM structure.
146
- * @param index - The directive index to create the placeholder for.
147
- * @remarks
148
- * Used internally by structural directives such as `repeat`.
149
- */
150
- createBlockPlaceholder(index) {
151
- return `<!--${marker}:${index}-->`;
152
- },
153
- /**
154
- * Schedules DOM update work in the next async batch.
155
- * @param callable - The callable function or object to queue.
156
- */
157
- queueUpdate(callable) {
158
- if (updateQueue.length < 1) {
159
- window.requestAnimationFrame(DOM.processUpdates);
160
- }
161
- updateQueue.push(callable);
162
- },
163
- /**
164
- * Immediately processes all work previously scheduled
165
- * through queueUpdate.
166
- * @remarks
167
- * This also forces nextUpdate promises
168
- * to resolve.
169
- */
170
- processUpdates() {
171
- const capacity = 1024;
172
- let index = 0;
173
- while (index < updateQueue.length) {
174
- tryRunTask(updateQueue[index]);
175
- index++;
176
- // Prevent leaking memory for long chains of recursive calls to `DOM.queueUpdate`.
177
- // If we call `DOM.queueUpdate` within a task scheduled by `DOM.queueUpdate`, the queue will
178
- // grow, but to avoid an O(n) walk for every task we execute, we don't
179
- // shift tasks off the queue after they have been executed.
180
- // Instead, we periodically shift 1024 tasks off the queue.
181
- if (index > capacity) {
182
- // Manually shift all values starting at the index back to the
183
- // beginning of the queue.
184
- for (let scan = 0, newLength = updateQueue.length - index; scan < newLength; scan++) {
185
- updateQueue[scan] = updateQueue[scan + index];
186
- }
187
- updateQueue.length -= index;
188
- index = 0;
189
- }
190
- }
191
- updateQueue.length = 0;
192
- },
193
- /**
194
- * Resolves with the next DOM update.
195
- */
196
- nextUpdate() {
197
- return new Promise((resolve) => {
198
- DOM.queueUpdate(resolve);
199
- });
200
- },
201
- /**
202
- * Sets an attribute value on an element.
203
- * @param element - The element to set the attribute value on.
204
- * @param attributeName - The attribute name to set.
205
- * @param value - The value of the attribute to set.
206
- * @remarks
207
- * If the value is `null` or `undefined`, the attribute is removed, otherwise
208
- * it is set to the provided value using the standard `setAttribute` API.
209
- */
210
- setAttribute(element, attributeName, value) {
211
- if (value === null || value === undefined) {
212
- element.removeAttribute(attributeName);
213
- }
214
- else {
215
- element.setAttribute(attributeName, value);
216
- }
217
- },
218
- /**
219
- * Sets a boolean attribute value.
220
- * @param element - The element to set the boolean attribute value on.
221
- * @param attributeName - The attribute name to set.
222
- * @param value - The value of the attribute to set.
223
- * @remarks
224
- * If the value is true, the attribute is added; otherwise it is removed.
225
- */
226
- setBooleanAttribute(element, attributeName, value) {
227
- value
228
- ? element.setAttribute(attributeName, "")
229
- : element.removeAttribute(attributeName);
230
- },
231
- /**
232
- * Removes all the child nodes of the provided parent node.
233
- * @param parent - The node to remove the children from.
234
- */
235
- removeChildNodes(parent) {
236
- for (let child = parent.firstChild; child !== null; child = parent.firstChild) {
237
- parent.removeChild(child);
238
- }
239
- },
240
- /**
241
- * Creates a TreeWalker configured to walk a template fragment.
242
- * @param fragment - The fragment to walk.
243
- */
244
- createTemplateWalker(fragment) {
245
- return document.createTreeWalker(fragment, 133, // element, text, comment
246
- null, false);
247
- },
248
- });
249
-
250
- function spilloverSubscribe(subscriber) {
251
- const spillover = this.spillover;
252
- const index = spillover.indexOf(subscriber);
253
- if (index === -1) {
254
- spillover.push(subscriber);
255
- }
256
- }
257
- function spilloverUnsubscribe(subscriber) {
258
- const spillover = this.spillover;
259
- const index = spillover.indexOf(subscriber);
260
- if (index !== -1) {
261
- spillover.splice(index, 1);
262
- }
263
- }
264
- function spilloverNotifySubscribers(args) {
265
- const spillover = this.spillover;
266
- const source = this.source;
267
- for (let i = 0, ii = spillover.length; i < ii; ++i) {
268
- spillover[i].handleChange(source, args);
269
- }
270
- }
271
- function spilloverHas(subscriber) {
272
- return this.spillover.indexOf(subscriber) !== -1;
273
- }
274
- /**
275
- * An implementation of {@link Notifier} that efficiently keeps track of
276
- * subscribers interested in a specific change notification on an
277
- * observable source.
278
- *
279
- * @remarks
280
- * This set is optimized for the most common scenario of 1 or 2 subscribers.
281
- * With this in mind, it can store a subscriber in an internal field, allowing it to avoid Array#push operations.
282
- * If the set ever exceeds two subscribers, it upgrades to an array automatically.
283
- * @public
284
- */
285
- class SubscriberSet {
286
- /**
287
- * Creates an instance of SubscriberSet for the specified source.
288
- * @param source - The object source that subscribers will receive notifications from.
289
- * @param initialSubscriber - An initial subscriber to changes.
290
- */
291
- constructor(source, initialSubscriber) {
292
- this.sub1 = void 0;
293
- this.sub2 = void 0;
294
- this.spillover = void 0;
295
- this.source = source;
296
- this.sub1 = initialSubscriber;
297
- }
298
- /**
299
- * Checks whether the provided subscriber has been added to this set.
300
- * @param subscriber - The subscriber to test for inclusion in this set.
301
- */
302
- has(subscriber) {
303
- return this.sub1 === subscriber || this.sub2 === subscriber;
304
- }
305
- /**
306
- * Subscribes to notification of changes in an object's state.
307
- * @param subscriber - The object that is subscribing for change notification.
308
- */
309
- subscribe(subscriber) {
310
- if (this.has(subscriber)) {
311
- return;
312
- }
313
- if (this.sub1 === void 0) {
314
- this.sub1 = subscriber;
315
- return;
316
- }
317
- if (this.sub2 === void 0) {
318
- this.sub2 = subscriber;
319
- return;
320
- }
321
- this.spillover = [this.sub1, this.sub2, subscriber];
322
- this.subscribe = spilloverSubscribe;
323
- this.unsubscribe = spilloverUnsubscribe;
324
- this.notify = spilloverNotifySubscribers;
325
- this.has = spilloverHas;
326
- this.sub1 = void 0;
327
- this.sub2 = void 0;
328
- }
329
- /**
330
- * Unsubscribes from notification of changes in an object's state.
331
- * @param subscriber - The object that is unsubscribing from change notification.
332
- */
333
- unsubscribe(subscriber) {
334
- if (this.sub1 === subscriber) {
335
- this.sub1 = void 0;
336
- }
337
- else if (this.sub2 === subscriber) {
338
- this.sub2 = void 0;
339
- }
340
- }
341
- /**
342
- * Notifies all subscribers.
343
- * @param args - Data passed along to subscribers during notification.
344
- */
345
- notify(args) {
346
- const sub1 = this.sub1;
347
- const sub2 = this.sub2;
348
- const source = this.source;
349
- if (sub1 !== void 0) {
350
- sub1.handleChange(source, args);
351
- }
352
- if (sub2 !== void 0) {
353
- sub2.handleChange(source, args);
354
- }
355
- }
356
- }
357
- /**
358
- * An implementation of Notifier that allows subscribers to be notified
359
- * of individual property changes on an object.
360
- * @public
361
- */
362
- class PropertyChangeNotifier {
363
- /**
364
- * Creates an instance of PropertyChangeNotifier for the specified source.
365
- * @param source - The object source that subscribers will receive notifications from.
366
- */
367
- constructor(source) {
368
- this.subscribers = {};
369
- this.sourceSubscribers = null;
370
- this.source = source;
371
- }
372
- /**
373
- * Notifies all subscribers, based on the specified property.
374
- * @param propertyName - The property name, passed along to subscribers during notification.
375
- */
376
- notify(propertyName) {
377
- var _a;
378
- const subscribers = this.subscribers[propertyName];
379
- if (subscribers !== void 0) {
380
- subscribers.notify(propertyName);
381
- }
382
- (_a = this.sourceSubscribers) === null || _a === void 0 ? void 0 : _a.notify(propertyName);
383
- }
384
- /**
385
- * Subscribes to notification of changes in an object's state.
386
- * @param subscriber - The object that is subscribing for change notification.
387
- * @param propertyToWatch - The name of the property that the subscriber is interested in watching for changes.
388
- */
389
- subscribe(subscriber, propertyToWatch) {
390
- var _a;
391
- if (propertyToWatch) {
392
- let subscribers = this.subscribers[propertyToWatch];
393
- if (subscribers === void 0) {
394
- this.subscribers[propertyToWatch] = subscribers = new SubscriberSet(this.source);
395
- }
396
- subscribers.subscribe(subscriber);
397
- }
398
- else {
399
- this.sourceSubscribers = (_a = this.sourceSubscribers) !== null && _a !== void 0 ? _a : new SubscriberSet(this.source);
400
- this.sourceSubscribers.subscribe(subscriber);
401
- }
402
- }
403
- /**
404
- * Unsubscribes from notification of changes in an object's state.
405
- * @param subscriber - The object that is unsubscribing from change notification.
406
- * @param propertyToUnwatch - The name of the property that the subscriber is no longer interested in watching.
407
- */
408
- unsubscribe(subscriber, propertyToUnwatch) {
409
- var _a;
410
- if (propertyToUnwatch) {
411
- const subscribers = this.subscribers[propertyToUnwatch];
412
- if (subscribers !== void 0) {
413
- subscribers.unsubscribe(subscriber);
414
- }
415
- }
416
- else {
417
- (_a = this.sourceSubscribers) === null || _a === void 0 ? void 0 : _a.unsubscribe(subscriber);
418
- }
419
- }
420
- }
421
-
422
- const volatileRegex = /(:|&&|\|\||if)/;
423
- const notifierLookup = new WeakMap();
424
- const accessorLookup = new WeakMap();
425
- let watcher = void 0;
426
- let createArrayObserver = (array) => {
427
- throw new Error("Must call enableArrayObservation before observing arrays.");
428
- };
429
- class DefaultObservableAccessor {
430
- constructor(name) {
431
- this.name = name;
432
- this.field = `_${name}`;
433
- this.callback = `${name}Changed`;
434
- }
435
- getValue(source) {
436
- if (watcher !== void 0) {
437
- watcher.watch(source, this.name);
438
- }
439
- return source[this.field];
440
- }
441
- setValue(source, newValue) {
442
- const field = this.field;
443
- const oldValue = source[field];
444
- if (oldValue !== newValue) {
445
- source[field] = newValue;
446
- const callback = source[this.callback];
447
- if (typeof callback === "function") {
448
- callback.call(source, oldValue, newValue);
449
- }
450
- /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
451
- getNotifier(source).notify(this.name);
452
- }
453
- }
454
- }
455
- /**
456
- * Common Observable APIs.
457
- * @public
458
- */
459
- const Observable = Object.freeze({
460
- /**
461
- * @internal
462
- * @param factory - The factory used to create array observers.
463
- */
464
- setArrayObserverFactory(factory) {
465
- createArrayObserver = factory;
466
- },
467
- /**
468
- * Gets a notifier for an object or Array.
469
- * @param source - The object or Array to get the notifier for.
470
- */
471
- getNotifier(source) {
472
- let found = source.$fastController || notifierLookup.get(source);
473
- if (found === void 0) {
474
- if (Array.isArray(source)) {
475
- found = createArrayObserver(source);
476
- }
477
- else {
478
- notifierLookup.set(source, (found = new PropertyChangeNotifier(source)));
479
- }
480
- }
481
- return found;
482
- },
483
- /**
484
- * Records a property change for a source object.
485
- * @param source - The object to record the change against.
486
- * @param propertyName - The property to track as changed.
487
- */
488
- track(source, propertyName) {
489
- if (watcher !== void 0) {
490
- watcher.watch(source, propertyName);
491
- }
492
- },
493
- /**
494
- * Notifies watchers that the currently executing property getter or function is volatile
495
- * with respect to its observable dependencies.
496
- */
497
- trackVolatile() {
498
- if (watcher !== void 0) {
499
- watcher.needsRefresh = true;
500
- }
501
- },
502
- /**
503
- * Notifies subscribers of a source object of changes.
504
- * @param source - the object to notify of changes.
505
- * @param args - The change args to pass to subscribers.
506
- */
507
- notify(source, args) {
508
- /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
509
- getNotifier(source).notify(args);
510
- },
511
- /**
512
- * Defines an observable property on an object or prototype.
513
- * @param target - The target object to define the observable on.
514
- * @param nameOrAccessor - The name of the property to define as observable;
515
- * or a custom accessor that specifies the property name and accessor implementation.
516
- */
517
- defineProperty(target, nameOrAccessor) {
518
- if (typeof nameOrAccessor === "string") {
519
- nameOrAccessor = new DefaultObservableAccessor(nameOrAccessor);
520
- }
521
- this.getAccessors(target).push(nameOrAccessor);
522
- Reflect.defineProperty(target, nameOrAccessor.name, {
523
- enumerable: true,
524
- get: function () {
525
- return nameOrAccessor.getValue(this);
526
- },
527
- set: function (newValue) {
528
- nameOrAccessor.setValue(this, newValue);
529
- },
530
- });
531
- },
532
- /**
533
- * Finds all the observable accessors defined on the target,
534
- * including its prototype chain.
535
- * @param target - The target object to search for accessor on.
536
- */
537
- getAccessors(target) {
538
- let accessors = accessorLookup.get(target);
539
- if (accessors === void 0) {
540
- let currentTarget = Reflect.getPrototypeOf(target);
541
- while (accessors === void 0 && currentTarget !== null) {
542
- accessors = accessorLookup.get(currentTarget);
543
- currentTarget = Reflect.getPrototypeOf(currentTarget);
544
- }
545
- if (accessors === void 0) {
546
- accessors = [];
547
- }
548
- else {
549
- accessors = accessors.slice(0);
550
- }
551
- accessorLookup.set(target, accessors);
552
- }
553
- return accessors;
554
- },
555
- /**
556
- * Creates a {@link BindingObserver} that can watch the
557
- * provided {@link Binding} for changes.
558
- * @param binding - The binding to observe.
559
- * @param initialSubscriber - An initial subscriber to changes in the binding value.
560
- * @param isVolatileBinding - Indicates whether the binding's dependency list must be re-evaluated on every value evaluation.
561
- */
562
- binding(binding, initialSubscriber, isVolatileBinding = this.isVolatileBinding(binding)) {
563
- /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
564
- return new BindingObserverImplementation(binding, initialSubscriber, isVolatileBinding);
565
- },
566
- /**
567
- * Determines whether a binding expression is volatile and needs to have its dependency list re-evaluated
568
- * on every evaluation of the value.
569
- * @param binding - The binding to inspect.
570
- */
571
- isVolatileBinding(binding) {
572
- return volatileRegex.test(binding.toString());
573
- },
574
- });
575
- const getNotifier = Observable.getNotifier;
576
- Observable.trackVolatile;
577
- const queueUpdate = DOM.queueUpdate;
578
- /**
579
- * Decorator: Defines an observable property on the target.
580
- * @param target - The target to define the observable on.
581
- * @param nameOrAccessor - The property name or accessor to define the observable as.
582
- * @public
583
- */
584
- function observable(target, nameOrAccessor) {
585
- Observable.defineProperty(target, nameOrAccessor);
586
- }
587
- let currentEvent = null;
588
- /**
589
- * @param event - The event to set as current for the context.
590
- * @internal
591
- */
592
- function setCurrentEvent(event) {
593
- currentEvent = event;
594
- }
595
- /**
596
- * Provides additional contextual information available to behaviors and expressions.
597
- * @public
598
- */
599
- class ExecutionContext {
600
- constructor() {
601
- /**
602
- * The index of the current item within a repeat context.
603
- */
604
- this.index = 0;
605
- /**
606
- * The length of the current collection within a repeat context.
607
- */
608
- this.length = 0;
609
- /**
610
- * The parent data object within a repeat context.
611
- */
612
- this.parent = null;
613
- /**
614
- * The parent execution context when in nested context scenarios.
615
- */
616
- this.parentContext = null;
617
- }
618
- /**
619
- * The current event within an event handler.
620
- */
621
- get event() {
622
- return currentEvent;
623
- }
624
- /**
625
- * Indicates whether the current item within a repeat context
626
- * has an even index.
627
- */
628
- get isEven() {
629
- return this.index % 2 === 0;
630
- }
631
- /**
632
- * Indicates whether the current item within a repeat context
633
- * has an odd index.
634
- */
635
- get isOdd() {
636
- return this.index % 2 !== 0;
637
- }
638
- /**
639
- * Indicates whether the current item within a repeat context
640
- * is the first item in the collection.
641
- */
642
- get isFirst() {
643
- return this.index === 0;
644
- }
645
- /**
646
- * Indicates whether the current item within a repeat context
647
- * is somewhere in the middle of the collection.
648
- */
649
- get isInMiddle() {
650
- return !this.isFirst && !this.isLast;
651
- }
652
- /**
653
- * Indicates whether the current item within a repeat context
654
- * is the last item in the collection.
655
- */
656
- get isLast() {
657
- return this.index === this.length - 1;
658
- }
659
- }
660
- Observable.defineProperty(ExecutionContext.prototype, "index");
661
- Observable.defineProperty(ExecutionContext.prototype, "length");
662
- /**
663
- * The default execution context used in binding expressions.
664
- * @public
665
- */
666
- const defaultExecutionContext = Object.seal(new ExecutionContext());
667
- class BindingObserverImplementation extends SubscriberSet {
668
- constructor(binding, initialSubscriber, isVolatileBinding = false) {
669
- super(binding, initialSubscriber);
670
- this.binding = binding;
671
- this.isVolatileBinding = isVolatileBinding;
672
- this.needsRefresh = true;
673
- this.needsQueue = true;
674
- this.first = this;
675
- this.last = null;
676
- this.propertySource = void 0;
677
- this.propertyName = void 0;
678
- this.notifier = void 0;
679
- this.next = void 0;
680
- }
681
- observe(source, context) {
682
- if (this.needsRefresh && this.last !== null) {
683
- this.disconnect();
684
- }
685
- const previousWatcher = watcher;
686
- watcher = this.needsRefresh ? this : void 0;
687
- this.needsRefresh = this.isVolatileBinding;
688
- const result = this.binding(source, context);
689
- watcher = previousWatcher;
690
- return result;
691
- }
692
- disconnect() {
693
- if (this.last !== null) {
694
- let current = this.first;
695
- while (current !== void 0) {
696
- current.notifier.unsubscribe(this, current.propertyName);
697
- current = current.next;
698
- }
699
- this.last = null;
700
- this.needsRefresh = this.needsQueue = true;
701
- }
702
- }
703
- /** @internal */
704
- watch(propertySource, propertyName) {
705
- const prev = this.last;
706
- const notifier = getNotifier(propertySource);
707
- const current = prev === null ? this.first : {};
708
- current.propertySource = propertySource;
709
- current.propertyName = propertyName;
710
- current.notifier = notifier;
711
- notifier.subscribe(this, propertyName);
712
- if (prev !== null) {
713
- if (!this.needsRefresh) {
714
- // Declaring the variable prior to assignment below circumvents
715
- // a bug in Angular's optimization process causing infinite recursion
716
- // of this watch() method. Details https://github.com/microsoft/fast/issues/4969
717
- let prevValue;
718
- watcher = void 0;
719
- /* eslint-disable-next-line */
720
- prevValue = prev.propertySource[prev.propertyName];
721
- watcher = this;
722
- if (propertySource === prevValue) {
723
- this.needsRefresh = true;
724
- }
725
- }
726
- prev.next = current;
727
- }
728
- this.last = current;
729
- }
730
- /** @internal */
731
- handleChange() {
732
- if (this.needsQueue) {
733
- this.needsQueue = false;
734
- queueUpdate(this);
735
- }
736
- }
737
- /** @internal */
738
- call() {
739
- if (this.last !== null) {
740
- this.needsQueue = true;
741
- this.notify(this);
742
- }
743
- }
744
- records() {
745
- let next = this.first;
746
- return {
747
- next: () => {
748
- const current = next;
749
- if (current === undefined) {
750
- return { value: void 0, done: true };
751
- }
752
- else {
753
- next = next.next;
754
- return {
755
- value: current,
756
- done: false,
757
- };
758
- }
759
- },
760
- [Symbol.iterator]: function () {
761
- return this;
762
- },
763
- };
764
- }
765
- }
766
-
767
- /**
768
- * Instructs the template engine to apply behavior to a node.
769
- * @public
770
- */
771
- class HTMLDirective {
772
- constructor() {
773
- /**
774
- * The index of the DOM node to which the created behavior will apply.
775
- */
776
- this.targetIndex = 0;
777
- }
778
- }
779
- /**
780
- * A {@link HTMLDirective} that targets a named attribute or property on a node.
781
- * @public
782
- */
783
- class TargetedHTMLDirective extends HTMLDirective {
784
- constructor() {
785
- super(...arguments);
786
- /**
787
- * Creates a placeholder string based on the directive's index within the template.
788
- * @param index - The index of the directive within the template.
789
- */
790
- this.createPlaceholder = DOM.createInterpolationPlaceholder;
791
- }
792
- }
793
- /**
794
- * A directive that attaches special behavior to an element via a custom attribute.
795
- * @public
796
- */
797
- class AttachedBehaviorHTMLDirective extends HTMLDirective {
798
- /**
799
- *
800
- * @param name - The name of the behavior; used as a custom attribute on the element.
801
- * @param behavior - The behavior to instantiate and attach to the element.
802
- * @param options - Options to pass to the behavior during creation.
803
- */
804
- constructor(name, behavior, options) {
805
- super();
806
- this.name = name;
807
- this.behavior = behavior;
808
- this.options = options;
809
- }
810
- /**
811
- * Creates a placeholder string based on the directive's index within the template.
812
- * @param index - The index of the directive within the template.
813
- * @remarks
814
- * Creates a custom attribute placeholder.
815
- */
816
- createPlaceholder(index) {
817
- return DOM.createCustomAttributePlaceholder(this.name, index);
818
- }
819
- /**
820
- * Creates a behavior for the provided target node.
821
- * @param target - The node instance to create the behavior for.
822
- * @remarks
823
- * Creates an instance of the `behavior` type this directive was constructed with
824
- * and passes the target and options to that `behavior`'s constructor.
825
- */
826
- createBehavior(target) {
827
- return new this.behavior(target, this.options);
828
- }
829
- }
830
-
831
- function normalBind(source, context) {
832
- this.source = source;
833
- this.context = context;
834
- if (this.bindingObserver === null) {
835
- this.bindingObserver = Observable.binding(this.binding, this, this.isBindingVolatile);
836
- }
837
- this.updateTarget(this.bindingObserver.observe(source, context));
838
- }
839
- function triggerBind(source, context) {
840
- this.source = source;
841
- this.context = context;
842
- this.target.addEventListener(this.targetName, this);
843
- }
844
- function normalUnbind() {
845
- this.bindingObserver.disconnect();
846
- this.source = null;
847
- this.context = null;
848
- }
849
- function contentUnbind() {
850
- this.bindingObserver.disconnect();
851
- this.source = null;
852
- this.context = null;
853
- const view = this.target.$fastView;
854
- if (view !== void 0 && view.isComposed) {
855
- view.unbind();
856
- view.needsBindOnly = true;
857
- }
858
- }
859
- function triggerUnbind() {
860
- this.target.removeEventListener(this.targetName, this);
861
- this.source = null;
862
- this.context = null;
863
- }
864
- function updateAttributeTarget(value) {
865
- DOM.setAttribute(this.target, this.targetName, value);
866
- }
867
- function updateBooleanAttributeTarget(value) {
868
- DOM.setBooleanAttribute(this.target, this.targetName, value);
869
- }
870
- function updateContentTarget(value) {
871
- // If there's no actual value, then this equates to the
872
- // empty string for the purposes of content bindings.
873
- if (value === null || value === undefined) {
874
- value = "";
875
- }
876
- // If the value has a "create" method, then it's a template-like.
877
- if (value.create) {
878
- this.target.textContent = "";
879
- let view = this.target.$fastView;
880
- // If there's no previous view that we might be able to
881
- // reuse then create a new view from the template.
882
- if (view === void 0) {
883
- view = value.create();
884
- }
885
- else {
886
- // If there is a previous view, but it wasn't created
887
- // from the same template as the new value, then we
888
- // need to remove the old view if it's still in the DOM
889
- // and create a new view from the template.
890
- if (this.target.$fastTemplate !== value) {
891
- if (view.isComposed) {
892
- view.remove();
893
- view.unbind();
894
- }
895
- view = value.create();
896
- }
897
- }
898
- // It's possible that the value is the same as the previous template
899
- // and that there's actually no need to compose it.
900
- if (!view.isComposed) {
901
- view.isComposed = true;
902
- view.bind(this.source, this.context);
903
- view.insertBefore(this.target);
904
- this.target.$fastView = view;
905
- this.target.$fastTemplate = value;
906
- }
907
- else if (view.needsBindOnly) {
908
- view.needsBindOnly = false;
909
- view.bind(this.source, this.context);
910
- }
911
- }
912
- else {
913
- const view = this.target.$fastView;
914
- // If there is a view and it's currently composed into
915
- // the DOM, then we need to remove it.
916
- if (view !== void 0 && view.isComposed) {
917
- view.isComposed = false;
918
- view.remove();
919
- if (view.needsBindOnly) {
920
- view.needsBindOnly = false;
921
- }
922
- else {
923
- view.unbind();
924
- }
925
- }
926
- this.target.textContent = value;
927
- }
928
- }
929
- function updatePropertyTarget(value) {
930
- this.target[this.targetName] = value;
931
- }
932
- function updateClassTarget(value) {
933
- const classVersions = this.classVersions || Object.create(null);
934
- const target = this.target;
935
- let version = this.version || 0;
936
- // Add the classes, tracking the version at which they were added.
937
- if (value !== null && value !== undefined && value.length) {
938
- const names = value.split(/\s+/);
939
- for (let i = 0, ii = names.length; i < ii; ++i) {
940
- const currentName = names[i];
941
- if (currentName === "") {
942
- continue;
943
- }
944
- classVersions[currentName] = version;
945
- target.classList.add(currentName);
946
- }
947
- }
948
- this.classVersions = classVersions;
949
- this.version = version + 1;
950
- // If this is the first call to add classes, there's no need to remove old ones.
951
- if (version === 0) {
952
- return;
953
- }
954
- // Remove classes from the previous version.
955
- version -= 1;
956
- for (const name in classVersions) {
957
- if (classVersions[name] === version) {
958
- target.classList.remove(name);
959
- }
960
- }
961
- }
962
- /**
963
- * A directive that configures data binding to element content and attributes.
964
- * @public
965
- */
966
- class HTMLBindingDirective extends TargetedHTMLDirective {
967
- /**
968
- * Creates an instance of BindingDirective.
969
- * @param binding - A binding that returns the data used to update the DOM.
970
- */
971
- constructor(binding) {
972
- super();
973
- this.binding = binding;
974
- this.bind = normalBind;
975
- this.unbind = normalUnbind;
976
- this.updateTarget = updateAttributeTarget;
977
- this.isBindingVolatile = Observable.isVolatileBinding(this.binding);
978
- }
979
- /**
980
- * Gets/sets the name of the attribute or property that this
981
- * binding is targeting.
982
- */
983
- get targetName() {
984
- return this.originalTargetName;
985
- }
986
- set targetName(value) {
987
- this.originalTargetName = value;
988
- if (value === void 0) {
989
- return;
990
- }
991
- switch (value[0]) {
992
- case ":":
993
- this.cleanedTargetName = value.substr(1);
994
- this.updateTarget = updatePropertyTarget;
995
- if (this.cleanedTargetName === "innerHTML") {
996
- const binding = this.binding;
997
- this.binding = (s, c) => DOM.createHTML(binding(s, c));
998
- }
999
- break;
1000
- case "?":
1001
- this.cleanedTargetName = value.substr(1);
1002
- this.updateTarget = updateBooleanAttributeTarget;
1003
- break;
1004
- case "@":
1005
- this.cleanedTargetName = value.substr(1);
1006
- this.bind = triggerBind;
1007
- this.unbind = triggerUnbind;
1008
- break;
1009
- default:
1010
- this.cleanedTargetName = value;
1011
- if (value === "class") {
1012
- this.updateTarget = updateClassTarget;
1013
- }
1014
- break;
1015
- }
1016
- }
1017
- /**
1018
- * Makes this binding target the content of an element rather than
1019
- * a particular attribute or property.
1020
- */
1021
- targetAtContent() {
1022
- this.updateTarget = updateContentTarget;
1023
- this.unbind = contentUnbind;
1024
- }
1025
- /**
1026
- * Creates the runtime BindingBehavior instance based on the configuration
1027
- * information stored in the BindingDirective.
1028
- * @param target - The target node that the binding behavior should attach to.
1029
- */
1030
- createBehavior(target) {
1031
- /* eslint-disable-next-line @typescript-eslint/no-use-before-define */
1032
- return new BindingBehavior(target, this.binding, this.isBindingVolatile, this.bind, this.unbind, this.updateTarget, this.cleanedTargetName);
1033
- }
1034
- }
1035
- /**
1036
- * A behavior that updates content and attributes based on a configured
1037
- * BindingDirective.
1038
- * @public
1039
- */
1040
- class BindingBehavior {
1041
- /**
1042
- * Creates an instance of BindingBehavior.
1043
- * @param target - The target of the data updates.
1044
- * @param binding - The binding that returns the latest value for an update.
1045
- * @param isBindingVolatile - Indicates whether the binding has volatile dependencies.
1046
- * @param bind - The operation to perform during binding.
1047
- * @param unbind - The operation to perform during unbinding.
1048
- * @param updateTarget - The operation to perform when updating.
1049
- * @param targetName - The name of the target attribute or property to update.
1050
- */
1051
- constructor(target, binding, isBindingVolatile, bind, unbind, updateTarget, targetName) {
1052
- /** @internal */
1053
- this.source = null;
1054
- /** @internal */
1055
- this.context = null;
1056
- /** @internal */
1057
- this.bindingObserver = null;
1058
- this.target = target;
1059
- this.binding = binding;
1060
- this.isBindingVolatile = isBindingVolatile;
1061
- this.bind = bind;
1062
- this.unbind = unbind;
1063
- this.updateTarget = updateTarget;
1064
- this.targetName = targetName;
1065
- }
1066
- /** @internal */
1067
- handleChange() {
1068
- this.updateTarget(this.bindingObserver.observe(this.source, this.context));
1069
- }
1070
- /** @internal */
1071
- handleEvent(event) {
1072
- setCurrentEvent(event);
1073
- const result = this.binding(this.source, this.context);
1074
- setCurrentEvent(null);
1075
- if (result !== true) {
1076
- event.preventDefault();
1077
- }
1078
- }
1079
- }
1080
-
1081
- let sharedContext = null;
1082
- class CompilationContext {
1083
- addFactory(factory) {
1084
- factory.targetIndex = this.targetIndex;
1085
- this.behaviorFactories.push(factory);
1086
- }
1087
- captureContentBinding(directive) {
1088
- directive.targetAtContent();
1089
- this.addFactory(directive);
1090
- }
1091
- reset() {
1092
- this.behaviorFactories = [];
1093
- this.targetIndex = -1;
1094
- }
1095
- release() {
1096
- sharedContext = this;
1097
- }
1098
- static borrow(directives) {
1099
- const shareable = sharedContext || new CompilationContext();
1100
- shareable.directives = directives;
1101
- shareable.reset();
1102
- sharedContext = null;
1103
- return shareable;
1104
- }
1105
- }
1106
- function createAggregateBinding(parts) {
1107
- if (parts.length === 1) {
1108
- return parts[0];
1109
- }
1110
- let targetName;
1111
- const partCount = parts.length;
1112
- const finalParts = parts.map((x) => {
1113
- if (typeof x === "string") {
1114
- return () => x;
1115
- }
1116
- targetName = x.targetName || targetName;
1117
- return x.binding;
1118
- });
1119
- const binding = (scope, context) => {
1120
- let output = "";
1121
- for (let i = 0; i < partCount; ++i) {
1122
- output += finalParts[i](scope, context);
1123
- }
1124
- return output;
1125
- };
1126
- const directive = new HTMLBindingDirective(binding);
1127
- directive.targetName = targetName;
1128
- return directive;
1129
- }
1130
- const interpolationEndLength = _interpolationEnd.length;
1131
- function parseContent(context, value) {
1132
- const valueParts = value.split(_interpolationStart);
1133
- if (valueParts.length === 1) {
1134
- return null;
1135
- }
1136
- const bindingParts = [];
1137
- for (let i = 0, ii = valueParts.length; i < ii; ++i) {
1138
- const current = valueParts[i];
1139
- const index = current.indexOf(_interpolationEnd);
1140
- let literal;
1141
- if (index === -1) {
1142
- literal = current;
1143
- }
1144
- else {
1145
- const directiveIndex = parseInt(current.substring(0, index));
1146
- bindingParts.push(context.directives[directiveIndex]);
1147
- literal = current.substring(index + interpolationEndLength);
1148
- }
1149
- if (literal !== "") {
1150
- bindingParts.push(literal);
1151
- }
1152
- }
1153
- return bindingParts;
1154
- }
1155
- function compileAttributes(context, node, includeBasicValues = false) {
1156
- const attributes = node.attributes;
1157
- for (let i = 0, ii = attributes.length; i < ii; ++i) {
1158
- const attr = attributes[i];
1159
- const attrValue = attr.value;
1160
- const parseResult = parseContent(context, attrValue);
1161
- let result = null;
1162
- if (parseResult === null) {
1163
- if (includeBasicValues) {
1164
- result = new HTMLBindingDirective(() => attrValue);
1165
- result.targetName = attr.name;
1166
- }
1167
- }
1168
- else {
1169
- result = createAggregateBinding(parseResult);
1170
- }
1171
- if (result !== null) {
1172
- node.removeAttributeNode(attr);
1173
- i--;
1174
- ii--;
1175
- context.addFactory(result);
1176
- }
1177
- }
1178
- }
1179
- function compileContent(context, node, walker) {
1180
- const parseResult = parseContent(context, node.textContent);
1181
- if (parseResult !== null) {
1182
- let lastNode = node;
1183
- for (let i = 0, ii = parseResult.length; i < ii; ++i) {
1184
- const currentPart = parseResult[i];
1185
- const currentNode = i === 0
1186
- ? node
1187
- : lastNode.parentNode.insertBefore(document.createTextNode(""), lastNode.nextSibling);
1188
- if (typeof currentPart === "string") {
1189
- currentNode.textContent = currentPart;
1190
- }
1191
- else {
1192
- currentNode.textContent = " ";
1193
- context.captureContentBinding(currentPart);
1194
- }
1195
- lastNode = currentNode;
1196
- context.targetIndex++;
1197
- if (currentNode !== node) {
1198
- walker.nextNode();
1199
- }
1200
- }
1201
- context.targetIndex--;
1202
- }
1203
- }
1204
- /**
1205
- * Compiles a template and associated directives into a raw compilation
1206
- * result which include a cloneable DocumentFragment and factories capable
1207
- * of attaching runtime behavior to nodes within the fragment.
1208
- * @param template - The template to compile.
1209
- * @param directives - The directives referenced by the template.
1210
- * @remarks
1211
- * The template that is provided for compilation is altered in-place
1212
- * and cannot be compiled again. If the original template must be preserved,
1213
- * it is recommended that you clone the original and pass the clone to this API.
1214
- * @public
1215
- */
1216
- function compileTemplate(template, directives) {
1217
- const fragment = template.content;
1218
- // https://bugs.chromium.org/p/chromium/issues/detail?id=1111864
1219
- document.adoptNode(fragment);
1220
- const context = CompilationContext.borrow(directives);
1221
- compileAttributes(context, template, true);
1222
- const hostBehaviorFactories = context.behaviorFactories;
1223
- context.reset();
1224
- const walker = DOM.createTemplateWalker(fragment);
1225
- let node;
1226
- while ((node = walker.nextNode())) {
1227
- context.targetIndex++;
1228
- switch (node.nodeType) {
1229
- case 1: // element node
1230
- compileAttributes(context, node);
1231
- break;
1232
- case 3: // text node
1233
- compileContent(context, node, walker);
1234
- break;
1235
- case 8: // comment
1236
- if (DOM.isMarker(node)) {
1237
- context.addFactory(directives[DOM.extractDirectiveIndexFromMarker(node)]);
1238
- }
1239
- }
1240
- }
1241
- let targetOffset = 0;
1242
- if (
1243
- // If the first node in a fragment is a marker, that means it's an unstable first node,
1244
- // because something like a when, repeat, etc. could add nodes before the marker.
1245
- // To mitigate this, we insert a stable first node. However, if we insert a node,
1246
- // that will alter the result of the TreeWalker. So, we also need to offset the target index.
1247
- DOM.isMarker(fragment.firstChild) ||
1248
- // Or if there is only one node and a directive, it means the template's content
1249
- // is *only* the directive. In that case, HTMLView.dispose() misses any nodes inserted by
1250
- // the directive. Inserting a new node ensures proper disposal of nodes added by the directive.
1251
- (fragment.childNodes.length === 1 && directives.length)) {
1252
- fragment.insertBefore(document.createComment(""), fragment.firstChild);
1253
- targetOffset = -1;
1254
- }
1255
- const viewBehaviorFactories = context.behaviorFactories;
1256
- context.release();
1257
- return {
1258
- fragment,
1259
- viewBehaviorFactories,
1260
- hostBehaviorFactories,
1261
- targetOffset,
1262
- };
1263
- }
1264
-
1265
- // A singleton Range instance used to efficiently remove ranges of DOM nodes.
1266
- // See the implementation of HTMLView below for further details.
1267
- const range = document.createRange();
1268
- /**
1269
- * The standard View implementation, which also implements ElementView and SyntheticView.
1270
- * @public
1271
- */
1272
- class HTMLView {
1273
- /**
1274
- * Constructs an instance of HTMLView.
1275
- * @param fragment - The html fragment that contains the nodes for this view.
1276
- * @param behaviors - The behaviors to be applied to this view.
1277
- */
1278
- constructor(fragment, behaviors) {
1279
- this.fragment = fragment;
1280
- this.behaviors = behaviors;
1281
- /**
1282
- * The data that the view is bound to.
1283
- */
1284
- this.source = null;
1285
- /**
1286
- * The execution context the view is running within.
1287
- */
1288
- this.context = null;
1289
- this.firstChild = fragment.firstChild;
1290
- this.lastChild = fragment.lastChild;
1291
- }
1292
- /**
1293
- * Appends the view's DOM nodes to the referenced node.
1294
- * @param node - The parent node to append the view's DOM nodes to.
1295
- */
1296
- appendTo(node) {
1297
- node.appendChild(this.fragment);
1298
- }
1299
- /**
1300
- * Inserts the view's DOM nodes before the referenced node.
1301
- * @param node - The node to insert the view's DOM before.
1302
- */
1303
- insertBefore(node) {
1304
- if (this.fragment.hasChildNodes()) {
1305
- node.parentNode.insertBefore(this.fragment, node);
1306
- }
1307
- else {
1308
- const parentNode = node.parentNode;
1309
- const end = this.lastChild;
1310
- let current = this.firstChild;
1311
- let next;
1312
- while (current !== end) {
1313
- next = current.nextSibling;
1314
- parentNode.insertBefore(current, node);
1315
- current = next;
1316
- }
1317
- parentNode.insertBefore(end, node);
1318
- }
1319
- }
1320
- /**
1321
- * Removes the view's DOM nodes.
1322
- * The nodes are not disposed and the view can later be re-inserted.
1323
- */
1324
- remove() {
1325
- const fragment = this.fragment;
1326
- const end = this.lastChild;
1327
- let current = this.firstChild;
1328
- let next;
1329
- while (current !== end) {
1330
- next = current.nextSibling;
1331
- fragment.appendChild(current);
1332
- current = next;
1333
- }
1334
- fragment.appendChild(end);
1335
- }
1336
- /**
1337
- * Removes the view and unbinds its behaviors, disposing of DOM nodes afterward.
1338
- * Once a view has been disposed, it cannot be inserted or bound again.
1339
- */
1340
- dispose() {
1341
- const parent = this.firstChild.parentNode;
1342
- const end = this.lastChild;
1343
- let current = this.firstChild;
1344
- let next;
1345
- while (current !== end) {
1346
- next = current.nextSibling;
1347
- parent.removeChild(current);
1348
- current = next;
1349
- }
1350
- parent.removeChild(end);
1351
- const behaviors = this.behaviors;
1352
- const oldSource = this.source;
1353
- for (let i = 0, ii = behaviors.length; i < ii; ++i) {
1354
- behaviors[i].unbind(oldSource);
1355
- }
1356
- }
1357
- /**
1358
- * Binds a view's behaviors to its binding source.
1359
- * @param source - The binding source for the view's binding behaviors.
1360
- * @param context - The execution context to run the behaviors within.
1361
- */
1362
- bind(source, context) {
1363
- const behaviors = this.behaviors;
1364
- if (this.source === source) {
1365
- return;
1366
- }
1367
- else if (this.source !== null) {
1368
- const oldSource = this.source;
1369
- this.source = source;
1370
- this.context = context;
1371
- for (let i = 0, ii = behaviors.length; i < ii; ++i) {
1372
- const current = behaviors[i];
1373
- current.unbind(oldSource);
1374
- current.bind(source, context);
1375
- }
1376
- }
1377
- else {
1378
- this.source = source;
1379
- this.context = context;
1380
- for (let i = 0, ii = behaviors.length; i < ii; ++i) {
1381
- behaviors[i].bind(source, context);
1382
- }
1383
- }
1384
- }
1385
- /**
1386
- * Unbinds a view's behaviors from its binding source.
1387
- */
1388
- unbind() {
1389
- if (this.source === null) {
1390
- return;
1391
- }
1392
- const behaviors = this.behaviors;
1393
- const oldSource = this.source;
1394
- for (let i = 0, ii = behaviors.length; i < ii; ++i) {
1395
- behaviors[i].unbind(oldSource);
1396
- }
1397
- this.source = null;
1398
- }
1399
- /**
1400
- * Efficiently disposes of a contiguous range of synthetic view instances.
1401
- * @param views - A contiguous range of views to be disposed.
1402
- */
1403
- static disposeContiguousBatch(views) {
1404
- if (views.length === 0) {
1405
- return;
1406
- }
1407
- range.setStartBefore(views[0].firstChild);
1408
- range.setEndAfter(views[views.length - 1].lastChild);
1409
- range.deleteContents();
1410
- for (let i = 0, ii = views.length; i < ii; ++i) {
1411
- const view = views[i];
1412
- const behaviors = view.behaviors;
1413
- const oldSource = view.source;
1414
- for (let j = 0, jj = behaviors.length; j < jj; ++j) {
1415
- behaviors[j].unbind(oldSource);
1416
- }
1417
- }
1418
- }
1419
- }
1420
-
1421
- /**
1422
- * A template capable of creating HTMLView instances or rendering directly to DOM.
1423
- * @public
1424
- */
1425
- /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
1426
- class ViewTemplate {
1427
- /**
1428
- * Creates an instance of ViewTemplate.
1429
- * @param html - The html representing what this template will instantiate, including placeholders for directives.
1430
- * @param directives - The directives that will be connected to placeholders in the html.
1431
- */
1432
- constructor(html, directives) {
1433
- this.behaviorCount = 0;
1434
- this.hasHostBehaviors = false;
1435
- this.fragment = null;
1436
- this.targetOffset = 0;
1437
- this.viewBehaviorFactories = null;
1438
- this.hostBehaviorFactories = null;
1439
- this.html = html;
1440
- this.directives = directives;
1441
- }
1442
- /**
1443
- * Creates an HTMLView instance based on this template definition.
1444
- * @param hostBindingTarget - The element that host behaviors will be bound to.
1445
- */
1446
- create(hostBindingTarget) {
1447
- if (this.fragment === null) {
1448
- let template;
1449
- const html = this.html;
1450
- if (typeof html === "string") {
1451
- template = document.createElement("template");
1452
- template.innerHTML = DOM.createHTML(html);
1453
- const fec = template.content.firstElementChild;
1454
- if (fec !== null && fec.tagName === "TEMPLATE") {
1455
- template = fec;
1456
- }
1457
- }
1458
- else {
1459
- template = html;
1460
- }
1461
- const result = compileTemplate(template, this.directives);
1462
- this.fragment = result.fragment;
1463
- this.viewBehaviorFactories = result.viewBehaviorFactories;
1464
- this.hostBehaviorFactories = result.hostBehaviorFactories;
1465
- this.targetOffset = result.targetOffset;
1466
- this.behaviorCount =
1467
- this.viewBehaviorFactories.length + this.hostBehaviorFactories.length;
1468
- this.hasHostBehaviors = this.hostBehaviorFactories.length > 0;
1469
- }
1470
- const fragment = this.fragment.cloneNode(true);
1471
- const viewFactories = this.viewBehaviorFactories;
1472
- const behaviors = new Array(this.behaviorCount);
1473
- const walker = DOM.createTemplateWalker(fragment);
1474
- let behaviorIndex = 0;
1475
- let targetIndex = this.targetOffset;
1476
- let node = walker.nextNode();
1477
- for (let ii = viewFactories.length; behaviorIndex < ii; ++behaviorIndex) {
1478
- const factory = viewFactories[behaviorIndex];
1479
- const factoryIndex = factory.targetIndex;
1480
- while (node !== null) {
1481
- if (targetIndex === factoryIndex) {
1482
- behaviors[behaviorIndex] = factory.createBehavior(node);
1483
- break;
1484
- }
1485
- else {
1486
- node = walker.nextNode();
1487
- targetIndex++;
1488
- }
1489
- }
1490
- }
1491
- if (this.hasHostBehaviors) {
1492
- const hostFactories = this.hostBehaviorFactories;
1493
- for (let i = 0, ii = hostFactories.length; i < ii; ++i, ++behaviorIndex) {
1494
- behaviors[behaviorIndex] = hostFactories[i].createBehavior(hostBindingTarget);
1495
- }
1496
- }
1497
- return new HTMLView(fragment, behaviors);
1498
- }
1499
- /**
1500
- * Creates an HTMLView from this template, binds it to the source, and then appends it to the host.
1501
- * @param source - The data source to bind the template to.
1502
- * @param host - The Element where the template will be rendered.
1503
- * @param hostBindingTarget - An HTML element to target the host bindings at if different from the
1504
- * host that the template is being attached to.
1505
- */
1506
- render(source, host, hostBindingTarget) {
1507
- if (typeof host === "string") {
1508
- host = document.getElementById(host);
1509
- }
1510
- if (hostBindingTarget === void 0) {
1511
- hostBindingTarget = host;
1512
- }
1513
- const view = this.create(hostBindingTarget);
1514
- view.bind(source, defaultExecutionContext);
1515
- view.appendTo(host);
1516
- return view;
1517
- }
1518
- }
1519
- // Much thanks to LitHTML for working this out!
1520
- const lastAttributeNameRegex =
1521
- /* eslint-disable-next-line no-control-regex */
1522
- /([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;
1523
- /**
1524
- * Transforms a template literal string into a renderable ViewTemplate.
1525
- * @param strings - The string fragments that are interpolated with the values.
1526
- * @param values - The values that are interpolated with the string fragments.
1527
- * @remarks
1528
- * The html helper supports interpolation of strings, numbers, binding expressions,
1529
- * other template instances, and Directive instances.
1530
- * @public
1531
- */
1532
- function html(strings, ...values) {
1533
- const directives = [];
1534
- let html = "";
1535
- for (let i = 0, ii = strings.length - 1; i < ii; ++i) {
1536
- const currentString = strings[i];
1537
- let value = values[i];
1538
- html += currentString;
1539
- if (value instanceof ViewTemplate) {
1540
- const template = value;
1541
- value = () => template;
1542
- }
1543
- if (typeof value === "function") {
1544
- value = new HTMLBindingDirective(value);
1545
- }
1546
- if (value instanceof TargetedHTMLDirective) {
1547
- const match = lastAttributeNameRegex.exec(currentString);
1548
- if (match !== null) {
1549
- value.targetName = match[2];
1550
- }
1551
- }
1552
- if (value instanceof HTMLDirective) {
1553
- // Since not all values are directives, we can't use i
1554
- // as the index for the placeholder. Instead, we need to
1555
- // use directives.length to get the next index.
1556
- html += value.createPlaceholder(directives.length);
1557
- directives.push(value);
1558
- }
1559
- else {
1560
- html += value;
1561
- }
1562
- }
1563
- html += strings[strings.length - 1];
1564
- return new ViewTemplate(html, directives);
1565
- }
1566
-
1567
- /**
1568
- * Represents styles that can be applied to a custom element.
1569
- * @public
1570
- */
1571
- class ElementStyles {
1572
- constructor() {
1573
- this.targets = new WeakSet();
1574
- /** @internal */
1575
- this.behaviors = null;
1576
- }
1577
- /** @internal */
1578
- addStylesTo(target) {
1579
- this.targets.add(target);
1580
- }
1581
- /** @internal */
1582
- removeStylesFrom(target) {
1583
- this.targets.delete(target);
1584
- }
1585
- /** @internal */
1586
- isAttachedTo(target) {
1587
- return this.targets.has(target);
1588
- }
1589
- /**
1590
- * Associates behaviors with this set of styles.
1591
- * @param behaviors - The behaviors to associate.
1592
- */
1593
- withBehaviors(...behaviors) {
1594
- this.behaviors =
1595
- this.behaviors === null ? behaviors : this.behaviors.concat(behaviors);
1596
- return this;
1597
- }
1598
- }
1599
- /**
1600
- * Create ElementStyles from ComposableStyles.
1601
- */
1602
- ElementStyles.create = (() => {
1603
- if (DOM.supportsAdoptedStyleSheets) {
1604
- const styleSheetCache = new Map();
1605
- return (styles) =>
1606
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
1607
- new AdoptedStyleSheetsStyles(styles, styleSheetCache);
1608
- }
1609
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
1610
- return (styles) => new StyleElementStyles(styles);
1611
- })();
1612
- function reduceStyles(styles) {
1613
- return styles
1614
- .map((x) => x instanceof ElementStyles ? reduceStyles(x.styles) : [x])
1615
- .reduce((prev, curr) => prev.concat(curr), []);
1616
- }
1617
- function reduceBehaviors(styles) {
1618
- return styles
1619
- .map((x) => (x instanceof ElementStyles ? x.behaviors : null))
1620
- .reduce((prev, curr) => {
1621
- if (curr === null) {
1622
- return prev;
1623
- }
1624
- if (prev === null) {
1625
- prev = [];
1626
- }
1627
- return prev.concat(curr);
1628
- }, null);
1629
- }
1630
- /**
1631
- * https://wicg.github.io/construct-stylesheets/
1632
- * https://developers.google.com/web/updates/2019/02/constructable-stylesheets
1633
- *
1634
- * @internal
1635
- */
1636
- class AdoptedStyleSheetsStyles extends ElementStyles {
1637
- constructor(styles, styleSheetCache) {
1638
- super();
1639
- this.styles = styles;
1640
- this.styleSheetCache = styleSheetCache;
1641
- this._styleSheets = void 0;
1642
- this.behaviors = reduceBehaviors(styles);
1643
- }
1644
- get styleSheets() {
1645
- if (this._styleSheets === void 0) {
1646
- const styles = this.styles;
1647
- const styleSheetCache = this.styleSheetCache;
1648
- this._styleSheets = reduceStyles(styles).map((x) => {
1649
- if (x instanceof CSSStyleSheet) {
1650
- return x;
1651
- }
1652
- let sheet = styleSheetCache.get(x);
1653
- if (sheet === void 0) {
1654
- sheet = new CSSStyleSheet();
1655
- sheet.replaceSync(x);
1656
- styleSheetCache.set(x, sheet);
1657
- }
1658
- return sheet;
1659
- });
1660
- }
1661
- return this._styleSheets;
1662
- }
1663
- addStylesTo(target) {
1664
- target.adoptedStyleSheets = [...target.adoptedStyleSheets, ...this.styleSheets];
1665
- super.addStylesTo(target);
1666
- }
1667
- removeStylesFrom(target) {
1668
- const sourceSheets = this.styleSheets;
1669
- target.adoptedStyleSheets = target.adoptedStyleSheets.filter((x) => sourceSheets.indexOf(x) === -1);
1670
- super.removeStylesFrom(target);
1671
- }
1672
- }
1673
- let styleClassId = 0;
1674
- function getNextStyleClass() {
1675
- return `fast-style-class-${++styleClassId}`;
1676
- }
1677
- /**
1678
- * @internal
1679
- */
1680
- class StyleElementStyles extends ElementStyles {
1681
- constructor(styles) {
1682
- super();
1683
- this.styles = styles;
1684
- this.behaviors = null;
1685
- this.behaviors = reduceBehaviors(styles);
1686
- this.styleSheets = reduceStyles(styles);
1687
- this.styleClass = getNextStyleClass();
1688
- }
1689
- addStylesTo(target) {
1690
- const styleSheets = this.styleSheets;
1691
- const styleClass = this.styleClass;
1692
- target = this.normalizeTarget(target);
1693
- for (let i = 0; i < styleSheets.length; i++) {
1694
- const element = document.createElement("style");
1695
- element.innerHTML = styleSheets[i];
1696
- element.className = styleClass;
1697
- target.append(element);
1698
- }
1699
- super.addStylesTo(target);
1700
- }
1701
- removeStylesFrom(target) {
1702
- target = this.normalizeTarget(target);
1703
- const styles = target.querySelectorAll(`.${this.styleClass}`);
1704
- for (let i = 0, ii = styles.length; i < ii; ++i) {
1705
- target.removeChild(styles[i]);
1706
- }
1707
- super.removeStylesFrom(target);
1708
- }
1709
- isAttachedTo(target) {
1710
- return super.isAttachedTo(this.normalizeTarget(target));
1711
- }
1712
- normalizeTarget(target) {
1713
- return target === document ? document.body : target;
1714
- }
1715
- }
1716
-
1717
- /**
1718
- * A {@link ValueConverter} that converts to and from `boolean` values.
1719
- * @remarks
1720
- * Used automatically when the `boolean` {@link AttributeMode} is selected.
1721
- * @public
1722
- */
1723
- const booleanConverter = {
1724
- toView(value) {
1725
- return value ? "true" : "false";
1726
- },
1727
- fromView(value) {
1728
- if (value === null ||
1729
- value === void 0 ||
1730
- value === "false" ||
1731
- value === false ||
1732
- value === 0) {
1733
- return false;
1734
- }
1735
- return true;
1736
- },
1737
- };
1738
- /**
1739
- * An implementation of {@link Accessor} that supports reactivity,
1740
- * change callbacks, attribute reflection, and type conversion for
1741
- * custom elements.
1742
- * @public
1743
- */
1744
- class AttributeDefinition {
1745
- /**
1746
- * Creates an instance of AttributeDefinition.
1747
- * @param Owner - The class constructor that owns this attribute.
1748
- * @param name - The name of the property associated with the attribute.
1749
- * @param attribute - The name of the attribute in HTML.
1750
- * @param mode - The {@link AttributeMode} that describes the behavior of this attribute.
1751
- * @param converter - A {@link ValueConverter} that integrates with the property getter/setter
1752
- * to convert values to and from a DOM string.
1753
- */
1754
- constructor(Owner, name, attribute = name.toLowerCase(), mode = "reflect", converter) {
1755
- this.guards = new Set();
1756
- this.Owner = Owner;
1757
- this.name = name;
1758
- this.attribute = attribute;
1759
- this.mode = mode;
1760
- this.converter = converter;
1761
- this.fieldName = `_${name}`;
1762
- this.callbackName = `${name}Changed`;
1763
- this.hasCallback = this.callbackName in Owner.prototype;
1764
- if (mode === "boolean" && converter === void 0) {
1765
- this.converter = booleanConverter;
1766
- }
1767
- }
1768
- /**
1769
- * Sets the value of the attribute/property on the source element.
1770
- * @param source - The source element to access.
1771
- * @param value - The value to set the attribute/property to.
1772
- */
1773
- setValue(source, newValue) {
1774
- const oldValue = source[this.fieldName];
1775
- const converter = this.converter;
1776
- if (converter !== void 0) {
1777
- newValue = converter.fromView(newValue);
1778
- }
1779
- if (oldValue !== newValue) {
1780
- source[this.fieldName] = newValue;
1781
- this.tryReflectToAttribute(source);
1782
- if (this.hasCallback) {
1783
- source[this.callbackName](oldValue, newValue);
1784
- }
1785
- source.$fastController.notify(this.name);
1786
- }
1787
- }
1788
- /**
1789
- * Gets the value of the attribute/property on the source element.
1790
- * @param source - The source element to access.
1791
- */
1792
- getValue(source) {
1793
- Observable.track(source, this.name);
1794
- return source[this.fieldName];
1795
- }
1796
- /** @internal */
1797
- onAttributeChangedCallback(element, value) {
1798
- if (this.guards.has(element)) {
1799
- return;
1800
- }
1801
- this.guards.add(element);
1802
- this.setValue(element, value);
1803
- this.guards.delete(element);
1804
- }
1805
- tryReflectToAttribute(element) {
1806
- const mode = this.mode;
1807
- const guards = this.guards;
1808
- if (guards.has(element) || mode === "fromView") {
1809
- return;
1810
- }
1811
- DOM.queueUpdate(() => {
1812
- guards.add(element);
1813
- const latestValue = element[this.fieldName];
1814
- switch (mode) {
1815
- case "reflect":
1816
- const converter = this.converter;
1817
- DOM.setAttribute(element, this.attribute, converter !== void 0 ? converter.toView(latestValue) : latestValue);
1818
- break;
1819
- case "boolean":
1820
- DOM.setBooleanAttribute(element, this.attribute, latestValue);
1821
- break;
1822
- }
1823
- guards.delete(element);
1824
- });
1825
- }
1826
- /**
1827
- * Collects all attribute definitions associated with the owner.
1828
- * @param Owner - The class constructor to collect attribute for.
1829
- * @param attributeLists - Any existing attributes to collect and merge with those associated with the owner.
1830
- * @internal
1831
- */
1832
- static collect(Owner, ...attributeLists) {
1833
- const attributes = [];
1834
- attributeLists.push(Owner.attributes);
1835
- for (let i = 0, ii = attributeLists.length; i < ii; ++i) {
1836
- const list = attributeLists[i];
1837
- if (list === void 0) {
1838
- continue;
1839
- }
1840
- for (let j = 0, jj = list.length; j < jj; ++j) {
1841
- const config = list[j];
1842
- if (typeof config === "string") {
1843
- attributes.push(new AttributeDefinition(Owner, config));
1844
- }
1845
- else {
1846
- attributes.push(new AttributeDefinition(Owner, config.property, config.attribute, config.mode, config.converter));
1847
- }
1848
- }
1849
- }
1850
- return attributes;
1851
- }
1852
- }
1853
- function attr(configOrTarget, prop) {
1854
- let config;
1855
- function decorator($target, $prop) {
1856
- if (arguments.length > 1) {
1857
- // Non invocation:
1858
- // - @attr
1859
- // Invocation with or w/o opts:
1860
- // - @attr()
1861
- // - @attr({...opts})
1862
- config.property = $prop;
1863
- }
1864
- const attributes = $target.constructor.attributes ||
1865
- ($target.constructor.attributes = []);
1866
- attributes.push(config);
1867
- }
1868
- if (arguments.length > 1) {
1869
- // Non invocation:
1870
- // - @attr
1871
- config = {};
1872
- decorator(configOrTarget, prop);
1873
- return;
1874
- }
1875
- // Invocation with or w/o opts:
1876
- // - @attr()
1877
- // - @attr({...opts})
1878
- config = configOrTarget === void 0 ? {} : configOrTarget;
1879
- return decorator;
1880
- }
1881
-
1882
- const defaultShadowOptions = { mode: "open" };
1883
- const defaultElementOptions = {};
1884
- const fastDefinitions = new Map();
1885
- /**
1886
- * Defines metadata for a FASTElement.
1887
- * @public
1888
- */
1889
- class FASTElementDefinition {
1890
- /**
1891
- * Creates an instance of FASTElementDefinition.
1892
- * @param type - The type this definition is being created for.
1893
- * @param nameOrConfig - The name of the element to define or a config object
1894
- * that describes the element to define.
1895
- */
1896
- constructor(type, nameOrConfig = type.definition) {
1897
- if (typeof nameOrConfig === "string") {
1898
- nameOrConfig = { name: nameOrConfig };
1899
- }
1900
- this.type = type;
1901
- this.name = nameOrConfig.name;
1902
- this.template = nameOrConfig.template;
1903
- const attributes = AttributeDefinition.collect(type, nameOrConfig.attributes);
1904
- const observedAttributes = new Array(attributes.length);
1905
- const propertyLookup = {};
1906
- const attributeLookup = {};
1907
- for (let i = 0, ii = attributes.length; i < ii; ++i) {
1908
- const current = attributes[i];
1909
- observedAttributes[i] = current.attribute;
1910
- propertyLookup[current.name] = current;
1911
- attributeLookup[current.attribute] = current;
1912
- }
1913
- this.attributes = attributes;
1914
- this.observedAttributes = observedAttributes;
1915
- this.propertyLookup = propertyLookup;
1916
- this.attributeLookup = attributeLookup;
1917
- this.shadowOptions =
1918
- nameOrConfig.shadowOptions === void 0
1919
- ? defaultShadowOptions
1920
- : nameOrConfig.shadowOptions === null
1921
- ? void 0
1922
- : Object.assign(Object.assign({}, defaultShadowOptions), nameOrConfig.shadowOptions);
1923
- this.elementOptions =
1924
- nameOrConfig.elementOptions === void 0
1925
- ? defaultElementOptions
1926
- : Object.assign(Object.assign({}, defaultElementOptions), nameOrConfig.elementOptions);
1927
- this.styles =
1928
- nameOrConfig.styles === void 0
1929
- ? void 0
1930
- : Array.isArray(nameOrConfig.styles)
1931
- ? ElementStyles.create(nameOrConfig.styles)
1932
- : nameOrConfig.styles instanceof ElementStyles
1933
- ? nameOrConfig.styles
1934
- : ElementStyles.create([nameOrConfig.styles]);
1935
- }
1936
- /**
1937
- * Defines a custom element based on this definition.
1938
- * @param registry - The element registry to define the element in.
1939
- */
1940
- define(registry = customElements) {
1941
- const type = this.type;
1942
- if (!this.isDefined) {
1943
- const attributes = this.attributes;
1944
- const proto = type.prototype;
1945
- for (let i = 0, ii = attributes.length; i < ii; ++i) {
1946
- Observable.defineProperty(proto, attributes[i]);
1947
- }
1948
- Reflect.defineProperty(type, "observedAttributes", {
1949
- value: this.observedAttributes,
1950
- enumerable: true,
1951
- });
1952
- fastDefinitions.set(type, this);
1953
- this.isDefined = true;
1954
- }
1955
- if (!registry.get(this.name)) {
1956
- registry.define(this.name, type, this.elementOptions);
1957
- }
1958
- return this;
1959
- }
1960
- /**
1961
- * Gets the element definition associated with the specified type.
1962
- * @param type - The custom element type to retrieve the definition for.
1963
- */
1964
- static forType(type) {
1965
- return fastDefinitions.get(type);
1966
- }
1967
- }
1968
-
1969
- const shadowRoots = new WeakMap();
1970
- const defaultEventOptions = {
1971
- bubbles: true,
1972
- composed: true,
1973
- cancelable: true,
1974
- };
1975
- function getShadowRoot(element) {
1976
- return element.shadowRoot || shadowRoots.get(element) || null;
1977
- }
1978
- /**
1979
- * Controls the lifecycle and rendering of a `FASTElement`.
1980
- * @public
1981
- */
1982
- class Controller extends PropertyChangeNotifier {
1983
- /**
1984
- * Creates a Controller to control the specified element.
1985
- * @param element - The element to be controlled by this controller.
1986
- * @param definition - The element definition metadata that instructs this
1987
- * controller in how to handle rendering and other platform integrations.
1988
- * @internal
1989
- */
1990
- constructor(element, definition) {
1991
- super(element);
1992
- this.boundObservables = null;
1993
- this.behaviors = null;
1994
- this.needsInitialization = true;
1995
- this._template = null;
1996
- this._styles = null;
1997
- this._isConnected = false;
1998
- /**
1999
- * This allows Observable.getNotifier(...) to return the Controller
2000
- * when the notifier for the Controller itself is being requested. The
2001
- * result is that the Observable system does not need to create a separate
2002
- * instance of Notifier for observables on the Controller. The component and
2003
- * the controller will now share the same notifier, removing one-object construct
2004
- * per web component instance.
2005
- */
2006
- this.$fastController = this;
2007
- /**
2008
- * The view associated with the custom element.
2009
- * @remarks
2010
- * If `null` then the element is managing its own rendering.
2011
- */
2012
- this.view = null;
2013
- this.element = element;
2014
- this.definition = definition;
2015
- const shadowOptions = definition.shadowOptions;
2016
- if (shadowOptions !== void 0) {
2017
- const shadowRoot = element.attachShadow(shadowOptions);
2018
- if (shadowOptions.mode === "closed") {
2019
- shadowRoots.set(element, shadowRoot);
2020
- }
2021
- }
2022
- // Capture any observable values that were set by the binding engine before
2023
- // the browser upgraded the element. Then delete the property since it will
2024
- // shadow the getter/setter that is required to make the observable operate.
2025
- // Later, in the connect callback, we'll re-apply the values.
2026
- const accessors = Observable.getAccessors(element);
2027
- if (accessors.length > 0) {
2028
- const boundObservables = (this.boundObservables = Object.create(null));
2029
- for (let i = 0, ii = accessors.length; i < ii; ++i) {
2030
- const propertyName = accessors[i].name;
2031
- const value = element[propertyName];
2032
- if (value !== void 0) {
2033
- delete element[propertyName];
2034
- boundObservables[propertyName] = value;
2035
- }
2036
- }
2037
- }
2038
- }
2039
- /**
2040
- * Indicates whether or not the custom element has been
2041
- * connected to the document.
2042
- */
2043
- get isConnected() {
2044
- Observable.track(this, "isConnected");
2045
- return this._isConnected;
2046
- }
2047
- setIsConnected(value) {
2048
- this._isConnected = value;
2049
- Observable.notify(this, "isConnected");
2050
- }
2051
- /**
2052
- * Gets/sets the template used to render the component.
2053
- * @remarks
2054
- * This value can only be accurately read after connect but can be set at any time.
2055
- */
2056
- get template() {
2057
- return this._template;
2058
- }
2059
- set template(value) {
2060
- if (this._template === value) {
2061
- return;
2062
- }
2063
- this._template = value;
2064
- if (!this.needsInitialization) {
2065
- this.renderTemplate(value);
2066
- }
2067
- }
2068
- /**
2069
- * Gets/sets the primary styles used for the component.
2070
- * @remarks
2071
- * This value can only be accurately read after connect but can be set at any time.
2072
- */
2073
- get styles() {
2074
- return this._styles;
2075
- }
2076
- set styles(value) {
2077
- if (this._styles === value) {
2078
- return;
2079
- }
2080
- if (this._styles !== null) {
2081
- this.removeStyles(this._styles);
2082
- }
2083
- this._styles = value;
2084
- if (!this.needsInitialization && value !== null) {
2085
- this.addStyles(value);
2086
- }
2087
- }
2088
- /**
2089
- * Adds styles to this element. Providing an HTMLStyleElement will attach the element instance to the shadowRoot.
2090
- * @param styles - The styles to add.
2091
- */
2092
- addStyles(styles) {
2093
- const target = getShadowRoot(this.element) ||
2094
- this.element.getRootNode();
2095
- if (styles instanceof HTMLStyleElement) {
2096
- target.append(styles);
2097
- }
2098
- else if (!styles.isAttachedTo(target)) {
2099
- const sourceBehaviors = styles.behaviors;
2100
- styles.addStylesTo(target);
2101
- if (sourceBehaviors !== null) {
2102
- this.addBehaviors(sourceBehaviors);
2103
- }
2104
- }
2105
- }
2106
- /**
2107
- * Removes styles from this element. Providing an HTMLStyleElement will detach the element instance from the shadowRoot.
2108
- * @param styles - the styles to remove.
2109
- */
2110
- removeStyles(styles) {
2111
- const target = getShadowRoot(this.element) ||
2112
- this.element.getRootNode();
2113
- if (styles instanceof HTMLStyleElement) {
2114
- target.removeChild(styles);
2115
- }
2116
- else if (styles.isAttachedTo(target)) {
2117
- const sourceBehaviors = styles.behaviors;
2118
- styles.removeStylesFrom(target);
2119
- if (sourceBehaviors !== null) {
2120
- this.removeBehaviors(sourceBehaviors);
2121
- }
2122
- }
2123
- }
2124
- /**
2125
- * Adds behaviors to this element.
2126
- * @param behaviors - The behaviors to add.
2127
- */
2128
- addBehaviors(behaviors) {
2129
- const targetBehaviors = this.behaviors || (this.behaviors = new Map());
2130
- const length = behaviors.length;
2131
- const behaviorsToBind = [];
2132
- for (let i = 0; i < length; ++i) {
2133
- const behavior = behaviors[i];
2134
- if (targetBehaviors.has(behavior)) {
2135
- targetBehaviors.set(behavior, targetBehaviors.get(behavior) + 1);
2136
- }
2137
- else {
2138
- targetBehaviors.set(behavior, 1);
2139
- behaviorsToBind.push(behavior);
2140
- }
2141
- }
2142
- if (this._isConnected) {
2143
- const element = this.element;
2144
- for (let i = 0; i < behaviorsToBind.length; ++i) {
2145
- behaviorsToBind[i].bind(element, defaultExecutionContext);
2146
- }
2147
- }
2148
- }
2149
- /**
2150
- * Removes behaviors from this element.
2151
- * @param behaviors - The behaviors to remove.
2152
- * @param force - Forces unbinding of behaviors.
2153
- */
2154
- removeBehaviors(behaviors, force = false) {
2155
- const targetBehaviors = this.behaviors;
2156
- if (targetBehaviors === null) {
2157
- return;
2158
- }
2159
- const length = behaviors.length;
2160
- const behaviorsToUnbind = [];
2161
- for (let i = 0; i < length; ++i) {
2162
- const behavior = behaviors[i];
2163
- if (targetBehaviors.has(behavior)) {
2164
- const count = targetBehaviors.get(behavior) - 1;
2165
- count === 0 || force
2166
- ? targetBehaviors.delete(behavior) && behaviorsToUnbind.push(behavior)
2167
- : targetBehaviors.set(behavior, count);
2168
- }
2169
- }
2170
- if (this._isConnected) {
2171
- const element = this.element;
2172
- for (let i = 0; i < behaviorsToUnbind.length; ++i) {
2173
- behaviorsToUnbind[i].unbind(element);
2174
- }
2175
- }
2176
- }
2177
- /**
2178
- * Runs connected lifecycle behavior on the associated element.
2179
- */
2180
- onConnectedCallback() {
2181
- if (this._isConnected) {
2182
- return;
2183
- }
2184
- const element = this.element;
2185
- if (this.needsInitialization) {
2186
- this.finishInitialization();
2187
- }
2188
- else if (this.view !== null) {
2189
- this.view.bind(element, defaultExecutionContext);
2190
- }
2191
- const behaviors = this.behaviors;
2192
- if (behaviors !== null) {
2193
- for (const [behavior] of behaviors) {
2194
- behavior.bind(element, defaultExecutionContext);
2195
- }
2196
- }
2197
- this.setIsConnected(true);
2198
- }
2199
- /**
2200
- * Runs disconnected lifecycle behavior on the associated element.
2201
- */
2202
- onDisconnectedCallback() {
2203
- if (!this._isConnected) {
2204
- return;
2205
- }
2206
- this.setIsConnected(false);
2207
- const view = this.view;
2208
- if (view !== null) {
2209
- view.unbind();
2210
- }
2211
- const behaviors = this.behaviors;
2212
- if (behaviors !== null) {
2213
- const element = this.element;
2214
- for (const [behavior] of behaviors) {
2215
- behavior.unbind(element);
2216
- }
2217
- }
2218
- }
2219
- /**
2220
- * Runs the attribute changed callback for the associated element.
2221
- * @param name - The name of the attribute that changed.
2222
- * @param oldValue - The previous value of the attribute.
2223
- * @param newValue - The new value of the attribute.
2224
- */
2225
- onAttributeChangedCallback(name, oldValue, newValue) {
2226
- const attrDef = this.definition.attributeLookup[name];
2227
- if (attrDef !== void 0) {
2228
- attrDef.onAttributeChangedCallback(this.element, newValue);
2229
- }
2230
- }
2231
- /**
2232
- * Emits a custom HTML event.
2233
- * @param type - The type name of the event.
2234
- * @param detail - The event detail object to send with the event.
2235
- * @param options - The event options. By default bubbles and composed.
2236
- * @remarks
2237
- * Only emits events if connected.
2238
- */
2239
- emit(type, detail, options) {
2240
- if (this._isConnected) {
2241
- return this.element.dispatchEvent(new CustomEvent(type, Object.assign(Object.assign({ detail }, defaultEventOptions), options)));
2242
- }
2243
- return false;
2244
- }
2245
- finishInitialization() {
2246
- const element = this.element;
2247
- const boundObservables = this.boundObservables;
2248
- // If we have any observables that were bound, re-apply their values.
2249
- if (boundObservables !== null) {
2250
- const propertyNames = Object.keys(boundObservables);
2251
- for (let i = 0, ii = propertyNames.length; i < ii; ++i) {
2252
- const propertyName = propertyNames[i];
2253
- element[propertyName] = boundObservables[propertyName];
2254
- }
2255
- this.boundObservables = null;
2256
- }
2257
- const definition = this.definition;
2258
- // 1. Template overrides take top precedence.
2259
- if (this._template === null) {
2260
- if (this.element.resolveTemplate) {
2261
- // 2. Allow for element instance overrides next.
2262
- this._template = this.element.resolveTemplate();
2263
- }
2264
- else if (definition.template) {
2265
- // 3. Default to the static definition.
2266
- this._template = definition.template || null;
2267
- }
2268
- }
2269
- // If we have a template after the above process, render it.
2270
- // If there's no template, then the element author has opted into
2271
- // custom rendering and they will managed the shadow root's content themselves.
2272
- if (this._template !== null) {
2273
- this.renderTemplate(this._template);
2274
- }
2275
- // 1. Styles overrides take top precedence.
2276
- if (this._styles === null) {
2277
- if (this.element.resolveStyles) {
2278
- // 2. Allow for element instance overrides next.
2279
- this._styles = this.element.resolveStyles();
2280
- }
2281
- else if (definition.styles) {
2282
- // 3. Default to the static definition.
2283
- this._styles = definition.styles || null;
2284
- }
2285
- }
2286
- // If we have styles after the above process, add them.
2287
- if (this._styles !== null) {
2288
- this.addStyles(this._styles);
2289
- }
2290
- this.needsInitialization = false;
2291
- }
2292
- renderTemplate(template) {
2293
- const element = this.element;
2294
- // When getting the host to render to, we start by looking
2295
- // up the shadow root. If there isn't one, then that means
2296
- // we're doing a Light DOM render to the element's direct children.
2297
- const host = getShadowRoot(element) || element;
2298
- if (this.view !== null) {
2299
- // If there's already a view, we need to unbind and remove through dispose.
2300
- this.view.dispose();
2301
- this.view = null;
2302
- }
2303
- else if (!this.needsInitialization) {
2304
- // If there was previous custom rendering, we need to clear out the host.
2305
- DOM.removeChildNodes(host);
2306
- }
2307
- if (template) {
2308
- // If a new template was provided, render it.
2309
- this.view = template.render(element, host, element);
2310
- }
2311
- }
2312
- /**
2313
- * Locates or creates a controller for the specified element.
2314
- * @param element - The element to return the controller for.
2315
- * @remarks
2316
- * The specified element must have a {@link FASTElementDefinition}
2317
- * registered either through the use of the {@link customElement}
2318
- * decorator or a call to `FASTElement.define`.
2319
- */
2320
- static forCustomElement(element) {
2321
- const controller = element.$fastController;
2322
- if (controller !== void 0) {
2323
- return controller;
2324
- }
2325
- const definition = FASTElementDefinition.forType(element.constructor);
2326
- if (definition === void 0) {
2327
- throw new Error("Missing FASTElement definition.");
2328
- }
2329
- return (element.$fastController = new Controller(element, definition));
2330
- }
2331
- }
2332
-
2333
- /* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
2334
- function createFASTElement(BaseType) {
2335
- return class extends BaseType {
2336
- constructor() {
2337
- /* eslint-disable-next-line */
2338
- super();
2339
- Controller.forCustomElement(this);
2340
- }
2341
- $emit(type, detail, options) {
2342
- return this.$fastController.emit(type, detail, options);
2343
- }
2344
- connectedCallback() {
2345
- this.$fastController.onConnectedCallback();
2346
- }
2347
- disconnectedCallback() {
2348
- this.$fastController.onDisconnectedCallback();
2349
- }
2350
- attributeChangedCallback(name, oldValue, newValue) {
2351
- this.$fastController.onAttributeChangedCallback(name, oldValue, newValue);
2352
- }
2353
- };
2354
- }
2355
- /**
2356
- * A minimal base class for FASTElements that also provides
2357
- * static helpers for working with FASTElements.
2358
- * @public
2359
- */
2360
- const FASTElement = Object.assign(createFASTElement(HTMLElement), {
2361
- /**
2362
- * Creates a new FASTElement base class inherited from the
2363
- * provided base type.
2364
- * @param BaseType - The base element type to inherit from.
2365
- */
2366
- from(BaseType) {
2367
- return createFASTElement(BaseType);
2368
- },
2369
- /**
2370
- * Defines a platform custom element based on the provided type and definition.
2371
- * @param type - The custom element type to define.
2372
- * @param nameOrDef - The name of the element to define or a definition object
2373
- * that describes the element to define.
2374
- */
2375
- define(type, nameOrDef) {
2376
- return new FASTElementDefinition(type, nameOrDef).define().type;
2377
- },
2378
- });
4
+ class Focus extends FoundationElement {}
2379
5
 
2380
- /**
2381
- * Directive for use in {@link css}.
2382
- *
2383
- * @public
2384
- */
2385
- class CSSDirective {
2386
- /**
2387
- * Creates a CSS fragment to interpolate into the CSS document.
2388
- * @returns - the string to interpolate into CSS
2389
- */
2390
- createCSS() {
2391
- return "";
2392
- }
2393
- /**
2394
- * Creates a behavior to bind to the host element.
2395
- * @returns - the behavior to bind to the host element, or undefined.
2396
- */
2397
- createBehavior() {
2398
- return undefined;
2399
- }
2400
- }
6
+ var css_248z = ":host {\n display: contents;\n border-radius: inherit;\n}\n\n.control {\n position: absolute;\n box-sizing: border-box;\n border-radius: inherit;\n box-shadow: inset 0 0 0 2px var(--focus-stroke-color, var(--vvd-color-on-canvas)), inset 0 0 0 3px var(--focus-stroke-gap-color, currentColor);\n inset: 0;\n}";
7
+ styleInject(css_248z);
2401
8
 
2402
- /*! *****************************************************************************
2403
- Copyright (c) Microsoft Corporation.
2404
-
2405
- Permission to use, copy, modify, and/or distribute this software for any
2406
- purpose with or without fee is hereby granted.
2407
-
2408
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2409
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2410
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2411
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2412
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2413
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2414
- PERFORMANCE OF THIS SOFTWARE.
2415
- ***************************************************************************** */
2416
-
2417
- function __decorate(decorators, target, key, desc) {
2418
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2419
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2420
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2421
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2422
- }
2423
-
2424
- function __metadata(metadataKey, metadataValue) {
2425
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
2426
- }
9
+ let _ = t => t,
10
+ _t;
11
+ const focusTemplate = () => html(_t || (_t = _`
12
+ <span class="control"></span>`));
2427
13
 
2428
- /**
2429
- * Big thanks to https://github.com/fkleuver and the https://github.com/aurelia/aurelia project
2430
- * for the bulk of this code and many of the associated tests.
2431
- */
2432
- // Tiny polyfill for TypeScript's Reflect metadata API.
2433
- const metadataByTarget = new Map();
2434
- if (!("metadata" in Reflect)) {
2435
- Reflect.metadata = function (key, value) {
2436
- return function (target) {
2437
- Reflect.defineMetadata(key, value, target);
2438
- };
2439
- };
2440
- Reflect.defineMetadata = function (key, value, target) {
2441
- let metadata = metadataByTarget.get(target);
2442
- if (metadata === void 0) {
2443
- metadataByTarget.set(target, (metadata = new Map()));
2444
- }
2445
- metadata.set(key, value);
2446
- };
2447
- Reflect.getOwnMetadata = function (key, target) {
2448
- const metadata = metadataByTarget.get(target);
2449
- if (metadata !== void 0) {
2450
- return metadata.get(key);
2451
- }
2452
- return void 0;
2453
- };
2454
- }
2455
- /**
2456
- * A utility class used that constructs and registers resolvers for a dependency
2457
- * injection container. Supports a standard set of object lifetimes.
2458
- * @public
2459
- */
2460
- class ResolverBuilder {
2461
- /**
2462
- *
2463
- * @param container - The container to create resolvers for.
2464
- * @param key - The key to register resolvers under.
2465
- */
2466
- constructor(container, key) {
2467
- this.container = container;
2468
- this.key = key;
2469
- }
2470
- /**
2471
- * Creates a resolver for an existing object instance.
2472
- * @param value - The instance to resolve.
2473
- * @returns The resolver.
2474
- */
2475
- instance(value) {
2476
- return this.registerResolver(0 /* instance */, value);
2477
- }
2478
- /**
2479
- * Creates a resolver that enforces a singleton lifetime.
2480
- * @param value - The type to create and cache the singleton for.
2481
- * @returns The resolver.
2482
- */
2483
- singleton(value) {
2484
- return this.registerResolver(1 /* singleton */, value);
2485
- }
2486
- /**
2487
- * Creates a resolver that creates a new instance for every dependency request.
2488
- * @param value - The type to create instances of.
2489
- * @returns - The resolver.
2490
- */
2491
- transient(value) {
2492
- return this.registerResolver(2 /* transient */, value);
2493
- }
2494
- /**
2495
- * Creates a resolver that invokes a callback function for every dependency resolution
2496
- * request, allowing custom logic to return the dependency.
2497
- * @param value - The callback to call during resolution.
2498
- * @returns The resolver.
2499
- */
2500
- callback(value) {
2501
- return this.registerResolver(3 /* callback */, value);
2502
- }
2503
- /**
2504
- * Creates a resolver that invokes a callback function the first time that a dependency
2505
- * resolution is requested. The returned value is then cached and provided for all
2506
- * subsequent requests.
2507
- * @param value - The callback to call during the first resolution.
2508
- * @returns The resolver.
2509
- */
2510
- cachedCallback(value) {
2511
- return this.registerResolver(3 /* callback */, cacheCallbackResult(value));
2512
- }
2513
- /**
2514
- * Aliases the current key to a different key.
2515
- * @param destinationKey - The key to point the alias to.
2516
- * @returns The resolver.
2517
- */
2518
- aliasTo(destinationKey) {
2519
- return this.registerResolver(5 /* alias */, destinationKey);
2520
- }
2521
- registerResolver(strategy, state) {
2522
- const { container, key } = this;
2523
- /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
2524
- this.container = this.key = (void 0);
2525
- return container.registerResolver(key, new ResolverImpl(key, strategy, state));
2526
- }
2527
- }
2528
- function cloneArrayWithPossibleProps(source) {
2529
- const clone = source.slice();
2530
- const keys = Object.keys(source);
2531
- const len = keys.length;
2532
- let key;
2533
- for (let i = 0; i < len; ++i) {
2534
- key = keys[i];
2535
- if (!isArrayIndex(key)) {
2536
- clone[key] = source[key];
2537
- }
2538
- }
2539
- return clone;
2540
- }
2541
- /**
2542
- * A set of default resolvers useful in configuring a container.
2543
- * @public
2544
- */
2545
- const DefaultResolver = Object.freeze({
2546
- /**
2547
- * Disables auto-registration and throws for all un-registered dependencies.
2548
- * @param key - The key to create the resolver for.
2549
- */
2550
- none(key) {
2551
- throw Error(`${key.toString()} not registered, did you forget to add @singleton()?`);
2552
- },
2553
- /**
2554
- * Provides default singleton resolution behavior during auto-registration.
2555
- * @param key - The key to create the resolver for.
2556
- * @returns The resolver.
2557
- */
2558
- singleton(key) {
2559
- return new ResolverImpl(key, 1 /* singleton */, key);
2560
- },
2561
- /**
2562
- * Provides default transient resolution behavior during auto-registration.
2563
- * @param key - The key to create the resolver for.
2564
- * @returns The resolver.
2565
- */
2566
- transient(key) {
2567
- return new ResolverImpl(key, 2 /* transient */, key);
2568
- },
14
+ const VIVIDFocus = Focus.compose({
15
+ baseName: 'focus',
16
+ template: focusTemplate,
17
+ styles: css_248z
2569
18
  });
2570
- /**
2571
- * Configuration for a dependency injection container.
2572
- * @public
2573
- */
2574
- const ContainerConfiguration = Object.freeze({
2575
- /**
2576
- * The default configuration used when creating a DOM-disconnected container.
2577
- * @remarks
2578
- * The default creates a root container, with no parent container. It does not handle
2579
- * owner requests and it uses singleton resolution behavior for auto-registration.
2580
- */
2581
- default: Object.freeze({
2582
- parentLocator: () => null,
2583
- responsibleForOwnerRequests: false,
2584
- defaultResolver: DefaultResolver.singleton,
2585
- }),
2586
- });
2587
- const dependencyLookup = new Map();
2588
- function getParamTypes(key) {
2589
- return (Type) => {
2590
- return Reflect.getOwnMetadata(key, Type);
2591
- };
2592
- }
2593
- let rootDOMContainer = null;
2594
- /**
2595
- * The gateway to dependency injection APIs.
2596
- * @public
2597
- */
2598
- const DI = Object.freeze({
2599
- /**
2600
- * Creates a new dependency injection container.
2601
- * @param config - The configuration for the container.
2602
- * @returns A newly created dependency injection container.
2603
- */
2604
- createContainer(config) {
2605
- return new ContainerImpl(null, Object.assign({}, ContainerConfiguration.default, config));
2606
- },
2607
- /**
2608
- * Finds the dependency injection container responsible for providing dependencies
2609
- * to the specified node.
2610
- * @param node - The node to find the responsible container for.
2611
- * @returns The container responsible for providing dependencies to the node.
2612
- * @remarks
2613
- * This will be the same as the parent container if the specified node
2614
- * does not itself host a container configured with responsibleForOwnerRequests.
2615
- */
2616
- findResponsibleContainer(node) {
2617
- const owned = node.$$container$$;
2618
- if (owned && owned.responsibleForOwnerRequests) {
2619
- return owned;
2620
- }
2621
- return DI.findParentContainer(node);
2622
- },
2623
- /**
2624
- * Find the dependency injection container up the DOM tree from this node.
2625
- * @param node - The node to find the parent container for.
2626
- * @returns The parent container of this node.
2627
- * @remarks
2628
- * This will be the same as the responsible container if the specified node
2629
- * does not itself host a container configured with responsibleForOwnerRequests.
2630
- */
2631
- findParentContainer(node) {
2632
- const event = new CustomEvent(DILocateParentEventType, {
2633
- bubbles: true,
2634
- composed: true,
2635
- cancelable: true,
2636
- detail: { container: void 0 },
2637
- });
2638
- node.dispatchEvent(event);
2639
- return event.detail.container || DI.getOrCreateDOMContainer();
2640
- },
2641
- /**
2642
- * Returns a dependency injection container if one is explicitly owned by the specified
2643
- * node. If one is not owned, then a new container is created and assigned to the node.
2644
- * @param node - The node to find or create the container for.
2645
- * @param config - The configuration for the container if one needs to be created.
2646
- * @returns The located or created container.
2647
- * @remarks
2648
- * This API does not search for a responsible or parent container. It looks only for a container
2649
- * directly defined on the specified node and creates one at that location if one does not
2650
- * already exist.
2651
- */
2652
- getOrCreateDOMContainer(node, config) {
2653
- if (!node) {
2654
- return (rootDOMContainer ||
2655
- (rootDOMContainer = new ContainerImpl(null, Object.assign({}, ContainerConfiguration.default, config, {
2656
- parentLocator: () => null,
2657
- }))));
2658
- }
2659
- return (node.$$container$$ ||
2660
- new ContainerImpl(node, Object.assign({}, ContainerConfiguration.default, config, {
2661
- parentLocator: DI.findParentContainer,
2662
- })));
2663
- },
2664
- /**
2665
- * Gets the "design:paramtypes" metadata for the specified type.
2666
- * @param Type - The type to get the metadata for.
2667
- * @returns The metadata array or undefined if no metadata is found.
2668
- */
2669
- getDesignParamtypes: getParamTypes("design:paramtypes"),
2670
- /**
2671
- * Gets the "di:paramtypes" metadata for the specified type.
2672
- * @param Type - The type to get the metadata for.
2673
- * @returns The metadata array or undefined if no metadata is found.
2674
- */
2675
- getAnnotationParamtypes: getParamTypes("di:paramtypes"),
2676
- /**
2677
- *
2678
- * @param Type - Gets the "di:paramtypes" metadata for the specified type. If none is found,
2679
- * an empty metadata array is created and added.
2680
- * @returns The metadata array.
2681
- */
2682
- getOrCreateAnnotationParamTypes(Type) {
2683
- let annotationParamtypes = this.getAnnotationParamtypes(Type);
2684
- if (annotationParamtypes === void 0) {
2685
- Reflect.defineMetadata("di:paramtypes", (annotationParamtypes = []), Type);
2686
- }
2687
- return annotationParamtypes;
2688
- },
2689
- /**
2690
- * Gets the dependency keys representing what is needed to instantiate the specified type.
2691
- * @param Type - The type to get the dependencies for.
2692
- * @returns An array of dependency keys.
2693
- */
2694
- getDependencies(Type) {
2695
- // Note: Every detail of this getDependencies method is pretty deliberate at the moment, and probably not yet 100% tested from every possible angle,
2696
- // so be careful with making changes here as it can have a huge impact on complex end user apps.
2697
- // Preferably, only make changes to the dependency resolution process via a RFC.
2698
- let dependencies = dependencyLookup.get(Type);
2699
- if (dependencies === void 0) {
2700
- // Type.length is the number of constructor parameters. If this is 0, it could mean the class has an empty constructor
2701
- // but it could also mean the class has no constructor at all (in which case it inherits the constructor from the prototype).
2702
- // Non-zero constructor length + no paramtypes means emitDecoratorMetadata is off, or the class has no decorator.
2703
- // We're not doing anything with the above right now, but it's good to keep in mind for any future issues.
2704
- const inject = Type.inject;
2705
- if (inject === void 0) {
2706
- // design:paramtypes is set by tsc when emitDecoratorMetadata is enabled.
2707
- const designParamtypes = DI.getDesignParamtypes(Type);
2708
- // di:paramtypes is set by the parameter decorator from DI.createInterface or by @inject
2709
- const annotationParamtypes = DI.getAnnotationParamtypes(Type);
2710
- if (designParamtypes === void 0) {
2711
- if (annotationParamtypes === void 0) {
2712
- // Only go up the prototype if neither static inject nor any of the paramtypes is defined, as
2713
- // there is no sound way to merge a type's deps with its prototype's deps
2714
- const Proto = Object.getPrototypeOf(Type);
2715
- if (typeof Proto === "function" && Proto !== Function.prototype) {
2716
- dependencies = cloneArrayWithPossibleProps(DI.getDependencies(Proto));
2717
- }
2718
- else {
2719
- dependencies = [];
2720
- }
2721
- }
2722
- else {
2723
- // No design:paramtypes so just use the di:paramtypes
2724
- dependencies = cloneArrayWithPossibleProps(annotationParamtypes);
2725
- }
2726
- }
2727
- else if (annotationParamtypes === void 0) {
2728
- // No di:paramtypes so just use the design:paramtypes
2729
- dependencies = cloneArrayWithPossibleProps(designParamtypes);
2730
- }
2731
- else {
2732
- // We've got both, so merge them (in case of conflict on same index, di:paramtypes take precedence)
2733
- dependencies = cloneArrayWithPossibleProps(designParamtypes);
2734
- let len = annotationParamtypes.length;
2735
- let auAnnotationParamtype;
2736
- for (let i = 0; i < len; ++i) {
2737
- auAnnotationParamtype = annotationParamtypes[i];
2738
- if (auAnnotationParamtype !== void 0) {
2739
- dependencies[i] = auAnnotationParamtype;
2740
- }
2741
- }
2742
- const keys = Object.keys(annotationParamtypes);
2743
- len = keys.length;
2744
- let key;
2745
- for (let i = 0; i < len; ++i) {
2746
- key = keys[i];
2747
- if (!isArrayIndex(key)) {
2748
- dependencies[key] = annotationParamtypes[key];
2749
- }
2750
- }
2751
- }
2752
- }
2753
- else {
2754
- // Ignore paramtypes if we have static inject
2755
- dependencies = cloneArrayWithPossibleProps(inject);
2756
- }
2757
- dependencyLookup.set(Type, dependencies);
2758
- }
2759
- return dependencies;
2760
- },
2761
- /**
2762
- * Defines a property on a web component class. The value of this property will
2763
- * be resolved from the dependency injection container responsible for the element
2764
- * instance, based on where it is connected in the DOM.
2765
- * @param target - The target to define the property on.
2766
- * @param propertyName - The name of the property to define.
2767
- * @param key - The dependency injection key.
2768
- * @param respectConnection - Indicates whether or not to update the property value if the
2769
- * hosting component is disconnected and then re-connected at a different location in the DOM.
2770
- * @remarks
2771
- * The respectConnection option is only applicable to elements that descend from FASTElement.
2772
- */
2773
- defineProperty(target, propertyName, key, respectConnection = false) {
2774
- const diPropertyKey = `$di_${propertyName}`;
2775
- Reflect.defineProperty(target, propertyName, {
2776
- get: function () {
2777
- let value = this[diPropertyKey];
2778
- if (value === void 0) {
2779
- const container = this instanceof HTMLElement
2780
- ? DI.findResponsibleContainer(this)
2781
- : DI.getOrCreateDOMContainer();
2782
- value = container.get(key);
2783
- this[diPropertyKey] = value;
2784
- if (respectConnection && this instanceof FASTElement) {
2785
- const notifier = this.$fastController;
2786
- const handleChange = () => {
2787
- const newContainer = DI.findResponsibleContainer(this);
2788
- const newValue = newContainer.get(key);
2789
- const oldValue = this[diPropertyKey];
2790
- if (newValue !== oldValue) {
2791
- this[diPropertyKey] = value;
2792
- notifier.notify(propertyName);
2793
- }
2794
- };
2795
- notifier.subscribe({ handleChange }, "isConnected");
2796
- }
2797
- }
2798
- return value;
2799
- },
2800
- });
2801
- },
2802
- /**
2803
- * Creates a dependency injection key.
2804
- * @param nameConfigOrCallback - A friendly name for the key or a lambda that configures a
2805
- * default resolution for the dependency.
2806
- * @param configuror - If a friendly name was provided for the first parameter, then an optional
2807
- * lambda that configures a default resolution for the dependency can be provided second.
2808
- * @returns The created key.
2809
- * @remarks
2810
- * The created key can be used as a property decorator or constructor parameter decorator,
2811
- * in addition to its standard use in an inject array or through direct container APIs.
2812
- */
2813
- createInterface(nameConfigOrCallback, configuror) {
2814
- const configure = typeof nameConfigOrCallback === "function"
2815
- ? nameConfigOrCallback
2816
- : configuror;
2817
- const friendlyName = typeof nameConfigOrCallback === "string"
2818
- ? nameConfigOrCallback
2819
- : nameConfigOrCallback && "friendlyName" in nameConfigOrCallback
2820
- ? nameConfigOrCallback.friendlyName || defaultFriendlyName
2821
- : defaultFriendlyName;
2822
- const respectConnection = typeof nameConfigOrCallback === "string"
2823
- ? false
2824
- : nameConfigOrCallback && "respectConnection" in nameConfigOrCallback
2825
- ? nameConfigOrCallback.respectConnection || false
2826
- : false;
2827
- const Interface = function (target, property, index) {
2828
- if (target == null || new.target !== undefined) {
2829
- throw new Error(`No registration for interface: '${Interface.friendlyName}'`);
2830
- }
2831
- if (property) {
2832
- DI.defineProperty(target, property, Interface, respectConnection);
2833
- }
2834
- else {
2835
- const annotationParamtypes = DI.getOrCreateAnnotationParamTypes(target);
2836
- annotationParamtypes[index] = Interface;
2837
- }
2838
- };
2839
- Interface.$isInterface = true;
2840
- Interface.friendlyName = friendlyName == null ? "(anonymous)" : friendlyName;
2841
- if (configure != null) {
2842
- Interface.register = function (container, key) {
2843
- return configure(new ResolverBuilder(container, key !== null && key !== void 0 ? key : Interface));
2844
- };
2845
- }
2846
- Interface.toString = function toString() {
2847
- return `InterfaceSymbol<${Interface.friendlyName}>`;
2848
- };
2849
- return Interface;
2850
- },
2851
- /**
2852
- * A decorator that specifies what to inject into its target.
2853
- * @param dependencies - The dependencies to inject.
2854
- * @returns The decorator to be applied to the target class.
2855
- * @remarks
2856
- * The decorator can be used to decorate a class, listing all of the classes dependencies.
2857
- * Or it can be used to decorate a constructor paramter, indicating what to inject for that
2858
- * parameter.
2859
- * Or it can be used for a web component property, indicating what that property should resolve to.
2860
- */
2861
- inject(...dependencies) {
2862
- return function (target, key, descriptor) {
2863
- if (typeof descriptor === "number") {
2864
- // It's a parameter decorator.
2865
- const annotationParamtypes = DI.getOrCreateAnnotationParamTypes(target);
2866
- const dep = dependencies[0];
2867
- if (dep !== void 0) {
2868
- annotationParamtypes[descriptor] = dep;
2869
- }
2870
- }
2871
- else if (key) {
2872
- DI.defineProperty(target, key, dependencies[0]);
2873
- }
2874
- else {
2875
- const annotationParamtypes = descriptor
2876
- ? DI.getOrCreateAnnotationParamTypes(descriptor.value)
2877
- : DI.getOrCreateAnnotationParamTypes(target);
2878
- let dep;
2879
- for (let i = 0; i < dependencies.length; ++i) {
2880
- dep = dependencies[i];
2881
- if (dep !== void 0) {
2882
- annotationParamtypes[i] = dep;
2883
- }
2884
- }
2885
- }
2886
- };
2887
- },
2888
- /**
2889
- * Registers the `target` class as a transient dependency; each time the dependency is resolved
2890
- * a new instance will be created.
2891
- *
2892
- * @param target - The class / constructor function to register as transient.
2893
- * @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
2894
- *
2895
- * @example
2896
- * On an existing class
2897
- * ```ts
2898
- * class Foo { }
2899
- * DI.transient(Foo);
2900
- * ```
2901
- *
2902
- * @example
2903
- * Inline declaration
2904
- *
2905
- * ```ts
2906
- * const Foo = DI.transient(class { });
2907
- * // Foo is now strongly typed with register
2908
- * Foo.register(container);
2909
- * ```
2910
- *
2911
- * @public
2912
- */
2913
- transient(target) {
2914
- target.register = function register(container) {
2915
- const registration = Registration.transient(target, target);
2916
- return registration.register(container);
2917
- };
2918
- target.registerInRequestor = false;
2919
- return target;
2920
- },
2921
- /**
2922
- * Registers the `target` class as a singleton dependency; the class will only be created once. Each
2923
- * consecutive time the dependency is resolved, the same instance will be returned.
2924
- *
2925
- * @param target - The class / constructor function to register as a singleton.
2926
- * @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
2927
- * @example
2928
- * On an existing class
2929
- * ```ts
2930
- * class Foo { }
2931
- * DI.singleton(Foo);
2932
- * ```
2933
- *
2934
- * @example
2935
- * Inline declaration
2936
- * ```ts
2937
- * const Foo = DI.singleton(class { });
2938
- * // Foo is now strongly typed with register
2939
- * Foo.register(container);
2940
- * ```
2941
- *
2942
- * @public
2943
- */
2944
- singleton(target, options = defaultSingletonOptions) {
2945
- target.register = function register(container) {
2946
- const registration = Registration.singleton(target, target);
2947
- return registration.register(container);
2948
- };
2949
- target.registerInRequestor = options.scoped;
2950
- return target;
2951
- },
2952
- });
2953
- /**
2954
- * The interface key that resolves the dependency injection container itself.
2955
- * @public
2956
- */
2957
- const Container = DI.createInterface("Container");
2958
- /**
2959
- * A decorator that specifies what to inject into its target.
2960
- * @param dependencies - The dependencies to inject.
2961
- * @returns The decorator to be applied to the target class.
2962
- * @remarks
2963
- * The decorator can be used to decorate a class, listing all of the classes dependencies.
2964
- * Or it can be used to decorate a constructor paramter, indicating what to inject for that
2965
- * parameter.
2966
- * Or it can be used for a web component property, indicating what that property should resolve to.
2967
- *
2968
- * @public
2969
- */
2970
- DI.inject;
2971
- const defaultSingletonOptions = { scoped: false };
2972
- /** @internal */
2973
- class ResolverImpl {
2974
- constructor(key, strategy, state) {
2975
- this.key = key;
2976
- this.strategy = strategy;
2977
- this.state = state;
2978
- this.resolving = false;
2979
- }
2980
- get $isResolver() {
2981
- return true;
2982
- }
2983
- register(container) {
2984
- return container.registerResolver(this.key, this);
2985
- }
2986
- resolve(handler, requestor) {
2987
- switch (this.strategy) {
2988
- case 0 /* instance */:
2989
- return this.state;
2990
- case 1 /* singleton */: {
2991
- if (this.resolving) {
2992
- throw new Error(`Cyclic dependency found: ${this.state.name}`);
2993
- }
2994
- this.resolving = true;
2995
- this.state = handler
2996
- .getFactory(this.state)
2997
- .construct(requestor);
2998
- this.strategy = 0 /* instance */;
2999
- this.resolving = false;
3000
- return this.state;
3001
- }
3002
- case 2 /* transient */: {
3003
- // Always create transients from the requesting container
3004
- const factory = handler.getFactory(this.state);
3005
- if (factory === null) {
3006
- throw new Error(`Resolver for ${String(this.key)} returned a null factory`);
3007
- }
3008
- return factory.construct(requestor);
3009
- }
3010
- case 3 /* callback */:
3011
- return this.state(handler, requestor, this);
3012
- case 4 /* array */:
3013
- return this.state[0].resolve(handler, requestor);
3014
- case 5 /* alias */:
3015
- return requestor.get(this.state);
3016
- default:
3017
- throw new Error(`Invalid resolver strategy specified: ${this.strategy}.`);
3018
- }
3019
- }
3020
- getFactory(container) {
3021
- var _a, _b, _c;
3022
- switch (this.strategy) {
3023
- case 1 /* singleton */:
3024
- case 2 /* transient */:
3025
- return container.getFactory(this.state);
3026
- case 5 /* alias */:
3027
- return (_c = (_b = (_a = container.getResolver(this.state)) === null || _a === void 0 ? void 0 : _a.getFactory) === null || _b === void 0 ? void 0 : _b.call(_a, container)) !== null && _c !== void 0 ? _c : null;
3028
- default:
3029
- return null;
3030
- }
3031
- }
3032
- }
3033
- function containerGetKey(d) {
3034
- return this.get(d);
3035
- }
3036
- function transformInstance(inst, transform) {
3037
- return transform(inst);
3038
- }
3039
- /** @internal */
3040
- class FactoryImpl {
3041
- constructor(Type, dependencies) {
3042
- this.Type = Type;
3043
- this.dependencies = dependencies;
3044
- this.transformers = null;
3045
- }
3046
- construct(container, dynamicDependencies) {
3047
- let instance;
3048
- if (dynamicDependencies === void 0) {
3049
- instance = new this.Type(...this.dependencies.map(containerGetKey, container));
3050
- }
3051
- else {
3052
- instance = new this.Type(...this.dependencies.map(containerGetKey, container), ...dynamicDependencies);
3053
- }
3054
- if (this.transformers == null) {
3055
- return instance;
3056
- }
3057
- return this.transformers.reduce(transformInstance, instance);
3058
- }
3059
- registerTransformer(transformer) {
3060
- (this.transformers || (this.transformers = [])).push(transformer);
3061
- }
3062
- }
3063
- const containerResolver = {
3064
- $isResolver: true,
3065
- resolve(handler, requestor) {
3066
- return requestor;
3067
- },
3068
- };
3069
- function isRegistry(obj) {
3070
- return typeof obj.register === "function";
3071
- }
3072
- function isSelfRegistry(obj) {
3073
- return isRegistry(obj) && typeof obj.registerInRequestor === "boolean";
3074
- }
3075
- function isRegisterInRequester(obj) {
3076
- return isSelfRegistry(obj) && obj.registerInRequestor;
3077
- }
3078
- function isClass(obj) {
3079
- return obj.prototype !== void 0;
3080
- }
3081
- const InstrinsicTypeNames = new Set([
3082
- "Array",
3083
- "ArrayBuffer",
3084
- "Boolean",
3085
- "DataView",
3086
- "Date",
3087
- "Error",
3088
- "EvalError",
3089
- "Float32Array",
3090
- "Float64Array",
3091
- "Function",
3092
- "Int8Array",
3093
- "Int16Array",
3094
- "Int32Array",
3095
- "Map",
3096
- "Number",
3097
- "Object",
3098
- "Promise",
3099
- "RangeError",
3100
- "ReferenceError",
3101
- "RegExp",
3102
- "Set",
3103
- "SharedArrayBuffer",
3104
- "String",
3105
- "SyntaxError",
3106
- "TypeError",
3107
- "Uint8Array",
3108
- "Uint8ClampedArray",
3109
- "Uint16Array",
3110
- "Uint32Array",
3111
- "URIError",
3112
- "WeakMap",
3113
- "WeakSet",
3114
- ]);
3115
- const DILocateParentEventType = "__DI_LOCATE_PARENT__";
3116
- const factories = new Map();
3117
- /**
3118
- * @internal
3119
- */
3120
- class ContainerImpl {
3121
- constructor(owner, config) {
3122
- this.owner = owner;
3123
- this.config = config;
3124
- this._parent = void 0;
3125
- this.registerDepth = 0;
3126
- this.context = null;
3127
- if (owner !== null) {
3128
- owner.$$container$$ = this;
3129
- }
3130
- this.resolvers = new Map();
3131
- this.resolvers.set(Container, containerResolver);
3132
- if (owner instanceof Node) {
3133
- owner.addEventListener(DILocateParentEventType, (e) => {
3134
- if (e.composedPath()[0] !== this.owner) {
3135
- e.detail.container = this;
3136
- e.stopImmediatePropagation();
3137
- }
3138
- });
3139
- }
3140
- }
3141
- get parent() {
3142
- if (this._parent === void 0) {
3143
- this._parent = this.config.parentLocator(this.owner);
3144
- }
3145
- return this._parent;
3146
- }
3147
- get depth() {
3148
- return this.parent === null ? 0 : this.parent.depth + 1;
3149
- }
3150
- get responsibleForOwnerRequests() {
3151
- return this.config.responsibleForOwnerRequests;
3152
- }
3153
- registerWithContext(context, ...params) {
3154
- this.context = context;
3155
- this.register(...params);
3156
- this.context = null;
3157
- return this;
3158
- }
3159
- register(...params) {
3160
- if (++this.registerDepth === 100) {
3161
- throw new Error("Unable to autoregister dependency");
3162
- // Most likely cause is trying to register a plain object that does not have a
3163
- // register method and is not a class constructor
3164
- }
3165
- let current;
3166
- let keys;
3167
- let value;
3168
- let j;
3169
- let jj;
3170
- const context = this.context;
3171
- for (let i = 0, ii = params.length; i < ii; ++i) {
3172
- current = params[i];
3173
- if (!isObject(current)) {
3174
- continue;
3175
- }
3176
- if (isRegistry(current)) {
3177
- current.register(this, context);
3178
- }
3179
- else if (isClass(current)) {
3180
- Registration.singleton(current, current).register(this);
3181
- }
3182
- else {
3183
- keys = Object.keys(current);
3184
- j = 0;
3185
- jj = keys.length;
3186
- for (; j < jj; ++j) {
3187
- value = current[keys[j]];
3188
- if (!isObject(value)) {
3189
- continue;
3190
- }
3191
- // note: we could remove this if-branch and call this.register directly
3192
- // - the extra check is just a perf tweak to create fewer unnecessary arrays by the spread operator
3193
- if (isRegistry(value)) {
3194
- value.register(this, context);
3195
- }
3196
- else {
3197
- this.register(value);
3198
- }
3199
- }
3200
- }
3201
- }
3202
- --this.registerDepth;
3203
- return this;
3204
- }
3205
- registerResolver(key, resolver) {
3206
- validateKey(key);
3207
- const resolvers = this.resolvers;
3208
- const result = resolvers.get(key);
3209
- if (result == null) {
3210
- resolvers.set(key, resolver);
3211
- }
3212
- else if (result instanceof ResolverImpl &&
3213
- result.strategy === 4 /* array */) {
3214
- result.state.push(resolver);
3215
- }
3216
- else {
3217
- resolvers.set(key, new ResolverImpl(key, 4 /* array */, [result, resolver]));
3218
- }
3219
- return resolver;
3220
- }
3221
- registerTransformer(key, transformer) {
3222
- const resolver = this.getResolver(key);
3223
- if (resolver == null) {
3224
- return false;
3225
- }
3226
- if (resolver.getFactory) {
3227
- const factory = resolver.getFactory(this);
3228
- if (factory == null) {
3229
- return false;
3230
- }
3231
- // This type cast is a bit of a hacky one, necessary due to the duplicity of IResolverLike.
3232
- // Problem is that that interface's type arg can be of type Key, but the getFactory method only works on
3233
- // type Constructable. So the return type of that optional method has this additional constraint, which
3234
- // seems to confuse the type checker.
3235
- factory.registerTransformer(transformer);
3236
- return true;
3237
- }
3238
- return false;
3239
- }
3240
- getResolver(key, autoRegister = true) {
3241
- validateKey(key);
3242
- if (key.resolve !== void 0) {
3243
- return key;
3244
- }
3245
- /* eslint-disable-next-line @typescript-eslint/no-this-alias */
3246
- let current = this;
3247
- let resolver;
3248
- while (current != null) {
3249
- resolver = current.resolvers.get(key);
3250
- if (resolver == null) {
3251
- if (current.parent == null) {
3252
- const handler = isRegisterInRequester(key)
3253
- ? this
3254
- : current;
3255
- return autoRegister ? this.jitRegister(key, handler) : null;
3256
- }
3257
- current = current.parent;
3258
- }
3259
- else {
3260
- return resolver;
3261
- }
3262
- }
3263
- return null;
3264
- }
3265
- has(key, searchAncestors = false) {
3266
- return this.resolvers.has(key)
3267
- ? true
3268
- : searchAncestors && this.parent != null
3269
- ? this.parent.has(key, true)
3270
- : false;
3271
- }
3272
- get(key) {
3273
- validateKey(key);
3274
- if (key.$isResolver) {
3275
- return key.resolve(this, this);
3276
- }
3277
- /* eslint-disable-next-line @typescript-eslint/no-this-alias */
3278
- let current = this;
3279
- let resolver;
3280
- while (current != null) {
3281
- resolver = current.resolvers.get(key);
3282
- if (resolver == null) {
3283
- if (current.parent == null) {
3284
- const handler = isRegisterInRequester(key)
3285
- ? this
3286
- : current;
3287
- resolver = this.jitRegister(key, handler);
3288
- return resolver.resolve(current, this);
3289
- }
3290
- current = current.parent;
3291
- }
3292
- else {
3293
- return resolver.resolve(current, this);
3294
- }
3295
- }
3296
- throw new Error(`Unable to resolve key: ${key}`);
3297
- }
3298
- getAll(key, searchAncestors = false) {
3299
- validateKey(key);
3300
- /* eslint-disable-next-line @typescript-eslint/no-this-alias */
3301
- const requestor = this;
3302
- let current = requestor;
3303
- let resolver;
3304
- if (searchAncestors) {
3305
- let resolutions = emptyArray;
3306
- while (current != null) {
3307
- resolver = current.resolvers.get(key);
3308
- if (resolver != null) {
3309
- resolutions = resolutions.concat(
3310
- /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
3311
- buildAllResponse(resolver, current, requestor));
3312
- }
3313
- current = current.parent;
3314
- }
3315
- return resolutions;
3316
- }
3317
- else {
3318
- while (current != null) {
3319
- resolver = current.resolvers.get(key);
3320
- if (resolver == null) {
3321
- current = current.parent;
3322
- if (current == null) {
3323
- return emptyArray;
3324
- }
3325
- }
3326
- else {
3327
- return buildAllResponse(resolver, current, requestor);
3328
- }
3329
- }
3330
- }
3331
- return emptyArray;
3332
- }
3333
- getFactory(Type) {
3334
- let factory = factories.get(Type);
3335
- if (factory === void 0) {
3336
- if (isNativeFunction(Type)) {
3337
- throw new Error(`${Type.name} is a native function and therefore cannot be safely constructed by DI. If this is intentional, please use a callback or cachedCallback resolver.`);
3338
- }
3339
- factories.set(Type, (factory = new FactoryImpl(Type, DI.getDependencies(Type))));
3340
- }
3341
- return factory;
3342
- }
3343
- registerFactory(key, factory) {
3344
- factories.set(key, factory);
3345
- }
3346
- createChild(config) {
3347
- return new ContainerImpl(null, Object.assign({}, this.config, config, { parentLocator: () => this }));
3348
- }
3349
- jitRegister(keyAsValue, handler) {
3350
- if (typeof keyAsValue !== "function") {
3351
- throw new Error(`Attempted to jitRegister something that is not a constructor: '${keyAsValue}'. Did you forget to register this dependency?`);
3352
- }
3353
- if (InstrinsicTypeNames.has(keyAsValue.name)) {
3354
- throw new Error(`Attempted to jitRegister an intrinsic type: ${keyAsValue.name}. Did you forget to add @inject(Key)`);
3355
- }
3356
- if (isRegistry(keyAsValue)) {
3357
- const registrationResolver = keyAsValue.register(handler);
3358
- if (!(registrationResolver instanceof Object) ||
3359
- registrationResolver.resolve == null) {
3360
- const newResolver = handler.resolvers.get(keyAsValue);
3361
- if (newResolver != void 0) {
3362
- return newResolver;
3363
- }
3364
- throw new Error("A valid resolver was not returned from the static register method");
3365
- }
3366
- return registrationResolver;
3367
- }
3368
- else if (keyAsValue.$isInterface) {
3369
- throw new Error(`Attempted to jitRegister an interface: ${keyAsValue.friendlyName}`);
3370
- }
3371
- else {
3372
- const resolver = this.config.defaultResolver(keyAsValue, handler);
3373
- handler.resolvers.set(keyAsValue, resolver);
3374
- return resolver;
3375
- }
3376
- }
3377
- }
3378
- const cache = new WeakMap();
3379
- function cacheCallbackResult(fun) {
3380
- return function (handler, requestor, resolver) {
3381
- if (cache.has(resolver)) {
3382
- return cache.get(resolver);
3383
- }
3384
- const t = fun(handler, requestor, resolver);
3385
- cache.set(resolver, t);
3386
- return t;
3387
- };
3388
- }
3389
- /**
3390
- * You can use the resulting Registration of any of the factory methods
3391
- * to register with the container.
3392
- *
3393
- * @example
3394
- * ```
3395
- * class Foo {}
3396
- * const container = DI.createContainer();
3397
- * container.register(Registration.instance(Foo, new Foo()));
3398
- * container.get(Foo);
3399
- * ```
3400
- *
3401
- * @public
3402
- */
3403
- const Registration = Object.freeze({
3404
- /**
3405
- * Allows you to pass an instance.
3406
- * Every time you request this {@link Key} you will get this instance back.
3407
- *
3408
- * @example
3409
- * ```
3410
- * Registration.instance(Foo, new Foo()));
3411
- * ```
3412
- *
3413
- * @param key - The key to register the instance under.
3414
- * @param value - The instance to return when the key is requested.
3415
- */
3416
- instance(key, value) {
3417
- return new ResolverImpl(key, 0 /* instance */, value);
3418
- },
3419
- /**
3420
- * Creates an instance from the class.
3421
- * Every time you request this {@link Key} you will get the same one back.
3422
- *
3423
- * @example
3424
- * ```
3425
- * Registration.singleton(Foo, Foo);
3426
- * ```
3427
- *
3428
- * @param key - The key to register the singleton under.
3429
- * @param value - The class to instantiate as a singleton when first requested.
3430
- */
3431
- singleton(key, value) {
3432
- return new ResolverImpl(key, 1 /* singleton */, value);
3433
- },
3434
- /**
3435
- * Creates an instance from a class.
3436
- * Every time you request this {@link Key} you will get a new instance.
3437
- *
3438
- * @example
3439
- * ```
3440
- * Registration.instance(Foo, Foo);
3441
- * ```
3442
- *
3443
- * @param key - The key to register the instance type under.
3444
- * @param value - The class to instantiate each time the key is requested.
3445
- */
3446
- transient(key, value) {
3447
- return new ResolverImpl(key, 2 /* transient */, value);
3448
- },
3449
- /**
3450
- * Delegates to a callback function to provide the dependency.
3451
- * Every time you request this {@link Key} the callback will be invoked to provide
3452
- * the dependency.
3453
- *
3454
- * @example
3455
- * ```
3456
- * Registration.callback(Foo, () => new Foo());
3457
- * Registration.callback(Bar, (c: Container) => new Bar(c.get(Foo)));
3458
- * ```
3459
- *
3460
- * @param key - The key to register the callback for.
3461
- * @param callback - The function that is expected to return the dependency.
3462
- */
3463
- callback(key, callback) {
3464
- return new ResolverImpl(key, 3 /* callback */, callback);
3465
- },
3466
- /**
3467
- * Delegates to a callback function to provide the dependency and then caches the
3468
- * dependency for future requests.
3469
- *
3470
- * @example
3471
- * ```
3472
- * Registration.cachedCallback(Foo, () => new Foo());
3473
- * Registration.cachedCallback(Bar, (c: Container) => new Bar(c.get(Foo)));
3474
- * ```
3475
- *
3476
- * @param key - The key to register the callback for.
3477
- * @param callback - The function that is expected to return the dependency.
3478
- * @remarks
3479
- * If you pass the same Registration to another container, the same cached value will be used.
3480
- * Should all references to the resolver returned be removed, the cache will expire.
3481
- */
3482
- cachedCallback(key, callback) {
3483
- return new ResolverImpl(key, 3 /* callback */, cacheCallbackResult(callback));
3484
- },
3485
- /**
3486
- * Creates an alternate {@link Key} to retrieve an instance by.
3487
- *
3488
- * @example
3489
- * ```
3490
- * Register.singleton(Foo, Foo)
3491
- * Register.aliasTo(Foo, MyFoos);
3492
- *
3493
- * container.getAll(MyFoos) // contains an instance of Foo
3494
- * ```
3495
- *
3496
- * @param originalKey - The original key that has been registered.
3497
- * @param aliasKey - The alias to the original key.
3498
- */
3499
- aliasTo(originalKey, aliasKey) {
3500
- return new ResolverImpl(aliasKey, 5 /* alias */, originalKey);
3501
- },
3502
- });
3503
- /** @internal */
3504
- function validateKey(key) {
3505
- if (key === null || key === void 0) {
3506
- throw new Error("key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?");
3507
- }
3508
- }
3509
- function buildAllResponse(resolver, handler, requestor) {
3510
- if (resolver instanceof ResolverImpl &&
3511
- resolver.strategy === 4 /* array */) {
3512
- const state = resolver.state;
3513
- let i = state.length;
3514
- const results = new Array(i);
3515
- while (i--) {
3516
- results[i] = state[i].resolve(handler, requestor);
3517
- }
3518
- return results;
3519
- }
3520
- return [resolver.resolve(handler, requestor)];
3521
- }
3522
- const defaultFriendlyName = "(anonymous)";
3523
- function isObject(value) {
3524
- return (typeof value === "object" && value !== null) || typeof value === "function";
3525
- }
3526
- /**
3527
- * Determine whether the value is a native function.
3528
- *
3529
- * @param fn - The function to check.
3530
- * @returns `true` is the function is a native function, otherwise `false`
3531
- */
3532
- const isNativeFunction = (function () {
3533
- const lookup = new WeakMap();
3534
- let isNative = false;
3535
- let sourceText = "";
3536
- let i = 0;
3537
- return function (fn) {
3538
- isNative = lookup.get(fn);
3539
- if (isNative === void 0) {
3540
- sourceText = fn.toString();
3541
- i = sourceText.length;
3542
- // http://www.ecma-international.org/ecma-262/#prod-NativeFunction
3543
- isNative =
3544
- // 29 is the length of 'function () { [native code] }' which is the smallest length of a native function string
3545
- i >= 29 &&
3546
- // 100 seems to be a safe upper bound of the max length of a native function. In Chrome and FF it's 56, in Edge it's 61.
3547
- i <= 100 &&
3548
- // This whole heuristic *could* be tricked by a comment. Do we need to care about that?
3549
- sourceText.charCodeAt(i - 1) === 0x7d && // }
3550
- // TODO: the spec is a little vague about the precise constraints, so we do need to test this across various browsers to make sure just one whitespace is a safe assumption.
3551
- sourceText.charCodeAt(i - 2) <= 0x20 && // whitespace
3552
- sourceText.charCodeAt(i - 3) === 0x5d && // ]
3553
- sourceText.charCodeAt(i - 4) === 0x65 && // e
3554
- sourceText.charCodeAt(i - 5) === 0x64 && // d
3555
- sourceText.charCodeAt(i - 6) === 0x6f && // o
3556
- sourceText.charCodeAt(i - 7) === 0x63 && // c
3557
- sourceText.charCodeAt(i - 8) === 0x20 && //
3558
- sourceText.charCodeAt(i - 9) === 0x65 && // e
3559
- sourceText.charCodeAt(i - 10) === 0x76 && // v
3560
- sourceText.charCodeAt(i - 11) === 0x69 && // i
3561
- sourceText.charCodeAt(i - 12) === 0x74 && // t
3562
- sourceText.charCodeAt(i - 13) === 0x61 && // a
3563
- sourceText.charCodeAt(i - 14) === 0x6e && // n
3564
- sourceText.charCodeAt(i - 15) === 0x58; // [
3565
- lookup.set(fn, isNative);
3566
- }
3567
- return isNative;
3568
- };
3569
- })();
3570
- const isNumericLookup = {};
3571
- function isArrayIndex(value) {
3572
- switch (typeof value) {
3573
- case "number":
3574
- return value >= 0 && (value | 0) === value;
3575
- case "string": {
3576
- const result = isNumericLookup[value];
3577
- if (result !== void 0) {
3578
- return result;
3579
- }
3580
- const length = value.length;
3581
- if (length === 0) {
3582
- return (isNumericLookup[value] = false);
3583
- }
3584
- let ch = 0;
3585
- for (let i = 0; i < length; ++i) {
3586
- ch = value.charCodeAt(i);
3587
- if ((i === 0 && ch === 0x30 && length > 1) /* must not start with 0 */ ||
3588
- ch < 0x30 /* 0 */ ||
3589
- ch > 0x39 /* 9 */) {
3590
- return (isNumericLookup[value] = false);
3591
- }
3592
- }
3593
- return (isNumericLookup[value] = true);
3594
- }
3595
- default:
3596
- return false;
3597
- }
3598
- }
3599
-
3600
- function presentationKeyFromTag(tagName) {
3601
- return `${tagName.toLowerCase()}:presentation`;
3602
- }
3603
- const presentationRegistry = new Map();
3604
- /**
3605
- * An API gateway to component presentation features.
3606
- * @public
3607
- */
3608
- const ComponentPresentation = Object.freeze({
3609
- /**
3610
- * Defines a component presentation for an element.
3611
- * @param tagName - The element name to define the presentation for.
3612
- * @param presentation - The presentation that will be applied to matching elements.
3613
- * @param container - The dependency injection container to register the configuration in.
3614
- * @public
3615
- */
3616
- define(tagName, presentation, container) {
3617
- const key = presentationKeyFromTag(tagName);
3618
- const existing = presentationRegistry.get(key);
3619
- if (existing === void 0) {
3620
- presentationRegistry.set(key, presentation);
3621
- }
3622
- else {
3623
- // false indicates that we have more than one presentation
3624
- // registered for a tagName and we must resolve through DI
3625
- presentationRegistry.set(key, false);
3626
- }
3627
- container.register(Registration.instance(key, presentation));
3628
- },
3629
- /**
3630
- * Finds a component presentation for the specified element name,
3631
- * searching the DOM hierarchy starting from the provided element.
3632
- * @param tagName - The name of the element to locate the presentation for.
3633
- * @param element - The element to begin the search from.
3634
- * @returns The component presentation or null if none is found.
3635
- * @public
3636
- */
3637
- forTag(tagName, element) {
3638
- const key = presentationKeyFromTag(tagName);
3639
- const existing = presentationRegistry.get(key);
3640
- if (existing === false) {
3641
- const container = DI.findResponsibleContainer(element);
3642
- return container.get(key);
3643
- }
3644
- return existing || null;
3645
- },
3646
- });
3647
- /**
3648
- * The default implementation of ComponentPresentation, used by FoundationElement.
3649
- * @public
3650
- */
3651
- class DefaultComponentPresentation {
3652
- /**
3653
- * Creates an instance of DefaultComponentPresentation.
3654
- * @param template - The template to apply to the element.
3655
- * @param styles - The styles to apply to the element.
3656
- * @public
3657
- */
3658
- constructor(template, styles) {
3659
- this.template = template || null;
3660
- this.styles =
3661
- styles === void 0
3662
- ? null
3663
- : Array.isArray(styles)
3664
- ? ElementStyles.create(styles)
3665
- : styles instanceof ElementStyles
3666
- ? styles
3667
- : ElementStyles.create([styles]);
3668
- }
3669
- /**
3670
- * Applies the presentation details to the specified element.
3671
- * @param element - The element to apply the presentation details to.
3672
- * @public
3673
- */
3674
- applyTo(element) {
3675
- const controller = element.$fastController;
3676
- if (controller.template === null) {
3677
- controller.template = this.template;
3678
- }
3679
- if (controller.styles === null) {
3680
- controller.styles = this.styles;
3681
- }
3682
- }
3683
- }
3684
-
3685
- /**
3686
- * Defines a foundation element class that:
3687
- * 1. Connects the element to its ComponentPresentation
3688
- * 2. Allows resolving the element template from the instance or ComponentPresentation
3689
- * 3. Allows resolving the element styles from the instance or ComponentPresentation
3690
- *
3691
- * @public
3692
- */
3693
- class FoundationElement extends FASTElement {
3694
- constructor() {
3695
- super(...arguments);
3696
- this._presentation = void 0;
3697
- }
3698
- /**
3699
- * A property which resolves the ComponentPresentation instance
3700
- * for the current component.
3701
- * @public
3702
- */
3703
- get $presentation() {
3704
- if (this._presentation === void 0) {
3705
- this._presentation = ComponentPresentation.forTag(this.tagName, this);
3706
- }
3707
- return this._presentation;
3708
- }
3709
- templateChanged() {
3710
- if (this.template !== undefined) {
3711
- this.$fastController.template = this.template;
3712
- }
3713
- }
3714
- stylesChanged() {
3715
- if (this.styles !== undefined) {
3716
- this.$fastController.styles = this.styles;
3717
- }
3718
- }
3719
- /**
3720
- * The connected callback for this FASTElement.
3721
- * @remarks
3722
- * This method is invoked by the platform whenever this FoundationElement
3723
- * becomes connected to the document.
3724
- * @public
3725
- */
3726
- connectedCallback() {
3727
- if (this.$presentation !== null) {
3728
- this.$presentation.applyTo(this);
3729
- }
3730
- super.connectedCallback();
3731
- }
3732
- /**
3733
- * Defines an element registry function with a set of element definition defaults.
3734
- * @param elementDefinition - The definition of the element to create the registry
3735
- * function for.
3736
- * @public
3737
- */
3738
- static compose(elementDefinition) {
3739
- return (overrideDefinition = {}) => new FoundationElementRegistry(this === FoundationElement
3740
- ? class extends FoundationElement {
3741
- }
3742
- : this, elementDefinition, overrideDefinition);
3743
- }
3744
- }
3745
- __decorate([
3746
- observable
3747
- ], FoundationElement.prototype, "template", void 0);
3748
- __decorate([
3749
- observable
3750
- ], FoundationElement.prototype, "styles", void 0);
3751
- function resolveOption(option, context, definition) {
3752
- if (typeof option === "function") {
3753
- return option(context, definition);
3754
- }
3755
- return option;
3756
- }
3757
- /**
3758
- * Registry capable of defining presentation properties for a DOM Container hierarchy.
3759
- *
3760
- * @internal
3761
- */
3762
- /* eslint-disable @typescript-eslint/no-unused-vars */
3763
- class FoundationElementRegistry {
3764
- constructor(type, elementDefinition, overrideDefinition) {
3765
- this.type = type;
3766
- this.elementDefinition = elementDefinition;
3767
- this.overrideDefinition = overrideDefinition;
3768
- this.definition = Object.assign(Object.assign({}, this.elementDefinition), this.overrideDefinition);
3769
- }
3770
- register(container, context) {
3771
- const definition = this.definition;
3772
- const overrideDefinition = this.overrideDefinition;
3773
- const prefix = definition.prefix || context.elementPrefix;
3774
- const name = `${prefix}-${definition.baseName}`;
3775
- context.tryDefineElement({
3776
- name,
3777
- type: this.type,
3778
- baseClass: this.elementDefinition.baseClass,
3779
- callback: x => {
3780
- const presentation = new DefaultComponentPresentation(resolveOption(definition.template, x, definition), resolveOption(definition.styles, x, definition));
3781
- x.definePresentation(presentation);
3782
- let shadowOptions = resolveOption(definition.shadowOptions, x, definition);
3783
- if (x.shadowRootMode) {
3784
- // If the design system has overridden the shadow root mode, we need special handling.
3785
- if (shadowOptions) {
3786
- // If there are shadow options present in the definition, then
3787
- // either the component itself has specified an option or the
3788
- // registry function has overridden it.
3789
- if (!overrideDefinition.shadowOptions) {
3790
- // There were shadow options provided by the component and not overridden by
3791
- // the registry.
3792
- shadowOptions.mode = x.shadowRootMode;
3793
- }
3794
- }
3795
- else if (shadowOptions !== null) {
3796
- // If the component author did not provide shadow options,
3797
- // and did not null them out (light dom opt-in) then they
3798
- // were relying on the FASTElement default. So, if the
3799
- // design system provides a mode, we need to create the options
3800
- // to override the default.
3801
- shadowOptions = { mode: x.shadowRootMode };
3802
- }
3803
- }
3804
- x.defineElement({
3805
- elementOptions: resolveOption(definition.elementOptions, x, definition),
3806
- shadowOptions,
3807
- attributes: resolveOption(definition.attributes, x, definition),
3808
- });
3809
- },
3810
- });
3811
- }
3812
- }
3813
- /* eslint-enable @typescript-eslint/no-unused-vars */
3814
-
3815
- /**
3816
- * Retrieves the "composed parent" element of a node, ignoring DOM tree boundaries.
3817
- * When the parent of a node is a shadow-root, it will return the host
3818
- * element of the shadow root. Otherwise it will return the parent node or null if
3819
- * no parent node exists.
3820
- * @param element - The element for which to retrieve the composed parent
3821
- *
3822
- * @public
3823
- */
3824
- function composedParent(element) {
3825
- const parentNode = element.parentElement;
3826
- if (parentNode) {
3827
- return parentNode;
3828
- }
3829
- else {
3830
- const rootNode = element.getRootNode();
3831
- if (rootNode.host instanceof HTMLElement) {
3832
- // this is shadow-root
3833
- return rootNode.host;
3834
- }
3835
- }
3836
- return null;
3837
- }
3838
-
3839
- /**
3840
- * Determines if the reference element contains the test element in a "composed" DOM tree that
3841
- * ignores shadow DOM boundaries.
3842
- *
3843
- * Returns true of the test element is a descendent of the reference, or exist in
3844
- * a shadow DOM that is a logical descendent of the reference. Otherwise returns false.
3845
- * @param reference - The element to test for containment against.
3846
- * @param test - The element being tested for containment.
3847
- *
3848
- * @public
3849
- */
3850
- function composedContains(reference, test) {
3851
- let current = test;
3852
- while (current !== null) {
3853
- if (current === reference) {
3854
- return true;
3855
- }
3856
- current = composedParent(current);
3857
- }
3858
- return false;
3859
- }
3860
-
3861
- const defaultElement = document.createElement("div");
3862
- function isFastElement(element) {
3863
- return element instanceof FASTElement;
3864
- }
3865
- class QueuedStyleSheetTarget {
3866
- setProperty(name, value) {
3867
- DOM.queueUpdate(() => this.target.setProperty(name, value));
3868
- }
3869
- removeProperty(name) {
3870
- DOM.queueUpdate(() => this.target.removeProperty(name));
3871
- }
3872
- }
3873
- /**
3874
- * Handles setting properties for a FASTElement using Constructable Stylesheets
3875
- */
3876
- class ConstructableStyleSheetTarget extends QueuedStyleSheetTarget {
3877
- constructor(source) {
3878
- super();
3879
- const sheet = new CSSStyleSheet();
3880
- this.target = sheet.cssRules[sheet.insertRule(":host{}")].style;
3881
- source.$fastController.addStyles(ElementStyles.create([sheet]));
3882
- }
3883
- }
3884
- class DocumentStyleSheetTarget extends QueuedStyleSheetTarget {
3885
- constructor() {
3886
- super();
3887
- const sheet = new CSSStyleSheet();
3888
- this.target = sheet.cssRules[sheet.insertRule(":root{}")].style;
3889
- document.adoptedStyleSheets = [
3890
- ...document.adoptedStyleSheets,
3891
- sheet,
3892
- ];
3893
- }
3894
- }
3895
- class HeadStyleElementStyleSheetTarget extends QueuedStyleSheetTarget {
3896
- constructor() {
3897
- super();
3898
- this.style = document.createElement("style");
3899
- document.head.appendChild(this.style);
3900
- const { sheet } = this.style;
3901
- // Because the HTMLStyleElement has been appended,
3902
- // there shouldn't exist a case where `sheet` is null,
3903
- // but if-check it just in case.
3904
- if (sheet) {
3905
- // https://github.com/jsdom/jsdom uses https://github.com/NV/CSSOM for it's CSSOM implementation,
3906
- // which implements the DOM Level 2 spec for CSSStyleSheet where insertRule() requires an index argument.
3907
- const index = sheet.insertRule(":root{}", sheet.cssRules.length);
3908
- this.target = sheet.cssRules[index].style;
3909
- }
3910
- }
3911
- }
3912
- /**
3913
- * Handles setting properties for a FASTElement using an HTMLStyleElement
3914
- */
3915
- class StyleElementStyleSheetTarget {
3916
- constructor(target) {
3917
- this.store = new Map();
3918
- this.target = null;
3919
- const controller = target.$fastController;
3920
- this.style = document.createElement("style");
3921
- controller.addStyles(this.style);
3922
- Observable.getNotifier(controller).subscribe(this, "isConnected");
3923
- this.handleChange(controller, "isConnected");
3924
- }
3925
- targetChanged() {
3926
- if (this.target !== null) {
3927
- for (const [key, value] of this.store.entries()) {
3928
- this.target.setProperty(key, value);
3929
- }
3930
- }
3931
- }
3932
- setProperty(name, value) {
3933
- this.store.set(name, value);
3934
- DOM.queueUpdate(() => {
3935
- if (this.target !== null) {
3936
- this.target.setProperty(name, value);
3937
- }
3938
- });
3939
- }
3940
- removeProperty(name) {
3941
- this.store.delete(name);
3942
- DOM.queueUpdate(() => {
3943
- if (this.target !== null) {
3944
- this.target.removeProperty(name);
3945
- }
3946
- });
3947
- }
3948
- handleChange(source, key) {
3949
- // HTMLStyleElement.sheet is null if the element isn't connected to the DOM,
3950
- // so this method reacts to changes in DOM connection for the element hosting
3951
- // the HTMLStyleElement.
3952
- //
3953
- // All rules applied via the CSSOM also get cleared when the element disconnects,
3954
- // so we need to add a new rule each time and populate it with the stored properties
3955
- const { sheet } = this.style;
3956
- if (sheet) {
3957
- // Safari will throw if we try to use the return result of insertRule()
3958
- // to index the rule inline, so store as a const prior to indexing.
3959
- // https://github.com/jsdom/jsdom uses https://github.com/NV/CSSOM for it's CSSOM implementation,
3960
- // which implements the DOM Level 2 spec for CSSStyleSheet where insertRule() requires an index argument.
3961
- const index = sheet.insertRule(":host{}", sheet.cssRules.length);
3962
- this.target = sheet.cssRules[index].style;
3963
- }
3964
- else {
3965
- this.target = null;
3966
- }
3967
- }
3968
- }
3969
- __decorate([
3970
- observable
3971
- ], StyleElementStyleSheetTarget.prototype, "target", void 0);
3972
- /**
3973
- * Handles setting properties for a normal HTMLElement
3974
- */
3975
- class ElementStyleSheetTarget {
3976
- constructor(source) {
3977
- this.target = source.style;
3978
- }
3979
- setProperty(name, value) {
3980
- DOM.queueUpdate(() => this.target.setProperty(name, value));
3981
- }
3982
- removeProperty(name) {
3983
- DOM.queueUpdate(() => this.target.removeProperty(name));
3984
- }
3985
- }
3986
- /**
3987
- * Controls emission for default values. This control is capable
3988
- * of emitting to multiple {@link PropertyTarget | PropertyTargets},
3989
- * and only emits if it has at least one root.
3990
- *
3991
- * @internal
3992
- */
3993
- class RootStyleSheetTarget {
3994
- setProperty(name, value) {
3995
- RootStyleSheetTarget.properties[name] = value;
3996
- for (const target of RootStyleSheetTarget.roots.values()) {
3997
- PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(target)).setProperty(name, value);
3998
- }
3999
- }
4000
- removeProperty(name) {
4001
- delete RootStyleSheetTarget.properties[name];
4002
- for (const target of RootStyleSheetTarget.roots.values()) {
4003
- PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(target)).removeProperty(name);
4004
- }
4005
- }
4006
- static registerRoot(root) {
4007
- const { roots } = RootStyleSheetTarget;
4008
- if (!roots.has(root)) {
4009
- roots.add(root);
4010
- const target = PropertyTargetManager.getOrCreate(this.normalizeRoot(root));
4011
- for (const key in RootStyleSheetTarget.properties) {
4012
- target.setProperty(key, RootStyleSheetTarget.properties[key]);
4013
- }
4014
- }
4015
- }
4016
- static unregisterRoot(root) {
4017
- const { roots } = RootStyleSheetTarget;
4018
- if (roots.has(root)) {
4019
- roots.delete(root);
4020
- const target = PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(root));
4021
- for (const key in RootStyleSheetTarget.properties) {
4022
- target.removeProperty(key);
4023
- }
4024
- }
4025
- }
4026
- /**
4027
- * Returns the document when provided the default element,
4028
- * otherwise is a no-op
4029
- * @param root - the root to normalize
4030
- */
4031
- static normalizeRoot(root) {
4032
- return root === defaultElement ? document : root;
4033
- }
4034
- }
4035
- RootStyleSheetTarget.roots = new Set();
4036
- RootStyleSheetTarget.properties = {};
4037
- // Caches PropertyTarget instances
4038
- const propertyTargetCache = new WeakMap();
4039
- // Use Constructable StyleSheets for FAST elements when supported, otherwise use
4040
- // HTMLStyleElement instances
4041
- const propertyTargetCtor = DOM.supportsAdoptedStyleSheets
4042
- ? ConstructableStyleSheetTarget
4043
- : StyleElementStyleSheetTarget;
4044
- /**
4045
- * Manages creation and caching of PropertyTarget instances.
4046
- *
4047
- * @internal
4048
- */
4049
- const PropertyTargetManager = Object.freeze({
4050
- getOrCreate(source) {
4051
- if (propertyTargetCache.has(source)) {
4052
- /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
4053
- return propertyTargetCache.get(source);
4054
- }
4055
- let target;
4056
- if (source === defaultElement) {
4057
- target = new RootStyleSheetTarget();
4058
- }
4059
- else if (source instanceof Document) {
4060
- target = DOM.supportsAdoptedStyleSheets
4061
- ? new DocumentStyleSheetTarget()
4062
- : new HeadStyleElementStyleSheetTarget();
4063
- }
4064
- else if (isFastElement(source)) {
4065
- target = new propertyTargetCtor(source);
4066
- }
4067
- else {
4068
- target = new ElementStyleSheetTarget(source);
4069
- }
4070
- propertyTargetCache.set(source, target);
4071
- return target;
4072
- },
4073
- });
4074
-
4075
- /**
4076
- * Implementation of {@link (DesignToken:interface)}
4077
- */
4078
- class DesignTokenImpl extends CSSDirective {
4079
- constructor(configuration) {
4080
- super();
4081
- this.subscribers = new WeakMap();
4082
- this._appliedTo = new Set();
4083
- this.name = configuration.name;
4084
- if (configuration.cssCustomPropertyName !== null) {
4085
- this.cssCustomProperty = `--${configuration.cssCustomPropertyName}`;
4086
- this.cssVar = `var(${this.cssCustomProperty})`;
4087
- }
4088
- this.id = DesignTokenImpl.uniqueId();
4089
- DesignTokenImpl.tokensById.set(this.id, this);
4090
- }
4091
- get appliedTo() {
4092
- return [...this._appliedTo];
4093
- }
4094
- static from(nameOrConfig) {
4095
- return new DesignTokenImpl({
4096
- name: typeof nameOrConfig === "string" ? nameOrConfig : nameOrConfig.name,
4097
- cssCustomPropertyName: typeof nameOrConfig === "string"
4098
- ? nameOrConfig
4099
- : nameOrConfig.cssCustomPropertyName === void 0
4100
- ? nameOrConfig.name
4101
- : nameOrConfig.cssCustomPropertyName,
4102
- });
4103
- }
4104
- static isCSSDesignToken(token) {
4105
- return typeof token.cssCustomProperty === "string";
4106
- }
4107
- static isDerivedDesignTokenValue(value) {
4108
- return typeof value === "function";
4109
- }
4110
- /**
4111
- * Gets a token by ID. Returns undefined if the token was not found.
4112
- * @param id - The ID of the token
4113
- * @returns
4114
- */
4115
- static getTokenById(id) {
4116
- return DesignTokenImpl.tokensById.get(id);
4117
- }
4118
- getOrCreateSubscriberSet(target = this) {
4119
- return (this.subscribers.get(target) ||
4120
- (this.subscribers.set(target, new Set()) && this.subscribers.get(target)));
4121
- }
4122
- createCSS() {
4123
- return this.cssVar || "";
4124
- }
4125
- getValueFor(element) {
4126
- const value = DesignTokenNode.getOrCreate(element).get(this);
4127
- if (value !== undefined) {
4128
- return value;
4129
- }
4130
- throw new Error(`Value could not be retrieved for token named "${this.name}". Ensure the value is set for ${element} or an ancestor of ${element}.`);
4131
- }
4132
- setValueFor(element, value) {
4133
- this._appliedTo.add(element);
4134
- if (value instanceof DesignTokenImpl) {
4135
- value = this.alias(value);
4136
- }
4137
- DesignTokenNode.getOrCreate(element).set(this, value);
4138
- return this;
4139
- }
4140
- deleteValueFor(element) {
4141
- this._appliedTo.delete(element);
4142
- if (DesignTokenNode.existsFor(element)) {
4143
- DesignTokenNode.getOrCreate(element).delete(this);
4144
- }
4145
- return this;
4146
- }
4147
- withDefault(value) {
4148
- this.setValueFor(defaultElement, value);
4149
- return this;
4150
- }
4151
- subscribe(subscriber, target) {
4152
- const subscriberSet = this.getOrCreateSubscriberSet(target);
4153
- if (target && !DesignTokenNode.existsFor(target)) {
4154
- DesignTokenNode.getOrCreate(target);
4155
- }
4156
- if (!subscriberSet.has(subscriber)) {
4157
- subscriberSet.add(subscriber);
4158
- }
4159
- }
4160
- unsubscribe(subscriber, target) {
4161
- const list = this.subscribers.get(target || this);
4162
- if (list && list.has(subscriber)) {
4163
- list.delete(subscriber);
4164
- }
4165
- }
4166
- /**
4167
- * Notifies subscribers that the value for an element has changed.
4168
- * @param element - The element to emit a notification for
4169
- */
4170
- notify(element) {
4171
- const record = Object.freeze({ token: this, target: element });
4172
- if (this.subscribers.has(this)) {
4173
- this.subscribers.get(this).forEach(sub => sub.handleChange(record));
4174
- }
4175
- if (this.subscribers.has(element)) {
4176
- this.subscribers.get(element).forEach(sub => sub.handleChange(record));
4177
- }
4178
- }
4179
- /**
4180
- * Alias the token to the provided token.
4181
- * @param token - the token to alias to
4182
- */
4183
- alias(token) {
4184
- return ((target) => token.getValueFor(target));
4185
- }
4186
- }
4187
- DesignTokenImpl.uniqueId = (() => {
4188
- let id = 0;
4189
- return () => {
4190
- id++;
4191
- return id.toString(16);
4192
- };
4193
- })();
4194
- /**
4195
- * Token storage by token ID
4196
- */
4197
- DesignTokenImpl.tokensById = new Map();
4198
- class CustomPropertyReflector {
4199
- startReflection(token, target) {
4200
- token.subscribe(this, target);
4201
- this.handleChange({ token, target });
4202
- }
4203
- stopReflection(token, target) {
4204
- token.unsubscribe(this, target);
4205
- this.remove(token, target);
4206
- }
4207
- handleChange(record) {
4208
- const { token, target } = record;
4209
- this.add(token, target);
4210
- }
4211
- add(token, target) {
4212
- PropertyTargetManager.getOrCreate(target).setProperty(token.cssCustomProperty, this.resolveCSSValue(DesignTokenNode.getOrCreate(target).get(token)));
4213
- }
4214
- remove(token, target) {
4215
- PropertyTargetManager.getOrCreate(target).removeProperty(token.cssCustomProperty);
4216
- }
4217
- resolveCSSValue(value) {
4218
- return value && typeof value.createCSS === "function" ? value.createCSS() : value;
4219
- }
4220
- }
4221
- /**
4222
- * A light wrapper around BindingObserver to handle value caching and
4223
- * token notification
4224
- */
4225
- class DesignTokenBindingObserver {
4226
- constructor(source, token, node) {
4227
- this.source = source;
4228
- this.token = token;
4229
- this.node = node;
4230
- this.dependencies = new Set();
4231
- this.observer = Observable.binding(source, this, false);
4232
- // This is a little bit hacky because it's using internal APIs of BindingObserverImpl.
4233
- // BindingObserverImpl queues updates to batch it's notifications which doesn't work for this
4234
- // scenario because the DesignToken.getValueFor API is not async. Without this, using DesignToken.getValueFor()
4235
- // after DesignToken.setValueFor() when setting a dependency of the value being retrieved can return a stale
4236
- // value. Assigning .handleChange to .call forces immediate invocation of this classes handleChange() method,
4237
- // allowing resolution of values synchronously.
4238
- // TODO: https://github.com/microsoft/fast/issues/5110
4239
- this.observer.handleChange = this.observer.call;
4240
- this.handleChange();
4241
- }
4242
- disconnect() {
4243
- this.observer.disconnect();
4244
- }
4245
- /**
4246
- * @internal
4247
- */
4248
- handleChange() {
4249
- this.node.store.set(this.token, this.observer.observe(this.node.target, defaultExecutionContext));
4250
- }
4251
- }
4252
- /**
4253
- * Stores resolved token/value pairs and notifies on changes
4254
- */
4255
- class Store {
4256
- constructor() {
4257
- this.values = new Map();
4258
- }
4259
- set(token, value) {
4260
- if (this.values.get(token) !== value) {
4261
- this.values.set(token, value);
4262
- Observable.getNotifier(this).notify(token.id);
4263
- }
4264
- }
4265
- get(token) {
4266
- Observable.track(this, token.id);
4267
- return this.values.get(token);
4268
- }
4269
- delete(token) {
4270
- this.values.delete(token);
4271
- }
4272
- all() {
4273
- return this.values.entries();
4274
- }
4275
- }
4276
- const nodeCache = new WeakMap();
4277
- const childToParent = new WeakMap();
4278
- /**
4279
- * A node responsible for setting and getting token values,
4280
- * emitting values to CSS custom properties, and maintaining
4281
- * inheritance structures.
4282
- */
4283
- class DesignTokenNode {
4284
- constructor(target) {
4285
- this.target = target;
4286
- /**
4287
- * Stores all resolved token values for a node
4288
- */
4289
- this.store = new Store();
4290
- /**
4291
- * All children assigned to the node
4292
- */
4293
- this.children = [];
4294
- /**
4295
- * All values explicitly assigned to the node in their raw form
4296
- */
4297
- this.assignedValues = new Map();
4298
- /**
4299
- * Tokens currently being reflected to CSS custom properties
4300
- */
4301
- this.reflecting = new Set();
4302
- /**
4303
- * Binding observers for assigned and inherited derived values.
4304
- */
4305
- this.bindingObservers = new Map();
4306
- /**
4307
- * Emits notifications to token when token values
4308
- * change the DesignTokenNode
4309
- */
4310
- this.tokenValueChangeHandler = {
4311
- handleChange: (source, arg) => {
4312
- const token = DesignTokenImpl.getTokenById(arg);
4313
- if (token) {
4314
- // Notify any token subscribers
4315
- token.notify(this.target);
4316
- if (DesignTokenImpl.isCSSDesignToken(token)) {
4317
- const parent = this.parent;
4318
- const reflecting = this.isReflecting(token);
4319
- if (parent) {
4320
- const parentValue = parent.get(token);
4321
- const sourceValue = source.get(token);
4322
- if (parentValue !== sourceValue && !reflecting) {
4323
- this.reflectToCSS(token);
4324
- }
4325
- else if (parentValue === sourceValue && reflecting) {
4326
- this.stopReflectToCSS(token);
4327
- }
4328
- }
4329
- else if (!reflecting) {
4330
- this.reflectToCSS(token);
4331
- }
4332
- }
4333
- }
4334
- },
4335
- };
4336
- nodeCache.set(target, this);
4337
- // Map store change notifications to token change notifications
4338
- Observable.getNotifier(this.store).subscribe(this.tokenValueChangeHandler);
4339
- if (target instanceof FASTElement) {
4340
- target.$fastController.addBehaviors([this]);
4341
- }
4342
- else if (target.isConnected) {
4343
- this.bind();
4344
- }
4345
- }
4346
- /**
4347
- * Returns a DesignTokenNode for an element.
4348
- * Creates a new instance if one does not already exist for a node,
4349
- * otherwise returns the cached instance
4350
- *
4351
- * @param target - The HTML element to retrieve a DesignTokenNode for
4352
- */
4353
- static getOrCreate(target) {
4354
- return nodeCache.get(target) || new DesignTokenNode(target);
4355
- }
4356
- /**
4357
- * Determines if a DesignTokenNode has been created for a target
4358
- * @param target - The element to test
4359
- */
4360
- static existsFor(target) {
4361
- return nodeCache.has(target);
4362
- }
4363
- /**
4364
- * Searches for and return the nearest parent DesignTokenNode.
4365
- * Null is returned if no node is found or the node provided is for a default element.
4366
- */
4367
- static findParent(node) {
4368
- if (!(defaultElement === node.target)) {
4369
- let parent = composedParent(node.target);
4370
- while (parent !== null) {
4371
- if (nodeCache.has(parent)) {
4372
- return nodeCache.get(parent);
4373
- }
4374
- parent = composedParent(parent);
4375
- }
4376
- return DesignTokenNode.getOrCreate(defaultElement);
4377
- }
4378
- return null;
4379
- }
4380
- /**
4381
- * Finds the closest node with a value explicitly assigned for a token, otherwise null.
4382
- * @param token - The token to look for
4383
- * @param start - The node to start looking for value assignment
4384
- * @returns
4385
- */
4386
- static findClosestAssignedNode(token, start) {
4387
- let current = start;
4388
- do {
4389
- if (current.has(token)) {
4390
- return current;
4391
- }
4392
- current = current.parent
4393
- ? current.parent
4394
- : current.target !== defaultElement
4395
- ? DesignTokenNode.getOrCreate(defaultElement)
4396
- : null;
4397
- } while (current !== null);
4398
- return null;
4399
- }
4400
- /**
4401
- * The parent DesignTokenNode, or null.
4402
- */
4403
- get parent() {
4404
- return childToParent.get(this) || null;
4405
- }
4406
- /**
4407
- * Checks if a token has been assigned an explicit value the node.
4408
- * @param token - the token to check.
4409
- */
4410
- has(token) {
4411
- return this.assignedValues.has(token);
4412
- }
4413
- /**
4414
- * Gets the value of a token for a node
4415
- * @param token - The token to retrieve the value for
4416
- * @returns
4417
- */
4418
- get(token) {
4419
- const value = this.store.get(token);
4420
- if (value !== undefined) {
4421
- return value;
4422
- }
4423
- const raw = this.getRaw(token);
4424
- if (raw !== undefined) {
4425
- this.hydrate(token, raw);
4426
- return this.get(token);
4427
- }
4428
- }
4429
- /**
4430
- * Retrieves the raw assigned value of a token from the nearest assigned node.
4431
- * @param token - The token to retrieve a raw value for
4432
- * @returns
4433
- */
4434
- getRaw(token) {
4435
- var _a;
4436
- if (this.assignedValues.has(token)) {
4437
- return this.assignedValues.get(token);
4438
- }
4439
- return (_a = DesignTokenNode.findClosestAssignedNode(token, this)) === null || _a === void 0 ? void 0 : _a.getRaw(token);
4440
- }
4441
- /**
4442
- * Sets a token to a value for a node
4443
- * @param token - The token to set
4444
- * @param value - The value to set the token to
4445
- */
4446
- set(token, value) {
4447
- if (DesignTokenImpl.isDerivedDesignTokenValue(this.assignedValues.get(token))) {
4448
- this.tearDownBindingObserver(token);
4449
- }
4450
- this.assignedValues.set(token, value);
4451
- if (DesignTokenImpl.isDerivedDesignTokenValue(value)) {
4452
- this.setupBindingObserver(token, value);
4453
- }
4454
- else {
4455
- this.store.set(token, value);
4456
- }
4457
- }
4458
- /**
4459
- * Deletes a token value for the node.
4460
- * @param token - The token to delete the value for
4461
- */
4462
- delete(token) {
4463
- this.assignedValues.delete(token);
4464
- this.tearDownBindingObserver(token);
4465
- const upstream = this.getRaw(token);
4466
- if (upstream) {
4467
- this.hydrate(token, upstream);
4468
- }
4469
- else {
4470
- this.store.delete(token);
4471
- }
4472
- }
4473
- /**
4474
- * Invoked when the DesignTokenNode.target is attached to the document
4475
- */
4476
- bind() {
4477
- const parent = DesignTokenNode.findParent(this);
4478
- if (parent) {
4479
- parent.appendChild(this);
4480
- }
4481
- for (const key of this.assignedValues.keys()) {
4482
- key.notify(this.target);
4483
- }
4484
- }
4485
- /**
4486
- * Invoked when the DesignTokenNode.target is detached from the document
4487
- */
4488
- unbind() {
4489
- if (this.parent) {
4490
- const parent = childToParent.get(this);
4491
- parent.removeChild(this);
4492
- }
4493
- }
4494
- /**
4495
- * Appends a child to a parent DesignTokenNode.
4496
- * @param child - The child to append to the node
4497
- */
4498
- appendChild(child) {
4499
- if (child.parent) {
4500
- childToParent.get(child).removeChild(child);
4501
- }
4502
- const reParent = this.children.filter(x => child.contains(x));
4503
- childToParent.set(child, this);
4504
- this.children.push(child);
4505
- reParent.forEach(x => child.appendChild(x));
4506
- Observable.getNotifier(this.store).subscribe(child);
4507
- // How can we not notify *every* subscriber?
4508
- for (const [token, value] of this.store.all()) {
4509
- child.hydrate(token, this.bindingObservers.has(token) ? this.getRaw(token) : value);
4510
- }
4511
- }
4512
- /**
4513
- * Removes a child from a node.
4514
- * @param child - The child to remove.
4515
- */
4516
- removeChild(child) {
4517
- const childIndex = this.children.indexOf(child);
4518
- if (childIndex !== -1) {
4519
- this.children.splice(childIndex, 1);
4520
- }
4521
- Observable.getNotifier(this.store).unsubscribe(child);
4522
- return child.parent === this ? childToParent.delete(child) : false;
4523
- }
4524
- /**
4525
- * Tests whether a provided node is contained by
4526
- * the calling node.
4527
- * @param test - The node to test
4528
- */
4529
- contains(test) {
4530
- return composedContains(this.target, test.target);
4531
- }
4532
- /**
4533
- * Instructs the node to reflect a design token for the provided token.
4534
- * @param token - The design token to reflect
4535
- */
4536
- reflectToCSS(token) {
4537
- if (!this.isReflecting(token)) {
4538
- this.reflecting.add(token);
4539
- DesignTokenNode.cssCustomPropertyReflector.startReflection(token, this.target);
4540
- }
4541
- }
4542
- /**
4543
- * Stops reflecting a DesignToken to CSS
4544
- * @param token - The design token to stop reflecting
4545
- */
4546
- stopReflectToCSS(token) {
4547
- if (this.isReflecting(token)) {
4548
- this.reflecting.delete(token);
4549
- DesignTokenNode.cssCustomPropertyReflector.stopReflection(token, this.target);
4550
- }
4551
- }
4552
- /**
4553
- * Determines if a token is being reflected to CSS for a node.
4554
- * @param token - The token to check for reflection
4555
- * @returns
4556
- */
4557
- isReflecting(token) {
4558
- return this.reflecting.has(token);
4559
- }
4560
- /**
4561
- * Handle changes to upstream tokens
4562
- * @param source - The parent DesignTokenNode
4563
- * @param property - The token ID that changed
4564
- */
4565
- handleChange(source, property) {
4566
- const token = DesignTokenImpl.getTokenById(property);
4567
- if (!token) {
4568
- return;
4569
- }
4570
- this.hydrate(token, this.getRaw(token));
4571
- }
4572
- /**
4573
- * Hydrates a token with a DesignTokenValue, making retrieval available.
4574
- * @param token - The token to hydrate
4575
- * @param value - The value to hydrate
4576
- */
4577
- hydrate(token, value) {
4578
- if (!this.has(token)) {
4579
- const observer = this.bindingObservers.get(token);
4580
- if (DesignTokenImpl.isDerivedDesignTokenValue(value)) {
4581
- if (observer) {
4582
- // If the binding source doesn't match, we need
4583
- // to update the binding
4584
- if (observer.source !== value) {
4585
- this.tearDownBindingObserver(token);
4586
- this.setupBindingObserver(token, value);
4587
- }
4588
- }
4589
- else {
4590
- this.setupBindingObserver(token, value);
4591
- }
4592
- }
4593
- else {
4594
- if (observer) {
4595
- this.tearDownBindingObserver(token);
4596
- }
4597
- this.store.set(token, value);
4598
- }
4599
- }
4600
- }
4601
- /**
4602
- * Sets up a binding observer for a derived token value that notifies token
4603
- * subscribers on change.
4604
- *
4605
- * @param token - The token to notify when the binding updates
4606
- * @param source - The binding source
4607
- */
4608
- setupBindingObserver(token, source) {
4609
- const binding = new DesignTokenBindingObserver(source, token, this);
4610
- this.bindingObservers.set(token, binding);
4611
- return binding;
4612
- }
4613
- /**
4614
- * Tear down a binding observer for a token.
4615
- */
4616
- tearDownBindingObserver(token) {
4617
- if (this.bindingObservers.has(token)) {
4618
- this.bindingObservers.get(token).disconnect();
4619
- this.bindingObservers.delete(token);
4620
- return true;
4621
- }
4622
- return false;
4623
- }
4624
- }
4625
- /**
4626
- * Responsible for reflecting tokens to CSS custom properties
4627
- */
4628
- DesignTokenNode.cssCustomPropertyReflector = new CustomPropertyReflector();
4629
- __decorate([
4630
- observable
4631
- ], DesignTokenNode.prototype, "children", void 0);
4632
- function create(nameOrConfig) {
4633
- return DesignTokenImpl.from(nameOrConfig);
4634
- }
4635
- /* eslint-enable @typescript-eslint/no-unused-vars */
4636
- /**
4637
- * Factory object for creating {@link (DesignToken:interface)} instances.
4638
- * @public
4639
- */
4640
- const DesignToken = Object.freeze({
4641
- create,
4642
- /**
4643
- * Informs DesignToken that an HTMLElement for which tokens have
4644
- * been set has been connected to the document.
4645
- *
4646
- * The browser does not provide a reliable mechanism to observe an HTMLElement's connectedness
4647
- * in all scenarios, so invoking this method manually is necessary when:
4648
- *
4649
- * 1. Token values are set for an HTMLElement.
4650
- * 2. The HTMLElement does not inherit from FASTElement.
4651
- * 3. The HTMLElement is not connected to the document when token values are set.
4652
- *
4653
- * @param element - The element to notify
4654
- * @returns - true if notification was successful, otherwise false.
4655
- */
4656
- notifyConnection(element) {
4657
- if (!element.isConnected || !DesignTokenNode.existsFor(element)) {
4658
- return false;
4659
- }
4660
- DesignTokenNode.getOrCreate(element).bind();
4661
- return true;
4662
- },
4663
- /**
4664
- * Informs DesignToken that an HTMLElement for which tokens have
4665
- * been set has been disconnected to the document.
4666
- *
4667
- * The browser does not provide a reliable mechanism to observe an HTMLElement's connectedness
4668
- * in all scenarios, so invoking this method manually is necessary when:
4669
- *
4670
- * 1. Token values are set for an HTMLElement.
4671
- * 2. The HTMLElement does not inherit from FASTElement.
4672
- *
4673
- * @param element - The element to notify
4674
- * @returns - true if notification was successful, otherwise false.
4675
- */
4676
- notifyDisconnection(element) {
4677
- if (element.isConnected || !DesignTokenNode.existsFor(element)) {
4678
- return false;
4679
- }
4680
- DesignTokenNode.getOrCreate(element).unbind();
4681
- return true;
4682
- },
4683
- /**
4684
- * Registers and element or document as a DesignToken root.
4685
- * {@link CSSDesignToken | CSSDesignTokens} with default values assigned via
4686
- * {@link (DesignToken:interface).withDefault} will emit CSS custom properties to all
4687
- * registered roots.
4688
- * @param target - The root to register
4689
- */
4690
- registerRoot(target = defaultElement) {
4691
- RootStyleSheetTarget.registerRoot(target);
4692
- },
4693
- /**
4694
- * Unregister an element or document as a DesignToken root.
4695
- * @param target - The root to deregister
4696
- */
4697
- unregisterRoot(target = defaultElement) {
4698
- RootStyleSheetTarget.unregisterRoot(target);
4699
- },
4700
- });
4701
- /* eslint-enable @typescript-eslint/no-non-null-assertion */
4702
-
4703
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
4704
- /**
4705
- * Indicates what to do with an ambiguous (duplicate) element.
4706
- * @public
4707
- */
4708
- const ElementDisambiguation = Object.freeze({
4709
- /**
4710
- * Skip defining the element but still call the provided callback passed
4711
- * to DesignSystemRegistrationContext.tryDefineElement
4712
- */
4713
- definitionCallbackOnly: null,
4714
- /**
4715
- * Ignore the duplicate element entirely.
4716
- */
4717
- ignoreDuplicate: Symbol(),
4718
- });
4719
- const elementTypesByTag = new Map();
4720
- const elementTagsByType = new Map();
4721
- let rootDesignSystem = null;
4722
- const designSystemKey = DI.createInterface(x => x.cachedCallback(handler => {
4723
- if (rootDesignSystem === null) {
4724
- rootDesignSystem = new DefaultDesignSystem(null, handler);
4725
- }
4726
- return rootDesignSystem;
4727
- }));
4728
- /**
4729
- * An API gateway to design system features.
4730
- * @public
4731
- */
4732
- const DesignSystem = Object.freeze({
4733
- /**
4734
- * Returns the HTML element name that the type is defined as.
4735
- * @param type - The type to lookup.
4736
- * @public
4737
- */
4738
- tagFor(type) {
4739
- return elementTagsByType.get(type);
4740
- },
4741
- /**
4742
- * Searches the DOM hierarchy for the design system that is responsible
4743
- * for the provided element.
4744
- * @param element - The element to locate the design system for.
4745
- * @returns The located design system.
4746
- * @public
4747
- */
4748
- responsibleFor(element) {
4749
- const owned = element.$$designSystem$$;
4750
- if (owned) {
4751
- return owned;
4752
- }
4753
- const container = DI.findResponsibleContainer(element);
4754
- return container.get(designSystemKey);
4755
- },
4756
- /**
4757
- * Gets the DesignSystem if one is explicitly defined on the provided element;
4758
- * otherwise creates a design system defined directly on the element.
4759
- * @param element - The element to get or create a design system for.
4760
- * @returns The design system.
4761
- * @public
4762
- */
4763
- getOrCreate(node) {
4764
- if (!node) {
4765
- if (rootDesignSystem === null) {
4766
- rootDesignSystem = DI.getOrCreateDOMContainer().get(designSystemKey);
4767
- }
4768
- return rootDesignSystem;
4769
- }
4770
- const owned = node.$$designSystem$$;
4771
- if (owned) {
4772
- return owned;
4773
- }
4774
- const container = DI.getOrCreateDOMContainer(node);
4775
- if (container.has(designSystemKey, false)) {
4776
- return container.get(designSystemKey);
4777
- }
4778
- else {
4779
- const system = new DefaultDesignSystem(node, container);
4780
- container.register(Registration.instance(designSystemKey, system));
4781
- return system;
4782
- }
4783
- },
4784
- });
4785
- function extractTryDefineElementParams(params, elementDefinitionType, elementDefinitionCallback) {
4786
- if (typeof params === "string") {
4787
- return {
4788
- name: params,
4789
- type: elementDefinitionType,
4790
- callback: elementDefinitionCallback,
4791
- };
4792
- }
4793
- else {
4794
- return params;
4795
- }
4796
- }
4797
- class DefaultDesignSystem {
4798
- constructor(owner, container) {
4799
- this.owner = owner;
4800
- this.container = container;
4801
- this.designTokensInitialized = false;
4802
- this.prefix = "fast";
4803
- this.shadowRootMode = undefined;
4804
- this.disambiguate = () => ElementDisambiguation.definitionCallbackOnly;
4805
- if (owner !== null) {
4806
- owner.$$designSystem$$ = this;
4807
- }
4808
- }
4809
- withPrefix(prefix) {
4810
- this.prefix = prefix;
4811
- return this;
4812
- }
4813
- withShadowRootMode(mode) {
4814
- this.shadowRootMode = mode;
4815
- return this;
4816
- }
4817
- withElementDisambiguation(callback) {
4818
- this.disambiguate = callback;
4819
- return this;
4820
- }
4821
- withDesignTokenRoot(root) {
4822
- this.designTokenRoot = root;
4823
- return this;
4824
- }
4825
- register(...registrations) {
4826
- const container = this.container;
4827
- const elementDefinitionEntries = [];
4828
- const disambiguate = this.disambiguate;
4829
- const shadowRootMode = this.shadowRootMode;
4830
- const context = {
4831
- elementPrefix: this.prefix,
4832
- tryDefineElement(params, elementDefinitionType, elementDefinitionCallback) {
4833
- const extractedParams = extractTryDefineElementParams(params, elementDefinitionType, elementDefinitionCallback);
4834
- const { name, callback, baseClass } = extractedParams;
4835
- let { type } = extractedParams;
4836
- let elementName = name;
4837
- let typeFoundByName = elementTypesByTag.get(elementName);
4838
- let needsDefine = true;
4839
- while (typeFoundByName) {
4840
- const result = disambiguate(elementName, type, typeFoundByName);
4841
- switch (result) {
4842
- case ElementDisambiguation.ignoreDuplicate:
4843
- return;
4844
- case ElementDisambiguation.definitionCallbackOnly:
4845
- needsDefine = false;
4846
- typeFoundByName = void 0;
4847
- break;
4848
- default:
4849
- elementName = result;
4850
- typeFoundByName = elementTypesByTag.get(elementName);
4851
- break;
4852
- }
4853
- }
4854
- if (needsDefine) {
4855
- if (elementTagsByType.has(type) || type === FoundationElement) {
4856
- type = class extends type {
4857
- };
4858
- }
4859
- elementTypesByTag.set(elementName, type);
4860
- elementTagsByType.set(type, elementName);
4861
- if (baseClass) {
4862
- elementTagsByType.set(baseClass, elementName);
4863
- }
4864
- }
4865
- elementDefinitionEntries.push(new ElementDefinitionEntry(container, elementName, type, shadowRootMode, callback, needsDefine));
4866
- },
4867
- };
4868
- if (!this.designTokensInitialized) {
4869
- this.designTokensInitialized = true;
4870
- if (this.designTokenRoot !== null) {
4871
- DesignToken.registerRoot(this.designTokenRoot);
4872
- }
4873
- }
4874
- container.registerWithContext(context, ...registrations);
4875
- for (const entry of elementDefinitionEntries) {
4876
- entry.callback(entry);
4877
- if (entry.willDefine && entry.definition !== null) {
4878
- entry.definition.define();
4879
- }
4880
- }
4881
- return this;
4882
- }
4883
- }
4884
- class ElementDefinitionEntry {
4885
- constructor(container, name, type, shadowRootMode, callback, willDefine) {
4886
- this.container = container;
4887
- this.name = name;
4888
- this.type = type;
4889
- this.shadowRootMode = shadowRootMode;
4890
- this.callback = callback;
4891
- this.willDefine = willDefine;
4892
- this.definition = null;
4893
- }
4894
- definePresentation(presentation) {
4895
- ComponentPresentation.define(this.name, presentation, this.container);
4896
- }
4897
- defineElement(definition) {
4898
- this.definition = new FASTElementDefinition(this.type, Object.assign(Object.assign({}, definition), { name: this.name }));
4899
- }
4900
- tagFor(type) {
4901
- return DesignSystem.tagFor(type);
4902
- }
4903
- }
4904
- /* eslint-enable @typescript-eslint/no-non-null-assertion */
4905
-
4906
- function provideVividDesignSystem(element) {
4907
- return DesignSystem.getOrCreate(element).withPrefix('vwc');
4908
- }
4909
- const designSystem = provideVividDesignSystem();
19
+ designSystem.register(VIVIDFocus());
4910
20
 
4911
- export { AttachedBehaviorHTMLDirective as A, DOM as D, FoundationElement as F, __decorate as _, attr as a, __metadata as b, designSystem as d, emptyArray as e, html as h, observable as o };
21
+ export { Focus as F, VIVIDFocus as V };