An open source design system that's fully customizable and agent ready
TypeScript
fix(core): one modality call per component, reading the component's own document (#9148)
Cindy Zhangb56b6d4fc6bd
diff --git a/.changeset/modality-one-call.md b/.changeset/modality-one-call.mdnew file mode 100644index 0000000000..ac3238ffbb--- /dev/null+++ b/.changeset/modality-one-call.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Components rendered into a same-origin iframe or a Document Picture-in-Picture window now read the last input in their own document for their keyboard focus rings and keyboard highlights (Slider, MultiSelector, DropdownMenu, ChatComposer, CommandPalette, panel search fields, menus), and for the ring on focus they move themselves. On the page, behavior is unchanged. Where an overlay returns focus on close is unchanged. vjeux wrote the original per-document fix, for Dialog (#8381); this extends it to every reader.++@cixzhangdiff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex d4ebd50e35..4be03d1c39 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -99,6 +99,7 @@ import {} from '../theme/tokens.stylex';import {useDevWarning} from '../hooks/useDevWarning';import {useScrollLock} from '../hooks/useScrollLock';+import {useMergedRefs} from '../hooks/useMergedRefs';import {mergeProps} from '../utils/mergeProps';import {LayerDepthProvider} from '../Layer/LayerDepthContext';import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';@@ -711,7 +712,8 @@ function StandaloneBottomSheet({[finalFocusRef, hasScrim, isOpen],);- useInteractionModalityTracking();+ const {ref: modalityRef} = useInteractionModalityTracking();+ const dialogComposedRef = useMergedRefs(dialogRef, modalityRef);useScrollLock(shouldPresent && hasScrim);useDevWarning('BottomSheet',@@ -797,7 +799,7 @@ function StandaloneBottomSheet({hasScrim && isExiting && styles.scrimClosing,!hasScrim && styles.dialogNonModal,)}- ref={dialogRef}+ ref={dialogComposedRef}// A non-modal sheet is hosted in the top layer as a manual popover// (no light dismiss, no backdrop), so sheets order by presentation// without a page-level z-index. Below the Popover API floor thediff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsxindex 6892c80c9c..f566909628 100644--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx@@ -527,7 +527,7 @@ function BreadcrumbMenuTrigger({// The menu's rows move focus with the last input// (`architecture:interaction-modality` INV1); this menu has no press model// to activate the tracking they read, so it activates it itself.- useInteractionModalityTracking();+ const {ref: modalityRef} = useInteractionModalityTracking();const popover = usePopover({hasLightDismiss: true,@@ -646,6 +646,7 @@ function BreadcrumbMenuTrigger({ref={useMergedRefs(ref as React.Ref<HTMLButtonElement>,buttonRef,+ modalityRef,popover.triggerRef,)}type="button"diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsxindex bdff0dd2f4..92b131148c 100644--- a/packages/core/src/Chat/ChatComposer.tsx+++ b/packages/core/src/Chat/ChatComposer.tsx@@ -54,11 +54,9 @@ import {ChatSendButton} from './ChatSendButton';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';+import {useMergedRefs} from '../hooks/useMergedRefs';import {focusOutlineStyles} from '../utils/focusOutline.stylex';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';// =============================================================================// Types@@ -394,8 +392,6 @@ export function ChatComposer(props: ChatComposerProps) {const [internalValue, setInternalValue] = useState('');const [hasKeyboardEditorFocus, setHasKeyboardEditorFocus] = useState(false);- useInteractionModalityTracking();-const isControlled = controlledValue !== undefined;const currentValue = isControlled ? controlledValue : internalValue;@@ -424,6 +420,8 @@ export function ChatComposer(props: ChatComposerProps) {const canSend = currentValue.trim().length > 0 && !isDisabled;const bodyRef = useRef<HTMLDivElement>(null);+ const {ref: modalityRef, readModality} = useInteractionModalityTracking();+ const bodyComposedRef = useMergedRefs(bodyRef, modalityRef);// Input slot registers its focus (and future) control here so the shell can// drive it without knowing its DOM shape. Stable ref — safe in the memoized@@ -458,11 +456,10 @@ export function ChatComposer(props: ChatComposerProps) {const handleBodyFocusCapture = useCallback((event: FocusEvent<HTMLDivElement>) => {setHasKeyboardEditorFocus(- isComposerEditor(event.target) &&- getInteractionModality() === 'keyboard',+ isComposerEditor(event.target) && readModality() === 'keyboard',);},- [],+ [readModality],);const handleBodyBlurCapture = useCallback(@@ -550,7 +547,7 @@ export function ChatComposer(props: ChatComposerProps) {{drawer}<div- ref={bodyRef}+ ref={bodyComposedRef}onClick={handleBodyClick}onPointerDownCapture={() => setHasKeyboardEditorFocus(false)}onFocusCapture={handleBodyFocusCapture}diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.tsxindex 867f35ae1d..6267a96563 100644--- a/packages/core/src/CommandPalette/CommandPaletteInput.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteInput.tsx@@ -37,10 +37,7 @@ import {useDialogContext} from '../Dialog/DialogContext';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -223,13 +220,13 @@ export function CommandPaletteInput({// Text-entry controls match :focus-visible after pointer focus in Chromium.// Keep the shared selector, but narrow its ring to focus acquired through// keyboard navigation so a click or pointer-opened palette stays unringed.- useInteractionModalityTracking();+ const {ref: modalityRef, readModality} = useInteractionModalityTracking();const handleFocus = useCallback((event: React.FocusEvent<HTMLInputElement>) => {- setIsKeyboardFocus(getInteractionModality() === 'keyboard');+ setIsKeyboardFocus(readModality() === 'keyboard');onFocus?.(event);},- [onFocus],+ [onFocus, readModality],);const handleBlur = useCallback((event: React.FocusEvent<HTMLInputElement>) => {@@ -312,7 +309,7 @@ export function CommandPaletteInput({</span><input{...props}- ref={useMergedRefs(ref, inputRef)}+ ref={useMergedRefs(ref, inputRef, modalityRef)}{...(isKeyboardFocus? focusOutlineProps.focusVisible(styles.input): focusOutlineProps.suppressed(styles.input))}diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex 261d77b712..97592f8164 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -76,11 +76,7 @@ import {DialogContext} from './DialogContext';import {themeProps} from '../utils/themeProps';import type {DialogVariantMap} from './index';import {focusOutlineProps} from '../utils/focusOutline.stylex';-import {- getInteractionModality,- trackInteractionModalityIn,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {focusForLastInput} from '../utils/focusReturn';import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';@@ -533,25 +529,17 @@ export function Dialog({[titleId, hasConsumerName],);- const mergedDialogRef = useMergedRefs(ref, attachDialog);-- // Capture the element that was focused when the dialog opened, for- // directional animation origin and focus restoration on close.- const triggerElementRef = useRef<HTMLElement | null>(null);-- useInteractionModalityTracking();-// Input in a second document (a same-origin iframe, a Document// Picture-in-Picture window) never reaches the page's listeners, so the// dialog's own document keeps its own last input for the focus return while// this Dialog is mounted, from before it opens until it unmounts.- useEffect(() => {- const ownerDocument = dialogRef.current?.ownerDocument;- if (ownerDocument == null || ownerDocument === document) {- return undefined;- }- return trackInteractionModalityIn(ownerDocument);- }, [isInline]);+ const {ref: modalityRef} = useInteractionModalityTracking();++ const mergedDialogRef = useMergedRefs(ref, attachDialog, modalityRef);++ // Capture the element that was focused when the dialog opened, for+ // directional animation origin and focus restoration on close.+ const triggerElementRef = useRef<HTMLElement | null>(null);// This runs in a layout effect so the capture lands before any descendant's// passive mount effect: all layout effects run before any passive effect,@@ -622,11 +610,7 @@ export function Dialog({// the last input in that element's own document calls for.const trigger = triggerElementRef.current;if (trigger) {- focusForLastInput(- trigger,- undefined,- getInteractionModality(trigger.ownerDocument),- );+ focusForLastInput(trigger);}triggerElementRef.current = null;}diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex a1282181e6..370e758c84 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -622,9 +622,13 @@ function DropdownMenuBottomSheet({const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)};const backLabel = t('@astryx.dropdownMenu.back');const buttonRef = useRef<HTMLElement>(null);+ // The trigger, where focus returns after the sheet closes, carries the+ // modality tracking for its document.+ const modality = useInteractionModalityTracking();// The caller's `button.ref` rides along with the sheet's own trigger ref.const triggerRef = useMergedRefs<HTMLButtonElement>(buttonRef as React.Ref<HTMLButtonElement>,+ modality.ref,button.ref,);const triggerId = useId();@@ -636,7 +640,7 @@ function DropdownMenuBottomSheet({onFocusReturnTargetFocus,prepareFocusReturn,resetFocusReturn,- } = useFocusReturnVisibility();+ } = useFocusReturnVisibility(modality);const viewHeadingRef = useRef<HTMLHeadingElement>(null);const previousSubmenuDepthRef = useRef(0);const [internalIsOpen, setInternalIsOpen] = useState(false);@@ -793,9 +797,14 @@ function DropdownMenuBottomSheet({</Heading>);// A stable ref: an inline one re-runs on every render (null, then the element).- const sheetTriggerRef = useCallback((el: HTMLElement | null) => {- buttonRef.current = el;- }, []);+ const sheetModalityRef = modality.ref;+ const sheetTriggerRef = useCallback(+ (el: HTMLElement | null) => {+ buttonRef.current = el;+ sheetModalityRef(el);+ },+ [sheetModalityRef],+ );return (<>{renderTrigger != null ? (@@ -950,14 +959,14 @@ function DropdownMenuPopover({const pendingControlledOpenRef = useRef(false);const suppressControlledRollbackHideRef = useRef(false);- useInteractionModalityTracking();+ const contentRef = useRef<HTMLDivElement | null>(null);+ const modality = useInteractionModalityTracking();const {isFocusRingSuppressed,onFocusReturnTargetFocus,prepareFocusReturn,resetFocusReturn,- } = useFocusReturnVisibility();- const contentRef = useRef<HTMLDivElement | null>(null);+ } = useFocusReturnVisibility(modality);const headerRef = useRef<HTMLDivElement | null>(null);const footerRef = useRef<HTMLDivElement | null>(null);const hasRegions = useMemo(@@ -1598,12 +1607,18 @@ function DropdownMenuPopover({// popover's anchor off the trigger and back: two inline-style writes on the// trigger per render of the menu.const popoverTriggerRef = popover.triggerRef;+ // The trigger, where focus returns, also carries the modality tracking for+ // its document.+ const modalityRef = modality.ref;const triggerRef = useCallback((el: HTMLElement | null) => {buttonRef.current = el;popoverTriggerRef(el);+ // Called with each node and with `null`, so its cleanup isn't returned+ // (a returned cleanup would stop React's `null` call to the others).+ modalityRef(el);},- [popoverTriggerRef],+ [popoverTriggerRef, modalityRef],);const consumerButtonRef = button.ref;const buttonTriggerRef = useCallback(@@ -1715,7 +1730,7 @@ function DropdownMenuPopover({)?.(event);if (event.target === event.currentTarget) {setIsMenuKeyboardFocused(- getInteractionModality() === 'keyboard',+ getInteractionModality(event.currentTarget) === 'keyboard',);}}}diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex ba205437fc..52fa94314d 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -1183,7 +1183,9 @@ export function DropdownMenuSubMenu(// on the menu element shows the ring the base style otherwise removes.const handleMenuFocus = (event: React.FocusEvent<HTMLDivElement>) => {if (hasRegions && event.target === event.currentTarget) {- setIsMenuKeyboardFocused(getInteractionModality() === 'keyboard');+ setIsMenuKeyboardFocused(+ getInteractionModality(event.currentTarget) === 'keyboard',+ );}};const handleMenuBlur = (event: React.FocusEvent<HTMLDivElement>) => {diff --git a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsxindex 0449745896..f903644e7a 100644--- a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx+++ b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx@@ -17,9 +17,10 @@ import {Icon, renderIconSlot} from '../Icon/Icon';import {List} from '../List/List';import {ListItem} from '../List/ListItem';import {useMenuPress} from '../hooks/useMenuPress';+import {useMergedRefs} from '../hooks/useMergedRefs';import {colorVars, spacingVars} from '../theme/tokens.stylex';import {rtlStyles} from '../utils/rtlStyles';-import {getInteractionModality} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import type {DropdownMenuItemData, DropdownMenuOption} from './DropdownMenu';import {isModifiedClick} from './menuItemRoles';@@ -68,6 +69,8 @@ export function MenuBottomSheetActionList({onOpenSubmenu: (item: DropdownMenuItemData) => void;}) {const listRef = useRef<HTMLUListElement>(null);+ const {ref: modalityRef, readModality} = useInteractionModalityTracking();+ const listComposedRef = useMergedRefs(listRef, modalityRef);// The press model: the row under a finger's RELEASE acts, and the// highlight (focus) follows the finger across the rows. The sheet is modal,// so a release outside it is the scrim's, not a dismissal of ours.@@ -90,7 +93,7 @@ export function MenuBottomSheetActionList({event.preventDefault();return;}- if (getInteractionModality() === 'pointer') {+ if (readModality() === 'pointer') {(event.currentTarget as HTMLElement).blur();}if (isSubmenu) {@@ -146,7 +149,7 @@ export function MenuBottomSheetActionList({return (<List- ref={listRef}+ ref={listComposedRef}density="spacious"xstyle={styles.list}{...menuPress.menuProps}>diff --git a/packages/core/src/Field/PanelSearchInput.secondDocument.test.tsx b/packages/core/src/Field/PanelSearchInput.secondDocument.test.tsxnew file mode 100644index 0000000000..e4d245bb3b--- /dev/null+++ b/packages/core/src/Field/PanelSearchInput.secondDocument.test.tsx@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PanelSearchInput.secondDocument.test.tsx+ * @input PanelSearchInput rendered into a same-origin iframe's document+ * @output Verifies its keyboard-focus ring reads the iframe's last input, not+ * the page's, through the one modality hook call+ * @position A non-Dialog reader of per-document interaction modality+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, describe, expect, it} from 'vitest';+import {PanelSearchInput} from './PanelSearchInput';++let root: Root | null = null;+let frame: HTMLIFrameElement | null = null;++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ frame?.remove();+ frame = null;+});++function renderInFrame() {+ frame = document.createElement('iframe');+ document.body.appendChild(frame);+ const frameDocument = frame.contentDocument!;+ const container = frameDocument.createElement('div');+ frameDocument.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root!.render(+ <PanelSearchInput+ label="Search"+ clearLabel="Clear search"+ value=""+ onValueChange={() => {}}+ />,+ );+ });+ const input = frameDocument.querySelector('input')!;+ return {frameDocument, input};+}++describe('PanelSearchInput in a second document', () => {+ it("rings on focus after keyboard input in its own document, though the page's last input was a pointer", () => {+ const {frameDocument, input} = renderInFrame();+ document.dispatchEvent(new Event('pointerdown'));+ frameDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ act(() => {+ input.focus();+ });+ expect(+ frameDocument.querySelector('[data-keyboard-focus="true"]'),+ ).not.toBeNull();+ });++ it("stays unringed after pointer input in its own document, though the page's last input was a key", () => {+ const {frameDocument, input} = renderInFrame();+ document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ frameDocument.dispatchEvent(new Event('pointerdown'));+ act(() => {+ input.focus();+ });+ expect(+ frameDocument.querySelector('[data-keyboard-focus="true"]'),+ ).toBeNull();+ });+});diff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsxindex 00ce2d7607..cb557dc001 100644--- a/packages/core/src/Field/PanelSearchInput.tsx+++ b/packages/core/src/Field/PanelSearchInput.tsx@@ -45,10 +45,8 @@ import type {StyleXStyles} from '@stylexjs/stylex';import {Icon} from '../Icon/Icon';import {InputClearButton} from './InputClearButton';import {mergeProps} from '../utils/mergeProps';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';+import {useMergedRefs} from '../hooks/useMergedRefs';import {colorVars,durationVars,@@ -220,14 +218,15 @@ export function PanelSearchInput({// stays `:focus-visible`, this only narrows it.const [isKeyboardFocus, setIsKeyboardFocus] = useState(false);- useInteractionModalityTracking();+ const {ref: modalityRef, readModality} = useInteractionModalityTracking();+ const mergedInputRef = useMergedRefs(ref, modalityRef);const handleFocus = useCallback((e: React.FocusEvent<HTMLInputElement>) => {- setIsKeyboardFocus(getInteractionModality() === 'keyboard');+ setIsKeyboardFocus(readModality() === 'keyboard');onFocus?.(e);},- [onFocus],+ [onFocus, readModality],);const handleBlur = useCallback(@@ -272,7 +271,7 @@ export function PanelSearchInput({)}><Icon icon="search" size="sm" color="secondary" xstyle={styles.icon} /><input- ref={ref}+ ref={mergedInputRef}type="text"aria-label={label}placeholder={placeholder}diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.tsindex 02c9243c57..16b9793c17 100644--- a/packages/core/src/Layer/useTouchTrigger.ts+++ b/packages/core/src/Layer/useTouchTrigger.ts@@ -39,10 +39,7 @@import {useCallback, useEffect, useRef, type RefObject} from 'react';import {currentGesture} from './gestureCounter';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTrackingFor} from '../utils/interactionModality';/*** How a hover layer behaves on a touch pointer.@@ -252,7 +249,7 @@ export function useTouchTrigger(// waiting. The next press, a cancel, the tap itself or unmounting calls it.const forgetPendingTapRef = useRef<(() => void) | null>(null);- useInteractionModalityTracking();+ const readModality = useInteractionModalityTrackingFor(triggerRef);const disarmOutsideDismiss = useCallback(() => {isTapOpenRef.current = false;@@ -307,8 +304,8 @@ export function useTouchTrigger(useEffect(() => () => forgetPendingTapRef.current?.(), []);const isTouchInteraction = useCallback(- () => isTouchPointerRef.current && getInteractionModality() === 'pointer',- [],+ () => isTouchPointerRef.current && readModality() === 'pointer',+ [readModality],);const handlePointerEnter = useCallback((event: PointerEvent) => {diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex 4224570f50..46b9b97223 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -20,6 +20,7 @@ import {} from 'vitest';import {act,+ cleanup,render,screen,fireEvent,@@ -34,6 +35,7 @@ import {type MultiSelectorChange,} from './MultiSelector';import {useRef, useState} from 'react';+import {createPortal} from 'react-dom';import {Dialog} from '../Dialog/Dialog';import {Icon} from '../Icon';import {InternationalizationProvider} from '../i18n';@@ -4583,6 +4585,67 @@ describe('MultiSelector option actions (grid)', () => {}});+ // A caller-rendered trigger in a same-origin iframe reads the iframe's last+ // input, as the built-in trigger does: after a click on the page and keys+ // in the iframe, the highlighted action cell takes the ring.+ it('rings the action cell after keyboard input in the iframe a caller-rendered trigger lives in', () => {+ const ring = stylex.create({+ active: {+ outlineWidth: focusVars['--focus-outline-width'],+ outlineStyle: focusVars['--focus-outline-style'],+ outlineColor: focusVars['--focus-outline-color'],+ outlineOffset: focusVars['--focus-outline-offset'],+ },+ });+ const ringClasses = stylex+ .props(ring.active)+ .className!.split(' ')+ .filter(token => /^x[a-z0-9]+$/.test(token));+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ const frameDocument = frame.contentDocument!;+ // The test setup's popover stand-ins, on the second window's prototype.+ const {prototype} = frameDocument.defaultView!.HTMLElement;+ prototype.showPopover = HTMLElement.prototype.showPopover;+ prototype.hidePopover = HTMLElement.prototype.hidePopover;+ prototype.togglePopover = HTMLElement.prototype.togglePopover;+ try {+ render(+ createPortal(+ <MultiSelector+ label="Labels"+ options={OPTIONS}+ value={[]}+ onChange={() => {}}+ renderTrigger={props => (+ <button type="button" {...props}>+ Pick labels+ </button>+ )}+ />,+ frameDocument.body,+ ),+ );+ const frameScreen = within(frameDocument.body);+ const opener = frameScreen.getByRole('button', {name: 'Pick labels'});+ fireEvent.click(opener);+ // The page saw a pointer; the iframe sees the keys.+ document.dispatchEvent(new Event('pointerdown'));+ // With a caller-rendered trigger the open grid holds focus and the keys.+ const grid = within(frameDocument.documentElement).getByRole('grid', h);+ fireEvent.keyDown(grid, {key: 'ArrowRight'});+ const bug = within(grid).getByRole('row', {name: 'Bug', ...h});+ const actionCell = bug.children[1] as HTMLElement;+ expect(grid).toHaveAttribute('aria-activedescendant', actionCell.id);+ for (const token of ringClasses) {+ expect(actionCell).toHaveClass(token);+ }+ } finally {+ cleanup();+ frame.remove();+ }+ });+describe('ring under mixed input', () => {const ringClasses = () => {const ring = stylex.create({diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex aa23936e92..c10e33e87d 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -77,10 +77,7 @@ import {useMultiCombobox} from './hooks';import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';import {joinAriaIDs} from '../utils/inputAria';import {devWarn, warnOnce} from '../utils/devWarning';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {useAnnounce} from '../hooks/useAnnounce';import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';@@ -1192,7 +1189,17 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// Read by the live region above so it speaks what this element renders.const emptyStateRef = useRef<HTMLDivElement>(null);const triggerRef = useRef<HTMLElement>(null);- const triggerButtonRef = useMergedRefs<HTMLElement>(triggerRef, ref);+ // A hover moves the highlight too, but the focus ring follows the shared+ // interaction modality (architecture:interaction-modality INV1): it is read+ // whenever a key or the pointer moves the highlight, so an action cell+ // highlighted after pointer input keeps the hover treatment and no ring.+ const triggerModality = useInteractionModalityTracking();+ const readModality = triggerModality.readModality;+ const triggerButtonRef = useMergedRefs<HTMLElement>(+ triggerRef,+ triggerModality.ref,+ ref,+ );const searchRef = useRef<HTMLInputElement>(null);const listboxRef = useRef<HTMLDivElement>(null);@@ -1448,6 +1455,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({onHide: handleLayerHide,onShow: handleLayerShow,triggerRef,+ triggerModality,isFocusReturnAlways: hasExternalTrigger,popoverOptions: {hasLightDismiss: true,@@ -1850,27 +1858,22 @@ export function MultiSelector<T extends MultiSelectorOptionType>({),});- // A hover moves the highlight too, but the focus ring follows the shared- // interaction modality (architecture:interaction-modality INV1): it is read- // whenever a key or the pointer moves the highlight, so an action cell- // highlighted after pointer input keeps the hover treatment and no ring.- useInteractionModalityTracking();const [isKeyboardHighlight, setIsKeyboardHighlight] = useState(- () => getInteractionModality() === 'keyboard',+ () => readModality() === 'keyboard',);const onKeyDown = useCallback((event: React.KeyboardEvent<HTMLElement>) => {onComboboxKeyDown(event);- setIsKeyboardHighlight(getInteractionModality() === 'keyboard');+ setIsKeyboardHighlight(readModality() === 'keyboard');},- [onComboboxKeyDown],+ [onComboboxKeyDown, readModality],);const onItemMouseEnter = useCallback((...args: Parameters<typeof onComboboxItemMouseEnter>) => {onComboboxItemMouseEnter(...args);- setIsKeyboardHighlight(getInteractionModality() === 'keyboard');+ setIsKeyboardHighlight(readModality() === 'keyboard');},- [onComboboxItemMouseEnter],+ [onComboboxItemMouseEnter, readModality],);// The trigger button owns its click so a consumer `onClick`, which lands on@@ -2541,7 +2544,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({if (el != null && !el.matches(FOCUSABLE_SELECTOR)) {el.tabIndex = -1;}- }, ref),+ }, triggerModality.ref, ref),id: triggerId,onClick: isEffectivelyReadOnly? onClickdiff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 5e4528be5c..723aa55d46 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -89,6 +89,7 @@ import {} from '../Field/fieldParts';import {composeEventHandlers} from '../utils/composeEventHandlers';import {useMergedRefs} from '../hooks/useMergedRefs';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';@@ -1038,8 +1039,10 @@ export function Selector<T extends SelectorOptionType>(// shorter inner button makes every size's selected row land too low.const anchorRef = useRef<HTMLDivElement>(null);const triggerRef = useRef<HTMLElement>(null);+ const triggerModality = useInteractionModalityTracking();const triggerButtonRef = useMergedRefs<HTMLButtonElement>(triggerRef as React.Ref<HTMLButtonElement>,+ triggerModality.ref,ref,);const searchRef = useRef<HTMLInputElement>(null);@@ -1181,6 +1184,7 @@ export function Selector<T extends SelectorOptionType>(onHide: handleLayerHide,onShow: handleLayerShow,triggerRef,+ triggerModality,popoverOptions: {hasLightDismiss: true,hasCloseButton: false,diff --git a/packages/core/src/Selector/useSelectorPresentation.ts b/packages/core/src/Selector/useSelectorPresentation.tsindex 1853c224d5..f9a31d7e8a 100644--- a/packages/core/src/Selector/useSelectorPresentation.ts+++ b/packages/core/src/Selector/useSelectorPresentation.ts@@ -26,6 +26,7 @@ import {type AdaptivePresentation,type ResolvedAdaptivePresentation,} from '../hooks/useAdaptivePresentation';+import type {InteractionModalityTracking} from '../utils/interactionModality';import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';interface UseSelectorPresentationOptions {@@ -34,6 +35,11 @@ interface UseSelectorPresentationOptions {onShow: () => void;popoverOptions: Omit<UsePopoverOptions, 'onHide' | 'onShow'>;triggerRef: RefObject<HTMLElement | null>;+ /**+ * The component's one modality tracking, its `ref` attached to the trigger,+ * so the returned trigger's ring follows the trigger's own document.+ */+ triggerModality: Pick<InteractionModalityTracking, 'readModality'>;/*** Return focus to the trigger on every close, even when a press already* moved focus to another element. A caller-rendered trigger needs this@@ -62,6 +68,7 @@ export function useSelectorPresentation({onShow,popoverOptions,triggerRef,+ triggerModality,isFocusReturnAlways = false,}: UseSelectorPresentationOptions): SelectorPresentationController {const resolvedPresentation = useAdaptivePresentation(presentation);@@ -84,7 +91,7 @@ export function useSelectorPresentation({onFocusReturnTargetFocus,prepareFocusReturn,resetFocusReturn,- } = useFocusReturnVisibility();+ } = useFocusReturnVisibility(triggerModality);onHideRef.current = onHide;onShowRef.current = onShow;diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsxindex d4e19910e6..47eeeb4196 100644--- a/packages/core/src/Slider/Slider.tsx+++ b/packages/core/src/Slider/Slider.tsx@@ -45,10 +45,7 @@ import type {InputStatus} from '../Field/types';import {mergeProps, rtlStyles} from '../utils';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {joinAriaIDs} from '../utils/inputAria';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {isRtlElement} from '../hooks/isRtlElement';import {type FieldInputBaseProps,@@ -560,16 +557,14 @@ export function Slider({ref, ...props}: SliderProps) {null,);- useInteractionModalityTracking();+ const {ref: modalityRef, readModality} = useInteractionModalityTracking();const handleThumbFocus = useCallback((thumbIndex: number, _e: FocusEvent<HTMLDivElement>) => {// A focused disabled thumb still shows the ring (spec:AST-085 FR6).- setKeyboardFocusThumb(- getInteractionModality() === 'keyboard' ? thumbIndex : null,- );+ setKeyboardFocusThumb(readModality() === 'keyboard' ? thumbIndex : null);},- [],+ [readModality],);const handleThumbBlur = useCallback((_e: FocusEvent<HTMLDivElement>) => {@@ -975,7 +970,7 @@ export function Slider({ref, ...props}: SliderProps) {!e.metaKey &&!e.altKey &&!e.ctrlKey &&- getInteractionModality() === 'keyboard'+ readModality() === 'keyboard') {setKeyboardFocusThumb(thumbIndex);}@@ -1055,6 +1050,7 @@ export function Slider({ref, ...props}: SliderProps) {minStepsBetweenThumbs,updateValue,fireChangeEnd,+ readModality,],);@@ -1274,6 +1270,7 @@ export function Slider({ref, ...props}: SliderProps) {ref={useMergedRefs(isRange ? ref : undefined,trackRef,+ modalityRef,disabledMessageTooltip.ref,)}{...(isRangediff --git a/packages/core/src/hooks/useFocusReturnVisibility.test.ts b/packages/core/src/hooks/useFocusReturnVisibility.test.tsnew file mode 100644index 0000000000..b023a35f1f--- /dev/null+++ b/packages/core/src/hooks/useFocusReturnVisibility.test.ts@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useFocusReturnVisibility.test.ts+ * @input useFocusReturnVisibility with an element in a second document+ * @output Verifies the returned-focus ring follows the last input in the+ * element's own document, not the page's+ * @position Unit coverage for useFocusReturnVisibility.ts+ */++import {act, renderHook} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {useFocusReturnVisibility} from './useFocusReturnVisibility';+import {useInteractionModalityTracking} from '../utils/interactionModality';++describe('useFocusReturnVisibility in a second document', () => {+ it("suppresses or keeps the ring by the element's own document's last input", () => {+ const secondDocument = document.implementation.createHTMLDocument();+ const trigger = secondDocument.createElement('button');+ const {result, unmount} = renderHook(() => {+ const modality = useInteractionModalityTracking();+ return {modality, ...useFocusReturnVisibility(modality)};+ });+ // The component attaches its tracking ref to the trigger.+ act(() => {+ result.current.modality.ref(trigger);+ });++ // The page saw a key; the trigger's document saw a pointer.+ document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ secondDocument.dispatchEvent(new Event('pointerdown'));+ act(() => result.current.prepareFocusReturn());+ expect(result.current.isFocusRingSuppressed).toBe(true);++ // The page saw a pointer; the trigger's document saw a key.+ document.dispatchEvent(new Event('pointerdown'));+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ act(() => result.current.prepareFocusReturn());+ expect(result.current.isFocusRingSuppressed).toBe(false);+ unmount();+ });+});diff --git a/packages/core/src/hooks/useFocusReturnVisibility.ts b/packages/core/src/hooks/useFocusReturnVisibility.tsindex d9af1b7723..61f9427983 100644--- a/packages/core/src/hooks/useFocusReturnVisibility.ts+++ b/packages/core/src/hooks/useFocusReturnVisibility.ts@@ -4,35 +4,38 @@/*** @file useFocusReturnVisibility.ts- * @input Uses the shared interaction-modality tracker+ * @input The component's shared interaction-modality tracking* @output Preserves returned focus while suppressing pointer-only focus rings* @position Internal focus-return policy for adaptive overlays*/import {useCallback, useState} from 'react';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import type {InteractionModalityTracking} from '../utils/interactionModality';-export function useFocusReturnVisibility() {+/**+ * Pass the component's one modality tracking (its `ref` attached to the+ * overlay's element or trigger) so the ring follows the last input in that+ * element's own document (a same-origin iframe, a Document Picture-in-Picture+ * window), not the page's.+ */+export function useFocusReturnVisibility({+ readModality,+}: Pick<InteractionModalityTracking, 'readModality'>) {const [isFocusRingSuppressed, setIsFocusRingSuppressed] = useState(false);- useInteractionModalityTracking();-const prepareFocusReturn = useCallback(() => {- setIsFocusRingSuppressed(getInteractionModality() === 'pointer');- }, []);+ setIsFocusRingSuppressed(readModality() === 'pointer');+ }, [readModality]);const resetFocusReturn = useCallback(() => {setIsFocusRingSuppressed(false);}, []);const onFocusReturnTargetFocus = useCallback(() => {- if (getInteractionModality() === 'keyboard') {+ if (readModality() === 'keyboard') {setIsFocusRingSuppressed(false);}- }, []);+ }, [readModality]);return {isFocusRingSuppressed,diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.tsindex 8313a32ade..451c2552c5 100644--- a/packages/core/src/hooks/useMenuPress.ts+++ b/packages/core/src/hooks/useMenuPress.ts@@ -69,7 +69,7 @@ import {import {useLongPress, type UseLongPressHandlers} from './useLongPress';import {edgeAutoscroll} from '../utils/edgeAutoscroll';import {focusForLastInput} from '../utils/focusReturn';-import {useInteractionModalityTracking} from '../utils/interactionModality';+import {useInteractionModalityTrackingFor} from '../utils/interactionModality';/** Marks a menu root that carries this press model. */export const MENU_PRESS_MARKER = 'data-astryx-menu-press';@@ -340,8 +340,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {const optionsRef = useRef(options);optionsRef.current = options;// The highlight, and the hover focus of the rows in this menu, follow the- // last input, which this tracks for the document.- useInteractionModalityTracking();+ // last input, which this tracks for the menu's own document.+ useInteractionModalityTrackingFor(options.menuRef);const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);const pointerIdRef = useRef<number | null>(null);diff --git a/packages/core/src/utils/focusReturn.test.ts b/packages/core/src/utils/focusReturn.test.tsindex 2dec110ded..1807d02078 100644--- a/packages/core/src/utils/focusReturn.test.ts+++ b/packages/core/src/utils/focusReturn.test.ts@@ -5,6 +5,7 @@ import {focusForLastInput, isFocusDetached} from './focusReturn';import {__resetInteractionModalityForTest,__startInteractionModalityTrackingForTest,+ __trackInteractionModalityInForTest,} from './interactionModality';describe('isFocusDetached', () => {@@ -117,3 +118,28 @@ describe('focusForLastInput', () => {expect(document.activeElement).toBe(element);});});++describe('focusForLastInput in a second document', () => {+ it("follows the last input in the element's own document by default", () => {+ __startInteractionModalityTrackingForTest();+ const secondDocument = document.implementation.createHTMLDocument();+ const release = __trackInteractionModalityInForTest(secondDocument);+ const button = secondDocument.createElement('button');+ secondDocument.body.appendChild(button);+ const focus = vi.spyOn(button, 'focus');++ // The page's last input was a pointer; the button's document saw a key.+ document.dispatchEvent(new Event('pointerdown'));+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ focusForLastInput(button);+ expect(focus).toHaveBeenLastCalledWith();++ // And the other way round: the page saw a key, the button's document a+ // pointer, so the ring is suppressed.+ document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ secondDocument.dispatchEvent(new Event('pointerdown'));+ focusForLastInput(button);+ expect(focus).toHaveBeenLastCalledWith({focusVisible: false});+ release();+ });+});diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.tsindex e9528330f0..bcb0477475 100644--- a/packages/core/src/utils/focusReturn.ts+++ b/packages/core/src/utils/focusReturn.ts@@ -46,9 +46,11 @@ export function isFocusDetached(doc: Document = document): boolean {* autofocus target, the control that opened a Dialog, or a menu trigger the* caller renders. Pass `options` (for example `preventScroll`) as to `focus()`.*- * `modality` defaults to the page's last input. A caller moving focus inside a- * second document (a same-origin iframe, a Document Picture-in-Picture window)- * passes that document's, which it tracks with `trackInteractionModalityIn`.+ * `modality` defaults to the last input in the element's own document: the+ * page's for an element on the page, and a second document's (a same-origin+ * iframe, a Document Picture-in-Picture window) for an element there, which+ * the component tracks by passing its element's ref to+ * `useInteractionModalityTracking`.** Make sure modality tracking is active (`useInteractionModalityTracking()`)* in the component that calls this.@@ -56,7 +58,7 @@ export function isFocusDetached(doc: Document = document): boolean {export function focusForLastInput(element: HTMLElement,options?: FocusOptions,- modality: InteractionModality = getInteractionModality(),+ modality: InteractionModality = getInteractionModality(element),): void {// A text-entry field paints its own focus treatment to show where typing// goes, and an extra blur there can run validation or mark it touched. Thediff --git a/packages/core/src/utils/interactionModality.test.ts b/packages/core/src/utils/interactionModality.test.tsindex 3d54d18e75..1431a27fc6 100644--- a/packages/core/src/utils/interactionModality.test.ts+++ b/packages/core/src/utils/interactionModality.test.ts@@ -8,7 +8,9 @@* @position Unit coverage for interactionModality.ts*/-import {afterEach, describe, expect, it, vi} from 'vitest';+import type {ReactNode} from 'react';+import {afterEach, describe, expect, it, vi, type MockInstance} from 'vitest';+import {renderHook} from '@testing-library/react';const isolatedDocument = document.implementation.createHTMLDocument();@@ -95,7 +97,7 @@ describe('interactionModality', () => {vi.stubGlobal('document', pageDocument);const tracker = await loadTracker();tracker.__startInteractionModalityTrackingForTest();- tracker.trackInteractionModalityIn(secondDocument);+ tracker.__trackInteractionModalityInForTest(secondDocument);pageDocument.dispatchEvent(new Event('pointerdown'));secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}));@@ -113,8 +115,10 @@ describe('interactionModality', () => {const secondDocument = document.implementation.createHTMLDocument();const tracker = await loadTracker();const removeEventListener = vi.spyOn(secondDocument, 'removeEventListener');- const releaseFirst = tracker.trackInteractionModalityIn(secondDocument);- const releaseSecond = tracker.trackInteractionModalityIn(secondDocument);+ const releaseFirst =+ tracker.__trackInteractionModalityInForTest(secondDocument);+ const releaseSecond =+ tracker.__trackInteractionModalityInForTest(secondDocument);secondDocument.dispatchEvent(new Event('pointerdown'));expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');@@ -132,6 +136,263 @@ describe('interactionModality', () => {expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');});+ it("tracks a hook consumer's object-ref document until its last consumer unmounts", async () => {+ const tracker = await loadTracker();+ const secondDocument = document.implementation.createHTMLDocument();+ const addEventListener = vi.spyOn(secondDocument, 'addEventListener');+ const removeEventListener = vi.spyOn(secondDocument, 'removeEventListener');+ const elementRef = {current: secondDocument.createElement('div')};++ const first = renderHook(() =>+ tracker.useInteractionModalityTrackingFor(elementRef),+ );+ const second = renderHook(() =>+ tracker.useInteractionModalityTrackingFor(elementRef),+ );+ // One listener pair for the document, however many components track it.+ expect(+ addEventListener.mock.calls.filter(([type]) => type === 'pointerdown'),+ ).toHaveLength(1);+ secondDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');++ // A re-render keeps the same tracking; it neither adds nor drops it.+ first.rerender();+ expect(+ addEventListener.mock.calls.filter(([type]) => type === 'pointerdown'),+ ).toHaveLength(1);+ expect(removeEventListener).not.toHaveBeenCalled();++ first.unmount();+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');+ expect(removeEventListener).not.toHaveBeenCalled();++ // The last component in that document unmounts: tracking there stops.+ second.unmount();+ expect(removeEventListener.mock.calls.map(([type]) => type).sort()).toEqual(+ ['keydown', 'pointerdown'],+ );+ secondDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');+ });++ it("keeps the page's document-lifetime tracking for a component on the page", async () => {+ const tracker = await loadTracker();+ const removeEventListener = vi.spyOn(document, 'removeEventListener');+ const elementRef = {current: document.createElement('div')};+ const {unmount} = renderHook(() =>+ tracker.useInteractionModalityTrackingFor(elementRef),+ );+ document.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality()).toBe('pointer');+ unmount();+ expect(+ removeEventListener.mock.calls.filter(+ ([type]) => type === 'pointerdown' || type === 'keydown',+ ),+ ).toHaveLength(0);+ });++ it('moves the tracking when the element moves to another document', async () => {+ const tracker = await loadTracker();+ const firstDocument = document.implementation.createHTMLDocument();+ const secondDocument = document.implementation.createHTMLDocument();+ const firstRemove = vi.spyOn(firstDocument, 'removeEventListener');+ const elementRef: {current: Element | null} = {+ current: firstDocument.createElement('div'),+ };+ const {rerender, unmount} = renderHook(() =>+ tracker.useInteractionModalityTrackingFor(elementRef),+ );+ elementRef.current = secondDocument.createElement('div');+ rerender();+ expect(firstRemove.mock.calls.map(([type]) => type).sort()).toEqual([+ 'keydown',+ 'pointerdown',+ ]);+ secondDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');+ unmount();+ });++ it('releases an object-ref document when the element detaches, and holds one under StrictMode replay', async () => {+ const tracker = await loadTracker();+ const {StrictMode, createElement} = await import('react');+ const secondDocument = document.implementation.createHTMLDocument();+ const addEventListener = vi.spyOn(secondDocument, 'addEventListener');+ const removeEventListener = vi.spyOn(secondDocument, 'removeEventListener');+ const elementRef: {current: Element | null} = {+ current: secondDocument.createElement('div'),+ };+ const listeners = (spy: typeof addEventListener) =>+ spy.mock.calls.filter(([type]) => type === 'pointerdown').length;++ const {rerender, unmount} = renderHook(+ () => tracker.useInteractionModalityTrackingFor(elementRef),+ {wrapper: ({children}) => createElement(StrictMode, null, children)},+ );+ // StrictMode replays the effects; one hold remains.+ expect(listeners(addEventListener) - listeners(removeEventListener)).toBe(+ 1,+ );+ secondDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');++ // `null` detachment releases the document.+ elementRef.current = null;+ rerender();+ expect(listeners(addEventListener) - listeners(removeEventListener)).toBe(+ 0,+ );++ // Re-attaching tracks it again; unmount releases it.+ elementRef.current = secondDocument.createElement('div');+ rerender();+ expect(listeners(addEventListener) - listeners(removeEventListener)).toBe(+ 1,+ );+ unmount();+ expect(listeners(addEventListener) - listeners(removeEventListener)).toBe(+ 0,+ );+ });++ describe('the callback ref a component attaches', () => {+ async function renderInFrame(element: ReactNode) {+ const {createRoot} = await import('react-dom/client');+ const {act} = await import('react');+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ const frameDocument = frame.contentDocument!;+ const container = frameDocument.createElement('div');+ frameDocument.body.appendChild(container);+ const root = createRoot(container);+ const render = async (next: ReactNode) => {+ await act(async () => {+ root.render(next);+ });+ };+ await render(element);+ return {+ frameDocument,+ render,+ unmount: async () => {+ await act(async () => {+ root.unmount();+ });+ frame.remove();+ },+ };+ }++ function listenerCount(add: MockInstance, remove: MockInstance) {+ const count = (spy: MockInstance) =>+ spy.mock.calls.filter(([type]) => type === 'pointerdown').length;+ return count(add) - count(remove);+ }++ it('holds the element document once, keeps it across re-renders, and releases it with the last component', async () => {+ const tracker = await loadTracker();+ const {createElement: h, Fragment} = await import('react');+ function Probe() {+ const {ref} = tracker.useInteractionModalityTracking();+ return h('div', {ref});+ }+ const both = h(+ Fragment,+ null,+ h(Probe, {key: 'a'}),+ h(Probe, {key: 'b'}),+ );+ const frame = await renderInFrame(both);+ const add = vi.spyOn(frame.frameDocument, 'addEventListener');+ const remove = vi.spyOn(frame.frameDocument, 'removeEventListener');+ // Spies attach after the first render; re-render to prove no churn.+ await frame.render(both);+ expect(add).not.toHaveBeenCalled();+ expect(remove).not.toHaveBeenCalled();+ frame.frameDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(frame.frameDocument)).toBe(+ 'pointer',+ );++ await frame.render(h(Fragment, null, h(Probe, {key: 'a'})));+ expect(remove).not.toHaveBeenCalled();+ await frame.render(h(Fragment, null));+ expect(remove.mock.calls.map(([type]) => type).sort()).toEqual([+ 'keydown',+ 'pointerdown',+ ]);+ await frame.unmount();+ });++ it('releases the old node before holding a replacement, and holds one under StrictMode', async () => {+ const tracker = await loadTracker();+ const {createElement: h, StrictMode} = await import('react');+ function Probe({tag}: {tag: 'div' | 'span'}) {+ const {ref} = tracker.useInteractionModalityTracking();+ return h(tag, {ref});+ }+ const frame = await renderInFrame(+ h(StrictMode, null, h(Probe, {tag: 'div'})),+ );+ const add = vi.spyOn(frame.frameDocument, 'addEventListener');+ const remove = vi.spyOn(frame.frameDocument, 'removeEventListener');+ // A different tag replaces the node: the old hold releases first, so the+ // document's listeners are removed and added back, one pair at the end.+ await frame.render(h(StrictMode, null, h(Probe, {tag: 'span'})));+ expect(listenerCount(add, remove)).toBe(0);+ expect(remove.mock.invocationCallOrder[0]).toBeLessThan(+ add.mock.invocationCallOrder[0],+ );+ frame.frameDocument.dispatchEvent(new Event('pointerdown'));+ expect(tracker.getInteractionModality(frame.frameDocument)).toBe(+ 'pointer',+ );+ await frame.unmount();+ expect(listenerCount(add, remove)).toBe(-1);+ });++ it('reads the element document, and the page before it attaches', async () => {+ const tracker = await loadTracker();+ const {result} = renderHook(() =>+ tracker.useInteractionModalityTracking(),+ );+ document.dispatchEvent(new Event('pointerdown'));+ expect(result.current.readModality()).toBe('pointer');+ const secondDocument = document.implementation.createHTMLDocument();+ const node = secondDocument.createElement('div');+ const cleanup = result.current.ref(node);+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ expect(result.current.readModality()).toBe('keyboard');+ // React's ref cleanup and a later `null` call release it only once.+ const remove = vi.spyOn(secondDocument, 'removeEventListener');+ cleanup?.();+ result.current.ref(null);+ expect(+ remove.mock.calls.filter(([type]) => type === 'pointerdown'),+ ).toHaveLength(1);+ // A detached element no longer answers from its old document.+ document.dispatchEvent(new Event('pointerdown'));+ expect(result.current.readModality()).toBe('pointer');+ });++ it('forgets the node when React runs the ref cleanup instead of a null call', async () => {+ const tracker = await loadTracker();+ const {result} = renderHook(() =>+ tracker.useInteractionModalityTracking(),+ );+ const secondDocument = document.implementation.createHTMLDocument();+ const cleanup = result.current.ref(secondDocument.createElement('div'));+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));+ document.dispatchEvent(new Event('pointerdown'));+ expect(result.current.readModality()).toBe('keyboard');+ cleanup?.();+ expect(result.current.readModality()).toBe('pointer');+ });+ });+it('uses the keyboard-safe default without a document', async () => {vi.stubGlobal('document', undefined);const serverModule = await loadTracker();diff --git a/packages/core/src/utils/interactionModality.ts b/packages/core/src/utils/interactionModality.tsindex abfd8829aa..babb199b9f 100644--- a/packages/core/src/utils/interactionModality.ts+++ b/packages/core/src/utils/interactionModality.ts@@ -5,10 +5,13 @@/*** @file interactionModality.ts* @input Global pointerdown/keydown events- * @output `useInteractionModalityTracking()` activates document-lifetime tracking;- * `getInteractionModality()` reads how the user last interacted;- * `trackInteractionModalityIn(doc)` and `getInteractionModality(doc)` do the- * same for a second document+ * @output `useInteractionModalityTracking()` activates tracking for the page and+ * returns a callback ref that tracks the element's second document, if any,+ * with a reader for that element's own document;+ * `useInteractionModalityTrackingFor(objectRef)` does the same for hooks+ * that receive a consumer's object ref;+ * `getInteractionModality(target?)` reads how the user last interacted in a+ * node's or document's own document (the page by default)* @position Internal document-wide singleton; used where `:focus-visible` alone* is too broad*@@ -31,12 +34,20 @@* between consumers is not lost. A second document (a same-origin iframe, a* Document Picture-in-Picture window) gets its own store when a component* tracks it, since input there never reaches the page's listeners; its- * listeners stay only while a consumer there is mounted. Importing this module+ * listeners stay only while a consumer there is mounted. A component attaches+ * the one hook's callback ref to its element and gets both; it never tracks a+ * document itself. Importing this module* has no DOM side effects, and server rendering keeps the keyboard-safe* default.*/-import {useEffect} from 'react';+import {+ useCallback,+ useEffect,+ useRef,+ type RefCallback,+ type RefObject,+} from 'react';export type InteractionModality = 'keyboard' | 'pointer';@@ -86,15 +97,20 @@ function getStore(targetDocument: Document): InteractionModalityStore {return store;}-function trackInteractionModality(): () => void {- if (typeof document === 'undefined') {- return () => {};+/**+ * Start or stop hearing a document's input. The one place that listens, so a+ * change in how input is heard touches nothing else.+ */+function setListening(+ targetDocument: Document,+ store: InteractionModalityStore,+ isListening: boolean,+): void {+ if (store.isListening === isListening) {+ return;}-- const targetDocument = document;- const store = getStore(targetDocument);- if (!store.isListening) {- store.isListening = true;+ store.isListening = isListening;+ if (isListening) {targetDocument.addEventListener('pointerdown', store.onPointerDown, {capture: true,passive: true,@@ -103,45 +119,42 @@ function trackInteractionModality(): () => void {capture: true,passive: true,});+ } else {+ targetDocument.removeEventListener('pointerdown', store.onPointerDown, {+ capture: true,+ });+ targetDocument.removeEventListener('keydown', store.onKeyDown, {+ capture: true,+ });}+}++function trackInteractionModality(): () => void {+ if (typeof document === 'undefined') {+ return () => {};+ }++ setListening(document, getStore(document), true);// The document owns these listeners once activated. Removing them when the// last consumer unmounts would miss input before the next consumer mounts.return () => {};}-/** Activate shared modality tracking when the first consumer mounts. */-export function useInteractionModalityTracking(): void {- useEffect(() => trackInteractionModality(), []);-}-/*** Track a second document while a consumer there is mounted: a component an* app renders into a same-origin iframe or a Document Picture-in-Picture* window gets input there that never reaches the page's listeners. The first* consumer installs the document's listener pair and the last one's cleanup- * removes it. Read the value with `getInteractionModality(doc)`. The page's- * own document keeps its document-lifetime listeners.+ * removes it. The page's own document keeps its document-lifetime listeners.*/-export function trackInteractionModalityIn(- targetDocument: Document,-): () => void {+function trackInteractionModalityIn(targetDocument: Document): () => void {if (typeof document !== 'undefined' && targetDocument === document) {return trackInteractionModality();}const store = getStore(targetDocument);store.consumers = (store.consumers ?? 0) + 1;- if (store.consumers === 1) {- store.isListening = true;- targetDocument.addEventListener('pointerdown', store.onPointerDown, {- capture: true,- passive: true,- });- targetDocument.addEventListener('keydown', store.onKeyDown, {- capture: true,- passive: true,- });- }+ setListening(targetDocument, store, true);let isReleased = false;return () => {if (isReleased) {@@ -150,21 +163,126 @@ export function trackInteractionModalityIn(isReleased = true;store.consumers = (store.consumers ?? 1) - 1;if (store.consumers === 0) {- store.isListening = false;- targetDocument.removeEventListener('pointerdown', store.onPointerDown, {- capture: true,- });- targetDocument.removeEventListener('keydown', store.onKeyDown, {- capture: true,- });+ setListening(targetDocument, store, false);}};}-/** How the user last interacted with the page, or with `targetDocument`. */+/** What a component gets from its one modality call. */+export type InteractionModalityTracking = {+ /**+ * Attach to the element the component renders (merge it with the element's+ * other refs with useMergedRefs, or call it with each node and `null` from+ * a callback ref of the component's own without returning its cleanup).+ * While the element lives in a second document (a same-origin iframe, a+ * Document Picture-in-Picture window), that document is tracked; detaching+ * or replacing the node releases it first (INV6).+ */+ ref: RefCallback<Element>;+ /** How the user last interacted in the element's own document. */+ readModality: () => InteractionModality;+};++/**+ * A second-document hold for the node a ref callback receives: called with+ * each node and with `null`, it releases the previous document before it holds+ * a new one, and its returned cleanup releases it too, so React's ref cleanup+ * and `null` calls both work and a release never runs twice.+ */+function holdNodeDocument(+ node: Element | null,+ previous: {release: (() => void) | null},+): (() => void) | undefined {+ previous.release?.();+ previous.release = null;+ const ownerDocument = node?.ownerDocument;+ if (+ ownerDocument == null ||+ (typeof document !== 'undefined' && ownerDocument === document)+ ) {+ return undefined;+ }+ const release = trackInteractionModalityIn(ownerDocument);+ previous.release = release;+ return () => {+ release();+ if (previous.release === release) {+ previous.release = null;+ }+ };+}++/**+ * Activate shared modality tracking when the first consumer mounts, and read+ * it for the element the component renders: attach the returned `ref` to that+ * element. The component makes this one call and adds no effect, listener or+ * tracker of its own for modality.+ */+export function useInteractionModalityTracking(): InteractionModalityTracking {+ useEffect(() => trackInteractionModality(), []);+ const nodeRef = useRef<Element | null>(null);+ const holdRef = useRef<{release: (() => void) | null}>({release: null});+ const ref = useCallback((node: Element | null) => {+ nodeRef.current = node;+ const release = holdNodeDocument(node, holdRef.current);+ // React's ref cleanup runs instead of a `null` call; it must also forget+ // the detached node, so the reader never answers from a document whose+ // listeners are gone.+ return () => {+ release?.();+ if (nodeRef.current === node) {+ nodeRef.current = null;+ }+ };+ }, []);+ const readModality = useCallback(+ () => getInteractionModality(nodeRef.current),+ [],+ );+ return {ref, readModality};+}++/**+ * The same, for a hook that receives an object ref its consumer owns+ * (useMenuPress's `menuRef`, useTouchTrigger's trigger), so it cannot attach a+ * callback ref. After every commit it holds the ref's CURRENT owner document,+ * and the same Effect's cleanup releases it (INV3), so a detached, replaced or+ * moved node releases the old document before the new one is held (INV6).+ */+export function useInteractionModalityTrackingFor(+ elementRef: RefObject<Element | null>,+): () => InteractionModality {+ useEffect(() => trackInteractionModality(), []);+ useEffect(() => {+ const ownerDocument = elementRef.current?.ownerDocument;+ if (+ ownerDocument == null ||+ (typeof document !== 'undefined' && ownerDocument === document)+ ) {+ return undefined;+ }+ return trackInteractionModalityIn(ownerDocument);+ });+ return useCallback(+ () => getInteractionModality(elementRef.current),+ [elementRef],+ );+}++/**+ * How the user last interacted with the page, or in `target`'s own document+ * (a document, or any node in one: an element in a same-origin iframe or a+ * Document Picture-in-Picture window answers for that document).+ */export function getInteractionModality(- targetDocument?: Document,+ target?: Document | Node | null,): InteractionModality {+ const targetDocument =+ target == null+ ? null+ : target.nodeType === 9+ ? (target as Document)+ : target.ownerDocument;if (targetDocument != null) {return getStore(targetDocument).modality;}@@ -183,3 +301,6 @@ export function __resetInteractionModalityForTest(): void {/** Test-only: activate the tracker without rendering a hook. */export const __startInteractionModalityTrackingForTest =trackInteractionModality;++/** Test-only: track a second document without rendering a hook. */+export const __trackInteractionModalityInForTest = trackInteractionModalityIn;