-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCustomElement.js
1277 lines (1159 loc) · 37 KB
/
CustomElement.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
/* eslint-disable max-classes-per-file */
import Composition from './Composition.js';
import { css } from './css.js';
import { attrNameFromPropName, attrValueFromDataValue } from './dom.js';
import { applyMergePatch } from './jsonMergePatch.js';
import { defineObservableProperty } from './observe.js';
import { addInlineFunction, html } from './template.js';
/** @typedef {import('./observe.js').ObserverPropertyType} ObserverPropertyType */
/**
* @template {any} T
* @typedef {{
* [P in keyof T]:
* T[P] extends (...args:any[]) => infer T2 ? T2
* : T[P] extends ObserverPropertyType
* ? import('./observe.js').ParsedObserverPropertyType<T[P]>
* : T[P] extends {type: ObserverPropertyType}
* ? import('./observe.js').ParsedObserverPropertyType<T[P]['type']>
* : T[P] extends ObserverOptions<null, infer T2>
* ? unknown extends T2 ? string : T2
* : never
* }} ParsedProps
*/
/**
* @template {ObserverPropertyType} T1
* @template {any} T2
* @template {Object} [C=any]
* @typedef {import('./observe.js').ObserverOptions<T1,T2,C>} ObserverOptions
*/
/**
* @template {{ prototype: unknown; }} T
* @typedef {T} ClassOf<T>
*/
/**
* @template {any} [T=any]
* @template {any[]} [A=any[]]
* @typedef {abstract new (...args: A) => T} Class
*/
/**
* @template {any} T1
* @template {any} [T2=T1]
* @callback HTMLTemplater
* @param {TemplateStringsArray} string
* @param {...(string|DocumentFragment|Element|((this:T1, data:T2) => any))} substitutions
* @return {DocumentFragment}
*/
/**
* @template {any} [T1=any]
* @template {any} [T2=T1]
* @typedef {Object} CallbackArguments
* @prop {Composition<T1>} composition
* @prop {Record<string, HTMLElement>} refs
* @prop {HTMLTemplater<T1, Partial<T2>>} html
* @prop {(fn: (this:T1, data: T2) => any) => string} inline
* @prop {DocumentFragment} template
* @prop {T1} element
*/
/**
* @template {any} T1
* @template {any} [T2=T1]
* @typedef {{
* composed?: (this: T1, options: CallbackArguments<T1, T2>) => any,
* constructed?: (this: T1, options: CallbackArguments<T1, T2>) => any,
* connected?: (this: T1, options: CallbackArguments<T1, T2>) => any,
* disconnected?: (this: T1, options: CallbackArguments<T1, T2>) => any,
* props?: {
* [P in keyof T1] : (
* this: T1,
* oldValue: T1[P],
* newValue: T1[P],
* changes:any,
* element: T1
* ) => any
* },
* attrs?: {[K in keyof any]: (
* this: T1,
* oldValue: string,
* newValue: string,
* element: T1
* ) => unknown
* },
* } & {
* [P in keyof T1 & string as `${P}Changed`]?: (
* this: T1,
* oldValue: T1[P],
* newValue: T1[P],
* changes:any,
* element: T1
* ) => any
* }} CompositionCallback
*/
/**
* @template {Object} C
* @typedef {{
* [P in string] :
* ObserverPropertyType
* | ObserverOptions<ObserverPropertyType, unknown, C>
* | ((this:C, data:Partial<C>, fn?: () => any) => any)
* }} IDLParameter
*/
/**
* @template T
* @typedef {(T | Array<[keyof T & string, T[keyof T]]>)} ObjectOrObjectEntries
*/
/**
* @template {abstract new (...args: any) => unknown} T
* @param {InstanceType<T>} instance
*/
function superOf(instance) {
const staticContext = instance.constructor;
const superOfStatic = Object.getPrototypeOf(staticContext);
return superOfStatic.prototype;
}
/**
* Clone attribute
* @param {string} name
* @param {string} target
* @return {(oldValue:string, newValue:string, element: CustomElement) => void}
*/
export function cloneAttributeCallback(name, target) {
return (oldValue, newValue, element) => {
if (newValue == null) {
element.refs[target].removeAttribute(name);
} else {
element.refs[target].setAttribute(name, newValue);
}
};
}
/**
* Web Component that can cache templates for minification or performance
*/
export default class CustomElement extends HTMLElement {
/** @type {string} */
static elementName;
/** @return {Iterable<string>} */
static get observedAttributes() {
return this.attrList.keys();
}
/** @type {import('./Composition.js').Compositor<?>} */
compose() {
// eslint-disable-next-line no-return-assign
return (this.#composition ??= new Composition());
}
/** @type {Composition<?>} */
static _composition = null;
/** @type {Map<string, import('./observe.js').ObserverConfiguration<?,?,?>>} */
static _props = new Map();
/** @type {Map<string, import('./observe.js').ObserverConfiguration<?,?,?>>} */
static _attrs = new Map();
/** @type {Map<string, Function[]>} */
static _propChangedCallbacks = new Map();
/** @type {Map<string, Function[]>} */
static _attributeChangedCallbacks = new Map();
/** @type {((callback: CallbackArguments) => any)[]} */
static _onComposeCallbacks = [];
/** @type {((callback: CallbackArguments) => any)[]} */
static _onConnectedCallbacks = [];
/** @type {((callback: CallbackArguments) => any)[]} */
static _onDisconnectedCallbacks = [];
/** @type {((callback: CallbackArguments) => any)[]} */
static _onConstructedCallbacks = [];
static interpolatesTemplate = true;
static supportsElementInternals = 'attachInternals' in HTMLElement.prototype;
static supportsElementInternalsRole = CustomElement.supportsElementInternals
&& 'role' in ElementInternals.prototype;
/** @type {boolean} */
static templatable = null;
static defined = false;
static autoRegistration = true;
/** @type {Map<string, typeof CustomElement>} */
static registrations = new Map();
/**
* Expressions are idempotent functions that are selectively called whenever
* a render is requested.
* Expressions are constructed exactly as methods though differ in expected
* arguments. The first argument should be destructured to ensure each used
* property is accessed at least once in order to inspect used properties.
*
* The Composition API will inspect this function with a proxy for `this` to
* catalog what observables are used by the expression. This allows the
* Composition API to build a cache as well as selective invoke the expression
* only when needed.
*
* When used with in element templates, the element itself will be passed as
* its first argument.
* ````js
* Button
* .prop('filled', 'boolean')
* .prop('outlined', 'boolean')
* .expresssions({
* _isFilledOrOutlined({filled, outlined}) {
* return (filled || outlined)
* },
* })
* .html`<div custom={_isFilledOrOutlined}></div>`;
* ````
*
* When used with external data source, that data source
* will be passed to the expression with all properties being `null` at first
* inspection.
* ````js
* const externalData = {first: 'John', last: 'Doe'};
* ContactCard
* .expresssions({
* _fullName({first, last}) {
* return [first, last].filter(Boolean).join(' ');
* },
* })
* myButton.render(externalData);
* ````
*
* Expressions may be support argumentless calls by using default
* parameters with `this`.
* ````js
* Button
* .expresssions({
* isFilledOrOutlined({filled, outlined} = this) {
* return (filled || outlined)
* },
* });
* myButton.isFilledorOutlined();
* ````
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends {
* [K in keyof any]: K extends `_${any}` ? ((data: INSTANCE, state?: Record<string, any>) => string|boolean|null)
* : ((data?: INSTANCE, state?: Record<string, any>) => string|boolean|null)
* } & ThisType<INSTANCE>
* >(this: CLASS, expressions: PROPS & ThisType<INSTANCE & PROPS>):
* CLASS & Class<{
* [K in keyof PROPS]: K extends `_${any}` ? never : () => ReturnType<PROPS[K]> }
* ,ARGS>
* }}
*/
static expressions = /** @type {any} */ (this.set);
static methods = this.set;
/**
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends Partial<INSTANCE>>
* (this: CLASS, source: PROPS & ThisType<PROPS & INSTANCE>, options?: Partial<PropertyDescriptor>)
* : CLASS & Class<PROPS,ARGS>
* }}
*/
static overrides = /** @type {any} */ (this.set);
/**
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* KEY extends string,
* OPTIONS extends ObserverPropertyType
* | ObserverOptions<ObserverPropertyType, unknown, INSTANCE>
* | ((this:INSTANCE, data:Partial<INSTANCE>, fn?: () => any) => any),
* VALUE extends Record<KEY, OPTIONS extends (...args2:any[]) => infer R ? R
* : OPTIONS extends ObserverPropertyType ? import('./observe.js').ParsedObserverPropertyType<OPTIONS>
* : OPTIONS extends {type: 'object'} & ObserverOptions<any, infer R> ? (unknown extends R ? object : R)
* : OPTIONS extends {type: ObserverPropertyType} ? import('./observe.js').ParsedObserverPropertyType<OPTIONS['type']>
* : OPTIONS extends ObserverOptions<any, infer R> ? (unknown extends R ? string : R)
* : never
* >
* > (this: CLASS, name: KEY, options: OPTIONS)
* : CLASS & Class<VALUE,ARGS>;
* }}
*/
static props = /** @type {any} */ (this.observe);
static idl = this.prop;
/**
* @this T
* @template {typeof CustomElement} T
* @template {keyof T} K
* @param {K} collection
* @param {T[K] extends (infer R)[] ? R : never} callback
*/
static _addCallback(collection, callback) {
if (!this.hasOwnProperty(collection)) {
// @ts-expect-error not typed
this[collection] = [...this[collection], callback];
return;
}
// @ts-expect-error any
this[collection].push(callback);
}
/**
* Append parts to composition
* @type {{
* <
* T extends typeof CustomElement,
* >
* (this: T, ...parts: ConstructorParameters<typeof Composition<InstanceType<T>>>): T;
* }}
*/
static append(...parts) {
this._addCallback('_onComposeCallbacks', ({ composition }) => {
composition.append(...parts);
});
// @ts-expect-error Can't cast T
return this;
}
/**
* After composition, invokes callback.
* May be called multiple times.
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends InstanceType<T1>,
* T3 extends CompositionCallback<T2, T2>['composed'],
* >
* (this: T1, callback: T3): T1
* }}
*/
static recompose(callback) {
this._addCallback('_onComposeCallbacks', callback);
// @ts-expect-error Can't cast T
return this;
}
/**
* Appends styles to composition
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends TemplateStringsArray|HTMLStyleElement|CSSStyleSheet|string>(
* this: T1,
* array: T2,
* ...rest: T2 extends string ? any : T2 extends TemplateStringsArray ? any[] : (HTMLStyleElement|CSSStyleSheet)[]
* ): T1
* }}
*/
static css(array, ...substitutions) {
this._addCallback('_onComposeCallbacks', ({ composition }) => {
if (typeof array === 'string' || Array.isArray(array)) {
// @ts-expect-error Complex cast
composition.append(css(array, ...substitutions));
} else {
// @ts-expect-error Complex cast
composition.append(array, ...substitutions);
}
});
// @ts-expect-error Can't cast T
return this;
}
/**
* Registers class asynchronously at end of current event loop cycle
* via `queueMicrotask`. If class is registered before then,
* does nothing.
* @type {{
* <T extends typeof CustomElement>(this: T, elementName: string): T;
* }}
*/
static autoRegister(elementName) {
if (this.hasOwnProperty('defined') && this.defined) {
console.warn(this.elementName, 'already registered.');
// @ts-expect-error Can't cast T
return this;
}
this.register(elementName);
// @ts-expect-error Can't cast T
return this;
}
/**
* Appends DocumentFragment to composition
* @type {{
* <T extends typeof CustomElement>(
* this: T,
* string: TemplateStringsArray,
* ...substitutions: (string|Element|((this:InstanceType<T>, data:InstanceType<T>, injections?:any) => any))[]
* ): T
* }}
*/
static html(strings, ...substitutions) {
this._addCallback('_onComposeCallbacks', ({ composition }) => {
// console.log('onComposed:html', strings);
composition.append(html(strings, ...substitutions));
});
// @ts-expect-error Can't cast T
return this;
}
/**
* Extends base class into a new class.
* Use to avoid mutating base class.
* @type {{
* <T1 extends typeof CustomElement, T2 extends T1, T3 extends (Base:T1) => T2>
* (this: T1,customExtender?: T3|null): T3 extends null ? T1 : T2;
* }}
*/
static extend(customExtender) {
// @ts-expect-error Can't cast T
return customExtender ? customExtender(this) : class extends this {};
}
/**
* Assigns static values to class
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends {
* [K in keyof any]: (
* ((this:T1, ...args:any[]) => any)
* |string|number|boolean|any[]|object)}
* >
* (this: T1, source: T2 & ThisType<T1 & T2>):T1 & T2;
* }}
*/
static setStatic(source) {
Object.assign(this, source);
// @ts-expect-error Can't cast T
return this;
}
/**
* Assigns values directly to all instances (via prototype)
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends object>
* (this: CLASS, source: PROPS & ThisType<PROPS & INSTANCE>, options?: Partial<PropertyDescriptor>)
* : CLASS & Class<PROPS,ARGS>
* }}
*/
static readonly(source, options) {
// @ts-expect-error Can't cast T
return this.set(source, { ...options, writable: false });
}
/**
* Assigns values directly to all instances (via prototype)
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends object>
* (this: CLASS, source: PROPS & ThisType<PROPS & INSTANCE>, options?: Partial<PropertyDescriptor>)
* : CLASS & Class<PROPS,ARGS>
* }}
*/
static set(source, options) {
Object.defineProperties(
this.prototype,
Object.fromEntries([
...Object.entries(source).map(([name, value]) => {
// Tap into .map() to avoid double iteration
// Property may be redefined observable
this.undefine(name);
return [
name,
{
enumerable: name[0] !== '_',
configurable: true,
value,
writable: true,
...options,
},
];
}),
...Object.getOwnPropertySymbols(source).map((symbol) => [
symbol,
{
enumerable: false,
configurable: true,
value: source[symbol],
writable: true,
...options,
},
]),
]),
);
// @ts-expect-error Can't cast T
return this;
}
/**
* Returns result of calling mixin with current class
* @type {{
* <
* BASE extends typeof CustomElement,
* FN extends (...args:any[]) => any,
* RETURN extends ReturnType<FN>,
* SUBCLASS extends ClassOf<RETURN>,
* (this: BASE, mixin: FN): SUBCLASS & BASE
* }}
*/
static mixin(mixin) {
return mixin(this);
}
/**
* Registers class with window.customElements synchronously
* @type {{
* <T extends typeof CustomElement>(this: T, elementName?: string, force?: boolean): T;
* }}
*/
static register(elementName) {
if (elementName) {
this.elementName = elementName;
}
customElements.define(this.elementName, this);
CustomElement.registrations.set(this.elementName, this);
this.defined = true;
// @ts-expect-error Can't cast T
return this;
}
static get propList() {
if (!this.hasOwnProperty('_props')) {
this._props = new Map(this._props);
}
return this._props;
}
static get attrList() {
if (!this.hasOwnProperty('_attrs')) {
this._attrs = new Map(this._attrs);
}
return this._attrs;
}
static get propChangedCallbacks() {
if (!this.hasOwnProperty('_propChangedCallbacks')) {
// structuredClone()
this._propChangedCallbacks = new Map(
[
...this._propChangedCallbacks,
].map(([name, array]) => [name, array.slice()]),
);
}
return this._propChangedCallbacks;
}
static get attributeChangedCallbacks() {
if (!this.hasOwnProperty('_attributeChangedCallbacks')) {
this._attributeChangedCallbacks = new Map(
[
...this._attributeChangedCallbacks,
].map(([name, array]) => [name, array.slice()]),
);
}
return this._attributeChangedCallbacks;
}
/**
* Creates observable property on instances (via prototype)
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* KEY extends string,
* OPTIONS extends ObserverPropertyType
* | ObserverOptions<ObserverPropertyType, unknown, INSTANCE>
* | ((this:INSTANCE, data:Partial<INSTANCE>, fn?: () => any) => any),
* VALUE extends Record<KEY, OPTIONS extends (...args2:any[]) => infer R ? R
* : OPTIONS extends ObserverPropertyType ? import('./observe').ParsedObserverPropertyType<OPTIONS>
* : OPTIONS extends {type: 'object'} & ObserverOptions<any, infer R> ? (unknown extends R ? object : R)
* : OPTIONS extends {type: ObserverPropertyType} ? import('./observe').ParsedObserverPropertyType<OPTIONS['type']>
* : OPTIONS extends ObserverOptions<any, infer R> ? (unknown extends R ? string : R)
* : never
* >
* > (this: CLASS, name: KEY, options: OPTIONS)
* : CLASS & Class<VALUE,ARGS>
* }}
*/
static prop(name, typeOrOptions) {
// TODO: Cache and save configuration for reuse (mixins)
const config = defineObservableProperty(
/** @type {any} */ (this.prototype),
name,
/** @type {any} */ (typeOrOptions),
);
const { changedCallback, attr, reflect, watchers } = config;
if (changedCallback) {
watchers.push([name, changedCallback]);
}
// TODO: Inspect possible closure bloat
config.changedCallback = function wrappedChangedCallback(oldValue, newValue, changes) {
this._onObserverPropertyChanged.call(this, name, oldValue, newValue, changes);
};
this.propList.set(name, config);
if (attr && (reflect === true || reflect === 'read')) {
this.attrList.set(attr, config);
}
this.onPropChanged(watchers);
// @ts-expect-error Can't cast T
return this;
}
/**
* Define properties on instances via Object.defineProperties().
* Automatically sets property non-enumerable if name begins with `_`.
* Functions will be remapped as getters
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends {
* [P in keyof any] :
* {
* enumerable?: boolean;
* configurable?: boolean;
* writable?: boolean;
* value?: any;
* get?: ((this: INSTANCE) => any);
* set?: (this: INSTANCE, value: any) => void;
* } | ((this: INSTANCE, ...args:any[]) => any)
* },
* VALUE extends {
* [KEY in keyof PROPS]: PROPS[KEY] extends (...args2:any[]) => infer R ? R
* : PROPS[KEY] extends TypedPropertyDescriptor<infer R> ? R : never
* }>
* (this: CLASS, props: PROPS & ThisType<PROPS & INSTANCE>): CLASS
* & Class<VALUE,ARGS>
* }}
*/
static define(props) {
Object.defineProperties(
this.prototype,
Object.fromEntries(
Object.entries(props).map(([name, options]) => {
// Tap into .map() to avoid double iteration
// Property may be redefined observable
this.undefine(name);
return [
name,
{
enumerable: name[0] !== '_',
configurable: true,
...(
typeof options === 'function'
? { get: options }
: options
),
},
];
}),
),
);
// @ts-expect-error Can't cast T
return this;
}
static undefine(name) {
Reflect.deleteProperty(this.prototype, name);
if (!this.propList.has(name)) return this;
const { watchers, attr, reflect } = this.propList.get(name);
if (watchers.length && this.propChangedCallbacks.has(name)) {
const propWatchers = this.propChangedCallbacks.get(name);
for (const watcher of watchers) {
const index = propWatchers.indexOf(watcher);
if (index !== -1) {
console.warn('Unwatching', name);
propWatchers.splice(index, 1);
}
}
}
if (attr && (reflect === true || reflect === 'read')) {
this.attrList.delete(attr);
}
this.propList.delete(name);
return this;
}
/**
* Creates observable properties on instances
* @type {{
* <
* CLASS extends typeof CustomElement,
* ARGS extends ConstructorParameters<CLASS>,
* INSTANCE extends InstanceType<CLASS>,
* PROPS extends IDLParameter<INSTANCE & VALUE>,
* VALUE extends {
* [KEY in keyof PROPS]:
* PROPS[KEY] extends (...args2:any[]) => infer R ? R
* : PROPS[KEY] extends ObserverPropertyType ? import('./observe').ParsedObserverPropertyType<PROPS[KEY]>
* : PROPS[KEY] extends {type: 'object'} & ObserverOptions<any, infer R> ? (unknown extends R ? object : R)
* : PROPS[KEY] extends {type: ObserverPropertyType} ? import('./observe').ParsedObserverPropertyType<PROPS[KEY]['type']>
* : PROPS[KEY] extends ObserverOptions<any, infer R> ? (unknown extends R ? string : R)
* : never
* },
* > (this: CLASS, props: PROPS)
* : CLASS & Class<VALUE,ARGS>
* }}
*/
static observe(props) {
for (const [name, typeOrOptions] of Object.entries(props ?? {})) {
/** @type {any} */
const options = (typeof typeOrOptions === 'function')
? { reflect: false, get: typeOrOptions }
: typeOrOptions;
this.prop(name, options);
}
// @ts-expect-error Can't cast T
return this;
}
/**
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends IDLParameter<T1>>
* (this: T1, props: T2):T1 & ParsedProps<T2>
* }}
*/
static defineStatic(props) {
for (const [name, typeOrOptions] of Object.entries(props ?? {})) {
const options = (typeof typeOrOptions === 'function')
? { get: typeOrOptions }
: (typeof typeOrOptions === 'string'
? { type: typeOrOptions }
: typeOrOptions);
defineObservableProperty(this, name, {
reflect: false,
...options,
});
}
// @ts-expect-error Can't cast T
return this;
}
/**
* @type {{
* <T extends typeof CustomElement>
* (
* this: T,
* listeners?: import('./Composition').CompositionEventListenerObject<InstanceType<T>>,
* options?: Partial<import('./Composition').CompositionEventListener<InstanceType<T>>>,
* ): T;
* }}
*/
static events(listeners, options) {
this.on({
composed({ composition }) {
for (const [key, listenerOptions] of Object.entries(listeners)) {
const [, flags, type] = key.match(/^([*1~]+)?(.*)$/);
// TODO: Make abstract
let prop;
/** @type {string[]} */
let deepProp = [];
if (typeof listenerOptions === 'string') {
const parsedProps = listenerOptions.split('.');
if (parsedProps.length === 1) {
prop = listenerOptions;
deepProp = [];
} else {
prop = parsedProps[0];
deepProp = parsedProps;
}
}
composition.addCompositionEventListener({
type,
once: flags?.includes('1'),
passive: flags?.includes('~'),
capture: flags?.includes('*'),
...(
typeof listenerOptions === 'function'
? { handleEvent: listenerOptions }
: (typeof listenerOptions === 'string'
? { prop, deepProp }
: listenerOptions)
),
...(
options
)
,
});
}
},
});
// @ts-expect-error Can't cast T
return this;
}
/**
* @type {{
* <T extends typeof CustomElement>
* (
* this: T,
* listenerMap: {
* [P in keyof any]: import('./Composition').CompositionEventListenerObject<InstanceType<T>>
* },
* options?: Partial<import('./Composition').CompositionEventListener<InstanceType<T>>>,
* ): T;
* }}
*/
static childEvents(listenerMap, options) {
for (const [tag, listeners] of Object.entries(listenerMap)) {
// @ts-expect-error Can't cast T
this.events(listeners, {
tag: attrNameFromPropName(tag),
...options,
});
}
// @ts-expect-error Can't cast T
return this;
}
/** @type {typeof CustomElement['events']} */
static rootEvents(listeners, options) {
// @ts-expect-error Can't cast T
return this.events(listeners, {
tag: Composition.shadowRootTag,
...options,
});
}
/**
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends InstanceType<T1>,
* T3 extends CompositionCallback<T2, T2>,
* T4 extends keyof T3,
* >
* (this: T1, name: T3|T4, callbacks?: T3[T4] & ThisType<T2>): T1
* }}
*/
static on(nameOrCallbacks, callback) {
const callbacks = typeof nameOrCallbacks === 'string'
? { [nameOrCallbacks]: callback }
: nameOrCallbacks;
for (const [name, fn] of Object.entries(callbacks)) {
/** @type {keyof (typeof CustomElement)} */
let arrayPropName;
switch (name) {
case 'composed': arrayPropName = '_onComposeCallbacks'; break;
case 'constructed': arrayPropName = '_onConstructedCallbacks'; break;
case 'connected': arrayPropName = '_onConnectedCallbacks'; break;
case 'disconnected': arrayPropName = '_onDisconnectedCallbacks'; break;
case 'props':
this.onPropChanged(fn);
continue;
case 'attrs':
this.onAttributeChanged(fn);
continue;
default:
if (name.endsWith('Changed')) {
const prop = name.slice(0, name.length - 'Changed'.length);
this.onPropChanged({ [prop]: fn });
continue;
}
throw new Error('Invalid callback name');
}
this._addCallback(arrayPropName, fn);
}
// @ts-expect-error Can't cast T
return this;
}
/**
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends InstanceType<T1>
* >
* (
* this: T1,
* options: ObjectOrObjectEntries<{
* [P in keyof T2]? : (
* this: T2,
* oldValue: T2[P],
* newValue: T2[P],
* changes:any,
* element: T2
* ) => void
* }>,
* ): T1;
* }}
*/
static onPropChanged(options) {
const entries = Array.isArray(options) ? options : Object.entries(options);
const { propChangedCallbacks } = this;
for (const [prop, callback] of entries) {
if (propChangedCallbacks.has(prop)) {
propChangedCallbacks.get(prop).push(callback);
} else {
propChangedCallbacks.set(prop, [callback]);
}
}
// @ts-expect-error Can't cast T
return this;
}
/**
* @type {{
* <
* T1 extends typeof CustomElement,
* T2 extends InstanceType<T1>
* >
* (
* this: T1,
* options: {
* [x:string]: (
* this: T2,
* oldValue: string,
* newValue: string,
* element: T2
* ) => void
* },
* ): T1;
* }}
*/
static onAttributeChanged(options) {
const entries = Array.isArray(options) ? options : Object.entries(options);
const { attributeChangedCallbacks } = this;
for (const [name, callback] of entries) {
if (attributeChangedCallbacks.has(name)) {
attributeChangedCallbacks.get(name).push(callback);
} else {
attributeChangedCallbacks.set(name, [callback]);
}
}
// @ts-expect-error Can't cast T
return this;
}
/** @type {Record<string, HTMLElement>}} */
#refsProxy;
/** @type {Map<string, WeakRef<HTMLElement>>}} */
#refsCache = new Map();
/** @type {Map<string, WeakRef<HTMLElement>>}} */
#refsCompositionCache = new Map();
/** @type {Composition<?>} */
#composition;
/** @type {Map<string,{stringValue:string, parsedValue:any}>} */
_propAttributeCache;
/** @type {CallbackArguments} */
_callbackArguments = null;