An open source design system that's fully customizable and agent ready
TypeScript
fix(core): gestures read another window's nodes and touches (#10224)
Cindy Zhang3060510907f5
diff --git a/.changeset/gestures-another-window.md b/.changeset/gestures-another-window.mdnew file mode 100644index 0000000000..d528d72443--- /dev/null+++ b/.changeset/gestures-another-window.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Touch gestures work on a component rendered into another window's document, such as a same-origin iframe or a Document Picture-in-Picture window. The gesture host checked nodes and touches against this window's classes, so it ignored that window's own. A finger's scroll, a layer's input hold, the press delay inside a scroll view and the iOS selection lock read that window's nodes too.++@vjeuxdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1d7fd44008..a739cdad98 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2702,7 +2702,7 @@ jobs:id: scopeuses: ./.test-scope/.github/actions/test-scopewith:- paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver|scrollView)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/Layer/(inputHold|modalOutlet)\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(playwright-legs|a11y-pr-contracts|lane-environment)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/(playwright-leg-durations|lane-environments)\.json$|\.github/actions/test-scope/|.*\.interaction\.browser\.spec\.ts$)'+ paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver|scrollView|nodeType)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/Layer/(inputHold|modalOutlet)\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(playwright-legs|a11y-pr-contracts|lane-environment)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/(playwright-leg-durations|lane-environments)\.json$|\.github/actions/test-scope/|.*\.interaction\.browser\.spec\.ts$)'outside-pull-request: skiprequires-head-file: playwright.interaction.config.ts# Lists the changed files, so the planner adds a changed spec.diff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.tsindex d00e234a74..25d8ddd9fe 100644--- a/packages/core/src/Layer/inputHold.ts+++ b/packages/core/src/Layer/inputHold.ts@@ -21,6 +21,7 @@ import {parentAcrossShadow,} from '../utils/flatTree';import {getLastPointerType, subscribeInput} from '../utils/inputStream';+import {isDocument, isElement, isHTMLElement, isNode} from '../utils/nodeType';/*** What a hold does. `'viewport'` and `'layer'` add one shield over the whole@@ -99,7 +100,7 @@ export function isInHeldLayer(target: Node | null): boolean {node != null;node = parentAcrossShadow(node)) {- if (node instanceof Element && held.has(node)) {+ if (isElement(node) && held.has(node)) {return true;}}@@ -115,7 +116,7 @@ export function isInHeldLayer(target: Node | null): boolean {* held, this answers false.*/export function holdsTouch(target: Node): boolean {- const doc = target instanceof Document ? target : target.ownerDocument;+ const doc = isDocument(target) ? target : target.ownerDocument;// The gesture host asks for every touch: with nothing held, answer at once.if (doc == null || !heldDocuments.has(doc)) {return false;@@ -130,7 +131,7 @@ export function holdsTouch(target: Node): boolean {node != null;node = parentAcrossShadow(node)) {- const state = node instanceof Element ? held.get(node) : undefined;+ const state = isElement(node) ? held.get(node) : undefined;if (state != null) {if (state.layer > 0) {return true;@@ -479,7 +480,7 @@ function createPressHold(doc: Document): PressHold | null {}if (state.surface > 0 &&- target instanceof Node &&+ isNode(target) &&containsAlongFlatTree(layer, target)) {return true;@@ -717,7 +718,7 @@ function makeContentInert(}const focused = deepActiveElement(layer.ownerDocument);if (- focused instanceof HTMLElement &&+ isHTMLElement(focused) &&[...content.keys()].some(child => containsAlongFlatTree(child, focused))) {focused.blur();diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.tsindex e3be73ae42..142def81ea 100644--- a/packages/core/src/Layer/outsidePress.ts+++ b/packages/core/src/Layer/outsidePress.ts@@ -24,6 +24,7 @@*/import {useCallback, useEffect, useMemo, useRef} from 'react';+import {isElement, isNode, isShadowRoot} from '../utils/nodeType';// 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.@@ -118,25 +119,6 @@ export function useOutsidePress(): OutsidePressWatch {return useMemo(() => ({start, stop}), [start, stop]);}-// Node, Element and ShadowRoot are checked by nodeType, not instanceof: a-// node from a same-origin iframe or a Picture-in-Picture window belongs to-// another realm, where instanceof against this window's classes is false.-function isNode(target: unknown): target is Node {- return (- typeof target === 'object' &&- target !== null &&- typeof (target as {nodeType?: unknown}).nodeType === 'number'- );-}--function isElement(node: Node): node is Element {- return node.nodeType === 1;-}--function isShadowRoot(node: Node): node is ShadowRoot {- return node.nodeType === 11 && 'host' in node;-}-/** Whether `node` is the layer with this id, or inside it across shadow roots. */function isWithinLayer(node: Node, layerId: string): boolean {for (diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.tsindex ade9ceb823..a6cd3a96bb 100644--- a/packages/core/src/gestures/GestureHost.ts+++ b/packages/core/src/gestures/GestureHost.ts@@ -191,6 +191,7 @@ import {} from '../utils/selectionLock';import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';import {gestureHosts} from './hostRegistry';+import {isElement, isHTMLElement, isNode} from '../utils/nodeType';interface Registration {readonly recognizers: GestureRecognizer[];@@ -888,12 +889,11 @@ export class GestureHost {height: doc.defaultView?.innerHeight ?? 0,}),// The writing direction through core's one helper.- isRtl: view =>- view instanceof Element && isRtlElement(view as HTMLElement),+ isRtl: view => isElement(view) && isRtlElement(view as HTMLElement),// A screen-edge pan tells a view within its edge band from any other// by its box (spec:AST-094 FR18).viewRect: view => {- if (!(view instanceof Element)) {+ if (!isElement(view)) {return null;}const {left, top, width, height} = view.getBoundingClientRect();@@ -1214,7 +1214,7 @@ export class GestureHost {return native;}const found = hit;- const node = native instanceof Node ? native : null;+ const node = isNode(native) ? native : null;const isAboutMover = movers.some(mover =>containsAlongFlatTree(mover, found) ||@@ -1278,12 +1278,12 @@ export class GestureHost {pointerType: string,): void {const view = this.doc.defaultView;- if (!(target instanceof Element) || !target.isConnected || view == null) {+ if (!isElement(target) || !target.isConnected || view == null) {return;}armClickGuard(this.doc, {takesLateMouse: pointerType === 'touch'});if (- target instanceof view.HTMLElement &&+ isHTMLElement(target) &&target.matches('input, textarea, select, [contenteditable]')) {target.focus();@@ -1426,7 +1426,7 @@ export class GestureHost {}private refresh(element: Element, registration: Registration): void {- if (registration.manageStyle && element instanceof HTMLElement) {+ if (registration.manageStyle && isHTMLElement(element)) {this.applyStyle(element, registration);}this.syncTouchMoveListener(element, registration);@@ -2093,7 +2093,7 @@ export class GestureHost {// The window's own blur; an element's blur (a Node's) reaches the// window's capture phase too and means nothing here.subscribeInput(view, 'blur', event => {- if (!(event.target instanceof view.Node)) {+ if (!isNode(event.target)) {this.onBlur();}}),@@ -2151,18 +2151,18 @@ export class GestureHost {// The host asks the hold, so the hold needs nothing from gestures/. A// root-entry component can then use the hold with no gesture code.if (- target instanceof Node &&+ isNode(target) &&(holdsTouch(target) || [...this.touchGates].some(gate => gate(target)))) {return {recognizers, consumer, consumerElement};}let hasConsumerOwner = pointerType == null;for (- let node: Node | null = target instanceof Node ? target : null;+ let node: Node | null = isNode(target) ? target : null;node != null;node = parentAcrossShadow(node)) {- if (!(node instanceof Element)) {+ if (!isElement(node)) {continue;}const registration = this.registry.get(node);@@ -2224,7 +2224,7 @@ export class GestureHost {const lock = recognizer.selectionLock;if (lock != null &&- recognizer.view instanceof Element &&+ isElement(recognizer.view) &&managed(recognizer.view, recognizer)) {const elements = byLock.get(lock) ?? new Set<Element>();@@ -2522,11 +2522,11 @@ export class GestureHost {});const takers: GestureRecognizer[] = [];for (- let node: Node | null = target instanceof Node ? target : null;+ let node: Node | null = isNode(target) ? target : null;node != null;node = parentAcrossShadow(node)) {- if (!(node instanceof Element)) {+ if (!isElement(node)) {continue;}for (const recognizer of this.registry.get(node)?.recognizers ?? []) {@@ -2626,7 +2626,7 @@ export class GestureHost {keepsBoundary: boolean,): boolean {for (- let node: Node | null = target instanceof Node ? target : null;+ let node: Node | null = isNode(target) ? target : null;node != null;node = parentAcrossShadow(node)) {@@ -2634,7 +2634,7 @@ export class GestureHost {break;}if (- node instanceof Element &&+ isElement(node) &&canElementScroll(node, isHorizontal ? -dx : 0, isHorizontal ? 0 : -dy)) {return true;@@ -2717,7 +2717,7 @@ export class GestureHost {// every touch. An element's blur reaches the window's capture phase// too and means nothing here.subscribeInput(view, 'blur', event => {- if (!(event.target instanceof view.Node)) {+ if (!isNode(event.target)) {cancelWheel();}}),@@ -3007,10 +3007,9 @@ export class GestureHost {if (previous != null) {stale.push(previous);}- const native =- touch.target instanceof Node- ? landedOn(event, touch.target)- : landedOn(event);+ const native = isNode(touch.target)+ ? landedOn(event, touch.target)+ : landedOn(event);const target = this.presentedTarget(native,touch.clientX,@@ -3095,7 +3094,7 @@ export class GestureHost {// Stamped after the consumers judged the touch: the brake asks whether// an EARLIER finger is still driving a scroll.const landed = landedOn(event);- if (landed instanceof Node) {+ if (isNode(landed)) {this.lastTouch = {target: landed, time};}};@@ -3188,8 +3187,8 @@ export class GestureHost {finger.pointerType !== 'touch' ||finger.phase === 'ended' ||finger.phase === 'cancelled' ||- !(finger.target instanceof Node) ||- !(touch.target instanceof Node) ||+ !isNode(finger.target) ||+ !isNode(touch.target) ||// Along the flat tree, both ways: the finger's target can be inside// an open shadow root while its touches reach the host retargeted.!(@@ -3326,7 +3325,7 @@ export class GestureHost {}// The lift is when momentum starts: the clock the brake wants most.const landed = landedOn(event);- if (landed instanceof Node) {+ if (isNode(landed)) {this.lastTouch = {target: landed, time};}const dispositions =@@ -3980,7 +3979,7 @@ export class GestureHost {disarmClickGuard(this.doc);const target = touch.target;const view = this.doc.defaultView;- if (!(target instanceof Element) || !target.isConnected || view == null) {+ if (!isElement(target) || !target.isConnected || view == null) {return;}withoutClickGuard(() =>@@ -4054,7 +4053,7 @@ export class GestureHost {private readonly onScroll = (event: Event): void => {const time = eventTime(event);const scroller = event.target === this.doc ? this.doc : event.target;- if (!(scroller instanceof Node) || this.ownedScrolls.has(scroller)) {+ if (!isNode(scroller) || this.ownedScrolls.has(scroller)) {return;}// A scroll is a finger's only if that finger was inside this scroller,@@ -4079,7 +4078,7 @@ export class GestureHost {continue;}if (- touch.target instanceof Node &&+ isNode(touch.target) &&containsAlongFlatTree(scroller, touch.target) &&// Only a pan this finger drove takes the touch: the browser starts// one only once the finger has travelled the take distance@@ -4102,7 +4101,7 @@ export class GestureHost {const fingers: Node[] = [];for (const touch of touchesOf(event.touches)) {if ((touch as StylusTouch).touchType !== 'stylus') {- if (touch.target instanceof Node) {+ if (isNode(touch.target)) {fingers.push(touch.target);}}diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.tsindex d7341b8d6b..20480251d3 100644--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts@@ -4369,8 +4369,12 @@ describe('an action group under a fine pointer (family:action-groups FR5; spec:Aconst one = frameDocument.getElementById('one') as HTMLElement;const row = frameDocument.getElementById('row') as HTMLElement;const added = vi.spyOn(frameWindow, 'addEventListener');- const clickListeners = () =>- added.mock.calls.filter(call => call[0] === 'click').length;+ const removed = vi.spyOn(frameWindow, 'removeEventListener');+ const count = (spy: typeof added | typeof removed) =>+ spy.mock.calls.filter(call => call[0] === 'click').length;+ // The click listeners on the window now: the guard's goes when the next+ // press disarms it.+ const clickListeners = () => count(added) - count(removed);try {const send = (type: 'pointerdown' | 'pointerup', time: number) => {const event = new frameWindow.PointerEvent(type, {@@ -4396,9 +4400,10 @@ describe('an action group under a fine pointer (family:action-groups FR5; spec:A});send('pointerdown', 0);send('pointerup', 80);- // At most the click guard's own listener, while it is armed.- const afterFirst = clickListeners();- expect(afterFirst).toBeLessThanOrEqual(1);+ // The group claimed the press, so the guard is armed. Its listener is+ // the only one.+ expect(isClickGuardArmed(frameDocument)).toBe(true);+ expect(clickListeners()).toBe(1);// A per-event recognizer installs the host mid-press: still no click// listener of the press's own.send('pointerdown', 1000);@@ -4406,11 +4411,13 @@ describe('an action group under a fine pointer (family:action-groups FR5; spec:AperEventPointer: true,});send('pointerup', 1080);- expect(clickListeners()).toBe(afterFirst);+ expect(isClickGuardArmed(frameDocument)).toBe(true);+ expect(clickListeners()).toBe(1);detachRow();detachGroup();} finally {added.mockRestore();+ removed.mockRestore();frame.remove();}});@@ -7556,3 +7563,105 @@ describe('nothing left after the last detach (spec:AST-094 FR21, FR24)', () => {expectNothingLeft(subject);});});++describe("an element in another window's document", () => {+ /**+ * A same-origin iframe's document, as a component rendered into another+ * window's document has: its nodes and events belong to that window.+ */+ function frame(html: string) {+ const element = document.createElement('iframe');+ document.body.append(element);+ const doc = element.contentDocument as Document;+ const view = doc.defaultView as Window & typeof globalThis;+ doc.body.innerHTML = html;+ const subject = new GestureHost(doc, {+ clock,+ isPrimaryPointerCoarse: () => true,+ });+ // The finger-scroll watch reads the iframe's own window: a phone there.+ detachers.push(pointerQuery(true, view).restore);+ /** A touch event made by the iframe's own window. */+ const send = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ target: EventTarget,+ changed: Contact[],+ all: Contact[],+ time: number,+ ) => {+ const event = new view.Event(type, {+ bubbles: true,+ cancelable: true,+ composed: true,+ });+ const toTouch = (contact: Contact) => ({+ identifier: contact.id,+ clientX: contact.x,+ clientY: contact.y,+ target: contact.target ?? target,+ });+ Object.defineProperty(event, 'changedTouches', {+ value: changed.map(toTouch),+ });+ Object.defineProperty(event, 'touches', {value: all.map(toTouch)});+ Object.defineProperty(event, 'timeStamp', {value: time});+ target.dispatchEvent(event);+ };+ detachers.push(() => element.remove());+ return {doc, view, subject, send};+ }++ it('recognizes a finger on an element in a same-origin iframe', () => {+ const {doc, subject, send} = frame('<div id="pad"></div>');+ const pad = doc.getElementById('pad') as HTMLElement;+ // Another realm: this window's classes do not match the iframe's nodes.+ expect(pad instanceof Element).toBe(false);+ const pan = new PanGestureRecognizer({name: 'pan'});+ const states: string[] = [];+ pan.addTransitionListener((_current, _from, to) => states.push(to));+ detachers.push(subject.attach(pad, pan));+ const down = {id: 1, x: 20, y: 20};+ send('touchstart', pad, [down], [down], 0);+ for (let step = 1; step <= 6; step++) {+ const at = {...down, x: 20 + step * 10};+ send('touchmove', pad, [at], [at], step * 16);+ }+ const up = {...down, x: 80};+ send('touchend', pad, [up], [], 112);+ expect(states[0]).toBe('began');+ expect(states).toContain('changed');+ expect(states.slice(-2)).toEqual(['ended', 'possible']);+ });++ it('reads a scroll in a same-origin iframe while a finger that landed inside is down as the finger’s', () => {+ const {doc, view, subject, send} = frame(+ '<div id="list"><div id="row"></div></div>',+ );+ const list = doc.getElementById('list') as HTMLElement;+ const row = doc.getElementById('row') as HTMLElement;+ detachers.push(watchFingerScrolls(subject, list));+ const finger = {id: 1, x: 10, y: 10};+ send('touchstart', row, [finger], [finger], 0);+ list.dispatchEvent(new view.Event('scroll'));+ expect(isFingerScroll(subject, list)).toBe(true);+ send('touchend', row, [finger], [], 120);+ list.dispatchEvent(new view.Event('scrollend'));+ expect(isFingerScroll(subject, list)).toBe(false);+ });++ it('compares a finger inside an open shadow root in a same-origin iframe along the flat tree', () => {+ const {doc, view, subject, send} = frame(+ '<div id="list"><div id="outer"></div></div>',+ );+ const list = doc.getElementById('list') as HTMLElement;+ const outer = doc.getElementById('outer') as HTMLElement;+ const shadow = outer.attachShadow({mode: 'open'});+ shadow.innerHTML = '<div id="row">x</div>';+ const row = shadow.getElementById('row') as HTMLElement;+ detachers.push(watchFingerScrolls(subject, list));+ const finger = {id: 1, x: 10, y: 10, target: outer};+ send('touchstart', row, [finger], [finger], 0);+ list.dispatchEvent(new view.Event('scroll'));+ expect(isFingerScroll(subject, list)).toBe(true);+ });+});diff --git a/packages/core/src/gestures/__tests__/browser/bareFixture.ts b/packages/core/src/gestures/__tests__/browser/bareFixture.tsindex eabd17f666..435ef316c6 100644--- a/packages/core/src/gestures/__tests__/browser/bareFixture.ts+++ b/packages/core/src/gestures/__tests__/browser/bareFixture.ts@@ -3,10 +3,11 @@/*** @file bareFixture.ts* @input Nothing: bundled by esbuild and injected into a blank page- * @output A page with nothing attached: the document's gesture host and the- * recognizers (pan, screen-edge pan, tap, long press) on `window.__api`, for a test to attach what it needs, and- * `window.__pageTouch`, the count of touch listeners on the window and the- * document right now+ * @output A page with nothing attached. `window.__api` holds the document's+ * gesture host and the host lookup for another document. It also holds+ * the recognizers (pan, screen-edge pan, tap, long press), for a test to+ * attach what it needs. `window.__pageTouch` is the count of touch+ * listeners on the window and the document right now.* @position Browser fixture of gestures.interaction.browser.spec.ts for the* checks that need a page with no other gesture on it (FR19, FR24);* test-only@@ -26,6 +27,7 @@ declare global {__wheelLog: string[];__api: {host: ReturnType<typeof getGestureHost>;+ getGestureHost: typeof getGestureHost;LongPressGestureRecognizer: typeof LongPressGestureRecognizer;PanGestureRecognizer: typeof PanGestureRecognizer;PinchGestureRecognizer: typeof PinchGestureRecognizer;@@ -94,6 +96,7 @@ EventTarget.prototype.removeEventListener = function (document.body.style.margin = '0';window.__api = {host: getGestureHost(document),+ getGestureHost,LongPressGestureRecognizer,PanGestureRecognizer,PinchGestureRecognizer,diff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.tsindex 6fd41c183b..0d76254d0c 100644--- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts+++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts@@ -3116,3 +3116,88 @@ test('a watcher follows a touch the browser scrolls with to the lift, and cancel'possible',]);});++test("a pan on an element in a same-origin iframe follows a finger: the host reads that window's nodes and touches", async ({+ page,+ browserName,+}) => {+ const driver = await openBare(page, browserName);+ // The page's code drives an iframe's document, as a component rendered into+ // another window's document does. The iframe's nodes and touch events+ // belong to its own window.+ const start = await page.evaluate(() => {+ const frame = document.createElement('iframe');+ frame.style.cssText =+ 'position: absolute; left: 0; top: 0; width: 320px; height: 480px; border: 0';+ document.body.append(frame);+ const doc = frame.contentDocument as Document;+ doc.body.style.margin = '0';+ doc.body.innerHTML =+ '<div id="pad" style="width: 240px; height: 240px; background: #ddd"></div>';+ const pad = doc.getElementById('pad') as HTMLElement;+ const {getGestureHost, PanGestureRecognizer} = window.__api;+ const pan = new PanGestureRecognizer();+ const states: string[] = [];+ (window as unknown as {__frameStates: string[]}).__frameStates = states;+ pan.addTransitionListener((_current, _from, to) => states.push(to));+ getGestureHost(doc).attach(pad, pan);+ const box = pad.getBoundingClientRect();+ return {x: box.left + box.width / 2, y: box.top + box.height / 2};+ });+ await driver.play(drag(start, {x: start.x + 80, y: start.y + 4}));+ const states = await page.evaluate(+ () => (window as unknown as {__frameStates: string[]}).__frameStates,+ );+ expect(states[0]).toBe('began');+ expect(states).toContain('changed');+ expect(states.slice(-2)).toEqual(['ended', 'possible']);+});++test('a pan on an element the page moves into a same-origin iframe keeps its touch-action and follows a finger', async ({+ page,+ browserName,+}) => {+ const driver = await openBare(page, browserName);+ // Document Picture-in-Picture moves the page's own elements into another+ // window's document, where they keep the page's classes. A pan on the page+ // gives the expected touch-action.+ const start = await page.evaluate(() => {+ const {getGestureHost, PanGestureRecognizer} = window.__api;+ const reference = document.createElement('div');+ document.body.append(reference);+ getGestureHost(document).attach(reference, new PanGestureRecognizer());+ const expected = getComputedStyle(reference).touchAction;+ reference.remove();+ const frame = document.createElement('iframe');+ frame.style.cssText =+ 'position: absolute; left: 0; top: 0; width: 320px; height: 480px; border: 0';+ document.body.append(frame);+ const doc = frame.contentDocument as Document;+ doc.body.style.margin = '0';+ const pad = document.createElement('div');+ pad.style.cssText = 'width: 240px; height: 240px; background: #ddd';+ doc.body.append(pad);+ const pan = new PanGestureRecognizer();+ const states: string[] = [];+ (window as unknown as {__movedStates: string[]}).__movedStates = states;+ pan.addTransitionListener((_current, _from, to) => states.push(to));+ getGestureHost(doc).attach(pad, pan);+ const box = pad.getBoundingClientRect();+ return {+ x: box.left + box.width / 2,+ y: box.top + box.height / 2,+ expected,+ touchAction: (doc.defaultView as Window).getComputedStyle(pad)+ .touchAction,+ };+ });+ expect(start.expected).not.toBe('auto');+ expect(start.touchAction).toBe(start.expected);+ await driver.play(drag(start, {x: start.x + 80, y: start.y + 4}));+ const states = await page.evaluate(+ () => (window as unknown as {__movedStates: string[]}).__movedStates,+ );+ expect(states[0]).toBe('began');+ expect(states).toContain('changed');+ expect(states.slice(-2)).toEqual(['ended', 'possible']);+});diff --git a/packages/core/src/gestures/__tests__/haptics.test.ts b/packages/core/src/gestures/__tests__/haptics.test.tsindex 6492c68668..52e6e709ea 100644--- a/packages/core/src/gestures/__tests__/haptics.test.ts+++ b/packages/core/src/gestures/__tests__/haptics.test.ts@@ -177,6 +177,48 @@ describe('attachTapHaptic', () => {}});+ it("leaves a switch's label as it is in a same-origin iframe's document", () => {+ // Another window: its nodes do not match this window's classes.+ const frame = document.createElement('iframe');+ document.body.append(frame);+ try {+ const doc = frame.contentDocument as Document;+ doc.body.innerHTML =+ '<label id="a"><input type="checkbox" switch> Wi-Fi</label>';+ const label = doc.getElementById('a') as HTMLLabelElement;+ const control = label.control;+ expect(control instanceof HTMLInputElement).toBe(false);+ const release = attachTapHaptic(label);+ // Plain values: the test runner cannot print another window's nodes.+ expect(label.querySelectorAll('input').length).toBe(1);+ expect(label.control === control).toBe(true);+ release();+ } finally {+ frame.remove();+ }+ });++ it("leaves a switch's label as it is when the page moves it into a same-origin iframe's document", () => {+ // The label keeps this window's classes while the iframe owns it, as an+ // element moved into a Picture-in-Picture window does.+ const frame = document.createElement('iframe');+ document.body.append(frame);+ try {+ const doc = frame.contentDocument as Document;+ const label = document.createElement('label');+ label.innerHTML = '<input type="checkbox" switch> Wi-Fi';+ doc.body.append(label);+ const control = label.control;+ const release = attachTapHaptic(label);+ // Plain values: the test runner cannot print another window's nodes.+ expect(label.querySelectorAll('input').length).toBe(1);+ expect(label.control === control).toBe(true);+ release();+ } finally {+ frame.remove();+ }+ });+it('reports whether the browser knows the switch control', () => {// jsdom has no `switch` property on checkbox inputs, like browsers// before Safari 17.4.diff --git a/packages/core/src/gestures/__tests__/pointerQuery.ts b/packages/core/src/gestures/__tests__/pointerQuery.tsindex 688d4ac04c..257c651b18 100644--- a/packages/core/src/gestures/__tests__/pointerQuery.ts+++ b/packages/core/src/gestures/__tests__/pointerQuery.ts@@ -25,10 +25,20 @@ export interface PointerQuery {/*** The primary pointer is coarse (`isCoarse`) or fine until `restore` runs;- * `set` changes it as a tablet docking a mouse would.+ * `set` changes it as a tablet docking a mouse would. `view` is the window+ * that answers: this one, or an iframe's.*/-export function pointerQuery(isCoarse: boolean): PointerQuery {- const matchMedia = window.matchMedia;+export function pointerQuery(+ isCoarse: boolean,+ view: Window = window,+): PointerQuery {+ const own: Window['matchMedia'] | undefined = view.matchMedia;+ // jsdom gives an iframe's window no matchMedia: its other queries go to+ // this window's.+ const answerOther =+ own == null+ ? (media: string) => window.matchMedia(media)+ : (media: string) => own.call(view, media);const listeners = new Set<() => void>();let coarse = isCoarse;const query = {@@ -51,8 +61,8 @@ export function pointerQuery(isCoarse: boolean): PointerQuery {},dispatchEvent: () => false,} as unknown as MediaQueryList;- window.matchMedia = (media: string) =>- media.trim() === TOUCH_QUERY ? query : matchMedia(media);+ view.matchMedia = (media: string) =>+ media.trim() === TOUCH_QUERY ? query : answerOther(media);return {set(next) {if (next === coarse) {@@ -64,7 +74,11 @@ export function pointerQuery(isCoarse: boolean): PointerQuery {}},restore: () => {- window.matchMedia = matchMedia;+ if (own == null) {+ Reflect.deleteProperty(view, 'matchMedia');+ } else {+ view.matchMedia = own;+ }},};}diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.tsindex b6f9e7b9c9..597575ba6f 100644--- a/packages/core/src/gestures/fingerScroll.ts+++ b/packages/core/src/gestures/fingerScroll.ts@@ -25,6 +25,7 @@import {subscribeInput} from '../utils/inputStream';import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';import type {GestureHost} from './GestureHost';+import {isNode} from '../utils/nodeType';/*** Where the browser sends no `scrollend`, how long a finger-driven scroller@@ -66,7 +67,7 @@ function start(host: GestureHost, watch: Watch): () => void {const doc = host.document;const scrollerOf = (event: Event): Node | null => {const target = event.target === doc ? doc : event.target;- return target instanceof Node ? target : null;+ return isNode(target) ? target : null;};// A finger's scroll ends at the scroller's scrollend, or, where the// browser sends none, after a quiet spell.diff --git a/packages/core/src/gestures/haptics.ts b/packages/core/src/gestures/haptics.tsindex 7604c355cb..1a7bb5b962 100644--- a/packages/core/src/gestures/haptics.ts+++ b/packages/core/src/gestures/haptics.ts@@ -45,6 +45,7 @@ import {} from '../motion/uikit/gestures';import {isDisabledControl} from '../utils/pressDisabled';import {markHapticSwitch} from '../privateAttributes/hapticSwitch.stylex';+import {isHTMLElement} from '../utils/nodeType';/** Whether this browser vibrates at all. */export function canVibrate(): boolean {@@ -112,7 +113,9 @@ function swallow(event: Event): void {export function attachTapHaptic(label: HTMLLabelElement): () => void {const existing = label.control;if (- (existing instanceof HTMLInputElement && isSwitch(existing)) ||+ (isHTMLElement(existing) &&+ existing.localName === 'input' &&+ isSwitch(existing as HTMLInputElement)) ||(existing != null && label.htmlFor !== '')) {return () => {};@@ -143,7 +146,7 @@ export function attachTapHaptic(label: HTMLLabelElement): () => void {const onFocus = (event: FocusEvent) => {const previous = event.relatedTarget;if (- existing instanceof HTMLElement &&+ isHTMLElement(existing) &&existing.tabIndex >= 0 &&!isDisabledControl(existing)) {@@ -152,7 +155,7 @@ export function attachTapHaptic(label: HTMLLabelElement): () => void {if (doc.activeElement !== input) {return;}- if (previous instanceof HTMLElement && previous.isConnected) {+ if (isHTMLElement(previous) && previous.isConnected) {previous.focus({preventScroll: true});}if (doc.activeElement === input) {@@ -171,7 +174,7 @@ export function attachTapHaptic(label: HTMLLabelElement): () => void {if (existing != null) {label.prepend(input);if (- existing instanceof HTMLElement &&+ isHTMLElement(existing) &&!existing.hasAttribute('aria-labelledby') &&!existing.hasAttribute('aria-label')) {diff --git a/packages/core/src/gestures/nativeScroll.ts b/packages/core/src/gestures/nativeScroll.tsindex 43b5d5a493..6921a52d22 100644--- a/packages/core/src/gestures/nativeScroll.ts+++ b/packages/core/src/gestures/nativeScroll.ts@@ -38,6 +38,7 @@ import {SCROLLABLE_OVERFLOW as SCROLLABLE,type AllowedPans,} from '../utils/scrollView';+import {isElement} from '../utils/nodeType';export {parentAcrossShadow};@@ -77,7 +78,7 @@ function buildChain(target: Element, readsTouchAction: boolean): Chain {node != null;node = parentAcrossShadow(node)) {- if (!(node instanceof Element)) {+ if (!isElement(node)) {continue;}const style = view.getComputedStyle(node);@@ -111,7 +112,7 @@ function buildChain(target: Element, readsTouchAction: boolean): Chain {break;}}- if (!reachedRoot && root instanceof Element) {+ if (!reachedRoot && isElement(root)) {chain.push({element: root,x: allowX && SCROLLABLE.has(rootOverflow(doc, 'x')),@@ -204,10 +205,9 @@ export function createNativeScrollProbe(): NativeScrollProbe {let chain: Chain | null = null;const getChain = (): ChainEntry[] => {- chain ??=- target instanceof Element- ? buildChain(target, readsTouchAction)- : {entries: [], allowsPan: false};+ chain ??= isElement(target)+ ? buildChain(target, readsTouchAction)+ : {entries: [], allowsPan: false};return chain.entries;};return {@@ -239,8 +239,7 @@ export function createNativeScrollProbe(},get isInsideScroller(): boolean {return (- target instanceof Element &&- isInsideScrollView(target, {readsTouchAction})+ isElement(target) && isInsideScrollView(target, {readsTouchAction}));},};diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.tsindex 882614021f..ef646cecde 100644--- a/packages/core/src/gestures/types.ts+++ b/packages/core/src/gestures/types.ts@@ -10,6 +10,7 @@*/import type {SelectionLock} from './GestureRecognizer';+import {isElement} from '../utils/nodeType';/*** UIGestureRecognizer.State. A discrete recognizer goes straight from@@ -155,13 +156,16 @@ export const DEFAULT_ENVIRONMENT: GestureEnvironment = {return {width: window.innerWidth, height: window.innerHeight};},isRtl(view) {- if (typeof window === 'undefined' || !(view instanceof Element)) {+ if (typeof window === 'undefined' || !isElement(view)) {return false;}- return window.getComputedStyle(view).direction === 'rtl';+ return (+ (view.ownerDocument.defaultView ?? window).getComputedStyle(view)+ .direction === 'rtl'+ );},viewRect(view) {- if (typeof Element === 'undefined' || !(view instanceof Element)) {+ if (!isElement(view)) {return null;}const {left, top, width, height} = view.getBoundingClientRect();diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.tsindex 2d1cf15de1..7d3fa3ee06 100644--- a/packages/core/src/gestures/useFingerScroll.ts+++ b/packages/core/src/gestures/useFingerScroll.ts@@ -34,10 +34,7 @@ import {isFingerScroll, watchFingerScrolls} from './fingerScroll';import {getGestureHost} from './GestureHost';import {useAttachment} from '../hooks/useAttachment';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';--function isDocument(value: unknown): value is Document {- return typeof Document !== 'undefined' && value instanceof Document;-}+import {isDocument} from '../utils/nodeType';/** The document a scroller is in: itself, for the page's own scroll. */function documentOf(node: Element | Document): Document {diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex 4892e4d478..62c4adaa7b 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -19,6 +19,7 @@import {useCallback, useEffect, useRef} from 'react';import {isFocusLost} from '../utils/focusReturn';+import {isHTMLElement} from '../utils/nodeType';import {FOCUSABLE_SELECTOR} from './focusableSelector';import {useLayerDismissal} from '../Layer/useLayerDismissal';@@ -141,16 +142,6 @@ function trapDocument(container: HTMLElement | null): Document {return container?.ownerDocument ?? document;}-/**- * `instanceof HTMLElement`, asked of the node's own window: an element of a- * second document is an instance of that window's `HTMLElement`, not of this- * one's.- */-function isHTMLElement(node: Node | null): node is HTMLElement {- const view = node?.ownerDocument?.defaultView;- return view != null && node instanceof view.HTMLElement;-}-/*** Whether node `a` comes before node `b` in document order.*/diff --git a/packages/core/src/keyboard/keyboardHeight.ts b/packages/core/src/keyboard/keyboardHeight.tsindex 3a16909b8f..ef4cb6c8d4 100644--- a/packages/core/src/keyboard/keyboardHeight.ts+++ b/packages/core/src/keyboard/keyboardHeight.ts@@ -17,6 +17,7 @@*/import {subscribeInput} from '../utils/inputStream';+import {isNode} from '../utils/nodeType';import {layoutViewportHeight} from '../utils/layoutViewport';// A shortfall smaller than this is rounding, not a keyboard.@@ -95,12 +96,6 @@ interface KeyboardStore {const stores = new WeakMap<Window, KeyboardStore>();-// A window's capture phase also hears its document's events. A window's own-// event has no node as its target.-export function isNodeTarget(target: EventTarget | null): boolean {- return target != null && typeof (target as Node).nodeType === 'number';-}-function storeOf(win: Window): KeyboardStore {let store = stores.get(win);if (store == null) {@@ -132,9 +127,10 @@ function attach(win: Window, store: KeyboardStore): () => void {};viewport?.addEventListener('resize', onViewport);viewport?.addEventListener('scroll', onViewport);- // Only the window's own resize reports.+ // Only the window's own resize reports: a window's own event has no node as+ // its target.const stopResize = subscribeInput(win, 'resize', event => {- if (!isNodeTarget(event.target)) {+ if (!isNode(event.target)) {onViewport(event);}});@@ -361,7 +357,7 @@ export function refuseFocusReveal(// runs before the browser's own focus step. The window's own blur moves// no focus inside the document.const stop = subscribeInput(view, 'blur', event => {- if (isNodeTarget(event.target)) {+ if (isNode(event.target)) {listener(event);}});diff --git a/packages/core/src/keyboard/useMobileKeyboard.ts b/packages/core/src/keyboard/useMobileKeyboard.tsindex c59259c3fc..c753b2c74f 100644--- a/packages/core/src/keyboard/useMobileKeyboard.ts+++ b/packages/core/src/keyboard/useMobileKeyboard.ts@@ -20,6 +20,7 @@ import {useMediaQuery} from '../hooks/useMediaQuery';import {animatorFor, type Animator} from '../motion/animator';import {subscribeInput} from '../utils/inputStream';import {layoutViewportHeight} from '../utils/layoutViewport';+import {isDocument, isNode} from '../utils/nodeType';import {observeResize} from '../utils/sharedResizeObserver';import {TOUCH_QUERY} from '../utils/touchPresentation';import {@@ -27,7 +28,6 @@ import {findTextEntryControl,getKeyboardHeight,isKeyboardMeasurable,- isNodeTarget,isTextEntryControl,refuseFocusReveal,subscribeKeyboardHeight,@@ -824,7 +824,7 @@ export function useMobileKeyboard(// the page's own scroll moves the document.const stopDocumentScroll = subscribeInput(window, 'scroll', event => {const target = event.target;- if (!isNodeTarget(target) || (target as Node).nodeType === 9) {+ if (!isNode(target) || isDocument(target)) {handleDocumentScroll();}});diff --git a/packages/core/src/motion/presentation.ts b/packages/core/src/motion/presentation.tsindex 580ef91d3e..a443cf99cf 100644--- a/packages/core/src/motion/presentation.ts+++ b/packages/core/src/motion/presentation.ts@@ -34,6 +34,7 @@*/import {parentAcrossShadow} from '../utils/flatTree';+import {isElement} from '../utils/nodeType';/** How far an element is drawn from where the engine hit-tests it, CSS px. */export interface PresentedOffset {@@ -128,7 +129,7 @@ export function presentedOffsetOf(node != null;node = parentAcrossShadow(node)) {- const source = node instanceof Element ? sources.get(node) : undefined;+ const source = isElement(node) ? sources.get(node) : undefined;if (source != null) {const offset = source.offset(time);x += offset.x;diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.tsindex de9dcc8f39..12bda5792d 100644--- a/packages/core/src/utils/flatTree.ts+++ b/packages/core/src/utils/flatTree.ts@@ -11,6 +11,8 @@* gesture system) and the Layer module's input hold*/+import {isShadowRoot} from './nodeType';+/** The node's parent, crossing out of shadow roots. */export function parentAcrossShadow(node: Node): Node | null {// The flat tree the browser scrolls and dispatches through: a slotted node@@ -20,7 +22,7 @@ export function parentAcrossShadow(node: Node): Node | null {return slot;}if (node.parentNode != null) {- return node.parentNode instanceof ShadowRoot+ return isShadowRoot(node.parentNode)? node.parentNode.host: node.parentNode;}diff --git a/packages/core/src/utils/nodeType.test.ts b/packages/core/src/utils/nodeType.test.tsnew file mode 100644index 0000000000..d3e29b7733--- /dev/null+++ b/packages/core/src/utils/nodeType.test.ts@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file nodeType.test.ts+ * @input jsdom nodes from this window, from a same-origin iframe's window,+ * moved from this window into the iframe's document, and from a document+ * with no window+ * @output Checks that each guard holds for a node from any window, where+ * `instanceof` against this window's classes fails for the iframe's nodes+ * @position Unit tests for utils/nodeType.ts+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ isDocument,+ isElement,+ isHTMLElement,+ isNode,+ isShadowRoot,+} from './nodeType';++afterEach(() => {+ document.body.innerHTML = '';+});++/** A same-origin iframe's document, whose window has classes of its own. */+function frameDocument(): Document {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ return frame.contentDocument as Document;+}++describe('nodeType', () => {+ it("holds for a same-origin iframe's nodes, which this window's classes do not match", () => {+ const doc = frameDocument();+ doc.body.innerHTML = '<div id="host"></div><svg id="icon"></svg>';+ const host = doc.getElementById('host') as HTMLElement;+ const icon = doc.getElementById('icon') as Element;+ const shadow = host.attachShadow({mode: 'open'});+ const text = doc.createTextNode('x');+ expect(host instanceof Element).toBe(false);+ expect(isNode(text)).toBe(true);+ expect(isElement(host)).toBe(true);+ expect(isHTMLElement(host)).toBe(true);+ expect(isDocument(doc)).toBe(true);+ expect(isShadowRoot(shadow)).toBe(true);+ expect(isElement(icon)).toBe(true);+ expect(isHTMLElement(icon)).toBe(false);+ expect(isElement(text)).toBe(false);+ expect(isDocument(host)).toBe(false);+ expect(isShadowRoot(doc.createDocumentFragment())).toBe(false);+ });++ it("holds for this window's nodes", () => {+ document.body.innerHTML = '<div id="host"></div>';+ const host = document.getElementById('host') as HTMLElement;+ const shadow = host.attachShadow({mode: 'open'});+ expect(isNode(host)).toBe(true);+ expect(isElement(host)).toBe(true);+ expect(isHTMLElement(host)).toBe(true);+ expect(isDocument(document)).toBe(true);+ expect(isShadowRoot(shadow)).toBe(true);+ });++ it('refuses a value that is not a node', () => {+ for (const value of [null, undefined, 1, 'div', {}, {nodeType: '1'}]) {+ expect(isNode(value)).toBe(false);+ expect(isElement(value)).toBe(false);+ expect(isHTMLElement(value)).toBe(false);+ expect(isDocument(value)).toBe(false);+ expect(isShadowRoot(value)).toBe(false);+ }+ });++ it('holds for an element this window makes and then moves into a same-origin iframe', () => {+ const doc = frameDocument();+ const moved = document.createElement('div');+ const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ doc.body.append(moved, icon);+ // The element keeps this window's class while the iframe owns it.+ expect(moved.ownerDocument === doc).toBe(true);+ expect(isHTMLElement(moved)).toBe(true);+ expect(isHTMLElement(icon)).toBe(false);+ });++ it('holds for an element of a document with no window', () => {+ const doc = document.implementation.createHTMLDocument('');+ const element = doc.createElement('div');+ expect(doc.defaultView).toBeNull();+ expect(isHTMLElement(element)).toBe(true);+ });+});diff --git a/packages/core/src/utils/nodeType.ts b/packages/core/src/utils/nodeType.tsnew file mode 100644index 0000000000..56c4b7f551--- /dev/null+++ b/packages/core/src/utils/nodeType.ts@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file nodeType.ts+ * @input A value that may be a DOM node from any window+ * @output isNode, isElement, isHTMLElement, isDocument and isShadowRoot:+ * type guards that hold for a node from any window+ * @position Shared DOM checks for code that handles nodes and events from+ * another window's document, such as a same-origin iframe's or a popup's+ *+ * Each check reads the node type or namespace, not `instanceof`. A node from+ * another window belongs to that window's realm, where `instanceof` against+ * this window's classes is false. An element moved into another window's+ * document keeps the realm it was made in.+ */++/** Whether `value` is a DOM node, from this window or another one. */+export function isNode(value: unknown): value is Node {+ return (+ typeof value === 'object' &&+ value !== null &&+ typeof (value as {nodeType?: unknown}).nodeType === 'number'+ );+}++/** Whether `value` is an element, from this window or another one. */+export function isElement(value: unknown): value is Element {+ return isNode(value) && value.nodeType === 1;+}++/** Whether `value` is a document, from this window or another one. */+export function isDocument(value: unknown): value is Document {+ return isNode(value) && value.nodeType === 9;+}++/** Whether `value` is a shadow root, from this window or another one. */+export function isShadowRoot(value: unknown): value is ShadowRoot {+ return isNode(value) && value.nodeType === 11 && 'host' in value;+}++/**+ * Whether `value` is an HTML element, from this window or another one. The+ * namespace decides, so an element moved between windows' documents passes.+ */+export function isHTMLElement(value: unknown): value is HTMLElement {+ return (+ isElement(value) && value.namespaceURI === 'http://www.w3.org/1999/xhtml'+ );+}diff --git a/packages/core/src/utils/scrollView.test.ts b/packages/core/src/utils/scrollView.test.tsnew file mode 100644index 0000000000..0ee393ec7c--- /dev/null+++ b/packages/core/src/utils/scrollView.test.ts@@ -0,0 +1,56 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scrollView.test.ts+ * @input isInsideScrollView on elements in a same-origin iframe's document,+ * in jsdom, with the boxes' scroll sizes stubbed+ * @output A touch in another window's document finds the scroll box above it,+ * and a fixed bar there ends the walk (`spec:AST-094` FR11)+ * @position Unit tests for utils/scrollView.ts+ */++import {afterEach, describe, expect, it} from 'vitest';+import {isInsideScrollView} from './scrollView';++/** Gives `element` the scroll sizes of a box that overflows on y. */+function overflowsY(element: Element): void {+ Object.defineProperty(element, 'scrollHeight', {+ configurable: true,+ value: 400,+ });+ Object.defineProperty(element, 'clientHeight', {+ configurable: true,+ value: 100,+ });+}++/** A same-origin iframe's document; the iframe goes with the body's reset. */+function frameDocument(): Document {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ return frame.contentDocument as Document;+}++afterEach(() => {+ document.body.innerHTML = '';+});++describe("isInsideScrollView in another window's document (spec:AST-094 FR11)", () => {+ it('finds the scroll box above the touch', () => {+ const doc = frameDocument();+ doc.body.innerHTML =+ '<div id="box" style="overflow-y: auto"><button id="row">Row</button></div>';+ overflowsY(doc.getElementById('box') as Element);+ expect(isInsideScrollView(doc.getElementById('row') as Element)).toBe(true);+ });++ it('stops at a fixed bar, though the page under it scrolls', () => {+ const doc = frameDocument();+ doc.body.innerHTML =+ '<div id="bar" style="position: fixed"><button id="tab">Tab</button></div>';+ overflowsY(doc.scrollingElement ?? doc.documentElement);+ expect(isInsideScrollView(doc.getElementById('tab') as Element)).toBe(+ false,+ );+ });+});diff --git a/packages/core/src/utils/scrollView.ts b/packages/core/src/utils/scrollView.tsindex 62b7430def..789fb8d526 100644--- a/packages/core/src/utils/scrollView.ts+++ b/packages/core/src/utils/scrollView.ts@@ -13,6 +13,7 @@*/import {parentAcrossShadow} from './flatTree';+import {isElement} from './nodeType';/** Overflow values that let a box scroll. */export const SCROLLABLE_OVERFLOW: ReadonlySet<string> = new Set([@@ -98,7 +99,7 @@ export function isInsideScrollView(let panX = true;let panY = true;for (let node: Node | null = element; node != null;) {- if (node instanceof Element) {+ if (isElement(node)) {const style = view.getComputedStyle(node);if (readsTouchAction) {const pans = parseTouchAction(style.touchAction || 'auto');diff --git a/packages/core/src/utils/selectionLock.test.ts b/packages/core/src/utils/selectionLock.test.tsindex 0f2e2d84d7..a30a425471 100644--- a/packages/core/src/utils/selectionLock.test.ts+++ b/packages/core/src/utils/selectionLock.test.ts@@ -71,6 +71,33 @@ describe('lockSelection where iOS WebKit runs', () => {restore();}});++ it('locks an element whose inline style comes from another window (spec:AST-094 FR41)', () => {+ const restore = asIosWebKit();+ try {+ const get = mount('<a id="row" href="/next">Next</a>');+ // jsdom builds every window's style objects in this realm. In a browser,+ // another window's style fails `instanceof Object`, as an object with no+ // prototype does here.+ const setProperty = vi.fn();+ const style = Object.assign(Object.create(null) as CSSStyleDeclaration, {+ setProperty,+ getPropertyValue: () => '',+ getPropertyPriority: () => '',+ removeProperty: vi.fn(),+ });+ Object.defineProperty(get('row'), 'style', {+ configurable: true,+ value: style,+ });+ const release = lockSelection([get('row')], get('row'));+ expect(setProperty).toHaveBeenCalledWith('-webkit-touch-callout', 'none');+ expect(setProperty).toHaveBeenCalledWith('user-select', 'none');+ release();+ } finally {+ restore();+ }+ });});describe('lockSelection elsewhere', () => {diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.tsindex 9ca4f1f196..84e8c80d08 100644--- a/packages/core/src/utils/selectionLock.ts+++ b/packages/core/src/utils/selectionLock.ts@@ -35,6 +35,7 @@ import {} from './flatTree';import {subscribeInput} from './inputStream';import {isIosWebKit} from './touchQueries';+import {isElement, isNode} from './nodeType';/** What a held finger must not start on a control or a cell. */const SELECTION_LOCK = [@@ -679,7 +680,7 @@ function lockStyles(set: ReadonlySet<Element>): () => void {*/function isSelectableControl(node: unknown): node is HTMLInputElement {return (- node instanceof Element &&+ isElement(node) &&node.localName === 'input' &&!TEXT_ENTRY_TYPES.has((node as HTMLInputElement).type));@@ -687,12 +688,11 @@ function isSelectableControl(node: unknown): node is HTMLInputElement {/** Text a held finger edits: it places the caret there. */function isTextEntry(node: EventTarget | null): boolean {- const element =- node instanceof Element- ? node- : node instanceof Node- ? node.parentElement- : null;+ const element = isElement(node)+ ? node+ : isNode(node)+ ? node.parentElement+ : null;if (element == null) {return false;}@@ -705,8 +705,11 @@ function isTextEntry(node: EventTarget | null): boolean {return (element as HTMLElement).isContentEditable;}-/** An element's inline style, when it has one (HTML and SVG elements). */+/**+ * An element's inline style, when it has one (HTML and SVG elements). It is+ * checked as an object, so another window's style passes too.+ */function styleOf(element: Element): CSSStyleDeclaration | null {const style = (element as Partial<ElementCSSInlineStyle>).style;- return style instanceof Object ? style : null;+ return typeof style === 'object' && style !== null ? style : null;}