An open source design system that's fully customizable and agent ready
TypeScript
chore(Layer): the outside-press watch can close on a pan, follow chosen pointer types, and judge a press in a closed shadow root (#9814)
Christopher Chedeaucd748d0e99ce
diff --git a/.changeset/outside-press-pan-watch.md b/.changeset/outside-press-pan-watch.mdnew file mode 100644index 0000000000..e71ae7e4c0--- /dev/null+++ b/.changeset/outside-press-pan-watch.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the layer's outside-press watch can follow chosen pointer types, close as a press that starts outside begins to pan (on either axis, at core's pan threshold) or when the browser takes it, and judge a press inside a closed shadow root, which the document sees as its host. No component passes these options yet, so every watch keeps today's behavior. Not exported from the package entry point.++@vjeuxdiff --git a/packages/core/src/Layer/outsidePress.test.ts b/packages/core/src/Layer/outsidePress.test.tsindex bea4e64dec..ca08558aa9 100644--- a/packages/core/src/Layer/outsidePress.test.ts+++ b/packages/core/src/Layer/outsidePress.test.ts@@ -2,13 +2,14 @@/*** @file outsidePress.test.ts- * @input isFocusInsideOwnedLayer and isPressInsideOwnedLayer- * @output The shared focus-leave test: the field, the layer (by id, across- * shadow roots and through popovers nested in it) are inside; anything- * else and a null target are outside+ * @input isFocusInsideOwnedLayer, isPressInsideOwnedLayer and+ * watchOutsidePress+ * @output The shared focus-leave test, and the outside-press watch that+ * closes as a finger outside begins to pan, at a cancel or at a lift*/-import {afterEach, describe, expect, it} from 'vitest';+import {fireEvent} from '@testing-library/react';+import {afterEach, describe, expect, it, vi} from 'vitest';import {isFocusInsideOwnedLayer,isPressInsideOwnedLayer,@@ -124,3 +125,214 @@ describe('outsideDismissalCount', () => {outside.remove();});});++describe('watchOutsidePress, closing on a pan', () => {+ afterEach(() => {+ document.body.replaceChildren();+ });++ const touch = (pointerId: number, x = 0, y = 0) => ({+ pointerType: 'touch',+ pointerId,+ clientX: x,+ clientY: y,+ composed: true,+ });++ function setup(root?: Node, closesOnPan = true, doc: Document = document) {+ const owner = doc.createElement('div');+ const layer = doc.createElement('div');+ const item = doc.createElement('button');+ layer.append(item);+ const outside = doc.createElement('button');+ doc.body.append(owner, outside);+ (root ?? doc.body).appendChild(layer);+ const onOutside = vi.fn();+ const stop = watchOutsidePress(+ owner,+ path => path.includes(layer),+ onOutside,+ {closesOnPan, pointerTypes: ['touch'], root},+ );+ return {item, outside, onOutside, stop};+ }++ it('closes as a press that starts outside pans past the pan threshold', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerMove(outside, touch(1, 0, 8));+ expect(onOutside).not.toHaveBeenCalled();+ fireEvent.pointerMove(outside, touch(1, 0, 30));+ expect(onOutside).toHaveBeenCalledOnce();+ fireEvent.pointerUp(outside, touch(1, 0, 30));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('measures the pan threshold on each axis, as a pan does: a diagonal drift under it on both axes does not close', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerMove(outside, touch(1, 8, 8));+ expect(onOutside).not.toHaveBeenCalled();+ fireEvent.pointerMove(outside, touch(1, 8, 30));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('begins the pan at the threshold itself, as a pan does: a finger outside that moves exactly 10 px closes', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerMove(outside, touch(1, 10, 0));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('closes when the browser takes the press, and at the lift of a tap', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerCancel(outside, touch(1));+ expect(onOutside).toHaveBeenCalledOnce();+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerUp(outside, touch(2));+ expect(onOutside).toHaveBeenCalledTimes(2);+ stop();+ });++ it('lets a second finger wait for the first, and leaves a mouse alone', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, {pointerType: 'mouse', pointerId: 9});+ fireEvent.pointerUp(outside, {pointerType: 'mouse', pointerId: 9});+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerDown(outside, touch(3));+ fireEvent.pointerUp(outside, touch(3));+ expect(onOutside).not.toHaveBeenCalled();+ fireEvent.pointerUp(outside, touch(2));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it.each([true, false])(+ 'keeps the layer open for a press that starts outside and lifts on it, in a closed shadow root too (closesOnPan: %s)',+ closesOnPan => {+ const host = document.createElement('div');+ document.body.append(host);+ const shadow = host.attachShadow({mode: 'closed'});+ const {item, outside, onOutside, stop} = setup(shadow, closesOnPan);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerUp(item, touch(1));+ expect(onOutside).not.toHaveBeenCalled();+ stop();+ },+ );++ it.each([true, false])(+ 'keeps the layer open for a press that starts outside and lifts on it, in a closed root inside another (closesOnPan: %s)',+ closesOnPan => {+ const outerHost = document.createElement('div');+ document.body.append(outerHost);+ const outer = outerHost.attachShadow({mode: 'closed'});+ const innerHost = document.createElement('div');+ outer.append(innerHost);+ const inner = innerHost.attachShadow({mode: 'closed'});+ const {item, outside, onOutside, stop} = setup(inner, closesOnPan);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerUp(item, touch(1));+ expect(onOutside).not.toHaveBeenCalled();+ // A lift on the outer root's own content is outside the layer.+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerUp(innerHost, touch(2));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ },+ );++ it.each([true, false])(+ 'closes for a lift on a control in an outer closed root that stops the lift (closesOnPan: %s)',+ closesOnPan => {+ const outerHost = document.createElement('div');+ document.body.append(outerHost);+ const outer = outerHost.attachShadow({mode: 'closed'});+ const control = document.createElement('button');+ control.addEventListener('pointerup', event => event.stopPropagation());+ const innerHost = document.createElement('div');+ outer.append(control, innerHost);+ const inner = innerHost.attachShadow({mode: 'closed'});+ const {outside, onOutside, stop} = setup(inner, closesOnPan);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerUp(control, touch(1));+ expect(onOutside).toHaveBeenCalledOnce();+ // The watch does not keep following that press: the next one closes too.+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerUp(outside, touch(2));+ expect(onOutside).toHaveBeenCalledTimes(2);+ stop();+ },+ );++ it('follows a new primary pointer when the followed press’s lift went unseen', () => {+ const {outside, onOutside, stop} = setup();+ fireEvent.pointerDown(outside, {...touch(1), isPrimary: true});+ // The lift of pointer 1 never reaches this document.+ fireEvent.pointerDown(outside, {...touch(2), isPrimary: true});+ fireEvent.pointerMove(outside, touch(2, 0, 12));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('keeps the layer open for a press that starts outside and lifts on it, in a closed root of a same-origin iframe', () => {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const frameDocument = frame.contentDocument!;+ const host = frameDocument.createElement('div');+ frameDocument.body.append(host);+ const shadow = host.attachShadow({mode: 'closed'});+ // The precondition this guards: another window's shadow root is not this+ // window's ShadowRoot.+ expect(shadow instanceof ShadowRoot).toBe(false);+ const {item, outside, onOutside, stop} = setup(shadow, true, frameDocument);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerUp(item, touch(1));+ expect(onOutside).not.toHaveBeenCalled();+ // The watch follows this window's presses: a lift outside closes.+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerUp(outside, touch(2));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('leaves a followed press alone when a pointer type it does not follow is cancelled', () => {+ const {outside, onOutside, stop} = setup(undefined, false);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerCancel(outside, {pointerType: 'pen', pointerId: 7});+ fireEvent.pointerUp(outside, touch(1));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });++ it('counts a layer it closes on a pan or a cancel as an outside dismissal, as at a lift', () => {+ const {outside, stop} = setup();+ const before = outsideDismissalCount(document);+ fireEvent.pointerDown(outside, touch(1));+ fireEvent.pointerMove(outside, touch(1, 0, 30));+ expect(outsideDismissalCount(document)).toBe(before + 1);+ fireEvent.pointerUp(outside, touch(1, 0, 30));+ fireEvent.pointerDown(outside, touch(2));+ fireEvent.pointerCancel(outside, touch(2));+ expect(outsideDismissalCount(document)).toBe(before + 2);+ stop();+ });++ it('counts a press inside the layer as inside, in a closed shadow root too', () => {+ const host = document.createElement('div');+ document.body.append(host);+ const shadow = host.attachShadow({mode: 'closed'});+ const {item, onOutside, stop} = setup(shadow);+ fireEvent.pointerDown(item, touch(1));+ fireEvent.pointerUp(item, touch(1));+ expect(onOutside).not.toHaveBeenCalled();+ fireEvent.pointerDown(host, touch(2));+ fireEvent.pointerUp(host, touch(2));+ expect(onOutside).toHaveBeenCalledOnce();+ stop();+ });+});diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.tsindex 142def81ea..4c34767d91 100644--- a/packages/core/src/Layer/outsidePress.ts+++ b/packages/core/src/Layer/outsidePress.ts@@ -4,27 +4,38 @@/*** @file outsidePress.ts- * @input Listens for pointerdown, pointerup and pointercancel on a document- * @output Exports watchOutsidePress and useOutsidePress, which owns one watch- * for a component: start on show, stop on hide, stop on unmount;- * noteOutsideDismissal and outsideDismissalCount, a per-document count of- * layers that an outside press or focus move closed; and the- * inside tests a text field's owner runs: isPressInsideOwnedLayer for a- * press, isFocusInsideOwnedLayer for a blur- * @position Internal to Layer; the outside-press dismissal for a manual- * popover whose owner decides what counts as inside (a combobox's field- * and its list). Not exported from the package.- *- * A press closes the layer only when it starts and ends outside, as native- * light dismiss does: a pointerdown outside is remembered, the pointerup that- * follows closes the layer if it is outside too, and a pointercancel (the- * browser took the gesture for a scroll or a pinch) forgets it. Inside is- * judged on the event's composed path, so a field or list inside an open- * shadow root, which the document sees as its shadow host, is still inside.+ * @input Pointer presses on a document and on the shadow roots around a+ * given root; with closesOnPan, pan moves from core's input stream+ * @output watchOutsidePress, and useOutsidePress, one watch per component.+ * noteOutsideDismissal and outsideDismissalCount keep a per-document count+ * of layers that an outside press or focus move closed. The inside tests+ * are isPressInsideOwnedLayer and isFocusInsideOwnedLayer+ * @position Internal to Layer: the outside-press dismissal for a manual+ * popover whose owner decides what counts as inside. Not exported.*/import {useCallback, useEffect, useMemo, useRef} from 'react';-import {isElement, isNode, isShadowRoot} from '../utils/nodeType';+import {UIKIT_PAN} from '../motion/uikit/gestures';+import {shadowHostOf, shadowRootsOutward} from '../utils/flatTree';+import {subscribeInput} from '../utils/inputStream';+import {isElement, isNode} from '../utils/nodeType';++export interface OutsidePressOptions {+ /** The pointer types the watch follows; every type when omitted. */+ readonly pointerTypes?: ReadonlyArray<string>;+ /**+ * A press outside also closes the layer as it begins to pan, or when the+ * browser takes it. While one press outside is followed, other pointers are+ * ignored. A new primary pointer starts a new press.+ */+ readonly closesOnPan?: boolean;+ /**+ * The shadow root the layer renders in. The document sees a press inside a+ * closed root as a press on its host. So each root from this one out to the+ * document judges presses too, and an inner root's judgment stands.+ */+ readonly root?: Node | null;+}// A modal host's backdrop press reads this. A press that closed a layer above// the host is that layer's, so the host stays open.@@ -47,39 +58,144 @@ export function outsideDismissalCount(doc: Document): number {* @param owner - The element that owns the layer (the field); its document is* watched.* @param isInside - Whether a press with this composed path is inside.- * @param onOutside - Called once for each press that starts and ends outside.+ * @param onOutside - Called once for each press that starts and ends outside,+ * as native light dismiss does. With `closesOnPan`, also when that press+ * pans or is cancelled.* @returns Stops watching.*/export function watchOutsidePress(owner: Element,isInside: (path: ReadonlyArray<EventTarget>) => boolean,onOutside: () => void,+ {pointerTypes, closesOnPan = false, root = null}: OutsidePressOptions = {},): () => void {const doc = owner.ownerDocument;+ const shadows = root == null ? [] : shadowRootsOutward(root);let startedOutside = false;+ let panStart: {id: number; x: number; y: number} | null = null;+ const follows = (event: PointerEvent) =>+ pointerTypes == null || pointerTypes.includes(event.pointerType);+ const close = () => {+ startedOutside = false;+ panStart = null;+ noteOutsideDismissal(doc);+ onOutside();+ };// Capture phase, so a press whose target stops propagation is still seen.+ // An inner root's listener runs after the outer ones', so its judgment+ // stands.const handleDown = (event: PointerEvent) => {+ if (!follows(event)) {+ return;+ }+ if (+ closesOnPan &&+ panStart != null &&+ panStart.id !== event.pointerId &&+ !event.isPrimary+ ) {+ return;+ }startedOutside = !isInside(event.composedPath());+ if (closesOnPan) {+ panStart = startedOutside+ ? {id: event.pointerId, x: event.clientX, y: event.clientY}+ : null;+ }+ };+ const handleMove = (event: PointerEvent) => {+ if (+ panStart?.id === event.pointerId &&+ Math.max(+ Math.abs(event.clientX - panStart.x),+ Math.abs(event.clientY - panStart.y),+ ) >= UIKIT_PAN.hysteresis.value+ ) {+ close();+ }};- const handleUp = (event: PointerEvent) => {+ const judgeUp = (event: PointerEvent) => {+ if (!follows(event) || (closesOnPan && panStart?.id !== event.pointerId)) {+ return;+ }const wasOutside = startedOutside;startedOutside = false;+ panStart = null;if (wasOutside && !isInside(event.composedPath())) {noteOutsideDismissal(doc);onOutside();}};- const handleCancel = () => {- startedOutside = false;+ // The document and each root see a lift inside a deeper closed root as a+ // lift on that root's host. So each of them judges, in the capture phase,+ // only a lift whose path does not hold the host below it. The innermost root+ // judges every lift it sees. A host judges a lift on itself, which no root+ // sees.+ let judgedLift: Event | null = null;+ const judgeUpUnlessBelow =+ (hostBelow: Element | null) => (event: PointerEvent) => {+ if (+ event === judgedLift ||+ (hostBelow != null && event.composedPath().includes(hostBelow))+ ) {+ return;+ }+ judgedLift = event;+ judgeUp(event);+ };+ const handleUp = judgeUpUnlessBelow(shadows.at(-1)?.host ?? null);+ const liftJudges = shadows.map(({root: shadow, host}, index) => ({+ shadow,+ host,+ handleRootUp: judgeUpUnlessBelow(+ index === 0 ? null : shadows[index - 1].host,+ ) as EventListener,+ handleHostUp: judgeUpUnlessBelow(null) as EventListener,+ }));+ const handleCancel = (event: PointerEvent) => {+ if (!follows(event)) {+ return;+ }+ if (closesOnPan && panStart?.id === event.pointerId) {+ close();+ } else if (!closesOnPan) {+ startedOutside = false;+ }};- doc.addEventListener('pointerdown', handleDown, true);+ const judges: EventTarget[] = [+ doc,+ ...shadows.map(({root: shadow}) => shadow),+ ];+ for (const target of judges) {+ target.addEventListener('pointerdown', handleDown as EventListener, true);+ }+ const view = doc.defaultView;+ const stopMoves =+ closesOnPan && view != null+ ? subscribeInput(view, 'pointermove', handleMove)+ : null;doc.addEventListener('pointerup', handleUp, true);+ for (const {shadow, host, handleRootUp, handleHostUp} of liftJudges) {+ shadow.addEventListener('pointerup', handleRootUp, true);+ host.addEventListener('pointerup', handleHostUp);+ }doc.addEventListener('pointercancel', handleCancel, true);return () => {- doc.removeEventListener('pointerdown', handleDown, true);+ for (const target of judges) {+ target.removeEventListener(+ 'pointerdown',+ handleDown as EventListener,+ true,+ );+ }+ stopMoves?.();doc.removeEventListener('pointerup', handleUp, true);+ for (const {shadow, host, handleRootUp, handleHostUp} of liftJudges) {+ shadow.removeEventListener('pointerup', handleRootUp, true);+ host.removeEventListener('pointerup', handleHostUp);+ }doc.removeEventListener('pointercancel', handleCancel, true);};}@@ -90,6 +206,7 @@ export interface OutsidePressWatch {owner: Element,isInside: (path: ReadonlyArray<EventTarget>) => boolean,onOutside: () => void,+ options?: OutsidePressOptions,) => void;/** Stop watching; does nothing when no watch is running. */stop: () => void;@@ -108,9 +225,9 @@ export function useOutsidePress(): OutsidePressWatch {stopRef.current = null;}, []);const start = useCallback<OutsidePressWatch['start']>(- (owner, isInside, onOutside) => {+ (owner, isInside, onOutside, options) => {stopRef.current?.();- stopRef.current = watchOutsidePress(owner, isInside, onOutside);+ stopRef.current = watchOutsidePress(owner, isInside, onOutside, options);},[],);@@ -124,8 +241,7 @@ function isWithinLayer(node: Node, layerId: string): boolean {for (let current: Node | null = node;current != null;- current =- current.parentNode ?? (isShadowRoot(current) ? current.host : null)+ current = current.parentNode ?? shadowHostOf(current)) {if (isElement(current) && current.id === layerId) {return true;diff --git a/packages/core/src/utils/flatTree.test.ts b/packages/core/src/utils/flatTree.test.tsindex 4c12f03770..4b24f12fb0 100644--- a/packages/core/src/utils/flatTree.test.ts+++ b/packages/core/src/utils/flatTree.test.ts@@ -1,7 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {afterEach, describe, expect, it} from 'vitest';-import {containsAlongFlatTree, deepActiveElement} from './flatTree';+import {+ containsAlongFlatTree,+ deepActiveElement,+ shadowHostOf,+ shadowRootsOutward,+} from './flatTree';afterEach(() => {document.body.innerHTML = '';@@ -66,3 +71,41 @@ describe('deepActiveElement', () => {expect(deepActiveElement(document)).toBe(button);});});++describe('shadowHostOf', () => {+ it('is the host of an open or closed shadow root, and null for any other node', () => {+ const open = document.createElement('div');+ const closed = document.createElement('div');+ document.body.append(open, closed);+ expect(shadowHostOf(open.attachShadow({mode: 'open'}))).toBe(open);+ expect(shadowHostOf(closed.attachShadow({mode: 'closed'}))).toBe(closed);+ expect(shadowHostOf(document)).toBeNull();+ expect(shadowHostOf(document.createDocumentFragment())).toBeNull();+ expect(shadowHostOf(open)).toBeNull();+ });++ it('is the host of a shadow root from another window too', () => {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const host = frame.contentDocument!.createElement('div');+ frame.contentDocument!.body.append(host);+ expect(shadowHostOf(host.attachShadow({mode: 'closed'}))).toBe(host);+ });+});++describe('shadowRootsOutward', () => {+ it('lists the roots from a root inside others out to the document, each with its host', () => {+ const outerHost = document.createElement('div');+ document.body.append(outerHost);+ const outer = outerHost.attachShadow({mode: 'closed'});+ const innerHost = document.createElement('div');+ outer.append(innerHost);+ const inner = innerHost.attachShadow({mode: 'open'});+ expect(shadowRootsOutward(inner)).toEqual([+ {root: inner, host: innerHost},+ {root: outer, host: outerHost},+ ]);+ expect(shadowRootsOutward(outer)).toEqual([{root: outer, host: outerHost}]);+ expect(shadowRootsOutward(document)).toEqual([]);+ });+});diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.tsindex 12bda5792d..2c1cd26e1a 100644--- a/packages/core/src/utils/flatTree.ts+++ b/packages/core/src/utils/flatTree.ts@@ -4,11 +4,12 @@* @file flatTree.ts* @input A DOM node* @output Exports parentAcrossShadow, containsAlongFlatTree, which walks it,- * and deepActiveElement+ * deepActiveElement, shadowHostOf, a shadow root's host, and+ * shadowRootsOutward* @position The flat-tree parent the browser scrolls and dispatches- * through, shared by the gesture host's native-scroll probe, the- * selection lock (which the press feedback controller uses without the- * gesture system) and the Layer module's input hold+ * through. The gesture host's native-scroll probe, the outside-press watch,+ * the selection lock and the Layer module's input hold share it. The press+ * feedback controller uses the selection lock without the gesture system*/import {isShadowRoot} from './nodeType';@@ -52,3 +53,29 @@ export function deepActiveElement(}return active;}++/**+ * The host of a shadow root, open or closed and from any window, and null for+ * any other node.+ */+export function shadowHostOf(node: Node): Element | null {+ return isShadowRoot(node) ? node.host : null;+}++/**+ * The shadow roots from `node` out to its document, innermost first, each with+ * its host. Empty when `node` is not a shadow root.+ */+export function shadowRootsOutward(+ node: Node,+): {readonly root: ShadowRoot; readonly host: Element}[] {+ const roots: {readonly root: ShadowRoot; readonly host: Element}[] = [];+ for (+ let at: Node = node, host = shadowHostOf(at);+ host != null;+ at = host.getRootNode(), host = shadowHostOf(at)+ ) {+ roots.push({root: at as ShadowRoot, host});+ }+ return roots;+}diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.tsindex 3344c2a649..bcb14f5e52 100644--- a/packages/core/src/utils/selectionLock.ts+++ b/packages/core/src/utils/selectionLock.ts@@ -32,6 +32,8 @@ import {containsAlongFlatTree,deepActiveElement,parentAcrossShadow,+ shadowHostOf,+ shadowRootsOutward,} from './flatTree';import {subscribeInput} from './inputStream';import {isIosWebKit} from './touchQueries';@@ -316,9 +318,7 @@ export function startsOnSelectableText(// Text directly under a shadow root takes its host's style.const element =node.parentElement ??- (node.parentNode?.nodeType === 11- ? (node.parentNode as ShadowRoot).host- : null);+ (node.parentNode == null ? null : shadowHostOf(node.parentNode));if (element == null || !allowsSelection(element) || isInButton(node)) {return false;}@@ -603,22 +603,12 @@ function ownShadowRoot(target: EventTarget | null): ShadowRoot[] {/** The open shadow roots on `target`'s root chain, innermost first. */function openShadowRootsOf(target: EventTarget | null): ShadowRoot[] {- const roots: ShadowRoot[] = [];- let root =- target != null && typeof (target as Node).nodeType === 'number'- ? (target as Node).getRootNode()- : null;- while (root != null && root.nodeType === 11) {- const host = (root as ShadowRoot).host as Element | undefined;- if (host == null) {- break;- }- if ((root as ShadowRoot).mode === 'open') {- roots.push(root as ShadowRoot);- }- root = host.getRootNode();+ if (target == null || typeof (target as Node).nodeType !== 'number') {+ return [];}- return roots;+ return shadowRootsOutward((target as Node).getRootNode())+ .map(({root}) => root)+ .filter(root => root.mode === 'open');}/**