-
Notifications
You must be signed in to change notification settings - Fork 4
/
Raw.ts
1535 lines (1402 loc) · 42.6 KB
/
Raw.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
/**
*
*/
interface RawElements
{
a(...params: Raw.Param<Raw.AnchorElementAttribute>[]): HTMLAnchorElement;
abbr(...params: Raw.Param[]): HTMLElement;
address(...params: Raw.Param[]): HTMLElement;
area(...params: Raw.Param[]): HTMLAreaElement;
article(...params: Raw.Param[]): HTMLElement;
aside(...params: Raw.Param[]): HTMLElement;
audio(...params: Raw.Param[]): HTMLAudioElement;
b(...params: Raw.Param[]): HTMLElement;
base(...params: Raw.Param<Raw.BaseElementAttribute>[]): HTMLBaseElement;
bdi(...params: Raw.Param[]): HTMLElement;
bdo(...params: Raw.Param[]): HTMLElement;
blockquote(...params: Raw.Param[]): HTMLQuoteElement;
body(...params: Raw.Param[]): HTMLBodyElement;
br(...params: Raw.Param[]): HTMLBRElement;
button(...params: Raw.Param[]): HTMLButtonElement;
canvas(...params: Raw.Param[]): HTMLCanvasElement;
caption(...params: Raw.Param[]): HTMLTableCaptionElement;
cite(...params: Raw.Param[]): HTMLElement;
code(...params: Raw.Param[]): HTMLElement;
col(...params: Raw.Param[]): HTMLTableColElement;
colgroup(...params: Raw.Param[]): HTMLTableColElement;
data(...params: Raw.Param[]): HTMLDataElement;
datalist(...params: Raw.Param[]): HTMLDataListElement;
dd(...params: Raw.Param[]): HTMLElement;
del(...params: Raw.Param[]): HTMLModElement;
details(...params: Raw.Param[]): HTMLDetailsElement;
dfn(...params: Raw.Param[]): HTMLElement;
dialog(...params: Raw.Param[]): HTMLDialogElement;
dir(...params: Raw.Param[]): HTMLDirectoryElement;
div(...params: Raw.Param[]): HTMLDivElement;
dl(...params: Raw.Param[]): HTMLDListElement;
dt(...params: Raw.Param[]): HTMLElement;
em(...params: Raw.Param[]): HTMLElement;
embed(...params: Raw.Param[]): HTMLEmbedElement;
fieldset(...params: Raw.Param[]): HTMLFieldSetElement;
figcaption(...params: Raw.Param[]): HTMLElement;
figure(...params: Raw.Param[]): HTMLElement;
font(...params: Raw.Param[]): HTMLFontElement;
footer(...params: Raw.Param[]): HTMLElement;
form(...params: Raw.Param<Raw.FormElementAttribute>[]): HTMLFormElement;
frame(...params: Raw.Param[]): HTMLFrameElement;
frameset(...params: Raw.Param[]): HTMLFrameSetElement;
h1(...params: Raw.Param[]): HTMLHeadingElement;
h2(...params: Raw.Param[]): HTMLHeadingElement;
h3(...params: Raw.Param[]): HTMLHeadingElement;
h4(...params: Raw.Param[]): HTMLHeadingElement;
h5(...params: Raw.Param[]): HTMLHeadingElement;
h6(...params: Raw.Param[]): HTMLHeadingElement;
head(...params: Raw.Param[]): HTMLHeadElement;
header(...params: Raw.Param[]): HTMLElement;
hgroup(...params: Raw.Param[]): HTMLElement;
hr(...params: Raw.Param[]): HTMLHRElement;
i(...params: Raw.Param[]): HTMLElement;
iframe(...params: Raw.Param<Raw.FrameElementAttribute>[]): HTMLIFrameElement;
img(...params: Raw.Param<Raw.ImageElementAttribute>[]): HTMLImageElement;
input(...params: Raw.Param<Raw.InputElementAttribute>[]): HTMLInputElement;
ins(...params: Raw.Param[]): HTMLModElement;
kbd(...params: Raw.Param[]): HTMLElement;
label(...params: Raw.Param[]): HTMLLabelElement;
legend(...params: Raw.Param[]): HTMLLegendElement;
li(...params: Raw.Param[]): HTMLLIElement;
link(...params: Raw.Param<Raw.LinkElementAttribute>[]): HTMLLinkElement;
main(...params: Raw.Param[]): HTMLElement;
map(...params: Raw.Param[]): HTMLMapElement;
mark(...params: Raw.Param[]): HTMLElement;
marquee(...params: Raw.Param[]): HTMLMarqueeElement;
menu(...params: Raw.Param[]): HTMLMenuElement;
meta(...params: Raw.Param<Raw.MetaElementAttribute>[]): HTMLMetaElement;
meter(...params: Raw.Param[]): HTMLMeterElement;
nav(...params: Raw.Param[]): HTMLElement;
noscript(...params: Raw.Param[]): HTMLElement;
object(...params: Raw.Param[]): HTMLObjectElement;
ol(...params: Raw.Param[]): HTMLOListElement;
optgroup(...params: Raw.Param[]): HTMLOptGroupElement;
option(...params: Raw.Param[]): HTMLOptionElement;
output(...params: Raw.Param[]): HTMLOutputElement;
p(...params: Raw.Param[]): HTMLParagraphElement;
param(...params: Raw.Param[]): HTMLParamElement;
picture(...params: Raw.Param[]): HTMLPictureElement;
pre(...params: Raw.Param[]): HTMLPreElement;
progress(...params: Raw.Param[]): HTMLProgressElement;
q(...params: Raw.Param[]): HTMLQuoteElement;
rp(...params: Raw.Param[]): HTMLElement;
rt(...params: Raw.Param[]): HTMLElement;
ruby(...params: Raw.Param[]): HTMLElement;
s(...params: Raw.Param[]): HTMLElement;
samp(...params: Raw.Param[]): HTMLElement;
script(...params: Raw.Param<Raw.ScriptElementAttribute>[]): HTMLScriptElement;
section(...params: Raw.Param[]): HTMLElement;
select(...params: Raw.Param[]): HTMLSelectElement;
slot(...params: Raw.Param[]): HTMLSlotElement;
small(...params: Raw.Param[]): HTMLElement;
source(...params: Raw.Param[]): HTMLSourceElement;
span(...params: Raw.Param[]): HTMLSpanElement;
strong(...params: Raw.Param[]): HTMLElement;
sub(...params: Raw.Param[]): HTMLElement;
summary(...params: Raw.Param[]): HTMLElement;
sup(...params: Raw.Param[]): HTMLElement;
table(...params: Raw.Param[]): HTMLTableElement;
tbody(...params: Raw.Param[]): HTMLTableSectionElement;
td(...params: Raw.Param[]): HTMLTableCellElement;
template(...params: Raw.Param[]): HTMLTemplateElement;
textarea(...params: Raw.Param[]): HTMLTextAreaElement;
tfoot(...params: Raw.Param[]): HTMLTableSectionElement;
th(...params: Raw.Param[]): HTMLTableCellElement;
thead(...params: Raw.Param[]): HTMLTableSectionElement;
time(...params: Raw.Param[]): HTMLTimeElement;
title(...params: Raw.Param[]): HTMLTitleElement;
tr(...params: Raw.Param[]): HTMLTableRowElement;
track(...params: Raw.Param[]): HTMLTrackElement;
u(...params: Raw.Param[]): HTMLElement;
ul(...params: Raw.Param[]): HTMLUListElement;
video(...params: Raw.Param<Raw.VideoElementAttribute>[]): HTMLVideoElement;
wbr(...params: Raw.Param[]): HTMLElement;
new(): RawElements;
}
/**
* JSX compatibility
*/
declare namespace JSX
{
type Element = globalThis.Element;
type E<T = Raw.ElementAttribute> = Partial<T | Raw.Style>;
interface IntrinsicElements
{
a: E<Raw.AnchorElementAttribute>;
abbr: E;
address: E;
area: E;
article: E;
aside: E;
audio: E;
b: E;
base: E<Raw.BaseElementAttribute>;
bdi: E;
bdo: E;
blockquote: E;
body: E;
br: E;
button: E;
canvas: E;
caption: E;
cite: E;
code: E;
col: E;
colgroup: E;
data: E;
datalist: E;
dd: E;
del: E;
details: E;
dfn: E;
dialog: E;
dir: E;
div: E;
dl: E;
dt: E;
em: E;
embed: E;
fieldset: E;
figcaption: E;
figure: E;
font: E;
footer: E;
form: E<Raw.FormElementAttribute>;
frame: E;
frameset: E;
h1: E;
h2: E;
h3: E;
h4: E;
h5: E;
h6: E;
head: E;
header: E;
hgroup: E;
hr: E;
i: E;
iframe: E<Raw.FrameElementAttribute>;
img: E<Raw.ImageElementAttribute>;
input: E<Raw.InputElementAttribute>;
ins: E;
kbd: E;
label: E;
legend: E;
li: E;
link: E<Raw.LinkElementAttribute>;
main: E;
map: E;
mark: E;
marquee: E;
menu: E;
meta: E<Raw.MetaElementAttribute>;
meter: E;
nav: E;
noscript: E;
object: E;
ol: E;
optgroup: E;
option: E;
output: E;
p: E;
param: E;
picture: E;
pre: E;
progress: E;
q: E;
rp: E;
rt: E;
ruby: E;
s: E;
samp: E;
script: E<Raw.ScriptElementAttribute>;
section: E;
select: E;
slot: E;
small: E;
source: E;
span: E;
strong: E;
sub: E;
summary: E;
sup: E;
table: E;
tbody: E;
td: E;
template: E;
textarea: E;
tfoot: E;
th: E;
thead: E;
time: E;
title: E;
tr: E;
track: E;
u: E;
ul: E;
video: E<Raw.VideoElementAttribute>;
wbr: E;
}
}
class Raw extends (() => Object as any as RawElements)()
{
/**
* Stores the immutable set of HTML elements that
* are recognized as HTML element creation functions.
*/
static readonly elements: ReadonlySet<string> = new Set<string>(["a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "i", "iframe", "img", "input", "ins", "kbd", "label", "legend", "li", "link", "main", "map", "mark", "marquee", "menu", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "slot", "small", "source", "span", "strong", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "video", "wbr"]);
/**
* Stores the list of strings that are recognized as CSS properties by RawJS,
* (as opposed to being recognized as HTML attributes). Users may contribute
* strings to this set in order to add support for custom CSS properties.
*/
static readonly properties = (() =>
{
const names: string[] = [];
if (typeof document !== "undefined")
for (const key in document.documentElement.style)
names.push(key);
return new Set<string>(names);
})();
/** */
static readonly HTMLCustomElement =
(typeof HTMLElement !== "undefined") as true &&
class HTMLCustomElement extends HTMLElement { };
/**
* Creates a new instance of a Raw element creator.
*
* @param doc A reference to the Document object over
* which this Raw instance operates.
*/
constructor(private readonly doc: Document)
{
super();
for (const tagName of Raw.elements)
this.define(tagName);
}
/**
* Defines a custom element which derives from the specified constructor.
*/
define(tagName: string, constructor: typeof HTMLElement = Raw.HTMLCustomElement)
{
if (!Raw.elements.has(tagName))
{
tagName += "-element";
if (typeof customElements !== "undefined")
customElements.define(tagName, constructor);
}
Object.defineProperty(this, tagName, {
value: (...params: Raw.Param[]) => this.apply(this.doc.createElement(tagName), params)
});
}
/**
* A function that creates a new DOM Text node, but which may be overridden
* in the constructor to return a different but compatible value.
*/
text(template: TemplateStringsArray, ...placeholders: (string | HTMLElement)[]): (Text | HTMLElement)[];
text(string: string): Text;
text(a: TemplateStringsArray | string, ...b: string[]): any
{
if (typeof a === "string")
return this.doc.createTextNode(a);
const nodes: (string | HTMLElement)[] = [];
for (let i = -1; ++i < b.length;)
nodes.push(a[i], b[i])
nodes.push(a[a.length - 1]);
return nodes.map(n => typeof n === "string" ? this.doc.createTextNode(n) : n);
}
/**
* Creates a new Raw context from the specified Element or series of Elements.
*/
get<T extends Element | Raw.HatLike>(e: T, ...others: Element[]): (...params: Raw.Param[]) => T;
get<T extends ShadowRoot>(e: T, ...others: Element[]): (...params: Raw.ShadowParam[]) => T;
get<T>(...elements: T[]): any
{
return (...params: Raw.Param[]) =>
{
for (const e of elements)
{
if (Raw.is.element(e) || Raw.is.shadow(e))
this.apply(e as Element, params);
else if (Raw.is.element((e as any as Raw.HatLike).head))
this.apply((e as any as Raw.HatLike).head, params);
}
return elements[0] || null;
};
}
/**
* An object that contains environment-agnostic guard functions
* to make various assertions about data.
*/
static readonly is = {
node(n: any): n is Node
{
const type = n?.nodeType;
return typeof type === "number" && type > 0 && type < 13;
},
element(e: any): e is HTMLElement
{
return !!e && e.nodeType === 1;
},
text(t: any): t is Text
{
return !!t && (t as Text).nodeType === 3;
},
comment(c: any): c is Comment
{
return !!c && (c as Comment).nodeType === 8;
},
shadow(c: any): c is ShadowRoot
{
return !!c && (c as ShadowRoot).nodeType === 11 && Raw.is.element(c.host);
},
/**
* Returns a boolean value that indicates whether the specified
* string is the name of a valid CSS property in camelCase format,
* for example, "fontWeight".
*/
property(name: string)
{
return Raw.properties.has(name);
}
};
/**
* Creates and returns a ShadowRoot, in order to access
* the shadow DOM of a particular element.
*/
shadow(...params: Raw.ShadowParam[]): Raw.Param
{
return e =>
{
const shadow = e.shadowRoot || e.attachShadow({ mode: "open" });
this.apply(shadow, params as Raw.Param[]);
};
}
/**
* Creates a DOM element using the standard JSX element creation call signature.
* Any Raw.Param values that are strings are converted to DOM Text nodes rather
* than class names.
*/
jsx(tag: string | Element, properties: Record<string, any> | null = null, ...params: Raw.Param[])
{
const e = typeof tag === "string" ? this.doc.createElement(tag) : tag;
if (properties)
for (const [n, v] of Object.entries(properties))
(e as any)[n] = v;
// Generated class names should be appended
// as class names rather than text content.
const reg = new RegExp("^" + Raw.GeneratedClassPrefix.value + "[a-z\\d]{9,11}$");
params = params
.filter(p => p)
.map(p => typeof p === "string" && !reg.test(p) ? this.text(p) : p);
return this.apply(e, params) as Element;
}
/**
* This is the main applicator method where all params are applied
* to the target.
*
* PROCEED WITH CAUTION. This code is VERY performance sensitive.
* It uses constructor checks instead of instanceof and typeof in an effort
* to nullify any performance overhead. Be careful of changing this code
* without having full knowledge of what you're doing. Chesterton's
* fence rule applies here.
*/
private apply(e: Element | ShadowRoot, params: Raw.Param[])
{
for (let i = -1, length = params.length; ++i < length;)
{
const param = params[i];
if (!param)
continue;
if (Raw.is.node(param))
{
e.append(param);
}
else if (Array.isArray(param))
{
this.apply(e, param);
}
else switch (param.constructor)
{
case Raw.PortableEvent:
{
if (e)
{
const he = param as Raw.PortableEvent;
if (he.target)
he.host = e;
else
{
e.addEventListener(he.type, he.handler, he.options);
if (he.type === "connected" || he.type === "rendered")
this.awaitingConnection.push([e, he.type === "rendered"]);
}
}
}
break; case String:
{
// Note that ShadowRoots cannot accept string parameters.
const cls = param as string;
(e as Element).classList.add(...cls.split(/\s+/g).filter(s => s));
if (cls.indexOf(Raw.GeneratedClassPrefix.value) === 0)
{
const maybeShadow = e.getRootNode();
if (Raw.is.shadow(maybeShadow))
this.toShadow(maybeShadow, cls);
}
}
break; case Object:
{
const el = e as any;
for (const [name, value] of Object.entries(param))
{
// JavaScript numbers that are specified in the width and height properties
// are injected as HTML attributes rather than assigned as CSS properties.
if (value &&
(name === "width" || name === "height") && typeof value === "number" ||
(e as Element).tagName === "META")
{
(e as Element).setAttribute(name, value.toString());
}
else if (name === "data")
{
for (const [attrName, attrValue] of Object.entries(value || {}))
(e as Element).setAttribute("data-" + attrName, String(attrValue));
}
// Add support for { class: "class names here" }
// Because strings are interpreted as strings, this should only ever come up
// when using JSX to construct elements such as: <div class="the class">
else if (name === "class")
{
(e as Element).classList.add(...value.split(/\s+/g));
}
// Width, height, and background properties are special cased.
// They are interpreted as CSS properties rather than HTML attributes.
else if (name in e &&
name !== "background" &&
name !== "width" &&
name !== "height")
{
// Some attributes can't be assigned with keyed property access,
// at least in Chromium-based browsers (HTMLVideoElement.muted).
// So here, we're assigning both the JavaScript property and calling
// the setAttribute() function to ensure that the attribute always
// shows up in the Element.getAttributes() list.
el[name] = value;
(e as Element).setAttribute(name, value);
}
else if (Raw.is.property(name))
{
this.setProperty(el, name, value);
}
}
}
break; case Function:
{
if (Raw.is.element(e) || Raw.is.shadow(e))
{
const fn = param as Function;
const subParams = fn(e);
if (subParams)
this.apply(e, Array.isArray(subParams) ? subParams : [subParams]);
}
}
default:
{
// Ugly, but high-performance way to check if the param is a Hat
// (meaning, an object with a .head HTMLElement property) coming
// from the Hat library.
if (!!(param as any).head && (param as any).head.ELEMENT_NODE === 1)
{
this.apply(e, [(param as any).head]);
}
else if (typeof param === "function" && param.constructor.name === "AsyncFunction")
{
this.apply(e, (param as Function)(e));
}
}
}
}
return e;
}
//# Event Related
/** */
static readonly PortableEvent = class PortableEvent
{
/** */
constructor(
readonly target: Node | null,
readonly type: string,
readonly handler: (ev: globalThis.Event) => void,
readonly options: Readonly<AddEventListenerOptions> = {})
{ }
/**
* Stores the element that "hosts" the event, which is not necessarily
* the target event. When the host element is removed from the DOM,
* the event handler is removed.
*/
host: Element | ShadowRoot | null = null;
}
/** */
on<K extends keyof Raw.EventMap>(
type: K,
listener: (this: HTMLElement, ev: Raw.EventMap[K]) => any,
options?: boolean | EventListenerOptions): Raw.PortableEvent;
/** */
on<K extends keyof Raw.EventMap>(
remoteTarget: Node | Window,
type: K,
listener: (this: HTMLElement, ev: Raw.EventMap[K]) => any,
options?: boolean | EventListenerOptions): Raw.PortableEvent;
/** */
on<K extends keyof WindowEventMap>(
remoteTarget: Window,
type: K,
listener: (this: Window, ev: WindowEventMap[K]) => any,
options?: boolean | EventListenerOptions): Raw.PortableEvent;
/** */
on(...args: any[])
{
const target: Node | null = typeof args[0] === "string" ? null : args[0];
const type: string = typeof args[0] === "string" ? args[0] : args[1];
const handler = typeof args[1] === "function" ? args[1] : args[2];
const last = args.pop();
const options: AddEventListenerOptions = typeof last === "function" ? {} : last;
if (type === "connected" || type === "disconnected")
{
this.maybeInstallRootObserver();
options.once = true;
}
const hev = new Raw.PortableEvent(target, type, handler, options);
// If the event has a defined target, then add the event listener right away,
// and the apply() function will assign any host element, if present.
if (target)
{
let handler: (ev: Event) => void;
target.addEventListener(hev.type, handler = (ev: Event) =>
{
if (hev.host?.isConnected !== false)
hev.handler(ev as any);
else
target.removeEventListener(hev.type, handler);
},
options);
}
return hev;
}
//# Connection Events
/** */
private maybeInstallRootObserver()
{
if (this.hasInstalledRootObserver || typeof MutationObserver === "undefined")
return;
this.hasInstalledRootObserver = true;
new MutationObserver(() =>
{
const invokations: [Element | ShadowRoot, boolean][] = [];
for (let i = this.awaitingConnection.length; i-- > 0;)
{
const tuple = this.awaitingConnection[i];
if (!tuple[0].isConnected)
continue;
this.awaitingConnection.splice(i, 1);
invokations.push(tuple);
}
// Run the callbacks in a separate pass, to deal with the fact that
// there could be multiple awaiters watching the same element,
// but also to handle the fact the callback functions could modify
// the awaiting list.
for (const [element, defer] of invokations)
{
const event = new Event("connected", {
bubbles: true,
cancelable: true,
});
if (defer)
setTimeout(() => element.dispatchEvent(event), 1);
else
element.dispatchEvent(event);
}
}).observe(this.doc.body, { childList: true, subtree: true });
}
private hasInstalledRootObserver = false;
private readonly awaitingConnection: [Element | ShadowRoot, boolean][] = [];
//# Style Related
/**
* Creates an HTML <style> element with the specified attributes,
* and with the specified CSS rules embedded.
*/
style(attributes: Raw.ElementAttribute, ...components: (string | Raw.Style)[]): Raw.HTMLRawStyleElement;
/**
* Creates an HTML <style> element with the specified CSS rules embedded.
*/
style(...components: (string | Raw.Style)[]): Raw.HTMLRawStyleElement;
/**
* Creates an HTML <style> element with the specified attributes,
* and with the specified raw CSS text embedded.
*/
style(attributes: Raw.ElementAttribute, ...rawCss: Text[]): Raw.HTMLRawStyleElement;
/**
* Creates an HTML <style> element that contains the specified raw CSS text embedded.
*/
style(...rawCss: Text[]): Raw.HTMLRawStyleElement;
style(...args: any[])
{
const element = this.doc.createElement("style") as Raw.HTMLRawStyleElement;
element.attach = (n?: Node) =>
{
const root = n ? n.getRootNode() : this.doc;
const container = root instanceof Document ? root.head : root;
container.appendChild(element);
return element;
};
if (args.length === 0)
return element;
if (typeof args[0] !== "string")
this.get(element)(args.shift());
if (args.every(a => Raw.is.text(a)))
{
element.append(...args);
return element;
}
const cssText: string[] = [];
// Creates a fake CSS rule, whose only purpose is to capture the calls
// to setProperty(), and forward the string contents to the cssText array,
// so that a string rule can be composed.
const fakeRule: Raw.ICSSStyleRuleLike = {
style: {
setProperty(name, value, important)
{
cssText.push(name + ": " + value + (important ? " !" + important : "") + ";");
}
}
};
for (const group of this.createCssRuleGroups(args))
{
cssText.push(group.selector, "{");
for (const stylesObject of group.styles)
for (let [n, v] of Object.entries(stylesObject))
if (typeof v === "string" || (typeof v === "number" && v === v))
this.setProperty(fakeRule, n, v, group.selector);
cssText.push("}");
}
element.append(new Text(cssText.join("")));
return element;
}
/**
* Creates a series of CSS rules internally, and returns a class that
* can be applied to HTML elements in order to apply the rules to
* them.
*/
css(...components: Raw.CssParam[])
{
const styleElement = this.getScopedStyleElement(this.doc);
const cssJsonText = JSON.stringify(components);
components = JSON.parse(cssJsonText);
const cssHashClass = Raw.GeneratedClassPrefix.value + this.hash(cssJsonText);
this.applyCssToScope(styleElement, cssHashClass, components);
return cssHashClass;
}
/**
* Copies the rules that are connected to the specified CSS class
* (which is expected to be a hash of CSS rules) so that they are
* visible within the specified ShadowRoot.
*/
private toShadow(shadow: ShadowRoot, cssHashClass: string)
{
const styleElement = this.getScopedStyleElement(shadow);
const cssParams = Raw.ruleData.get(styleElement)?.get(cssHashClass);
if (cssParams)
this.applyCssToScope(styleElement, cssHashClass, cssParams);
}
/** */
private applyCssToScope(
styleElement: HTMLStyleElement,
cssHashClass: string,
components: Raw.CssParam[])
{
// Don't create another CSS rule if there is already one
// that exists within the provided <style> element with
// the provided rule hash.
if (Raw.ruleData.get(styleElement)?.get(cssHashClass))
return;
const sheet = styleElement.sheet!;
const groups = this.createCssRuleGroups(components);
for (const group of groups)
{
const selectorParts = group.selector.split("&");
let selector = group.selector;
if (selector.startsWith("*"))
{
selector = "." + cssHashClass + " " + selector;
}
else if (selector !== ":root")
{
[selector] = this.trimImportant(
selectorParts.length === 1 ?
"." + cssHashClass + group.selector :
selectorParts.join("." + cssHashClass));
}
const idx = sheet.insertRule(selector + "{}");
const cssRule = sheet.cssRules[idx] as CSSStyleRule;
for (const stylesObject of group.styles)
for (let [n, v] of Object.entries(stylesObject))
if (typeof v === "string" || (typeof v === "number" && v === v))
this.setProperty(cssRule, n, v, group.selector);
}
let hashSet = Raw.ruleData.get(styleElement);
if (hashSet)
hashSet.set(cssHashClass, components);
else
Raw.ruleData.set(styleElement, hashSet = new Map([[cssHashClass, components]]));
}
/**
* Stores a WeakMap of Sets of the hashes of the contents of each CSS rule
* that has been applied to a given generated <style> element.
*/
private static readonly ruleData = new WeakMap<HTMLStyleElement, Map<string, Raw.CssParam[]>>();
/** */
private createCssRuleGroups(components: readonly (string | Raw.Style)[])
{
const groups: { selector: string, styles: Raw.Style[] }[] = [{ selector: "", styles: [] }];
for (let i = -1; ++i < components.length;)
{
const cur = components[i];
const last = i > 0 && components[i - 1];
if (typeof cur === "string" && typeof last === "object")
groups.push({ selector: "", styles: [] });
const group = groups[groups.length - 1];
if (typeof cur === "string")
group.selector += cur;
else
group.styles.push(cur);
}
return groups;
}
/** */
private setProperty(
styleable: Raw.ICSSStyleRuleLike,
property: string,
value: string | number | (string | number)[],
selectorOfContainingRule = "")
{
if (typeof value === "number")
value ||= 0;
const [, selectorImportant] = this.trimImportant(selectorOfContainingRule);
const p = this.toCssDashCase(property);
if (!Array.isArray(value))
{
const [v, valueImportant] = this.trimImportant(String(value));
styleable.style.setProperty(p, v, selectorImportant || valueImportant);
}
else for (const item of value)
{
const [v, valueImportant] = this.trimImportant(String(item));
styleable.style.setProperty(p, v, selectorImportant || valueImportant);
}
}
/** */
private toCssDashCase(p: string)
{
p = p.replace(/[A-Z]/g, char => "-" + char.toLowerCase());
if (p.slice(0, 6) === "webkit" || p.slice(0, 3) === "moz" || p.slice(0, 2) === "ms")
p = "-" + p;
return p;
}
/** */
private trimImportant(str: string): [string, string | undefined]
{
if (str.slice(-1) === "!")
str = str.slice(0, -1);
else if (str.slice(-10) === "!important")
str = str.slice(0, -10);
else return [str, undefined];
return [str, "important"];
}
/**
* Returns the CSSStyleSheet that stores the CSS rules that should
* target the specified element. If the element is within a shadow root,
* the sheet that is returned is the one that is contained within this
* shadow root.
*/
private getScopedStyleElement(applyTarget: ParentNode)
{
let container: ParentNode = (() =>
{
if (Raw.is.shadow(applyTarget))
return applyTarget;
const root = applyTarget.getRootNode();
return root instanceof Document ?
root.head :
root as ParentNode;
})();
const cls = "raw-style-sheet";
const children = Array.from(container.children);
const existing = children.find(e => e.classList.contains(cls));
if (existing instanceof HTMLStyleElement)
return existing;
const styleElement = this.doc.createElement("style") as HTMLStyleElement;
styleElement.className = cls;
container.append(styleElement);
return styleElement;
}
/**
* Hash calculation function adapted from:
* https://stackoverflow.com/a/52171480/133737
*/
private hash(value: { toString(): string; }, seed = 0)
{
const val = value.toString();
let h1 = 0xDEADBEEF ^ seed;
let h2 = 0X41C6CE57 ^ seed;
for (let i = 0; i < val.length; i++)
{
let ch = val.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
}
}
//# Element Related
declare namespace Raw
{
/**
* Fake node class, which is compatible with the actual Node interface,
* but done with minimal properties in order to not negatively affect
* the quality of the autocompletion experience.
*/
export interface INodeLike
{
/** */
readonly nodeType: number;
/** */
readonly nodeName: string;
/** */
readonly nodeValue: string | null;
}
/**
* A class that describes the minimal set of members that need to
* be implemented on HTML elements in order to create a custom
* raw.js compatible IHTMLElementLike.
*/
export interface IHTMLElementLike extends INodeLike
{
/** Minimal append method. */
append(node: string | INodeLike): void;
/** Minimal classList object. */
readonly classList: {
add(className: string): void;
toString(): string;
};
}