forked from stenciljs/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelement.ts
More file actions
805 lines (710 loc) · 19.8 KB
/
element.ts
File metadata and controls
805 lines (710 loc) · 19.8 KB
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
import { cloneAttributes } from './attribute';
import { NODE_TYPES } from './constants';
import { getStyleElementText, MockCSSStyleSheet, setStyleElementText } from './css-style-sheet';
import { createCustomElement } from './custom-element-registry';
import { MockDocumentFragment } from './document-fragment';
import { MockElement, MockHTMLElement, MockNode } from './node';
export function createElement(ownerDocument: any, tagName: string): any {
if (typeof tagName !== 'string' || tagName === '' || !/^[a-z0-9-_:]+$/i.test(tagName)) {
throw new Error(`The tag name provided (${tagName}) is not a valid name.`);
}
tagName = tagName.toLowerCase();
switch (tagName) {
case 'a':
return new MockAnchorElement(ownerDocument);
case 'base':
return new MockBaseElement(ownerDocument);
case 'button':
return new MockButtonElement(ownerDocument);
case 'canvas':
return new MockCanvasElement(ownerDocument);
case 'form':
return new MockFormElement(ownerDocument);
case 'img':
return new MockImageElement(ownerDocument);
case 'input':
return new MockInputElement(ownerDocument);
case 'label':
return new MockLabelElement(ownerDocument);
case 'link':
return new MockLinkElement(ownerDocument);
case 'meta':
return new MockMetaElement(ownerDocument);
case 'script':
return new MockScriptElement(ownerDocument);
case 'slot':
return new MockSlotElement(ownerDocument);
case 'slot-fb':
return new MockHTMLElement(ownerDocument, tagName);
case 'style':
return new MockStyleElement(ownerDocument);
case 'template':
return new MockTemplateElement(ownerDocument);
case 'title':
return new MockTitleElement(ownerDocument);
case 'ul':
return new MockUListElement(ownerDocument);
}
if (ownerDocument != null && tagName.includes('-')) {
const win = ownerDocument.defaultView;
if (win != null && win.customElements != null) {
return createCustomElement(win.customElements, ownerDocument, tagName);
}
}
return new MockHTMLElement(ownerDocument, tagName);
}
export function createElementNS(ownerDocument: any, namespaceURI: string, tagName: string) {
if (namespaceURI === 'http://www.w3.org/1999/xhtml') {
return createElement(ownerDocument, tagName);
} else if (namespaceURI === 'http://www.w3.org/2000/svg') {
switch (tagName.toLowerCase()) {
case 'text':
case 'tspan':
case 'tref':
case 'altglyph':
case 'textpath':
return new MockSVGTextContentElement(ownerDocument, tagName);
case 'circle':
case 'ellipse':
case 'image':
case 'line':
case 'path':
case 'polygon':
case 'polyline':
case 'rect':
case 'use':
return new MockSVGGraphicsElement(ownerDocument, tagName);
case 'svg':
return new MockSVGSVGElement(ownerDocument, tagName);
default:
return new MockSVGElement(ownerDocument, tagName);
}
} else {
return new MockElement(ownerDocument, tagName, namespaceURI);
}
}
export class MockAnchorElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'a');
}
get href() {
return fullUrl(this, 'href');
}
set href(value: string) {
this.setAttribute('href', value);
}
get pathname() {
if (!this.href) {
return '';
}
return new URL(this.href).pathname;
}
}
export class MockButtonElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'button');
}
get labels() {
return getLabelsForElement(this);
}
}
patchPropAttributes(
MockButtonElement.prototype,
{
type: String,
},
{
type: 'submit',
},
);
Object.defineProperty(MockButtonElement.prototype, 'form', {
get(this: MockElement) {
return this.hasAttribute('form') ? this.getAttribute('form') : null;
},
});
export class MockImageElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'img');
}
override get draggable() {
return this.getAttributeNS(null, 'draggable') !== 'false';
}
override set draggable(value: boolean) {
this.setAttributeNS(null, 'draggable', value);
}
get src() {
return fullUrl(this, 'src');
}
set src(value: string) {
this.setAttribute('src', value);
}
}
patchPropAttributes(MockImageElement.prototype, {
height: Number,
width: Number,
});
export class MockInputElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'input');
}
get list() {
const listId = this.getAttribute('list');
if (listId) {
return (this.ownerDocument as Document).getElementById(listId);
}
return null;
}
get labels() {
return getLabelsForElement(this);
}
}
patchPropAttributes(
MockInputElement.prototype,
{
accept: String,
autocomplete: String,
autofocus: Boolean,
capture: String,
checked: Boolean,
disabled: Boolean,
form: String,
formaction: String,
formenctype: String,
formmethod: String,
formnovalidate: String,
formtarget: String,
height: Number,
inputmode: String,
max: String,
maxLength: Number,
min: String,
minLength: Number,
multiple: Boolean,
name: String,
pattern: String,
placeholder: String,
required: Boolean,
readOnly: Boolean,
size: Number,
spellCheck: Boolean,
src: String,
step: String,
type: String,
value: String,
width: Number,
},
{
type: 'text',
},
);
export class MockFormElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'form');
}
}
patchPropAttributes(MockFormElement.prototype, {
name: String,
});
export class MockLabelElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'label');
}
get htmlFor() {
return this.getAttributeNS(null, 'for') || '';
}
set htmlFor(value: string) {
this.setAttributeNS(null, 'for', value);
}
get control(): MockHTMLElement | null {
const forAttr = this.htmlFor;
if (forAttr) {
// Label references an element by ID via the "for" attribute
return this.ownerDocument?.getElementById(forAttr) ?? null;
}
// If no "for" attribute, look for the first labelable descendant
const labelableSelector = 'button, input:not([type="hidden"]), meter, output, progress, select, textarea';
return this.querySelector(labelableSelector);
}
}
export class MockLinkElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'link');
}
get href() {
return fullUrl(this, 'href');
}
set href(value: string) {
this.setAttribute('href', value);
}
}
patchPropAttributes(MockLinkElement.prototype, {
crossorigin: String,
media: String,
rel: String,
type: String,
});
export class MockMetaElement extends MockHTMLElement {
content: string;
constructor(ownerDocument: any) {
super(ownerDocument, 'meta');
}
}
patchPropAttributes(MockMetaElement.prototype, {
charset: String,
content: String,
name: String,
});
export class MockScriptElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'script');
}
get src() {
return fullUrl(this, 'src');
}
set src(value: string) {
this.setAttribute('src', value);
}
}
patchPropAttributes(MockScriptElement.prototype, {
type: String,
});
export class MockDOMMatrix {
static fromMatrix() {
return new MockDOMMatrix();
}
a: number = 1;
b: number = 0;
c: number = 0;
d: number = 1;
e: number = 0;
f: number = 0;
m11: number = 1;
m12: number = 0;
m13: number = 0;
m14: number = 0;
m21: number = 0;
m22: number = 1;
m23: number = 0;
m24: number = 0;
m31: number = 0;
m32: number = 0;
m33: number = 1;
m34: number = 0;
m41: number = 0;
m42: number = 0;
m43: number = 0;
m44: number = 1;
is2D: boolean = true;
isIdentity: boolean = true;
inverse() {
return new MockDOMMatrix();
}
flipX() {
return new MockDOMMatrix();
}
flipY() {
return new MockDOMMatrix();
}
multiply() {
return new MockDOMMatrix();
}
rotate() {
return new MockDOMMatrix();
}
rotateAxisAngle() {
return new MockDOMMatrix();
}
rotateFromVector() {
return new MockDOMMatrix();
}
scale() {
return new MockDOMMatrix();
}
scaleNonUniform() {
return new MockDOMMatrix();
}
skewX() {
return new MockDOMMatrix();
}
skewY() {
return new MockDOMMatrix();
}
toJSON() {}
toString() {}
transformPoint() {
return new MockDOMPoint();
}
translate() {
return new MockDOMMatrix();
}
}
export class MockDOMPoint {
w: number = 1;
x: number = 0;
y: number = 0;
z: number = 0;
toJSON() {}
matrixTransform() {
return new MockDOMMatrix();
}
}
export class MockSVGRect {
height: number = 10;
width: number = 10;
x: number = 0;
y: number = 0;
}
export class MockStyleElement extends MockHTMLElement {
sheet: MockCSSStyleSheet;
constructor(ownerDocument: any) {
super(ownerDocument, 'style');
this.sheet = new MockCSSStyleSheet(this);
}
override get innerHTML() {
return getStyleElementText(this);
}
override set innerHTML(value: string) {
setStyleElementText(this, value);
}
override get innerText() {
return getStyleElementText(this);
}
override set innerText(value: string) {
setStyleElementText(this, value);
}
override get textContent() {
return getStyleElementText(this);
}
override set textContent(value: string) {
setStyleElementText(this, value);
}
}
export class MockSVGElement extends MockElement {
override __namespaceURI = 'http://www.w3.org/2000/svg';
// SVGElement properties and methods
get ownerSVGElement(): SVGSVGElement {
return null;
}
get viewportElement(): SVGElement {
return null;
}
onunload() {
/**/
}
// SVGGeometryElement properties and methods
get pathLength(): number {
return 0;
}
isPointInFill(_pt: DOMPoint): boolean {
return false;
}
isPointInStroke(_pt: DOMPoint): boolean {
return false;
}
getTotalLength(): number {
return 0;
}
}
export class MockSVGGraphicsElement extends MockSVGElement {
getBBox(_options?: { clipped: boolean; fill: boolean; markers: boolean; stroke: boolean }): MockSVGRect {
return new MockSVGRect();
}
getCTM(): MockDOMMatrix {
return new MockDOMMatrix();
}
getScreenCTM(): MockDOMMatrix {
return new MockDOMMatrix();
}
}
export class MockSVGSVGElement extends MockSVGGraphicsElement {
createSVGPoint(): MockDOMPoint {
return new MockDOMPoint();
}
}
export class MockSVGTextContentElement extends MockSVGGraphicsElement {
getComputedTextLength(): number {
return 0;
}
}
export class MockBaseElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'base');
}
get href() {
return fullUrl(this, 'href');
}
set href(value: string) {
this.setAttribute('href', value);
}
}
export class MockTemplateElement extends MockHTMLElement {
content: MockDocumentFragment;
constructor(ownerDocument: any) {
super(ownerDocument, 'template');
this.content = new MockDocumentFragment(ownerDocument);
}
override get innerHTML() {
return this.content.innerHTML;
}
override set innerHTML(html: string) {
this.content.innerHTML = html;
}
override cloneNode(deep?: boolean) {
const cloned = new MockTemplateElement(null);
cloned.attributes = cloneAttributes(this.attributes);
const styleCssText = this.getAttribute('style');
if (styleCssText != null && styleCssText.length > 0) {
cloned.setAttribute('style', styleCssText);
}
cloned.content = this.content.cloneNode(deep);
if (deep) {
for (let i = 0, ii = this.childNodes.length; i < ii; i++) {
const clonedChildNode = this.childNodes[i].cloneNode(true);
cloned.appendChild(clonedChildNode);
}
}
return cloned;
}
}
export class MockTitleElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'title');
}
get text() {
return this.textContent;
}
set text(value: string) {
this.textContent = value;
}
}
export class MockUListElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'ul');
}
}
export class MockSlotElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'slot');
}
assignedNodes(opts?: { flatten: boolean }): (MockNode | Node)[] {
let nodesToReturn: (MockNode | Node)[] = [];
const ownerHost = (this.getRootNode() as any).host as MockElement;
if (!ownerHost) return nodesToReturn;
if (ownerHost.childNodes.length) {
// try to find lightDOM nodes matching this slot's name (or lack of)
if ((this as any).name) {
nodesToReturn = ownerHost.childNodes.filter(
(n) =>
n.nodeType === NODE_TYPES.ELEMENT_NODE && (n as MockElement).getAttribute('slot') === (this as any).name,
);
} else {
// find elements that do not have a slot attribute or
// any other type of node
nodesToReturn = ownerHost.childNodes.filter(
(n) =>
(n.nodeType === NODE_TYPES.ELEMENT_NODE && !(n as MockElement).getAttribute('slot')) ||
n.nodeType !== NODE_TYPES.ELEMENT_NODE,
);
}
if (nodesToReturn.length) return nodesToReturn;
}
// no flatten option? Return whatever's in this slot (without nested slots)
if (!opts?.flatten) return this.childNodes.filter((n) => !(n instanceof MockSlotElement));
// flatten option? Return all nodes in this slot (including anything within nested slots)
return this.childNodes.reduce(
(acc, node) => {
if (node instanceof MockSlotElement) {
acc.push(...node.assignedNodes(opts));
} else {
acc.push(node);
}
return acc;
},
[] as (MockNode | Node)[],
);
}
assignedElements(opts?: { flatten: boolean }): (Element | MockHTMLElement)[] {
let elesToReturn: (Element | MockHTMLElement)[] = [];
const ownerHost = (this.getRootNode() as any).host as MockElement;
if (!ownerHost) return elesToReturn;
if (ownerHost.children.length) {
// try to find lightDOM elements matching this slot's name (or lack of)
if ((this as any).name) {
elesToReturn = ownerHost.children.filter((n) => (n as MockElement).getAttribute('slot') == (this as any).name);
} else {
elesToReturn = ownerHost.children.filter((n) => !(n as MockElement).getAttribute('slot'));
}
if (elesToReturn.length) return elesToReturn;
}
// no flatten option? Return whatever elements are in this slot (without nested slots)
if (!opts?.flatten) return this.children.filter((n) => !(n instanceof MockSlotElement));
// flatten option? Return all elements in this slot (including anything within nested slots)
return this.children.reduce(
(acc, node) => {
if (node instanceof MockSlotElement) {
acc.push(...node.assignedElements(opts));
} else {
acc.push(node);
}
return acc;
},
[] as (MockElement | Element)[],
);
}
}
patchPropAttributes(MockSlotElement.prototype, {
name: String,
});
type CanvasContext = '2d' | 'webgl' | 'webgl2' | 'bitmaprenderer';
export class CanvasRenderingContext {
context: CanvasContext;
contextAttributes: WebGLContextAttributes;
constructor(context: CanvasContext, contextAttributes?: WebGLContextAttributes) {
this.context = context;
this.contextAttributes = contextAttributes;
}
fillRect() {
return;
}
clearRect() {}
getImageData(_: number, __: number, w: number, h: number) {
return {
data: new Array(w * h * 4),
};
}
toDataURL() {
return 'data:,'; // blank image
}
putImageData() {}
createImageData(): ImageData {
return {} as ImageData;
}
setTransform() {}
drawImage() {}
save() {}
fillText() {}
restore() {}
beginPath() {}
moveTo() {}
lineTo() {}
closePath() {}
stroke() {}
translate() {}
scale() {}
rotate() {}
arc() {}
fill() {}
measureText() {
return { width: 0 };
}
transform() {}
rect() {}
clip() {}
}
export class MockCanvasElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'canvas');
}
getContext(context: CanvasContext, contextAttributes?: WebGLContextAttributes): CanvasRenderingContext {
return new CanvasRenderingContext(context, contextAttributes);
}
}
function fullUrl(elm: MockElement, attrName: string) {
const val = elm.getAttribute(attrName) || '';
if (elm.ownerDocument != null) {
const win = elm.ownerDocument.defaultView as Window;
if (win != null) {
const loc = win.location;
if (loc != null) {
try {
const url = new URL(val, loc.href);
return url.href;
} catch (e) {}
}
}
}
return val.replace(/\'|\"/g, '').trim();
}
function getLabelsForElement(elm: MockHTMLElement): MockHTMLElement[] {
const labels: MockHTMLElement[] = [];
const id = elm.id;
const doc = elm.ownerDocument;
if (doc) {
// Find labels with "for" attribute matching this element's ID
if (id) {
const allLabels = doc.getElementsByTagName('label');
for (let i = 0; i < allLabels.length; i++) {
const label = allLabels[i] as MockLabelElement;
if (label.htmlFor === id) {
labels.push(label);
}
}
}
// Find labels that contain this element as a descendant
let parent = elm.parentNode as MockHTMLElement | null;
while (parent) {
if (parent.nodeName === 'LABEL' && !labels.includes(parent)) {
labels.push(parent);
}
parent = parent.parentNode as MockHTMLElement | null;
}
}
return labels;
}
function patchPropAttributes(prototype: any, attrs: any, defaults: any = {}) {
Object.keys(attrs).forEach((propName) => {
const attr = attrs[propName];
const defaultValue = defaults[propName];
if (attr === Boolean) {
Object.defineProperty(prototype, propName, {
get(this: MockElement) {
return this.hasAttribute(propName);
},
set(this: MockElement, value: boolean) {
if (value) {
this.setAttribute(propName, '');
} else {
this.removeAttribute(propName);
}
},
});
} else if (attr === Number) {
Object.defineProperty(prototype, propName, {
get(this: MockElement) {
const value = this.getAttribute(propName);
return value ? parseInt(value, 10) : defaultValue === undefined ? 0 : defaultValue;
},
set(this: MockElement, value: boolean) {
this.setAttribute(propName, value);
},
});
} else {
Object.defineProperty(prototype, propName, {
get(this: MockElement) {
return this.hasAttribute(propName) ? this.getAttribute(propName) : defaultValue || '';
},
set(this: MockElement, value: boolean) {
this.setAttribute(propName, value);
},
});
}
});
}
MockElement.prototype.cloneNode = function (this: MockElement, deep?: boolean) {
// because we're creating elements, which extending specific HTML base classes there
// is a MockElement circular reference that bundling has trouble dealing with so
// the fix is to add cloneNode() to MockElement's prototype after the HTML classes
const cloned = createElement(this.ownerDocument, this.nodeName);
cloned.attributes = cloneAttributes(this.attributes);
const styleCssText = this.getAttribute('style');
if (styleCssText != null && styleCssText.length > 0) {
cloned.setAttribute('style', styleCssText);
}
if (deep) {
for (let i = 0, ii = this.childNodes.length; i < ii; i++) {
const clonedChildNode = this.childNodes[i].cloneNode(true);
cloned.appendChild(clonedChildNode);
}
}
return cloned;
};