UNPKG

1.81 kBPlain TextView Raw
1// Source: https://github.com/microsoft/tabster/blob/a89fc5d7e332d48f68d03b1ca6e344489d1c3898/src/Shadowdomize/DOMFunctions.ts#L16
2
3import {isShadowRoot} from '../domHelpers';
4import {shadowDOM} from '@react-stately/flags';
5
6/**
7 * ShadowDOM safe version of Node.contains.
8 */
9export function nodeContains(
10 node: Node | null | undefined,
11 otherNode: Node | null | undefined
12): boolean {
13 if (!shadowDOM()) {
14 return otherNode && node ? node.contains(otherNode) : false;
15 }
16
17 if (!node || !otherNode) {
18 return false;
19 }
20
21 let currentNode: HTMLElement | Node | null | undefined = otherNode;
22
23 while (currentNode !== null) {
24 if (currentNode === node) {
25 return true;
26 }
27
28 if ((currentNode as HTMLSlotElement).tagName === 'SLOT' &&
29 (currentNode as HTMLSlotElement).assignedSlot) {
30 // Element is slotted
31 currentNode = (currentNode as HTMLSlotElement).assignedSlot!.parentNode;
32 } else if (isShadowRoot(currentNode)) {
33 // Element is in shadow root
34 currentNode = currentNode.host;
35 } else {
36 currentNode = currentNode.parentNode;
37 }
38 }
39
40 return false;
41}
42
43/**
44 * ShadowDOM safe version of document.activeElement.
45 */
46export const getActiveElement = (doc: Document = document) => {
47 if (!shadowDOM()) {
48 return doc.activeElement;
49 }
50 let activeElement: Element | null = doc.activeElement;
51
52 while (activeElement && 'shadowRoot' in activeElement &&
53 activeElement.shadowRoot?.activeElement) {
54 activeElement = activeElement.shadowRoot.activeElement;
55 }
56
57 return activeElement;
58};
59
60/**
61 * ShadowDOM safe version of event.target.
62 */
63export function getEventTarget(event): Element {
64 if (shadowDOM() && event.target.shadowRoot) {
65 if (event.composedPath) {
66 return event.composedPath()[0];
67 }
68 }
69 return event.target;
70}