-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathshadow-dom.ts
More file actions
70 lines (59 loc) · 2.26 KB
/
shadow-dom.ts
File metadata and controls
70 lines (59 loc) · 2.26 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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
let shadowDomIsSupported: boolean;
interface DocumentHeadWithCreateShadowRoot extends HTMLElement {
createShadowRoot?: Function;
}
/** Checks whether the user's browser support Shadow DOM. */
export function _supportsShadowDom(): boolean {
if (shadowDomIsSupported == null) {
const head = typeof document !== 'undefined' ? document.head : null;
shadowDomIsSupported = !!(
head &&
((head as DocumentHeadWithCreateShadowRoot).createShadowRoot || head.attachShadow)
);
}
return shadowDomIsSupported;
}
/** Gets the shadow root of an element, if supported and the element is inside the Shadow DOM. */
export function _getShadowRoot(element: HTMLElement): ShadowRoot | null {
if (_supportsShadowDom()) {
const rootNode = element.getRootNode ? element.getRootNode() : null;
// Note that this should be caught by `_supportsShadowDom`, but some
// teams have been able to hit this code path on unsupported browsers.
if (typeof ShadowRoot !== 'undefined' && ShadowRoot && rootNode instanceof ShadowRoot) {
return rootNode;
}
}
return null;
}
/**
* Gets the currently-focused element on the page while
* also piercing through Shadow DOM boundaries.
*/
export function _getFocusedElementPierceShadowDom(): HTMLElement | null {
let activeElement =
typeof document !== 'undefined' && document
? (document.activeElement as HTMLElement | null)
: null;
while (activeElement && activeElement.shadowRoot) {
const newActiveElement = activeElement.shadowRoot.activeElement as HTMLElement | null;
if (newActiveElement === activeElement) {
break;
} else {
activeElement = newActiveElement;
}
}
return activeElement;
}
/** Gets the target of an event while accounting for Shadow DOM. */
export function _getEventTarget<T extends EventTarget>(event: Event): T | null {
// If an event is bound outside the Shadow DOM, the `event.target` will
// point to the shadow root so we have to use `composedPath` instead.
return (event.composedPath ? event.composedPath()[0] : event.target) as T | null;
}