-
Notifications
You must be signed in to change notification settings - Fork 13
/
x-element.js
1013 lines (949 loc) · 37.7 KB
/
x-element.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as defaultTemplateEngine from './x-template.js';
/** Base element class for creating custom elements. */
export default class XElement extends HTMLElement {
/**
* Extends HTMLElement.observedAttributes to handle the properties block.
* @returns {string[]}
*/
static get observedAttributes() {
XElement.#analyzeConstructor(this);
return [...XElement.#constructors.get(this).attributeMap.keys()];
}
/**
* Default templating engine. Use "templateEngine" to override.
* @returns {{[key: string]: Function}}
*/
static get defaultTemplateEngine() {
return defaultTemplateEngine;
}
/**
* Configured templating engine. Defaults to "defaultTemplateEngine".
* Override this as needed if x-element's default template engine does not
* meet your needs. A "render" method is the only required field. An "html"
* tagged template literal is expected, but not strictly required.
* @returns {{[key: string]: Function}}
*/
static get templateEngine() {
return XElement.defaultTemplateEngine;
}
/**
* Declare an array of CSSStyleSheet objects to adopt on the shadow root.
* Note that a CSSStyleSheet object is the type returned when importing a
* stylesheet file via import attributes.
* ```js
* import importedStyle from './path-to.css' with { type: 'css' };
* class MyElement extends XElement {
* static get styles() {
* const inlineStyle = new CSSStyleSheet();
* inlineStyle.replaceSync(`:host { display: block; }`);
* return [importedStyle, inlineStyle];
* }
* }
* ```
* @returns {CSSStyleSheet[]}
*/
static get styles() {
return [];
}
/**
* Observe callback.
* @callback observeCallback
* @param {HTMLElement} host
* @param {any} value
* @param {any} oldValue
*/
/**
* A property value.
* @typedef {object} Property
* @property {any} [type]
* @property {string} [attribute]
* @property {string[]} [input]
* @property {Function} [compute]
* @property {observeCallback} [observe]
* @property {boolean} [reflect]
* @property {boolean} [internal]
* @property {boolean} [readOnly]
* @property {any|Function} [initial]
* @property {any|Function} [default]
*/
/**
* Declare watched properties (and related attributes) on an element.
* ```js
* static get properties() {
* return {
* property1: {
* type: String,
* },
* property2: {
* type: Number,
* input: ['property1'],
* compute: this.computeProperty2,
* reflect: true,
* observe: this.observeProperty2,
* default: 0,
* }
* };
* }
* ```
* @returns {{[key: string]: Property}}
*/
static get properties() {
return {};
}
/**
* Listen callback.
* @callback delegatedListenCallback
* @param {HTMLElement} host
* @param {Event} event
*/
/**
* Declare event handlers on an element.
* ```js
* static get listeners() {
* return {
* click: this.onClick,
* }
* }
*```
* Note that listeners are added to the element's render root. Listeners are
* added during "connectedCallback" and removed during "disconnectedCallback".
* The arguments passed to your callback are always "(host, event)".
* @returns {{[key: string]: delegatedListenCallback}}
*/
static get listeners() {
return {};
}
/**
* Customize shadow root initialization and optionally forgo encapsulation.
* E.g., setup focus delegation or return host instead of host.shadowRoot.
* @param {HTMLElement} host
* @returns {HTMLElement|ShadowRoot}
*/
static createRenderRoot(host) {
return host.attachShadow({ mode: 'open' });
}
/**
* Template callback.
* @callback templateCallback
* @param {object} properties
* @param {HTMLElement} host
*/
/**
* Setup template callback to update DOM when properties change.
* ```js
* static template(html, { nullish }) {
* return (href) => {
* return html`<a href=${nullish(href)}>click me</a>`;
* }
* }
* ```
* @param {Function} html
* @param {{[key: string]: Function}} engine
* @returns {templateCallback}
*/
static template(html, engine) { // eslint-disable-line no-unused-vars
return (properties, host) => {}; // eslint-disable-line no-unused-vars
}
/**
* Standard instance constructor.
*/
constructor() {
super();
XElement.#constructHost(this);
}
/**
* Extends HTMLElement.prototype.connectedCallback.
*/
connectedCallback() {
XElement.#connectHost(this);
}
/**
* Extends HTMLElement.prototype.attributeChangedCallback.
* @param {string} attribute
* @param {string|null} oldValue
* @param {string|null} value
*/
attributeChangedCallback(attribute, oldValue, value) {
const { attributeMap } = XElement.#constructors.get(this.constructor);
// Authors may extend "observedAttributes". Optionally chain to account for
// attributes which we don't know about.
attributeMap.get(attribute)?.sync(this, value, oldValue);
}
/**
* Extends HTMLElement.prototype.adoptedCallback.
*/
adoptedCallback() {}
/**
* Extends HTMLElement.prototype.disconnectedCallback.
*/
disconnectedCallback() {
XElement.#disconnectHost(this);
}
/**
* Uses the result of your template callback to update your render root.
*
* This is called when properties update, but is exposed for advanced use cases.
*/
render() {
const { template, properties, renderRoot, render } = XElement.#hosts.get(this);
const result = template(properties, this);
try {
render(renderRoot, result);
} catch (error) {
const pathString = XElement.#toPathString(this);
// @ts-ignore — TypeScript doesn’t get that this can accept any class.
const tagName = customElements.getName(this.constructor);
const message = `Invalid template for "${this.constructor.name}" / <${tagName}> at path "${pathString}".`;
throw new Error(message, { cause: error });
}
}
/**
* Listen callback.
* @callback listenCallback
* @param {Event} event
*/
/**
* Wrapper around HTMLElement.addEventListener.
* Advanced — use this only if declaring listeners statically is not possible.
* @param {EventTarget} element
* @param {string} type
* @param {listenCallback} callback
* @param {object} [options]
*/
listen(element, type, callback, options) {
if (XElement.#typeIsWrong(EventTarget, element)) {
const typeName = XElement.#getTypeName(element);
throw new Error(`Unexpected element passed to listen (expected EventTarget, got ${typeName}).`);
}
if (XElement.#typeIsWrong(String, type)) {
const typeName = XElement.#getTypeName(type);
throw new Error(`Unexpected type passed to listen (expected String, got ${typeName}).`);
}
if (XElement.#typeIsWrong(Function, callback)) {
const typeName = XElement.#getTypeName(callback);
throw new Error(`Unexpected callback passed to listen (expected Function, got ${typeName}).`);
}
if (XElement.#notNullish(options) && XElement.#typeIsWrong(Object, options)) {
const typeName = XElement.#getTypeName(options);
throw new Error(`Unexpected options passed to listen (expected Object, got ${typeName}).`);
}
XElement.#addListener(this, element, type, callback, options);
}
/**
* Wrapper around HTMLElement.removeEventListener. Inverse of "listen".
* @param {EventTarget} element
* @param {string} type
* @param {listenCallback} callback
* @param {object} [options]
*/
unlisten(element, type, callback, options) {
if (XElement.#typeIsWrong(EventTarget, element)) {
const typeName = XElement.#getTypeName(element);
throw new Error(`Unexpected element passed to unlisten (expected EventTarget, got ${typeName}).`);
}
if (XElement.#typeIsWrong(String, type)) {
const typeName = XElement.#getTypeName(type);
throw new Error(`Unexpected type passed to unlisten (expected String, got ${typeName}).`);
}
if (XElement.#typeIsWrong(Function, callback)) {
const typeName = XElement.#getTypeName(callback);
throw new Error(`Unexpected callback passed to unlisten (expected Function, got ${typeName}).`);
}
if (XElement.#notNullish(options) && XElement.#typeIsWrong(Object, options)) {
const typeName = XElement.#getTypeName(options);
throw new Error(`Unexpected options passed to unlisten (expected Object, got ${typeName}).`);
}
XElement.#removeListener(this, element, type, callback, options);
}
/**
* Helper method to dispatch an "ErrorEvent" on the element.
* @param {Error} error
*/
dispatchError(error) {
const { message } = error;
const eventData = { error, message, bubbles: true, composed: true };
this.dispatchEvent(new ErrorEvent('error', eventData));
}
/**
* For element authors. Getter and setter for internal properties.
* Note that you can set read-only properties from host.internal. However, you
* must get read-only properties directly from the host.
* @returns {object}
*/
get internal() {
return XElement.#hosts.get(this).internal;
}
// Called once per class — kicked off from "static get observedAttributes".
static #analyzeConstructor(constructor) {
const { styles, properties, listeners } = constructor;
const propertiesEntries = Object.entries(properties);
const listenersEntries = Object.entries(listeners);
XElement.#validateProperties(constructor, properties, propertiesEntries);
XElement.#validateListeners(constructor, listeners, listenersEntries);
const propertyMap = new Map(propertiesEntries);
const internalPropertyMap = new Map();
// Use a normal object for better autocomplete when debugging in console.
const propertiesTarget = {};
const internalTarget = {};
const attributeMap = new Map();
for (const [key, property] of propertyMap) {
// We mutate (vs copy) to allow cross-referencing property objects.
XElement.#mutateProperty(constructor, propertyMap, key, property);
if (property.internal || property.readOnly) {
internalPropertyMap.set(key, property);
internalTarget[key] = undefined;
}
propertiesTarget[key] = undefined;
if (property.attribute) {
attributeMap.set(property.attribute, property);
}
}
const listenerMap = new Map(listenersEntries);
XElement.#constructors.set(constructor, {
styles, propertyMap, internalPropertyMap, attributeMap, listenerMap,
propertiesTarget, internalTarget,
});
}
// Called during constructor analysis.
static #validateProperties(constructor, properties, entries) {
const path = `${constructor.name}.properties`;
for (const [key, property] of entries) {
if (XElement.#typeIsWrong(Object, property)) {
const typeName = XElement.#getTypeName(property);
throw new Error(`${path}.${key} has an unexpected value (expected Object, got ${typeName}).`);
}
}
for (const [key, property] of entries) {
XElement.#validateProperty(constructor, key, property);
}
const attributes = new Set();
const inputMap = new Map();
for (const [key, property] of entries) {
if (XElement.#propertyHasAttribute(property)) {
// Attribute names are case-insensitive — lowercase to properly check for duplicates.
const attribute = property.attribute ?? XElement.#camelToKebab(key);
XElement.#validatePropertyAttribute(constructor, key, property, attribute);
if (attributes.has(attribute)) {
throw new Error(`${path}.${key} causes a duplicated attribute "${attribute}".`);
}
attributes.add(attribute);
}
if (property.input) {
inputMap.set(property, property.input.map(inputKey => properties[inputKey]));
for (const [index, inputKey] of Object.entries(property.input)) {
if (XElement.#typeIsWrong(Object, properties[inputKey])) {
throw new Error(`${path}.${key}.input[${index}] has an unexpected item ("${inputKey}" has not been declared).`);
}
}
}
}
for (const [key, property] of entries) {
if (XElement.#propertyIsCyclic(property, inputMap)) {
throw new Error(`${path}.${key}.input is cyclic.`);
}
}
}
static #validateProperty(constructor, key, property) {
const path = `${constructor.name}.properties.${key}`;
if (key.includes('-')) {
throw new Error(`Unexpected key "${path}" contains "-" (property names should be camelCased).`);
}
for (const propertyKey of Object.keys(property)) {
if (XElement.#propertyKeys.has(propertyKey) === false) {
throw new Error(`Unexpected key "${path}.${propertyKey}".`);
}
}
const { type, attribute, compute, input, reflect, internal, readOnly } = property;
if (Reflect.has(property, 'type') && XElement.#typeIsWrong(Function, type)) {
const typeName = XElement.#getTypeName(type);
throw new Error(`Unexpected value for "${path}.type" (expected constructor Function, got ${typeName}).`);
}
for (const subKey of ['compute', 'observe']) {
if (Reflect.has(property, subKey) && XElement.#typeIsWrong(Function, property[subKey])) {
const typeName = XElement.#getTypeName(property[subKey]);
throw new Error(`Unexpected value for "${path}.${subKey}" (expected Function, got ${typeName}).`);
}
}
for (const subKey of ['reflect', 'internal', 'readOnly']) {
if (Reflect.has(property, subKey) && XElement.#typeIsWrong(Boolean, property[subKey])) {
const typeName = XElement.#getTypeName(property[subKey]);
throw new Error(`Unexpected value for "${path}.${subKey}" (expected Boolean, got ${typeName}).`);
}
}
if (!internal && XElement.#prototypeInterface.has(key)) {
throw new Error(`Unexpected key "${path}" shadows in XElement.prototype interface.`);
}
if (Reflect.has(property, 'attribute') && XElement.#typeIsWrong(String, attribute)) {
const typeName = XElement.#getTypeName(attribute);
throw new Error(`Unexpected value for "${path}.attribute" (expected String, got ${typeName}).`);
}
if (Reflect.has(property, 'attribute') && attribute === '') {
throw new Error(`Unexpected value for "${path}.attribute" (expected non-empty String).`);
}
for (const subKey of ['initial', 'default']) {
const value = Reflect.get(property, subKey);
if (
XElement.#notNullish(value) &&
XElement.#typeIsWrong(Boolean, value) &&
XElement.#typeIsWrong(String, value) &&
XElement.#typeIsWrong(Number, value) &&
XElement.#typeIsWrong(Function, value)
) {
const typeName = XElement.#getTypeName(value);
throw new Error(`Unexpected value for "${path}.${subKey}" (expected Boolean, String, Number, or Function, got ${typeName}).`);
}
}
if (Reflect.has(property, 'input') && XElement.#typeIsWrong(Array, input)) {
const typeName = XElement.#getTypeName(input);
throw new Error(`Unexpected value for "${path}.input" (expected Array, got ${typeName}).`);
}
if (Reflect.has(property, 'input')) {
for (const [index, inputKey] of Object.entries(input)) {
if (XElement.#typeIsWrong(String, inputKey)) {
const typeName = XElement.#getTypeName(inputKey);
throw new Error(`Unexpected value for "${path}.input[${index}]" (expected String, got ${typeName}).`);
}
}
}
const unserializable = XElement.#serializableTypes.has(property.type) === false;
const typeName = property.type?.prototype && property.type?.name ? property.type.name : XElement.#getTypeName(property.type);
if (attribute && type && unserializable) {
throw new Error(`Found unserializable "${path}.type" (${typeName}) but "${path}.attribute" is defined.`);
}
if (reflect && unserializable) {
throw new Error(`Found unserializable "${path}.type" (${typeName}) but "${path}.reflect" is true.`);
}
if (compute && !input) {
throw new Error(`Found "${path}.compute" without "${path}.input" (computed properties require input).`);
}
if (input && !compute) {
throw new Error(`Found "${path}.input" without "${path}.compute" (computed properties require a compute callback).`);
}
if (Reflect.has(property, 'initial') && compute) {
throw new Error(`Found "${path}.initial" and "${path}.compute" (computed properties cannot set an initial value).`);
}
if (Reflect.has(property, 'readOnly') && compute) {
throw new Error(`Found "${path}.readOnly" and "${path}.compute" (computed properties cannot define read-only).`);
}
if (reflect && internal) {
throw new Error(`Both "${path}.reflect" and "${path}.internal" are true (reflected properties cannot be internal).`);
}
if (internal && readOnly) {
throw new Error(`Both "${path}.internal" and "${path}.readOnly" are true (read-only properties cannot be internal).`);
}
if (internal && attribute) {
throw new Error(`Found "${path}.attribute" but "${path}.internal" is true (internal properties cannot have attributes).`);
}
}
static #validatePropertyAttribute(constructor, key, property, attribute) {
const path = `${constructor.name}.properties`;
// Attribute names are case-insensitive — lowercase to properly check for duplicates.
if (attribute !== attribute.toLowerCase()) {
throw new Error(`${path}.${key} has non-standard attribute casing "${attribute}" (use lower-cased names).`);
}
}
// Determines if computed property inputs form a cycle.
static #propertyIsCyclic(property, inputMap, seen = new Set()) {
if (inputMap.has(property)) {
for (const input of inputMap.get(property)) {
const nextSeen = new Set([...seen, property]);
if (
input === property ||
seen.has(input) ||
XElement.#propertyIsCyclic(input, inputMap, nextSeen)
) {
return true;
}
}
}
}
static #validateListeners(constructor, listeners, entries) {
const path = `${constructor.name}.listeners`;
for (const [type, listener] of entries) {
if (XElement.#typeIsWrong(Function, listener)) {
const typeName = XElement.#getTypeName(listener);
throw new Error(`${path}.${type} has unexpected value (expected Function, got ${typeName}).`);
}
}
}
// Called once per-property during constructor analysis.
static #mutateProperty(constructor, propertyMap, key, property) {
property.key = key;
property.attribute = XElement.#propertyHasAttribute(property)
? property.attribute ?? XElement.#camelToKebab(key)
: undefined;
property.input = new Set((property.input ?? []).map(inputKey => propertyMap.get(inputKey)));
property.output = property.output ?? new Set();
for (const input of property.input) {
input.output = input.output ?? new Set();
input.output.add(property);
}
XElement.#addPropertyInitial(constructor, property);
XElement.#addPropertyDefault(constructor, property);
XElement.#addPropertySync(constructor, property);
XElement.#addPropertyCompute(constructor, property);
XElement.#addPropertyReflect(constructor, property);
XElement.#addPropertyObserve(constructor, property);
}
// Wrapper to improve ergonomics of coalescing nullish, initial value.
static #addPropertyInitial(constructor, property) {
// Should take `value` in and spit the initial or value out.
if (Reflect.has(property, 'initial')) {
const initialValue = property.initial;
const isFunction = XElement.#typeIsWrong(Function, initialValue) === false;
property.initial = value =>
value ?? (isFunction ? initialValue.call(constructor) : initialValue);
} else {
property.initial = value => value;
}
}
// Wrapper to improve ergonomics of coalescing nullish, default value.
static #addPropertyDefault(constructor, property) {
// Should take `value` in and spit the default or value out.
if (Reflect.has(property, 'default')) {
const { key, default: defaultValue } = property;
const isFunction = XElement.#typeIsWrong(Function, defaultValue) === false;
const getOrCreateDefault = host => {
const { defaultMap } = XElement.#hosts.get(host);
if (!defaultMap.has(key)) {
const value = isFunction ? defaultValue.call(constructor) : defaultValue;
defaultMap.set(key, value);
return value;
}
return defaultMap.get(key);
};
property.default = (host, value) => value ?? getOrCreateDefault(host);
} else {
property.default = (host, value) => value;
}
}
// Wrapper to improve ergonomics of syncing attributes back to properties.
static #addPropertySync(constructor, property) {
if (XElement.#propertyHasAttribute(property)) {
property.sync = (host, value, oldValue) => {
const { initialized, reflecting } = XElement.#hosts.get(host);
if (reflecting === false && initialized && value !== oldValue) {
const deserialization = XElement.#deserializeProperty(host, property, value);
host[property.key] = deserialization;
}
};
}
}
// Wrapper to centralize logic needed to perform reflection.
static #addPropertyReflect(constructor, property) {
if (property.reflect) {
property.reflect = host => {
const value = XElement.#getPropertyValue(host, property);
const serialization = XElement.#serializeProperty(host, property, value);
const hostInfo = XElement.#hosts.get(host);
hostInfo.reflecting = true;
serialization === undefined
? host.removeAttribute(property.attribute)
: host.setAttribute(property.attribute, serialization);
hostInfo.reflecting = false;
};
}
}
// Wrapper to prevent repeated compute callbacks.
static #addPropertyCompute(constructor, property) {
const { compute } = property;
if (compute) {
property.compute = host => {
const { computeMap, valueMap } = XElement.#hosts.get(host);
const saved = computeMap.get(property);
if (saved.valid === false) {
const args = [];
for (const input of property.input) {
args.push(XElement.#getPropertyValue(host, input));
}
if (saved.args === undefined || args.some((arg, index) => arg !== saved.args[index])) {
const value = property.default(host, compute.call(constructor, ...args));
XElement.#validatePropertyValue(host, property, value);
valueMap.set(property, value);
saved.args = args;
}
saved.valid = true;
}
return valueMap.get(property);
};
}
}
// Wrapper to provide last value to observe callbacks.
static #addPropertyObserve(constructor, property) {
const { observe } = property;
if (observe) {
property.observe = host => {
const saved = XElement.#hosts.get(host).observeMap.get(property);
const value = XElement.#getPropertyValue(host, property);
if (Object.is(value, saved.value) === false) {
observe.call(constructor, host, value, saved.value);
}
saved.value = value;
};
}
}
// Called once per-host during construction.
static #constructHost(host) {
const invalidProperties = new Set();
// The weak map prevents memory leaks. E.g., adding anonymous listeners.
const listenerMap = new WeakMap();
const valueMap = new Map();
const renderRoot = host.constructor.createRenderRoot(host);
if (!renderRoot || renderRoot !== host && renderRoot !== host.shadowRoot) {
throw new Error('Unexpected render root returned. Expected "host" or "host.shadowRoot".');
}
const { render, html, ...engine } = host.constructor.templateEngine;
const template = host.constructor.template(html, { html, ...engine }).bind(host.constructor);
const properties = XElement.#createProperties(host);
const internal = XElement.#createInternal(host);
const computeMap = new Map();
const observeMap = new Map();
const defaultMap = new Map();
const { styles, propertyMap } = XElement.#constructors.get(host.constructor);
if (styles.length > 0) {
if (renderRoot === host.shadowRoot) {
if (renderRoot.adoptedStyleSheets.length === 0) {
renderRoot.adoptedStyleSheets = styles;
} else {
throw new Error('Unexpected "styles" declared when preexisting "adoptedStyleSheets" exist.');
}
} else {
throw new Error('Unexpected "styles" declared without a shadow root.');
}
}
for (const property of propertyMap.values()) {
if (property.compute) {
computeMap.set(property, { valid: false, args: undefined });
}
if (property.observe) {
observeMap.set(property, { value: undefined });
}
}
XElement.#hosts.set(host, {
initialized: false, reflecting: false, invalidProperties, listenerMap,
renderRoot, render, template, properties, internal, computeMap,
observeMap, defaultMap, valueMap,
});
}
// Called during host construction.
static #createInternal(host) {
const { propertyMap, internalPropertyMap, internalTarget } = XElement.#constructors.get(host.constructor);
// Everything but "get", "set", "has", and "ownKeys" are considered invalid.
// Note that impossible traps like "apply" or "construct" are not guarded.
const invalid = () => { throw new Error('Invalid use of internal proxy.'); };
const get = (target, key) => {
const internalProperty = internalPropertyMap.get(key);
if (internalProperty?.internal) {
return XElement.#getPropertyValue(host, internalProperty);
} else {
const path = `${host.constructor.name}.properties.${key}`;
const property = propertyMap.get(key);
if (property === undefined) {
throw new Error(`Property "${path}" does not exist.`);
} else {
throw new Error(`Property "${path}" is publicly available (use normal getter).`);
}
}
};
const set = (target, key, value) => {
const internalProperty = internalPropertyMap.get(key);
if (internalProperty && Reflect.has(internalProperty, 'compute') === false) {
XElement.#setPropertyValue(host, internalProperty, value);
return true;
} else {
const path = `${host.constructor.name}.properties.${key}`;
const property = propertyMap.get(key);
if (property === undefined) {
throw new Error(`Property "${path}" does not exist.`);
} else if (property.compute) {
throw new Error(`Property "${path}" is computed (computed properties are read-only).`);
} else {
throw new Error(`Property "${path}" is publicly available (use normal setter).`);
}
}
};
const has = (target, key) => internalPropertyMap.has(key);
const ownKeys = () => [...internalPropertyMap.keys()];
const handler = {
defineProperty: invalid, deleteProperty: invalid, get,
getOwnPropertyDescriptor: invalid, getPrototypeOf: invalid, has,
isExtensible: invalid, ownKeys, preventExtensions: invalid,
set, setPrototypeOf: invalid,
};
return new Proxy(internalTarget, handler);
}
// Only available in template callback. Provides getter for all properties.
// Called during host construction.
static #createProperties(host) {
const { propertyMap, propertiesTarget } = XElement.#constructors.get(host.constructor);
// Everything but "get", "set", "has", and "ownKeys" are considered invalid.
const invalid = () => { throw new Error('Invalid use of properties proxy.'); };
const get = (target, key) => {
if (propertyMap.has(key)) {
return XElement.#getPropertyValue(host, propertyMap.get(key));
} else {
const path = `${host.constructor.name}.properties.${key}`;
throw new Error(`Property "${path}" does not exist.`);
}
};
const set = (target, key) => {
const path = `${host.constructor.name}.properties.${key}`;
if (propertyMap.has(key)) {
throw new Error(`Cannot set "${path}" via "properties".`);
} else {
throw new Error(`Property "${path}" does not exist.`);
}
};
const has = (target, key) => propertyMap.has(key);
const ownKeys = () => [...propertyMap.keys()];
const handler = {
defineProperty: invalid, deleteProperty: invalid, get,
getOwnPropertyDescriptor: invalid, getPrototypeOf: invalid, has,
isExtensible: invalid, ownKeys, preventExtensions: invalid, set,
setPrototypeOf: invalid,
};
return new Proxy(propertiesTarget, handler);
}
// Called once per-host from initial "connectedCallback".
static #connectHost(host) {
const initialized = XElement.#initializeHost(host);
XElement.#addListeners(host);
if (initialized) {
XElement.#updateHost(host);
}
}
static #disconnectHost(host) {
XElement.#removeListeners(host);
}
static #initializeHost(host) {
const hostInfo = XElement.#hosts.get(host);
const { computeMap, initialized, invalidProperties } = hostInfo;
if (initialized === false) {
XElement.#upgradeOwnProperties(host);
// Only reflect attributes when the element is connected.
const { propertyMap } = XElement.#constructors.get(host.constructor);
for (const property of propertyMap.values()) {
const { value, found } = XElement.#getPreUpgradePropertyValue(host, property);
XElement.#initializeProperty(host, property);
if (found) {
host[property.key] = property.default(host, property.initial(value));
} else if (!property.compute) {
// Set to a nullish value so that it coalesces to the default.
XElement.#setPropertyValue(host, property, property.default(host, property.initial()));
}
invalidProperties.add(property);
if (property.compute) {
computeMap.get(property).valid = false;
}
}
hostInfo.initialized = true;
return true;
}
return false;
}
// Prevent shadowing from properties added to element instance pre-upgrade.
static #upgradeOwnProperties(host) {
for (const key of Reflect.ownKeys(host)) {
const value = Reflect.get(host, key);
Reflect.deleteProperty(host, key);
Reflect.set(host, key, value);
}
}
// Called during host initialization.
static #getPreUpgradePropertyValue(host, property) {
// Process possible sources of initial state, with this priority:
// 1. imperative, e.g. `element.prop = 'value';`
// 2. declarative, e.g. `<element prop="value"></element>`
const { key, attribute, internal } = property;
let value;
let found = false;
if (!internal) {
// Only look for public (i.e., non-internal) properties.
if (Reflect.has(host, key)) {
value = host[key];
found = true;
} else if (attribute && host.hasAttribute(attribute)) {
const attributeValue = host.getAttribute(attribute);
value = XElement.#deserializeProperty(host, property, attributeValue);
found = true;
}
}
return { value, found };
}
static #initializeProperty(host, property) {
if (!property.internal) {
const { key, compute, readOnly } = property;
const path = `${host.constructor.name}.properties.${key}`;
const get = () => XElement.#getPropertyValue(host, property);
const set = compute || readOnly
? () => {
if (compute) {
throw new Error(`Property "${path}" is computed (computed properties are read-only).`);
} else {
throw new Error(`Property "${path}" is read-only.`);
}
}
: value => XElement.#setPropertyValue(host, property, value);
Reflect.deleteProperty(host, key);
Reflect.defineProperty(host, key, { get, set, enumerable: true });
}
}
static #addListener(host, element, type, callback, options) {
callback = XElement.#getListener(host, callback);
element.addEventListener(type, callback, options);
}
static #addListeners(host) {
const { listenerMap } = XElement.#constructors.get(host.constructor);
const { renderRoot } = XElement.#hosts.get(host);
for (const [type, listener] of listenerMap) {
XElement.#addListener(host, renderRoot, type, listener);
}
}
static #removeListener(host, element, type, callback, options) {
callback = XElement.#getListener(host, callback);
element.removeEventListener(type, callback, options);
}
static #removeListeners(host) {
const { listenerMap } = XElement.#constructors.get(host.constructor);
const { renderRoot } = XElement.#hosts.get(host);
for (const [type, listener] of listenerMap) {
XElement.#removeListener(host, renderRoot, type, listener);
}
}
static #getListener(host, listener) {
const { listenerMap } = XElement.#hosts.get(host);
if (listenerMap.has(listener) === false) {
listenerMap.set(listener, listener.bind(host.constructor, host));
}
return listenerMap.get(listener);
}
static #updateHost(host) {
// Order of operations: compute, reflect, render, then observe.
const { invalidProperties } = XElement.#hosts.get(host);
const invalidPropertiesCopy = new Set(invalidProperties);
invalidProperties.clear();
for (const property of invalidPropertiesCopy) {
property.reflect?.(host);
}
host.render();
for (const property of invalidPropertiesCopy) {
property.observe?.(host);
}
}
// Used to improve error messaging by appending DOM path information.
static #toPathString(host) {
const path = [];
let reference = host;
while (reference) {
path.push(reference);
reference = reference.parentElement ?? reference.getRootNode().host;
}
return path
.map(element => {
const tag = element.localName;
const attributes = Array.from(element.attributes)
.map(({ name, value }) => value ? `${name}="${value}"` : name);
return `${tag}${attributes.length ? `[${attributes.join('][')}]` : ''}`;
})
.join(' < ');
}
static async #invalidateProperty(host, property) {
const { initialized, invalidProperties, computeMap } = XElement.#hosts.get(host);
if (initialized) {
for (const output of property.output) {
XElement.#invalidateProperty(host, output);
}
const queueUpdate = invalidProperties.size === 0;
invalidProperties.add(property);
if (property.compute) {
computeMap.get(property).valid = false;
}
if (queueUpdate) {
// Queue a microtask. Allows multiple, synchronous changes.
await Promise.resolve();
XElement.#updateHost(host);
}
}
}
static #getPropertyValue(host, property) {
const { valueMap } = XElement.#hosts.get(host);
return property.compute?.(host) ?? valueMap.get(property);
}
static #validatePropertyValue(host, property, value) {
if (property.type && XElement.#notNullish(value)) {
if (XElement.#typeIsWrong(property.type, value)) {
const path = `${host.constructor.name}.properties.${property.key}`;
const typeName = XElement.#getTypeName(value);
throw new Error(`Unexpected value for "${path}" (expected ${property.type.name}, got ${typeName}).`);
}
}
}
static #setPropertyValue(host, property, value) {
const { valueMap } = XElement.#hosts.get(host);
if (Object.is(value, valueMap.get(property)) === false) {
value = property.default(host, value);
XElement.#validatePropertyValue(host, property, value);
valueMap.set(property, value);
XElement.#invalidateProperty(host, property);
}
}
static #serializeProperty(host, property, value) {
if (XElement.#notNullish(value)) {
if (property.type === Boolean) {
return value ? '' : undefined;
}
return value.toString();
}
}
static #deserializeProperty(host, property, value) {
if (property.type === Boolean) {
// Per HTML spec, every value other than null is considered true.
return value !== null;
} else if (value === null) {
// Null as an attribute is really "undefined" as a property.
return undefined;
} else if (!property.type) {
// Property doesn't have a type, leave it as a string.
return value;
} else {
// Coerce type as needed.
switch (property.type) {
case Number:
// Don't try and coerce something like "Number('') >> 0".
return value.trim() ? property.type(value) : Number.NaN;
default:
return property.type(value);
}
}
}
// Public properties which are serializable or typeless have attributes.
static #propertyHasAttribute(property) {
return !property.internal && (XElement.#serializableTypes.has(property.type) || !property.type);
}
static #getTypeName(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
static #notNullish(value) {
return value !== undefined && value !== null;
}
static #typeIsWrong(type, value) {
// Because `instanceof` fails on primitives (`'' instanceof String === false`)
// and `Object.prototype.toString` cannot handle inheritance, we use both.
return (
XElement.#notNullish(value) === false ||
(!(value instanceof type) && XElement.#getTypeName(value) !== type.name)
);
}
static #camelToKebab(camel) {