-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdom_shim.mjs
1400 lines (1120 loc) · 41.9 KB
/
dom_shim.mjs
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 l from './lang.mjs'
import * as o from './obj.mjs'
import * as dr from './dom_reg.mjs'
import * as p from './prax.mjs'
import * as u from './url.mjs'
import * as c from './coll.mjs'
/* Vars */
export const refKey = Symbol.for(`ref`)
export const dataKey = Symbol.for(`data`)
export const nameKey = Symbol.for(`name`)
export const valueKey = Symbol.for(`value`)
export const styleKey = Symbol.for(`style`)
export const doctypeKey = Symbol.for(`doctype`)
export const datasetKey = Symbol.for(`dataset`)
export const publicIdKey = Symbol.for(`publicId`)
export const systemIdKey = Symbol.for(`systemId`)
export const classListKey = Symbol.for(`classList`)
export const localNameKey = Symbol.for(`localName`)
export const attributesKey = Symbol.for(`attributes`)
export const parentNodeKey = Symbol.for(`parentNode`)
export const childNodesKey = Symbol.for(`childNodes`)
export const namespaceURIKey = Symbol.for(`namespaceURI`)
export const ownerDocumentKey = Symbol.for(`ownerDocument`)
export const implementationKey = Symbol.for(`implementation`)
export const documentElementKey = Symbol.for(`documentElement`)
/* Interfaces */
/*
TODO fully consolidate these with `dom.mjs`.
(We're trying to avoid unnecessary imports.)
*/
export function isChildNode(val) {return l.isObj(val) && `parentNode` in val}
export function reqChildNode(val) {return l.req(val, isChildNode)}
export function optChildNode(val) {return l.opt(val, isChildNode)}
export function isParentNode(val) {return l.isObj(val) && `childNodes` in val}
export function reqParentNode(val) {return l.req(val, isParentNode)}
export function optParentNode(val) {return l.opt(val, isParentNode)}
export function isElement(val) {return l.isObj(val) && val.nodeType === Node.ELEMENT_NODE}
export function reqElement(val) {return l.req(val, isElement)}
export function optElement(val) {return l.opt(val, isElement)}
export function isAttr(val) {return l.isObj(val) && val.nodeType === Node.ATTRIBUTE_NODE}
export function reqAttr(val) {return l.req(val, isAttr)}
export function optAttr(val) {return l.opt(val, isAttr)}
export function isText(val) {return l.isObj(val) && val.nodeType === Node.TEXT_NODE}
export function reqText(val) {return l.req(val, isText)}
export function optText(val) {return l.opt(val, isText)}
export function isComment(val) {return l.isObj(val) && val.nodeType === Node.COMMENT_NODE}
export function reqComment(val) {return l.req(val, isComment)}
export function optComment(val) {return l.opt(val, isComment)}
export function isDocument(val) {return l.isObj(val) && val.nodeType === Node.DOCUMENT_NODE}
export function reqDocument(val) {return l.req(val, isDocument)}
export function optDocument(val) {return l.opt(val, isDocument)}
export function isDocumentType(val) {return l.isObj(val) && val.nodeType === Node.DOCUMENT_TYPE_NODE}
export function reqDocumentType(val) {return l.req(val, isDocumentType)}
export function optDocumentType(val) {return l.opt(val, isDocumentType)}
export function isFragment(val) {return l.isObj(val) && val.nodeType === Node.DOCUMENT_FRAGMENT_NODE}
export function reqFragment(val) {return l.req(val, isFragment)}
export function optFragment(val) {return l.opt(val, isFragment)}
export function isDomImpl(val) {return l.hasMeth(val, `createDocument`)}
export function reqDomImpl(val) {return l.req(val, isDomImpl)}
export function optDomImpl(val) {return l.opt(val, isDomImpl)}
/* Standard classes */
export class Node extends l.Emp {
/* Standard behaviors. */
static get ELEMENT_NODE() {return 1}
static get ATTRIBUTE_NODE() {return 2}
static get TEXT_NODE() {return 3}
static get CDATA_SECTION_NODE() {return 4}
static get ENTITY_REFERENCE_NODE() {return 5}
static get ENTITY_NODE() {return 6}
static get PROCESSING_INSTRUCTION_NODE() {return 7}
static get COMMENT_NODE() {return 8}
static get DOCUMENT_NODE() {return 9}
static get DOCUMENT_TYPE_NODE() {return 10}
static get DOCUMENT_FRAGMENT_NODE() {return 11}
static get NOTATION_NODE() {return 12}
static get DOCUMENT_POSITION_DISCONNECTED() {return 1}
static get DOCUMENT_POSITION_PRECEDING() {return 2}
static get DOCUMENT_POSITION_FOLLOWING() {return 4}
static get DOCUMENT_POSITION_CONTAINS() {return 8}
static get DOCUMENT_POSITION_CONTAINED_BY() {return 16}
static get DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC() {return 32}
get [Symbol.toStringTag]() {return this.constructor.name}
get isConnected() {return isDocument(this.getRootNode())}
get parentElement() {return norm(l.only(this.parentNode, isElement))}
get childNodes() {return this[childNodesKey] ||= this.NodeList()}
set childNodes(val) {this[childNodesKey] = l.reqArr(val)}
get firstChild() {return norm(head(this[childNodesKey]))}
get lastChild() {return norm(last(this[childNodesKey]))}
get previousSibling() {return this.siblingAt(-1)}
get nextSibling() {return this.siblingAt(1)}
get ownerDocument() {return norm(this[ownerDocumentKey])}
set ownerDocument(val) {this[ownerDocumentKey] = optDocument(val)}
get nodeName() {return null}
get nodeType() {return null}
get nodeValue() {return null}
get parentNode() {return norm(this[parentNodeKey])}
set parentNode(val) {this[parentNodeKey] = val}
getRootNode() {
const val = this.parentNode
if (!val) return this
if (`getRootNode` in val) return val.getRootNode()
return val
}
hasChildNodes() {return !!this[childNodesKey]?.length}
contains(val) {return !!this[childNodesKey]?.includes(val)}
/*
Intentional deviation: we append fragments like they were normal nodes,
instead of stealing children. This is far simpler, more efficient,
and serves our purposes well enough. When traversing children for
serialization, we treat fragments as arrays of children, which we
also traverse recursively.
*/
appendChild(val) {
remove(val)
this.childNodes.push(val)
adopt(val, this)
return val
}
/*
Intentional deviation: attempting to remove a missing child doesn't throw,
but simply returns the missing node.
*/
removeChild(val) {
const nodes = this.childNodes
const ind = indexOf(nodes, val)
if (!(ind >= 0)) return val
nodes.splice(ind, 1)
adopt(val, null)
return val
}
replaceChild(next, prev) {
if (l.is(next, prev)) return prev
// May shift our children, must run first.
remove(next)
const nodes = this.childNodes
const ind = indexOf(nodes, prev)
if (!(ind >= 0)) {
throw Error(`unable to replace missing child ${l.show(prev)}`)
}
nodes[ind] = null
adopt(prev, null)
nodes[ind] = next
adopt(next, this)
return prev
}
insertBefore(next, prev) {
if (l.isNil(prev)) return this.appendChild(next)
const nodes = this.childNodes
const ind = indexOf(nodes, prev)
if (!(ind >= 0)) {
throw Error(`unable to insert before missing child ${l.show(prev)}`)
}
remove(next)
nodes.splice(ind, 0, next)
adopt(next, this)
return next
}
append(...val) {for (val of val) this.appendChild(val)}
prepend(...src) {
for (const val of src) remove(val)
// Potential trap. Has bad combinatorial complexity for large inputs.
this.childNodes.unshift(...src)
for (const val of src) adopt(val, this)
}
remove() {
const par = this.parentNode
if (l.isObj(par) && `removeChild` in par) par.removeChild(this)
if (this[parentNodeKey]) this.parentNode = null
}
/* Non-standard extensions. */
/*
TODO: use a structure with good combinatorial complexity for all relevant
operations: push/pop/unshift/shift/splice. JS arrays have decent pop/push.
At small sizes, they may also outperform other structures on
shift/unshift/splice. However, at large sizes, their shift/unshift/splice
can be horrendous.
*/
NodeList() {return []}
siblingAt(shift) {
l.reqInt(shift)
const nodes = this.parentNode?.childNodes
if (!nodes) return null
const ind = indexOf(nodes, this)
return ind >= 0 ? norm(nodes[ind + shift]) : null
}
owned(doc) {return this[ownerDocumentKey] = doc, this}
}
// Non-standard intermediary class for internal use.
export class Textable extends Node {
get textContent() {return this.foldTextContent(``, this[childNodesKey])}
set textContent(val) {
val = l.renderLax(val)
const nodes = this.childNodes
nodes.length = 0
if (val) nodes.push(val)
}
// Non-standard.
foldTextContent(acc, val) {
if (l.isNil(val) || isComment(val)) return acc
if (l.isScalar(val)) return acc + l.render(val)
if (`textContent` in val) return acc + l.laxStr(val.textContent)
if (isFragment(val)) return this.foldTextContent(acc, val.childNodes)
if (p.isSeq(val)) for (val of val) acc = this.foldTextContent(acc, val)
return acc
}
}
// Non-standard intermediary class for internal use.
export class TextableElementParent extends Textable {
get children() {return this[childNodesKey]?.filter(isElement) ?? []}
get childElementCount() {return count(this[childNodesKey], isElement)}
get firstElementChild() {return norm(this[childNodesKey]?.find(isElement))}
get lastElementChild() {return norm(this[childNodesKey]?.findLast(isElement))}
}
export class DocumentFragment extends TextableElementParent {
get nodeType() {return Node.DOCUMENT_FRAGMENT_NODE}
get nodeName() {return `#document-fragment`}
}
// Non-standard intermediary class for internal use.
export class Void extends Node {
appendChild() {throw errIllegal()}
removeChild() {throw errIllegal()}
replaceChild() {throw errIllegal()}
insertBefore() {throw errIllegal()}
append() {throw errIllegal()}
}
// Non-standard intermediary class for internal use.
export class Data extends Void {
constructor(val) {super().data = val}
get data() {return l.laxStr(this[dataKey])}
set data(val) {this[dataKey] = l.renderLax(val)}
}
export class CharacterData extends Data {
get textContent() {return this.data}
set textContent(val) {this.data = val}
get nodeValue() {return this.data}
set nodeValue(val) {this.data = val}
get length() {return this.data.length}
appendChild() {throw errIllegal()}
removeChild() {throw errIllegal()}
replaceChild() {throw errIllegal()}
insertBefore() {throw errIllegal()}
append() {throw errIllegal()}
}
export class Text extends CharacterData {
get nodeType() {return Node.TEXT_NODE}
get nodeName() {return `#text`}
get outerHTML() {return escapeText(this.data)}
toJSON() {return this.outerHTML}
}
export class Comment extends CharacterData {
get nodeType() {return Node.COMMENT_NODE}
get nodeName() {return `#comment`}
get outerHTML() {return `<!--` + escapeText(this.data) + `-->`}
toJSON() {return this.outerHTML}
}
/*
Note: `.parentNode` must be `NamedNodeMap`, otherwise reading and setting the
value doesn't work. As a result, `document.createAttribute` is currently not
fully implemented because the resulting attribute is not linked to a map.
*/
export class Attr extends Node {
constructor(key) {super()[nameKey] = l.reqStr(key)}
get name() {return this[nameKey]}
get value() {return l.laxStr(this.parentNode.get(this.name))}
set value(val) {this.parentNode.set(this.name, l.render(val))}
get nodeName() {return this.name}
get nodeType() {return Node.ATTRIBUTE_NODE}
}
export class NamedNodeMap extends Map {
/* Standard behaviors. */
getNamedItem(key) {return this.has(key) ? this.Attr(key) : undefined}
setNamedItem(val) {this.set(l.reqObj(val).name, val.value)}
removeNamedItem(key) {this.delete(key)}
// Extremely inefficient. Production code should never use this.
*[Symbol.iterator]() {
for (const key of this.keys()) yield this.getNamedItem(key)
}
/* Non-standard extensions. */
get(key) {return norm(super.get(key))}
set(key, val) {return super.set(l.reqStr(key), l.render(val))}
Attr(key) {
const tar = new Attr(key)
tar.parentNode = this
return tar
}
toString() {
let out = ``
for (const [key, val] of this.entries()) {
out += this.constructor.attr(key, val)
}
return out
}
static attr(key, val) {
if (!key) return ``
return ` ` + l.reqStr(key) + `="` + escapeAttr(val) + `"`
}
}
export class Element extends TextableElementParent {
/* Standard behaviors. */
get nodeType() {return Node.ELEMENT_NODE}
/*
A `localName` can be acquired in multiple ways.
When creating an element via `document.createElement` or
`document.createElementNS`, the DOM implementation determines which class to
use, makes an instance, and assigns the given local name to the instance. One
class, such as `HTMLElement`, may be used with multiple different local
names. In a native DOM API, built-in element classes can't be instantiated
via `new`, as there is no 1-1 mapping from classes to local names.
Custom elements work differently. Any element class registered via
`customElements` acquires a local name and its own custom name.
In "autonomous" custom elements, local name and custom name are identical,
and custom name doesn't need to be serialized. In "customized built-in"
custom elements, the names are distinct, and custom name must be serialized
via the "is" attribute. Unlike built-in elements, registered custom elements
can be instantiated via `new`. Instantiating them via
`document.createElement` also works. In either case, the resulting instance
knows its local name and custom name, and can be correctly serialized.
Our `dom_reg` assigns `localName` and `customName` to each registered class, as
static properties. Our shim classes rely on these properties.
*/
get localName() {return norm(this[localNameKey] ?? this.constructor.localName)}
set localName(val) {this[localNameKey] = l.optStr(val)}
get tagName() {return norm(this.localName?.toUpperCase())}
get namespaceURI() {return norm(this[namespaceURIKey])}
set namespaceURI(val) {this[namespaceURIKey] = l.optStr(val)}
get parentNode() {return super.parentNode}
set parentNode(val) {
const con = `connectedCallback` in this
const dis = `disconnectedCallback` in this
if (!con && !dis) {
super.parentNode = val
return
}
const was = this.isConnected
super.parentNode = val
if (!was && con && this.isConnected) this.connectedCallback()
else if (was && dis && !this.isConnected) this.disconnectedCallback()
}
get attributes() {return this[attributesKey] ||= this.Attributes()}
get id() {return l.laxStr(this.getAttribute(`id`))}
set id(val) {this.setAttribute(`id`, val)}
get style() {return (this[styleKey] ||= this.Style()).pro}
set style(val) {
if (l.isNil(val)) {
this.removeAttribute(`style`)
return
}
if (l.isStr(val)) {
this.setAttribute(`style`, val)
return
}
if (l.isStruct(val)) {
this[styleKey] = val
this.removeAttribute(`style`)
return
}
this.style = l.render(val)
}
get dataset() {return (this[datasetKey] ||= this.Dataset()).pro}
get className() {return l.laxStr(this.getAttribute(`class`))}
set className(val) {this.setAttribute(`class`, val)}
get classList() {return this[classListKey] ||= this.ClassList()}
get hidden() {return this.hasAttribute(`hidden`)}
set hidden(val) {this.toggleAttribute(`hidden`, l.laxBool(val))}
// TODO: default -1 for non-interactive elements.
get tabIndex() {return this.getAttribute(`tabindex`) | 0}
set tabIndex(val) {
this.setAttribute(`tabindex`, (l.isNum(val) ? val : l.render(val)) | 0)
}
get innerHTML() {return this.foldInnerHTML(``, this[childNodesKey])}
/*
Known limitation: the resulting element has incorrect `.textContent` because
we don't parse the given HTML.
*/
set innerHTML(val) {
val = l.render(val)
const nodes = this.childNodes
nodes.length = 0
if (val) nodes.push(new p.Raw(val))
}
get outerHTML() {
if (outerHtmlDyn.has()) return this.outerHtml()
outerHtmlDyn.set(this)
try {return this.outerHtml()}
finally {outerHtmlDyn.set()}
}
hasAttribute(key) {return !!this[attributesKey]?.has(key)}
getAttribute(key) {return norm(this[attributesKey]?.get(key))}
removeAttribute(key) {
this[attributesKey]?.delete(key)
if (this.isStyleChange(key)) {
this[styleKey] = undefined
}
else if (this.isDatasetChange(key)) {
this[datasetKey]?.attrDel(key)
}
}
setAttribute(key, val) {
val = l.render(val)
this.attributes.set(key, val)
if (this.isStyleChange(key)) {
this[styleKey]?.dec()
}
else if (this.isDatasetChange(key)) {
this[datasetKey]?.attrSet(key, val)
}
}
toggleAttribute(key, force) {
if (l.optBool(force) || (l.isNil(force) && !this.hasAttribute(key))) {
this.setAttribute(key, ``)
return true
}
this.removeAttribute(key)
return false
}
/* Non-standard extensions. */
Style() {return new StylePh(this)}
Dataset() {return new DatasetPh(this)}
ClassList() {return new ClassList(this)}
Attributes() {return new NamedNodeMap()}
toJSON() {return this.outerHTML}
// See explanation on `localName` getter.
get customName() {return this.constructor.customName}
attrSet(key, val) {
if (l.isNil(val)) this.removeAttribute(key)
else this.setAttribute(key, val)
}
isStyleChange(key) {return key === `style` && styleKey in this}
isDatasetChange(key) {return key.startsWith(`data-`) && datasetKey in this}
outerHtml() {
const tag = this.tagString()
if (!tag) throw Error(`missing localName on ${l.show(this)}`)
return (
`<` + tag + this.attrPrefix() + this.attrString() + `>` +
l.laxStr(this.innerHTML) +
`</` + tag + `>`
)
}
foldInnerHTML(acc, val) {
if (l.isNil(val)) return acc
if (p.isRaw(val)) return acc + l.laxStr(val.outerHTML)
if (l.isScalar(val)) return acc + escapeText(l.render(val))
if (isFragment(val)) return this.foldInnerHTML(acc, val.childNodes)
if (p.isSeq(val)) for (val of val) acc = this.foldInnerHTML(acc, val)
return acc
}
isVoid() {return p.VOID.has(this.localName)}
tagString() {return l.laxStr(this.localName)}
attrString() {return l.laxStr(this[attributesKey]?.toString())}
attrPrefix() {return this.attrIs() + this.attrXmlns()}
attrIs() {
const is = this.customName
if (!is || is === this.localName || this[attributesKey]?.has(`is`)) return ``
return NamedNodeMap.attr(`is`, is)
}
attrXmlns() {
if (this[attributesKey]?.has(`xmlns`)) return ``
const chiNs = this[namespaceURIKey]
if (!chiNs) return ``
const doc = this[ownerDocumentKey]
if (isHtmlDoc(doc)) return ``
const parNs = l.get(this.parentNode, `namespaceURI`)
if (parNs && parNs !== chiNs) return NamedNodeMap.attr(`xmlns`, chiNs)
if (outerHtmlDyn.get() !== this) return ``
return NamedNodeMap.attr(`xmlns`, chiNs)
}
}
export class HTMLElement extends Element {
get namespaceURI() {return super.namespaceURI || p.nsHtml}
set namespaceURI(val) {super.namespaceURI = val}
outerHtml() {
if (this.isVoid()) {
if (this.innerHTML) {
throw Error(`unexpected innerHTML in void element ${this.localName}`)
}
return `<` + this.tagString() + this.attrPrefix() + this.attrString() + ` />`
}
return super.outerHtml()
}
}
export class HTMLMetaElement extends HTMLElement {
get httpEquiv() {return this.getAttribute(`http-equiv`)}
set httpEquiv(val) {this.attrSet(`http-equiv`, val)}
}
export class HTMLAnchorElement extends HTMLElement {
get protocol() {return u.url(this.href).protocol}
get origin() {return u.url(this.href).origin}
get username() {return u.url(this.href).username}
get password() {return u.url(this.href).password}
get hostname() {return u.url(this.href).hostname}
get host() {return u.url(this.href).host}
get port() {return u.url(this.href).port}
get pathname() {return u.url(this.href).pathname}
get search() {return u.url(this.href).search}
get hash() {return u.url(this.href).hash}
get href() {return l.laxStr(this.getAttribute(`href`))}
set href(val) {this.setAttribute(`href`, val)}
get target() {return l.laxStr(this.getAttribute(`target`))}
set target(val) {this.setAttribute(`target`, val)}
get rel() {return l.laxStr(this.getAttribute(`rel`))}
set rel(val) {this.setAttribute(`rel`, val)}
}
export class HTMLLabelElement extends HTMLElement {
get htmlFor() {return l.laxStr(this.getAttribute(`for`))}
set htmlFor(val) {this.setAttribute(`for`, val)}
}
class ToggleElement extends HTMLElement {
get disabled() {return this.hasAttribute(`disabled`)}
set disabled(val) {this.toggleAttribute(`disabled`, l.laxBool(val))}
}
export class HTMLButtonElement extends ToggleElement {}
class TextInputElement extends ToggleElement {
get name() {return l.laxStr(this.getAttribute(`name`))}
set name(val) {this.setAttribute(`name`, val)}
get type() {return l.laxStr(this.getAttribute(`type`))}
set type(val) {this.setAttribute(`type`, val)}
get value() {return l.laxStr(this.getAttribute(`value`))}
set value(val) {this.setAttribute(`value`, val)}
get required() {return this.hasAttribute(`required`)}
set required(val) {this.toggleAttribute(`required`, l.laxBool(val))}
get checked() {return this.hasAttribute(`checked`)}
set checked(val) {this.toggleAttribute(`checked`, l.laxBool(val))}
get readOnly() {return this.hasAttribute(`readonly`)}
set readOnly(val) {this.toggleAttribute(`readonly`, l.laxBool(val))}
get placeholder() {return l.laxStr(this.getAttribute(`placeholder`))}
set placeholder(val) {this.setAttribute(`placeholder`, val)}
}
export class HTMLInputElement extends TextInputElement {
// Match bizarre standard behavior.
get value() {
if (this.type === `checkbox` && !this.hasAttribute(`value`)) return `on`
return super.value
}
set value(val) {this.setAttribute(`value`, val)}
get multiple() {return this.hasAttribute(`multiple`)}
set multiple(val) {this.toggleAttribute(`multiple`, l.laxBool(val))}
}
export class HTMLTextAreaElement extends TextInputElement {}
export class HTMLObjectElement extends HTMLElement {}
export class HTMLOutputElement extends HTMLElement {}
/*
Doesn't support the `.value` getter/setter because the correct way to render
pre-selection is via `HTMLOptionElement..selected`.
*/
export class HTMLSelectElement extends HTMLElement {
get name() {return l.laxStr(this.getAttribute(`name`))}
set name(val) {this.setAttribute(`name`, val)}
get multiple() {return this.hasAttribute(`multiple`)}
set multiple(val) {this.toggleAttribute(`multiple`, l.laxBool(val))}
}
export class HTMLOptionElement extends HTMLElement {
get value() {return l.laxStr(this.getAttribute(`value`))}
set value(val) {this.setAttribute(`value`, val)}
get selected() {return this.hasAttribute(`selected`)}
set selected(val) {this.toggleAttribute(`selected`, l.laxBool(val))}
}
export class HTMLFieldSetElement extends HTMLElement {}
export class HTMLFormElement extends HTMLElement {
get elements() {return new HTMLFormControlsCollection(this)}
}
export class HTMLTableElement extends HTMLElement {
get caption() {return this.childNodes?.find(isCaption)}
get tHead() {return this.childNodes?.find(isTableHead)}
get tBodies() {return this.childNodes?.filter(isTableBody) ?? []}
get tFoot() {return this.childNodes?.find(isTableFoot)}
// Incomplete. Known defects: not live; only body rows.
get rows() {return this.childNodes?.find(isTableBody)?.childNodes?.filter(isTableRow) ?? []}
}
export class HTMLScriptElement extends HTMLElement {
/*
Difference from all other elements: inner text is not escaped. We have to
duplicate the special case for `isRaw` because it has precedence over scalars.
*/
foldInnerHTML(acc, val) {
if (isText(val)) return acc + l.laxStr(val.textContent)
if (p.isRaw(val)) return acc + l.laxStr(val.outerHTML)
if (l.isScalar(val)) return acc + l.render(val)
return super.foldInnerHTML(acc, val)
}
}
/*
Has various deviations from the standard. For example, in a standard
`SVGElement`, the property `.className` is an object rather than a string.
Our implementation doesn't support any of that for now.
*/
export class SVGElement extends Element {
get namespaceURI() {return super.namespaceURI || p.nsSvg}
set namespaceURI(val) {super.namespaceURI = val}
}
export class DocumentType extends Node {
constructor(name, pub, sys) {
super()
this.name = l.reqStr(name)
this.publicId = pub
this.systemId = sys
}
get nodeType() {return Node.DOCUMENT_TYPE_NODE}
get nodeName() {return this.name}
get name() {return this[nameKey]}
set name(val) {this[nameKey] = l.optStr(val)}
get publicId() {return l.laxStr(this[publicIdKey])}
set publicId(val) {this[publicIdKey] = l.optStr(val)}
get systemId() {return l.laxStr(this[systemIdKey])}
set systemId(val) {this[systemIdKey] = l.optStr(val)}
// Non-standard.
get outerHTML() {return `<!doctype ${l.reqStr(this.name)}>`}
}
export class Document extends Node {
/* Standard behaviors. */
get nodeType() {return Node.DOCUMENT_NODE}
get nodeName() {return `#document`}
get implementation() {return this[implementationKey]}
set implementation(val) {this[implementationKey] = optDomImpl(val)}
get childNodes() {return [this.doctype, this.documentElement].filter(l.id)}
get doctype() {return norm(this[doctypeKey])}
set doctype(val) {
if ((this[doctypeKey] = optDocumentType(val))) {
remove(val)
adopt(val, this)
val.ownerDocument = this
}
}
get documentElement() {return norm(this[documentElementKey])}
set documentElement(val) {
if ((this[documentElementKey] = optElement(val))) {
remove(val)
adopt(val, this)
val.ownerDocument = this
}
}
get head() {return norm(this.documentElement?.childNodes?.find(isHead))}
set head(val) {this.documentElement?.replaceChild(val, this.head)}
get body() {return norm(this.documentElement?.childNodes?.find(isBody))}
set body(val) {this.documentElement?.replaceChild(val, this.body)}
get title() {return l.laxStr(this.titleNode()?.textContent)}
set title(val) {
const node = this.titleNode()
if (node) node.textContent = l.render(val)
}
createAttribute(key) {return new Attr(key).owned(this)}
createAttributeNS(ns, key) {
l.reqStr(ns)
const tar = this.createAttribute(key)
if (ns !== this.namespaceURI) tar.namespaceURI = ns
return tar
}
createDocumentFragment() {return new DocumentFragment().owned(this)}
createTextNode(val) {return new Text(val).owned(this)}
createComment(val) {return new Comment(val).owned(this)}
createElement(localName, opt) {
l.reqStr(localName)
const is = l.optStr(l.get(opt, `is`))
const cls = this.customElements.get(is || localName) || this.baseClassByTag(localName)
const tar = new cls()
tar.owned(this)
tar.localName = localName
if (is) tar.setAttribute(`is`, is)
return tar
}
createElementNS(ns, localName) {
l.reqStr(ns)
l.reqStr(localName)
const cls = this.baseClassByTag(localName)
if (!cls) throw Error(`unable to find class for ${l.show(localName)}`)
const tar = new cls()
tar.owned(this)
tar.localName = localName
tar.namespaceURI = ns
return tar
}
/* Non-standard extensions. */
get customElements() {return this.implementation.customElements}
titleNode() {return norm(this.head?.childNodes?.find(isTitle))}
baseClassByTag() {return Element}
}
export class HTMLDocument extends Document {
createElement(localName, opt) {
const tar = super.createElement(localName, opt)
tar.namespaceURI = p.nsHtml
return tar
}
createElementNS(ns, localName, opt) {
if (ns === p.nsHtml) return this.createElement(localName, opt)
return super.createElementNS(ns, localName, opt)
}
baseClassByTag(tag) {
return global[l.reqStr(dr.TagToCls.main.get(tag) || `HTMLElement`)]
}
}
export class DOMImplementation extends l.Emp {
/* Standard behaviors. */
createDocumentType(...val) {return new DocumentType(...val)}
// Browser implementations appear to ignore the namespace.
createDocument(_ns, name, typ) {
const doc = new this.Document()
doc.implementation = this
if (optDocumentType(typ)) doc.doctype = typ
if (l.laxStr(name)) doc.documentElement = doc.createElement(name)
return doc
}
createHTMLDocument(title) {
const doc = new this.HTMLDocument()
doc.implementation = this
doc.doctype = this.createDocumentType(`html`, ``, ``)
doc.documentElement = doc.createElement(`html`)
doc.documentElement.appendChild(doc.createElement(`head`))
doc.documentElement.appendChild(doc.createElement(`body`))
if (l.isSome(title)) doc.title = title
return doc
}
/* Non-standard extensions. */
get Document() {return Document}
get HTMLDocument() {return HTMLDocument}
get customElements() {return dr.CustomElementRegistry.main}
}
/* Non-standard classes */
export class DictPh extends l.Emp {
constructor(tar) {
super()
this.tar = l.reqInst(tar, Element)
this.buf = l.Emp()
this.pro = new Proxy(this.buf, this)
this.dec()
}
dec() {}
}
// Analogous to `CSSStyleDeclaration`.
export class StylePh extends DictPh {
/* Proxy handler traps. */
get(buf, key) {
if (!l.isStr(key) || key === `constructor`) return undefined
if (key === `cssText`) return l.laxStr(this.attrGet())
return l.laxStr(buf[this.styleToCss(key)])
}
set(buf, key, val) {
if (key === `cssText`) {
this.attrSet(val)
this.clear()
}
else {
buf[this.styleToCss(key)] = l.render(val)
this.enc()
}
return true
}
deleteProperty(buf, key) {
if (!l.isStr(key)) return true
key = this.styleToCss(key)
if (key in buf) delete buf[key], this.enc()
return true
}
/* Non-traps. */
dec() {this.decode(this.attrGet())}
enc() {this.attrSet(this.encode())}
clear() {for (const key of l.structKeys(this.buf)) delete this.buf[key]}
attrGet() {return this.tar[attributesKey]?.get(`style`)}
attrSet(val) {
if (!val && !this.tar.attributes.has(`style`)) return
this.tar.attributes.set(`style`, val)
}
decode(src) {
if (!src) return
for (src of split(src.trim(), /;\s*/g)) {
const ind = src.indexOf(`:`)
if (!(ind >= 0)) continue
const key = src.slice(0, ind)
if (!key) continue
const val = src.slice(ind + 1).trimStart()
if (val) this.buf[key] = val
}
}
encode() {
const {buf} = this
let out = ``
for (const key of l.structKeys(buf)) out += this.encodePair(key, buf[key])
return out.trim()
}
encodePair(key, val) {
if (!key || !val) return ``
return ` ` + l.reqStr(key) + `: ` + l.reqStr(val) + `;`
}
styleToCss(key) {return styleToCssCache.goc(key)}
}
class DatasetPh extends DictPh {
/* Proxy handler traps. */
set(buf, key, val) {
l.reqStr(key)
val = l.render(val)
buf[key] = val
this.tar.attributes.set(this.camelToData(key), val)
return true
}
deleteProperty(buf, key) {
l.reqStr(key)
delete buf[key]
this.tar.attributes.delete(this.camelToData(key))