-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1326 lines (992 loc) · 35.7 KB
/
index.ts
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
// ================================================
// =============== LISS exported types ============
// ================================================
/*
type S<A,B> = {
A: A,
B: B
};
type LH = S<unknown,unknown>;
type inferA<T> = T extends S<infer A, any> ? A : never;
function foo<T extends LH>(t: T): inferA<T> {
return t.A as inferA<T>;
}
let X = {
A: 32,
B: "str"
};
let c = foo(X);
*/
export type CSS_Resource = string|Response|HTMLStyleElement|CSSStyleSheet;
export type CSS_Source = CSS_Resource | Promise<CSS_Resource>;
export type HTML_Resource = string|Response|HTMLTemplateElement;
export type HTML_Source = HTML_Resource | Promise<HTML_Resource>;
export type LISSOptions<Extends extends Class,
Host extends HTMLElement,
Attrs extends string,
Parameters extends Record<string, any>> = {
extends?: Constructor<Extends>,
host ?: Constructor<Host>,
dependencies?: readonly Promise<any>[],
attributes ?: readonly Attrs[],
params ?: Readonly<Parameters>,
content?: HTML_Source,
css ?: CSS_Source | readonly CSS_Source[],
shadow ?: ShadowCfg,
};
export enum ShadowCfg {
NONE = 'none',
OPEN = 'open',
CLOSE= 'closed'
};
// ================================================
// =============== LISS Class =====================
// ================================================
let __cstr_host : any = null;
type Constructor<T> = new () => T;
interface Class {}
// https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow
const CAN_HAVE_SHADOW = [
null, 'article', 'aside', 'blockquote', 'body', 'div',
'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'main',
'nav', 'p', 'section', 'span'
];
function _canHasShadow(tag: typeof HTMLElement) {
return CAN_HAVE_SHADOW.includes( _element2tagname(tag) );
}
type Resource = URL|Response;
export default function LISS<Extends extends Class = Class,
Host extends HTMLElement = HTMLElement,
Attrs extends string = never,
Parameters extends Record<string,any> = {}>({
extends : p_extends,
host : p_host,
dependencies: p_deps,
attributes : p_attrs,
params,
content,
css,
shadow : p_shadow,
}: LISSOptions<Extends, Host, Attrs, Parameters> = {}) {
//TODO merge prop if extends LISS...
const host = p_host ?? HTMLElement as Constructor<Host>;
const _extends = p_extends ?? Object as unknown as Constructor<Extends>;
const attributes = p_attrs ?? [];
const dependencies= p_deps ? [...p_deps] : [];
const canHasShadow= _canHasShadow(host);
const shadow = p_shadow ?? (canHasShadow ? ShadowCfg.CLOSE : ShadowCfg.NONE);
if( ! canHasShadow && shadow !== ShadowCfg.NONE)
throw new Error(`Host element ${_element2tagname(host)} does not support ShadowRoot`);
// CONTENT processing
if( content !== undefined ) {
dependencies.push( ( async () => {
content = await content;
if(content instanceof HTMLTemplateElement)
content = content.innerHTML;
if( typeof content === "string") {
content = content.trim(); // Never return a text node of whitespace as the result
if(content === '')
content = undefined;
}
if( content instanceof Response )
content = await content.text();
return LISSBase.Parameters.content = content;
})() );
}
// CSS processing
let stylesheets: readonly CSSStyleSheet[] = [];
if( css !== undefined ) {
if( ! Array.isArray(css) )
css = [css as CSS_Source];
stylesheets = new Array<CSSStyleSheet>(css.length);
const fetch_css = (async (css: CSS_Source) => {
css = await css;
if(css instanceof CSSStyleSheet)
return css;
if( css instanceof HTMLStyleElement)
return css.sheet!;
let style = new CSSStyleSheet();
if( typeof css === "string" ) {
await style.replace(css);
return style;
}
//if( css instanceof Response )
await style.replace(await css.text());
return style;
});
dependencies.push( ...css.map( async (css, idx) => (stylesheets as any)[idx] = await fetch_css(css) ) );
}
type LHost = LISSHost<LISSBase>;
// @ts-ignore
class LISSBase extends _extends {
readonly #host: any; // prevents issue #1...
constructor() {
super();
// h4ck, okay because JS is monothreaded.
if( __cstr_host === null )
throw new Error("Please do not directly call this constructor");
this.#host = __cstr_host;
__cstr_host = null;
}
public get host(): Host {
return this.#host;
}
protected get attrs() {
return (this.#host as LHost).attrs;
}
protected setAttrDefault( attr: Attrs, value: string|null) {
return (this.#host as LHost).setAttrDefault(attr, value);
}
public get params(): Readonly<Parameters> {
return (this.#host as LHost).params;
}
public setParam<T extends keyof Parameters>(name: T, value: Parameters[T]) {
(this.#host as LHost).params[name] = value;
}
protected get content() {
return (this.#host as LHost).content!;
}
static readonly Parameters = {
host,
dependencies,
attributes,
params,
content,
stylesheets,
shadow,
};
protected onAttrChanged(_name: string,
_oldValue: string,
_newValue: string): void|false {}
public get isInDOM() {
return (this.#host as LHost).isInDOM;
}
protected onDOMConnected() {}
protected onDOMDisconnected() {}
}
return LISSBase;
}
//TODO: other options...
function extendsLISS<Extends extends Class,
Host extends HTMLElement,
Attrs1 extends string,
Attrs2 extends string,
Params extends Record<string,any>,
T extends LISSReturnType<Extends, Host, Attrs1, Params>>(Liss: T,
parameters: {
shadow ?: ShadowCfg,
attributes ?: readonly Attrs2[],
dependencies?: readonly Promise<any>[]
}) {
const attributes = [...Liss.Parameters.attributes , ...parameters.attributes ??[]];
const dependencies = [...Liss.Parameters.dependencies, ...parameters.dependencies??[]];
const params = Object.assign({}, Liss.Parameters, {
attributes,
dependencies
});
if( parameters.shadow !== undefined)
params.shadow = parameters.shadow;
// @ts-ignore : because TS stupid
class ExtendedLISS extends Liss {
constructor(...t: any[]) {
// @ts-ignore : because TS stupid
super(...t);
}
protected override get attrs() {
return super.attrs as Record<Attrs2|Attrs1, string|null>;
}
static override Parameters = params;
}
return ExtendedLISS;
}
LISS.extendsLISS = extendsLISS;
// ================================================
// =============== LISS type helpers ==============
// ================================================
type buildLISSHostReturnType<T> = T extends LISSReturnType<infer Extends extends Class,
infer Host extends HTMLElement,
infer Attrs extends string,
infer Params extends Record<string,any>>
? ReturnType<typeof buildLISSHost<Extends, Host, Attrs, Params, T>> : never;
export type LISSReturnType<
Extends extends Class,
Host extends HTMLElement,
Attrs extends string,
Params extends Record<string,any>> = ReturnType<typeof LISS<Extends, Host, Attrs, Params>>;
export type LISSBase<Extends extends Class,
Host extends HTMLElement,
Attrs extends string,
Params extends Record<string,any>> = InstanceType<LISSReturnType<Extends, Host, Attrs, Params>>;
export type LISSHost<LISS extends LISSBase<any,any,any,any> > = InstanceType<buildLISSHostReturnType<Constructor<LISS> & {Parameters: any}>>;
// ================================================
// =============== LISSHost class =================
// ================================================
let id = 0;
function buildLISSHost<Extends extends Class,
Host extends HTMLElement,
Attrs extends string,
Params extends Record<string,any>,
T extends LISSReturnType<Extends, Host, Attrs, Params>>(Liss: T, _params: Partial<Params> = {}) {
const {
host,
attributes,
content,
stylesheets,
shadow,
} = Liss.Parameters;
const alreadyDeclaredCSS = new Set();
const GET = Symbol('get');
const SET = Symbol('set');
const properties = Object.fromEntries( attributes.map(n => [n, {
enumerable: true,
get: function(): string|null { return (this as unknown as Attributes)[GET](n); },
set: function(value: string|null) { return (this as unknown as Attributes)[SET](n, value); }
}]) );
class Attributes {
[x: string]: string|null;
#data : Record<Attrs, string|null>;
#defaults : Record<Attrs, string|null>;
#setter : (name: Attrs, value: string|null) => void;
[GET](name: Attrs) {
return this.#data[name] ?? this.#defaults[name] ?? null;
};
[SET](name: Attrs, value: string|null){
return this.#setter(name, value); // required to get a clean object when doing {...attrs}
}
constructor(data : Record<Attrs, string|null>,
defaults: Record<Attrs, string|null>,
setter : (name: Attrs, value: string|null) => void) {
this.#data = data;
this.#defaults = defaults;
this.#setter = setter;
Object.defineProperties(this, properties);
}
}
// @ts-ignore : because TS is stupid.
class LISSHostBase extends host {
readonly #params: Params;
readonly #id = ++id; // for debug
constructor(params: Partial<Params> = {}) {
super();
this.#params = Object.assign({}, Liss.Parameters.params, _params, params);
this.#waitInit = new Promise( (resolve) => {
if(this.isInit)
return resolve(this.#API!);
this.#resolve = resolve;
});
}
/**** public API *************/
get isInit() {
return this.#API !== null;
}
initialize(params: Partial<Params> = {}) {
if( this.isInit )
throw new Error('Element already initialized!');
Object.assign(this.#params, params);
const api = this.init();
if( this.#isInDOM )
(api as any).onDOMConnected();
return api;
}
get LISSSync() {
if( ! this.isInit )
throw new Error('Accessing API before WebComponent initialization!');
return this.#API!;
}
get LISS() {
return this.#waitInit;
}
/*** init ***/
#waitInit: Promise<InstanceType<T>>;
#resolve: ((u: InstanceType<T>) => void) | null = null;
#API: InstanceType<T> | null = null;
#isInDOM = false;
get isInDOM() {
return this.#isInDOM;
}
disconnectedCallback() {
this.#isInDOM = false;
(this.#API! as any).onDOMDisconnected();
}
connectedCallback() {
this.#isInDOM = true;
if( ! this.isInit )
this.init();
(this.#API! as any).onDOMConnected();
}
private init() {
customElements.upgrade(this);
// shadow
this.#content = this as unknown as Host;
if( shadow !== 'none') {
this.#content = this.attachShadow({mode: shadow});
//@ts-ignore
this.#content.addEventListener('click', onClickEvent);
//@ts-ignore
this.#content.addEventListener('dblclick', onClickEvent);
}
// attrs
for(let obs of attributes!)
this.#attributes[obs] = this.getAttribute(obs);
// css
if( shadow !== 'none')
(this.#content as ShadowRoot).adoptedStyleSheets.push(sharedCSS);
if( stylesheets.length ) {
if( shadow !== 'none')
(this.#content as ShadowRoot).adoptedStyleSheets.push(...stylesheets);
else {
const cssselector = this.CSSSelector;
// if not yet inserted :
if( ! alreadyDeclaredCSS.has(cssselector) ) {
let style = document.createElement('style');
style.setAttribute('for', cssselector);
let html_stylesheets = "";
for(let style of stylesheets)
for(let rule of style.cssRules)
html_stylesheets += rule.cssText + '\n';
style.innerHTML = html_stylesheets.replace(':host', `:is(${cssselector})`);
document.head.append(style);
alreadyDeclaredCSS.add(cssselector);
}
}
}
// content
if( content !== undefined ) {
let template_elem = document.createElement('template');
let str = (content as string).replace(/\$\{(.+?)\}/g, (_, match) => this.getAttribute(match)??'')
template_elem.innerHTML = str;
this.#content.append(...template_elem.content.childNodes);
}
// build
// h4ck, okay because JS is monothreaded.
__cstr_host = this;
let obj = new Liss();
/*if( obj instanceof Promise)
obj = await obj;*/
this.#API = obj as InstanceType<T>;
// default slot
if( this.hasShadow && this.#content.childNodes.length === 0 )
this.#content.append( document.createElement('slot') );
if( this.#resolve !== null)
this.#resolve(this.#API);
return this.#API;
}
get params(): Params {
return this.#params;
}
public setParam<T extends keyof Params>(name: T, value: Params[T]) {
if( this.isInit )
return this.#API!.setParam(name, value);
this.#params[name] = value; // will be given to constructor.
}
/*** content ***/
#content: Host|ShadowRoot|null = null;
get content() {
return this.#content;
}
getPart(name: string) {
return this.hasShadow
? this.#content?.querySelector(`::part(${name})`)
: this.#content?.querySelector(`[part="${name}"]`);
}
getParts(name: string) {
return this.hasShadow
? this.#content?.querySelectorAll(`::part(${name})`)
: this.#content?.querySelectorAll(`[part="${name}"]`);
}
protected get hasShadow(): boolean {
return shadow !== 'none';
}
/*** CSS ***/
get CSSSelector() {
if(this.hasShadow || ! this.hasAttribute("is") )
return this.tagName;
return `${this.tagName}[is="${this.getAttribute("is")}"]`;
}
/*** attrs ***/
#attrs_flag = false;
#attributes = {} as Record<Attrs, string|null>;
#attributesDefaults = {} as Record<Attrs, string|null>;
#attrs = new Attributes(
this.#attributes,
this.#attributesDefaults,
(name: Attrs, value:string|null) => {
this.#attributes[name] = value;
this.#attrs_flag = true; // do not trigger onAttrsChanged.
if( value === null)
this.removeAttribute(name);
else
this.setAttribute(name, value);
}
) as unknown as Record<Attrs, string|null>;
setAttrDefault(name: Attrs, value: string|null) {
if( value === null)
delete this.#attributesDefaults[name];
else
this.#attributesDefaults[name] = value;
}
get attrs(): Readonly<Record<Attrs, string|null>> {
return this.#attrs;
}
static observedAttributes = attributes;
attributeChangedCallback(name : Attrs,
oldValue: string,
newValue: string) {
if(this.#attrs_flag) {
this.#attrs_flag = false;
return;
}
this.#attributes[name] = newValue;
if( ! this.isInit )
return;
if( (this.#API! as any).onAttrChanged(name, oldValue, newValue) === false) {
this.#attrs[name] = oldValue; // revert the change.
}
}
};
return LISSHostBase;
}
// ================================================
// =============== LISS define ====================
// ================================================
const _DOMContentLoaded = new Promise<void>( (resolve) => {
if(document.readyState === "interactive" || document.readyState === "complete")
return resolve();
document.addEventListener('DOMContentLoaded', () => {
resolve();
}, true);
});
LISS.define = async function<Extends extends Class,
Host extends HTMLElement,
Attrs extends string,
Params extends Record<string,any>,
T extends LISSReturnType<Extends, Host, Attrs, Params>>(
tagname: string,
ComponentClass: T,
{dependencies, params}: {params?: Partial<Params>, dependencies?: readonly Promise<string>[]} = {}) {
dependencies??=[];
params ??= {};
const Class = ComponentClass.Parameters.host;
let LISSBase: any = ComponentClass;
let htmltag = _element2tagname(Class)??undefined;
await Promise.all([_DOMContentLoaded, ...dependencies, ...LISSBase.Parameters.dependencies]);
const LISSclass = buildLISSHost<Extends, Host, Attrs, Params, T>(ComponentClass, params);
const opts = htmltag === undefined ? {}
: {extends: htmltag};
customElements.define(tagname, LISSclass, opts);
};
// ================================================
// =============== LISS ShadowRoot tools ==========
// ================================================
const sharedCSS = new CSSStyleSheet();
document.adoptedStyleSheets.push(sharedCSS);
LISS.insertGlobalCSSRules = function(css: string|HTMLStyleElement) {
let css_style!: CSSStyleSheet;
if( css instanceof HTMLStyleElement )
css_style = css.sheet!;
if( typeof css === "string") {
css_style = new CSSStyleSheet();
css_style.replaceSync(css);
}
for(let rule of css_style.cssRules)
sharedCSS.insertRule(rule.cssText);
}
type DelegatedHandler = [string, (ev: MouseEvent) => void];
const DELEGATED_EVENTS = {
"click": [] as DelegatedHandler[],
"dblclick": [] as DelegatedHandler[]
};
const ALREADY_PROCESSED = Symbol();
function onClickEvent(ev: MouseEvent) {
if( (ev as any)[ALREADY_PROCESSED] === true )
return;
(ev as any)[ALREADY_PROCESSED] = true;
const handlers = DELEGATED_EVENTS[ev.type as keyof typeof DELEGATED_EVENTS];
for(let elem of ev.composedPath() ) {
if( elem instanceof ShadowRoot || elem === document || elem === window )
continue;
var target = elem as Element;
for(let [selector, handler] of handlers) {
if( target.matches(selector) )
handler(ev);
}
}
}
LISS.insertGlobalDelegatedListener = function(event_name: keyof typeof DELEGATED_EVENTS, selector: string, handler: (ev: MouseEvent) => void ) {
DELEGATED_EVENTS[event_name].push([selector, handler])
}
document.addEventListener('click', onClickEvent);
document.addEventListener('dblclick', onClickEvent);
LISS.closest = function closest<E extends Element>(selector: string, element: Element) {
while(true) {
var result = element.closest<E>(selector);
if( result !== null)
return result;
const root = element.getRootNode();
if( ! ("host" in root) )
return null;
element = (root as ShadowRoot).host;
}
}
// ================================================
// =============== LISS helpers ===================
// ================================================
type inferParams<T> = T extends LISSBase<any,any,any, infer P extends Record<string,any>> ? P : never;
type BUILD_OPTIONS<T extends LISSBase<any,any,any,any>> = Partial<{
params : Partial<inferParams<T>>,
content : string|Node|readonly Node[],
id : string,
classes : readonly string[],
cssvars : Readonly<Record<string, string>>,
attrs : Readonly<Record<string, string|boolean>>,
data : Readonly<Record<string, string|boolean>>,
listeners : Readonly<Record<string, (ev: Event) => void>>
}> & ({
initialize: false,
parent: Element
}|{
initialize?: true,
parent?: Element
});
async function build<T extends keyof Components>(tagname: T, options?: BUILD_OPTIONS<Components[T]>): Promise<Components[T]>;
async function build<T extends LISSBase<any,any,any,any>>(tagname: string, options?: BUILD_OPTIONS<T>): Promise<T>;
async function build<T extends LISSBase<any,any,any,any>>(tagname: string, {
params = {},
initialize= true,
content = [],
parent = undefined,
id = undefined,
classes = [],
cssvars = {},
attrs = {},
data = {},
listeners = {}
}: BUILD_OPTIONS<T> = {}): Promise<T> {
if( ! initialize && parent === null)
throw new Error("A parent must be given if initialize is false");
let CustomClass = await customElements.whenDefined(tagname);
let elem = new CustomClass(params) as LISSHost<T>;
// Fix issue #2
if( elem.tagName.toLowerCase() !== tagname )
elem.setAttribute("is", tagname);
if( id !== undefined )
elem.id = id;
if( classes.length > 0)
elem.classList.add(...classes);
for(let name in cssvars)
elem.style.setProperty(`--${name}`, cssvars[name]);
for(let name in attrs) {
let value = attrs[name];
if( typeof value === "boolean")
elem.toggleAttribute(name, value);
else
elem.setAttribute(name, value);
}
for(let name in data) {
let value = data[name];
if( value === false)
delete elem.dataset[name];
else if(value === true)
elem.dataset[name] = "";
else
elem.dataset[name] = value;
}
if( ! Array.isArray(content) )
content = [content as any];
elem.replaceChildren(...content);
for(let name in listeners)
elem.addEventListener(name, listeners[name]);
if( parent !== undefined )
parent.append(elem);
if( ! elem.isInit && initialize )
return await LISS.initialize(elem);
return await LISS.getLISS(elem);
}
LISS.build = build;
function buildSync<T extends keyof Components>(tagname: T, options?: BUILD_OPTIONS<Components[T]>): Components[T];
function buildSync<T extends LISSBase<any,any,any,any>>(tagname: string, options?: BUILD_OPTIONS<T>): T;
function buildSync<T extends LISSBase<any,any,any,any>>(tagname: string, {
params = {},
initialize= true,
content = [],
parent = undefined,
id = undefined,
classes = [],
cssvars = {},
attrs = {},
data = {},
listeners = {}
}: BUILD_OPTIONS<T> = {}): T {
if( ! initialize && parent === null)
throw new Error("A parent must be given if initialize is false");
let CustomClass = customElements.get(tagname);
if(CustomClass === undefined)
throw new Error(`${tagname} not defined`);
let elem = new CustomClass(params) as LISSHost<T>;
//TODO: factorize...
// Fix issue #2
if( elem.tagName.toLowerCase() !== tagname )
elem.setAttribute("is", tagname);
if( id !== undefined )
elem.id = id;
if( classes.length > 0)
elem.classList.add(...classes);
for(let name in cssvars)
elem.style.setProperty(`--${name}`, cssvars[name]);
for(let name in attrs) {
let value = attrs[name];
if( typeof value === "boolean")
elem.toggleAttribute(name, value);
else
elem.setAttribute(name, value);
}
for(let name in data) {
let value = data[name];
if( value === false)
delete elem.dataset[name];
else if(value === true)
elem.dataset[name] = "";
else
elem.dataset[name] = value;
}
if( ! Array.isArray(content) )
content = [content as any];
elem.replaceChildren(...content);
for(let name in listeners)
elem.addEventListener(name, listeners[name]);
if( parent !== undefined )
parent.append(elem);
if( ! elem.isInit && initialize )
LISS.initializeSync(elem);
return LISS.getLISSSync(elem);
}
LISS.buildSync = buildSync;
LISS.whenDefined = async function(tagname: string, callback?: () => void ) : Promise<void> {
await customElements.whenDefined(tagname);
if( callback !== undefined)
callback();
return;
}
LISS.whenAllDefined = async function(tagnames: readonly string[], callback?: () => void ) : Promise<void> {
await Promise.all( tagnames.map( t => customElements.whenDefined(t) ) )
if( callback !== undefined)
callback();
}
LISS.isDefined = function(name: string) {
return customElements.get(name);
}
LISS.selector = function(name?: string) {
if(name === undefined) // just an h4ck
return "";
return `:is(${name}, [is="${name}"])`;
}
LISS.getLISS = async function<T extends LISSBase<any,any,any,any>>( element: Element ) {
await LISS.whenDefined( LISS.getName(element) );
return (element as LISSHost<T>).LISS; // ensure initialized.
}
LISS.getLISSSync= function<T extends LISSBase<any,any,any,any>>( element: Element ) {
const name = LISS.getName(element);
if( ! LISS.isDefined( name ) )
throw new Error(`${name} hasn't been defined yet.`);
let host = element as LISSHost<T>;
if( ! host.isInit )
throw new Error("Instance hasn't been initialized yet.");
return host.LISSSync;
}
LISS.initialize = async function<T extends LISSBase<any,any,any,any>>( element: Element) {
await LISS.whenDefined( LISS.getName(element) );
return await (element as LISSHost<T>).initialize(); // ensure initialization.
}
LISS.initializeSync = function<T extends LISSBase<any,any,any,any>>( element: Element) {
const name = LISS.getName(element);
if( ! LISS.isDefined(name) )
throw new Error(`${name} not defined`);
return (element as LISSHost<T>).initialize(); // ensure initialization.
}
LISS.getName = function( element: Element ): string {
const name = element.getAttribute('is') ?? element.tagName.toLowerCase();
if( ! name.includes('-') )
throw new Error(`Element ${name} is not a WebComponent`);
return name;
}
function _buildQS(selector: string, tagname_or_parent?: string | Element|DocumentFragment|Document, parent: Element|DocumentFragment|Document = document) {
if( tagname_or_parent !== undefined && typeof tagname_or_parent !== 'string') {
parent = tagname_or_parent;
tagname_or_parent = undefined;
}
return [`${selector}${LISS.selector(tagname_or_parent as string|undefined)}`, parent] as const;
}
// ================================================
// =============== LISS QuerySelectors ============
// ================================================
async function qs<T extends LISSBase<any,any,any,any>>(selector: string,
parent ?: Element|DocumentFragment|Document): Promise<T>;
async function qs<N extends keyof Components>(selector: string,
tagname : N,
parent ?: Element|DocumentFragment|Document): Promise< Components[N] >;
async function qs<T extends LISSBase<any,any,any,any>>( selector: string,
tagname_or_parent?: keyof Components | Element|DocumentFragment|Document,
parent : Element|DocumentFragment|Document = document) {
[selector, parent] = _buildQS(selector, tagname_or_parent, parent);
let result = await LISS.qso<T>(selector, parent);
if(result === null)
throw new Error(`Element ${selector} not found`);
return result!
}
LISS.qs = qs
async function qso<T extends LISSBase<any,any,any,any>>(selector: string,
parent ?: Element|DocumentFragment|Document): Promise<T>;
async function qso<N extends keyof Components>(selector: string,
tagname : N,
parent ?: Element|DocumentFragment|Document): Promise< Components[N] >;
async function qso<T extends LISSBase<any,any,any,any>>( selector: string,
tagname_or_parent?: keyof Components | Element|DocumentFragment|Document,
parent : Element|DocumentFragment|Document = document) {
[selector, parent] = _buildQS(selector, tagname_or_parent, parent);
const element = parent.querySelector<LISSHost<T>>(selector);
if( element === null )
return null;
return await LISS.getLISS( element );
}
LISS.qso = qso