-
Notifications
You must be signed in to change notification settings - Fork 382
/
shadow-root.ts
627 lines (599 loc) · 19.7 KB
/
shadow-root.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
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import {
ArrayFilter,
assign,
create,
defineProperties,
defineProperty,
fields,
isNull,
isTrue,
isUndefined,
setPrototypeOf,
} from '@lwc/shared';
import { addShadowRootEventListener, removeShadowRootEventListener } from './events';
import {
shadowRootQuerySelector,
shadowRootQuerySelectorAll,
shadowRootChildNodes,
isNodeOwnedBy,
isSlotElement,
} from './traverse';
import { getTextContent } from '../3rdparty/polymer/text-content';
import { createStaticNodeList } from '../shared/static-node-list';
import { DocumentPrototypeActiveElement, elementFromPoint, createComment } from '../env/document';
import {
compareDocumentPosition,
DOCUMENT_POSITION_CONTAINED_BY,
parentElementGetter,
textContextSetter,
isConnected,
removeChild,
insertBefore,
replaceChild,
appendChild,
COMMENT_NODE,
} from '../env/node';
import { createStaticHTMLCollection } from '../shared/static-html-collection';
import { getOuterHTML } from '../3rdparty/polymer/outer-html';
import { retarget } from '../3rdparty/polymer/retarget';
import { pathComposer } from '../3rdparty/polymer/path-composer';
import { getInternalChildNodes, setNodeKey, setNodeOwnerKey } from './node';
import { innerHTMLSetter } from '../env/element';
import { getOwnerDocument } from '../shared/utils';
const { getHiddenField, setHiddenField, createFieldName } = fields;
const ShadowRootResolverKey = '$shadowResolver$';
const InternalSlot = createFieldName('shadowRecord', 'synthetic-shadow');
const { createDocumentFragment } = document;
interface ShadowRootRecord {
mode: 'open' | 'closed';
delegatesFocus: boolean;
host: Element;
shadowRoot: SyntheticShadowRootInterface;
}
function getInternalSlot(root: SyntheticShadowRootInterface | Element): ShadowRootRecord {
const record: ShadowRootRecord | undefined = getHiddenField(root, InternalSlot);
if (isUndefined(record)) {
throw new TypeError();
}
return record;
}
const ShadowResolverPrivateKey = '$$ShadowResolverKey$$';
defineProperty(Node.prototype, ShadowRootResolverKey, {
set(this: Node, fn: ShadowRootResolver) {
this[ShadowResolverPrivateKey] = fn;
// TODO [#1164]: temporary propagation of the key
setNodeOwnerKey(this, (fn as any).nodeKey);
},
get(this: Node): string | undefined {
return this[ShadowResolverPrivateKey];
},
configurable: true,
enumerable: true,
});
// Function created per shadowRoot instance, it returns the shadowRoot, and is attached
// into every new element inserted into the shadow via the GetShadowRootFnKey
// property value.
export type ShadowRootResolver = () => ShadowRoot;
export function getShadowRootResolver(node: Node): undefined | ShadowRootResolver {
return node[ShadowRootResolverKey];
}
export function setShadowRootResolver(node: Node, fn: ShadowRootResolver) {
node[ShadowRootResolverKey] = fn;
}
export function isDelegatingFocus(host: HTMLElement): boolean {
return getInternalSlot(host).delegatesFocus;
}
export function getHost(root: SyntheticShadowRootInterface): Element {
return getInternalSlot(root).host;
}
export function getShadowRoot(elm: Element): SyntheticShadowRootInterface {
return getInternalSlot(elm).shadowRoot;
}
// Intentionally adding Node here as possible the first argument
// since this check is harmless for nodes as well, and it speeds up things
// to avoid casting before calling this method in few places.
export function isHostElement(elm: Element | Node): boolean {
return !isUndefined(getHiddenField(elm, InternalSlot));
}
let uid = 0;
export function attachShadow(elm: Element, options: ShadowRootInit): SyntheticShadowRootInterface {
if (!isUndefined(getHiddenField(elm, InternalSlot))) {
throw new Error(
`Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree.`
);
}
const { mode, delegatesFocus } = options;
// creating a real fragment for shadowRoot instance
const doc = getOwnerDocument(elm);
const sr = createDocumentFragment.call(doc) as SyntheticShadowRootInterface;
// creating shadow internal record
const record: ShadowRootRecord = {
mode,
delegatesFocus: !!delegatesFocus,
host: elm,
shadowRoot: sr,
};
setHiddenField(sr, InternalSlot, record);
setHiddenField(elm, InternalSlot, record);
const shadowResolver = () => sr;
const x = (shadowResolver.nodeKey = uid++);
setNodeKey(elm, x);
setShadowRootResolver(sr, shadowResolver);
// correcting the proto chain
setPrototypeOf(sr, SyntheticShadowRoot.prototype);
return sr;
}
export interface SyntheticShadowRootInterface extends ShadowRoot {
// Remove this interface once TS supports delegatesFocus
delegatesFocus: boolean;
}
const SyntheticShadowRootDescriptors = {
constructor: {
writable: true,
configurable: true,
value: SyntheticShadowRoot,
},
toString: {
writable: true,
configurable: true,
value() {
return `[object ShadowRoot]`;
},
},
};
const ShadowRootDescriptors = {
activeElement: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): Element | null {
const host = getHost(this);
const doc = getOwnerDocument(host);
const activeElement = DocumentPrototypeActiveElement.call(doc);
if (isNull(activeElement)) {
return activeElement;
}
if (
(compareDocumentPosition.call(host, activeElement) &
DOCUMENT_POSITION_CONTAINED_BY) ===
0
) {
return null;
}
// activeElement must be child of the host and owned by it
let node = activeElement;
while (!isNodeOwnedBy(host, node)) {
// parentElement is always an element because we are talking up the tree knowing
// that it is a child of the host.
node = parentElementGetter.call(node)!;
}
// If we have a slot element here that means that we were dealing
// with an element that was passed to one of our slots. In this
// case, activeElement returns null.
if (isSlotElement(node)) {
return null;
}
return node;
},
},
delegatesFocus: {
configurable: true,
get(this: SyntheticShadowRootInterface): boolean {
return getInternalSlot(this).delegatesFocus;
},
},
elementFromPoint: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, left: number, top: number) {
const host = getHost(this);
const doc = getOwnerDocument(host);
const element = elementFromPoint.call(doc, left, top);
if (isNull(element)) {
return element;
}
return retarget(this, pathComposer(element, true)) as Element | null;
},
},
elementsFromPoint: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, _left: number, _top: number): Element[] {
throw new Error();
},
},
getSelection: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface): Selection | null {
throw new Error();
},
},
host: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): Element {
return getHost(this);
},
},
mode: {
configurable: true,
get(this: SyntheticShadowRootInterface) {
return getInternalSlot(this).mode;
},
},
styleSheets: {
enumerable: true,
configurable: true,
get(): StyleSheetList {
throw new Error();
},
},
};
const NodePatchDescriptors = {
insertBefore: {
writable: true,
enumerable: true,
configurable: true,
value<T extends Node>(
this: SyntheticShadowRootInterface,
newChild: T,
refChild: Node | null
): T {
insertBefore.call(getHost(this), newChild, refChild);
return newChild;
},
},
removeChild: {
writable: true,
enumerable: true,
configurable: true,
value<T extends Node>(this: SyntheticShadowRootInterface, oldChild: T): T {
removeChild.call(getHost(this), oldChild);
return oldChild;
},
},
appendChild: {
writable: true,
enumerable: true,
configurable: true,
value<T extends Node>(this: SyntheticShadowRootInterface, newChild: T): T {
appendChild.call(getHost(this), newChild);
return newChild;
},
},
replaceChild: {
writable: true,
enumerable: true,
configurable: true,
value<T extends Node>(this: SyntheticShadowRootInterface, newChild: Node, oldChild: T): T {
replaceChild.call(getHost(this), newChild, oldChild);
return oldChild;
},
},
addEventListener: {
writable: true,
enumerable: true,
configurable: true,
value(
this: SyntheticShadowRootInterface,
type: string,
listener: EventListener,
options?: boolean | AddEventListenerOptions
) {
addShadowRootEventListener(this, type, listener, options);
},
},
removeEventListener: {
writable: true,
enumerable: true,
configurable: true,
value(
this: SyntheticShadowRootInterface,
type: string,
listener: EventListener,
options?: boolean | AddEventListenerOptions
) {
removeShadowRootEventListener(this, type, listener, options);
},
},
baseURI: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface) {
return getHost(this).baseURI;
},
},
childNodes: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): NodeListOf<Node & Element> {
return createStaticNodeList(shadowRootChildNodes(this));
},
},
compareDocumentPosition: {
writable: true,
enumerable: true,
configurable: true,
value(
this: SyntheticShadowRootInterface,
otherNode: Node | SyntheticShadowRootInterface
): number {
const host = getHost(this);
if (this === otherNode) {
// "this" and "otherNode" are the same shadow root.
return 0;
} else if (this.contains(otherNode as Node)) {
// "otherNode" belongs to the shadow tree where "this" is the shadow root.
return 20; // Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING
} else if (
compareDocumentPosition.call(host, otherNode) & DOCUMENT_POSITION_CONTAINED_BY
) {
// "otherNode" is in a different shadow tree contained by the shadow tree where "this" is the shadow root.
return 37; // Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
} else {
// "otherNode" is in a different shadow tree that is not contained by the shadow tree where "this" is the shadow root.
return 35; // Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
}
},
},
contains: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, otherNode: Node) {
if (this === otherNode) {
return true;
}
const host = getHost(this);
// must be child of the host and owned by it.
return (
(compareDocumentPosition.call(host, otherNode) & DOCUMENT_POSITION_CONTAINED_BY) !==
0 && isNodeOwnedBy(host, otherNode)
);
},
},
firstChild: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): ChildNode | null {
const childNodes = getInternalChildNodes(this);
return childNodes[0] || null;
},
},
lastChild: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): ChildNode | null {
const childNodes = getInternalChildNodes(this);
return childNodes[childNodes.length - 1] || null;
},
},
hasChildNodes: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface): boolean {
const childNodes = getInternalChildNodes(this);
return childNodes.length > 0;
},
},
isConnected: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface) {
return isConnected.call(getHost(this));
},
},
nextSibling: {
enumerable: true,
configurable: true,
get() {
return null;
},
},
previousSibling: {
enumerable: true,
configurable: true,
get() {
return null;
},
},
nodeName: {
enumerable: true,
configurable: true,
get() {
return '#document-fragment';
},
},
nodeType: {
enumerable: true,
configurable: true,
get() {
return 11; // Node.DOCUMENT_FRAGMENT_NODE
},
},
nodeValue: {
enumerable: true,
configurable: true,
get() {
return null;
},
},
ownerDocument: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): Document | null {
return getHost(this).ownerDocument;
},
},
parentElement: {
enumerable: true,
configurable: true,
get(): Element | null {
return null;
},
},
parentNode: {
enumerable: true,
configurable: true,
get(): Node | null {
return null;
},
},
textContent: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): string {
const childNodes = getInternalChildNodes(this);
let textContent = '';
for (let i = 0, len = childNodes.length; i < len; i += 1) {
const currentNode = childNodes[i];
if (currentNode.nodeType !== COMMENT_NODE) {
textContent += getTextContent(currentNode);
}
}
return textContent;
},
set(this: SyntheticShadowRootInterface, v: string) {
const host = getHost(this);
textContextSetter.call(host, v);
},
},
// Since the synthetic shadow root is a detached DocumentFragment, short-circuit the getRootNode behavior
getRootNode: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, options?: GetRootNodeOptions): Node {
return !isUndefined(options) && isTrue(options.composed)
? getHost(this).getRootNode(options)
: this;
},
},
};
const ElementPatchDescriptors = {
innerHTML: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): string {
const childNodes = getInternalChildNodes(this);
let innerHTML = '';
for (let i = 0, len = childNodes.length; i < len; i += 1) {
innerHTML += getOuterHTML(childNodes[i]);
}
return innerHTML;
},
set(this: SyntheticShadowRootInterface, v: string) {
const host = getHost(this);
innerHTMLSetter.call(host, v);
},
},
};
const ParentNodePatchDescriptors = {
childElementCount: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface): number {
return this.children.length;
},
},
children: {
enumerable: true,
configurable: true,
get(this: SyntheticShadowRootInterface) {
return createStaticHTMLCollection(
ArrayFilter.call(
shadowRootChildNodes(this),
(elm: Node | Element) => elm instanceof Element
)
);
},
},
firstElementChild: {
enumerable: true,
configurable: true,
get(this: Element): Element | null {
return this.children[0] || null;
},
},
lastElementChild: {
enumerable: true,
configurable: true,
get(this: Element): Element | null {
const { children } = this;
return children.item(children.length - 1) || null;
},
},
querySelector: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, selectors: string): Element | null {
return shadowRootQuerySelector(this, selectors);
},
},
querySelectorAll: {
writable: true,
enumerable: true,
configurable: true,
value(this: SyntheticShadowRootInterface, selectors: string): NodeListOf<Element> {
return createStaticNodeList(shadowRootQuerySelectorAll(this, selectors));
},
},
};
assign(
SyntheticShadowRootDescriptors,
NodePatchDescriptors,
ParentNodePatchDescriptors,
ElementPatchDescriptors,
ShadowRootDescriptors
);
export function SyntheticShadowRoot() {
throw new TypeError('Illegal constructor');
}
SyntheticShadowRoot.prototype = create(DocumentFragment.prototype, SyntheticShadowRootDescriptors);
/**
* This method is only intended to be used in non-production mode in IE11
* and its role is to produce a 1-1 mapping between a shadowRoot instance
* and a comment node that is intended to use to trick the IE11 DevTools
* to show the content of the shadowRoot in the DOM Explorer.
*/
export function getIE11FakeShadowRootPlaceholder(host: Element): Comment {
const shadowRoot = getShadowRoot(host);
// @ts-ignore this $$placeholder$$ is not a security issue because you must
// have access to the shadowRoot in order to extract the fake node, which give
// you access to the same childNodes of the shadowRoot, so, who cares.
let c = shadowRoot.$$placeholder$$;
if (!isUndefined(c)) {
return c;
}
const doc = getOwnerDocument(host);
// @ts-ignore $$placeholder$$ is fine, read the node above.
c = shadowRoot.$$placeholder$$ = createComment.call(doc, '');
defineProperties(c, {
childNodes: {
get() {
return shadowRoot.childNodes;
},
enumerable: true,
configurable: true,
},
tagName: {
get() {
return `#shadow-root (${shadowRoot.mode})`;
},
enumerable: true,
configurable: true,
},
});
return c;
}