Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(core): share interaction modality globally (#5881)

Cindy Zhangde72688e7165
diff --git a/.changeset/global-interaction-modality.md b/.changeset/global-interaction-modality.md
new file mode 100644
index 0000000000..5e459ed225
--- /dev/null
+++ b/.changeset/global-interaction-modality.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Core: track keyboard and pointer modality once per document instead of initializing global listeners from every consuming component.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index 547f3a1be3..522ad60cfb 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -76,6 +76,30 @@
"next": ".astryx-chat-message-bubble[data-sender=\"user\"]"
}
},
+ {
+ "component": "DropdownMenu",
+ "storyId": "core-dropdownmenu--alignment-end",
+ "dims": ["D4"],
+ "setup": {
+ "click": "button:has-text(\"Row actions\")"
+ },
+ "selectors": {
+ "overlay": ".astryx-dropdown-menu",
+ "overlayRoot": "body"
+ }
+ },
+ {
+ "component": "Layer",
+ "storyId": "core-layer--placements",
+ "dims": ["D4"],
+ "setup": {
+ "click": ["button:has-text(\"end\")", "button:has-text(\"Trigger\")"]
+ },
+ "selectors": {
+ "overlay": "[popover]:popover-open",
+ "overlayRoot": "body"
+ }
+ },
{
"component": "Lightbox",
"storyId": "core-lightbox--gallery",
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 10bc3fe144..824eb7808a 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -1,4 +1,8 @@
[
+ {
+ "component": "core/Field",
+ "reason": "The Core/Field stories use block-flow labels, controls, descriptions, and status text without directional icons, side-specific placement, order, scrolling, dragging, overlays, or keyboard behavior."
+ },
{
"component": "core/Spinner",
"reason": "No direction-sensitive visual, layout, or behavior. The ring is a concentric SVG — two <circle> elements sharing one center, sized by diameter and stroke, with no physical inset, offset, or asymmetry to mirror. Its only layout is the optional label wrapper, which is flexDirection: column + alignItems: center, so the label stacks below the ring on both axes' terms rather than beside it. The rotation keyframe (0deg to 360deg) is deliberately absolute: a loading spinner turns the same way in every locale, and mirroring it would be a bug, not RTL support."
diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsx
index b337f6d422..8776485f8a 100644
--- a/packages/core/src/Chat/ChatComposer.tsx
+++ b/packages/core/src/Chat/ChatComposer.tsx
@@ -25,7 +25,6 @@
import React, {
useState,
- useEffect,
useCallback,
useRef,
useMemo,
@@ -57,7 +56,7 @@ import {useTranslator} from '../i18n';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
// =============================================================================
@@ -372,9 +371,7 @@ export function ChatComposer(props: ChatComposerProps) {
const [internalValue, setInternalValue] = useState('');
const [hasKeyboardEditorFocus, setHasKeyboardEditorFocus] = useState(false);
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
const isControlled = controlledValue !== undefined;
const currentValue = isControlled ? controlledValue : internalValue;
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 9907099729..e84eafb795 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -80,7 +80,7 @@ import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
import {useTranslator} from '../i18n';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
@@ -605,9 +605,7 @@ function DropdownMenuPopover({
const isControlled = controlledIsOpen !== undefined;
const isOpen = isControlled ? controlledIsOpen : internalIsOpen;
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
// Keyboard dismissal returns focus to the trigger. Pointer dismissal leaves
// focus where the browser put it; Safari can otherwise paint a focus-visible
diff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsx
index 37d23e056a..4f436aad99 100644
--- a/packages/core/src/Field/PanelSearchInput.tsx
+++ b/packages/core/src/Field/PanelSearchInput.tsx
@@ -39,14 +39,14 @@
* that use it, not public API.
*/
-import {useCallback, useEffect, useState, type Ref} from 'react';
+import {useCallback, useState, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Icon} from '../Icon';
import {InputClearButton} from './InputClearButton';
import {mergeProps} from '../utils';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
import {
colorVars,
@@ -207,9 +207,7 @@ export function PanelSearchInput({
// stays `:focus-visible`, this only narrows it.
const [isKeyboardFocus, setIsKeyboardFocus] = useState(false);
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
const handleFocus = useCallback(
(e: React.FocusEvent<HTMLInputElement>) => {
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 41d859683b..cb027d3ffc 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -29,7 +29,7 @@
import {useCallback, useEffect, useRef, type RefObject} from 'react';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
/**
@@ -235,9 +235,7 @@ export function useTouchTrigger(
null,
);
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
const disarmOutsideDismiss = useCallback(() => {
isTapOpenRef.current = false;
diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsx
index 9f274dd91a..5199a8da73 100644
--- a/packages/core/src/Slider/Slider.tsx
+++ b/packages/core/src/Slider/Slider.tsx
@@ -17,7 +17,6 @@
*/
import {
- useEffect,
useId,
useMemo,
useRef,
@@ -46,7 +45,7 @@ import {mergeProps, rtlStyles} from '../utils';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
import {isRtlElement} from '../hooks/isRtlElement';
import type {BaseProps} from '../BaseProps';
@@ -508,9 +507,7 @@ export function Slider({ref, ...props}: SliderProps) {
null,
);
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
const handleThumbFocus = useCallback(
(thumbIndex: number, _e: FocusEvent<HTMLDivElement>) => {
diff --git a/packages/core/src/hooks/useFocusReturnVisibility.ts b/packages/core/src/hooks/useFocusReturnVisibility.ts
index fec50a1e6d..d9af1b7723 100644
--- a/packages/core/src/hooks/useFocusReturnVisibility.ts
+++ b/packages/core/src/hooks/useFocusReturnVisibility.ts
@@ -9,18 +9,16 @@
* @position Internal focus-return policy for adaptive overlays
*/
-import {useCallback, useEffect, useState} from 'react';
+import {useCallback, useState} from 'react';
import {
getInteractionModality,
- trackInteractionModality,
+ useInteractionModalityTracking,
} from '../utils/interactionModality';
export function useFocusReturnVisibility() {
const [isFocusRingSuppressed, setIsFocusRingSuppressed] = useState(false);
- useEffect(() => {
- trackInteractionModality();
- }, []);
+ useInteractionModalityTracking();
const prepareFocusReturn = useCallback(() => {
setIsFocusRingSuppressed(getInteractionModality() === 'pointer');
diff --git a/packages/core/src/utils/interactionModality.test.ts b/packages/core/src/utils/interactionModality.test.ts
new file mode 100644
index 0000000000..8aa0daca89
--- /dev/null
+++ b/packages/core/src/utils/interactionModality.test.ts
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file interactionModality.test.ts
+ * @input The interaction-modality utility loaded more than once
+ * @output Verifies document-wide listener and modality state continuity
+ * @position Unit coverage for interactionModality.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+const isolatedDocument = document.implementation.createHTMLDocument();
+
+async function loadTracker() {
+ vi.resetModules();
+ return import('./interactionModality');
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('interactionModality', () => {
+ it('does not touch the document when the module loads', async () => {
+ vi.stubGlobal('document', isolatedDocument);
+ const addEventListener = vi.spyOn(isolatedDocument, 'addEventListener');
+
+ await loadTracker();
+
+ expect(addEventListener).not.toHaveBeenCalled();
+ });
+
+ it('shares one listener pair and tracks input between consumers', async () => {
+ vi.stubGlobal('document', isolatedDocument);
+ const addEventListener = vi.spyOn(isolatedDocument, 'addEventListener');
+ const removeEventListener = vi.spyOn(
+ isolatedDocument,
+ 'removeEventListener',
+ );
+ const firstModule = await loadTracker();
+ const secondModule = await loadTracker();
+
+ const firstConsumer =
+ firstModule.__startInteractionModalityTrackingForTest();
+ const secondConsumer =
+ secondModule.__startInteractionModalityTrackingForTest();
+
+ expect(
+ addEventListener.mock.calls.filter(([type]) => type === 'pointerdown'),
+ ).toHaveLength(1);
+ expect(
+ addEventListener.mock.calls.filter(([type]) => type === 'keydown'),
+ ).toHaveLength(1);
+
+ isolatedDocument.dispatchEvent(new Event('pointerdown'));
+ expect(secondModule.getInteractionModality()).toBe('pointer');
+
+ firstConsumer();
+ secondConsumer();
+ isolatedDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
+ expect(firstModule.getInteractionModality()).toBe('keyboard');
+ expect(removeEventListener).not.toHaveBeenCalled();
+
+ secondModule.__startInteractionModalityTrackingForTest()();
+ expect(
+ addEventListener.mock.calls.filter(([type]) => type === 'pointerdown'),
+ ).toHaveLength(1);
+ expect(
+ addEventListener.mock.calls.filter(([type]) => type === 'keydown'),
+ ).toHaveLength(1);
+ });
+
+ it('uses the keyboard-safe default without a document', async () => {
+ vi.stubGlobal('document', undefined);
+ const serverModule = await loadTracker();
+
+ expect(serverModule.getInteractionModality()).toBe('keyboard');
+ expect(() =>
+ serverModule.__startInteractionModalityTrackingForTest()(),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/core/src/utils/interactionModality.ts b/packages/core/src/utils/interactionModality.ts
index e2cc3a67e8..e17c6b09d9 100644
--- a/packages/core/src/utils/interactionModality.ts
+++ b/packages/core/src/utils/interactionModality.ts
@@ -1,10 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+'use client';
+
/**
* @file interactionModality.ts
* @input Global pointerdown/keydown events
- * @output `getInteractionModality()` — how the user last interacted
- * @position Internal utility; used where `:focus-visible` alone is too broad
+ * @output `useInteractionModalityTracking()` activates document-lifetime tracking;
+ * `getInteractionModality()` reads how the user last interacted
+ * @position Internal document-wide singleton; used where `:focus-visible` alone
+ * is too broad
*
* `:focus-visible` is the right selector for a focus ring and should stay the
* condition that draws one. It is not, on its own, "focused by keyboard":
@@ -19,56 +23,104 @@
* it — the browser's heuristic still decides everything else, including
* `focus({focusVisible: true})`.
*
- * Listeners are registered once for the document, in the capture phase so they
- * run before the focus they explain, and are never removed: two passive
- * listeners for the whole app, versus a pair per mounted input.
+ * The store lives on `document`, so duplicate Astryx bundles share one state
+ * value and one listener pair. The first mounted consumer activates tracking;
+ * the listeners then remain for the document lifetime so input during a gap
+ * between consumers is not lost. Importing this module has no DOM side effects,
+ * and server rendering keeps the keyboard-safe default.
*/
+import {useEffect} from 'react';
+
export type InteractionModality = 'keyboard' | 'pointer';
-// Default to keyboard: with no interaction yet, focus arrived programmatically
-// or from the browser restoring it, and showing a ring is the safe error.
-let modality: InteractionModality = 'keyboard';
-let isListening = false;
+type InteractionModalityStore = {
+ modality: InteractionModality;
+ isListening: boolean;
+ onPointerDown: () => void;
+ onKeyDown: (event: KeyboardEvent) => void;
+};
-function onPointerDown(): void {
- modality = 'pointer';
-}
+const interactionModalityStoreKey = Symbol.for(
+ '@astryxdesign/core/interaction-modality/v1',
+);
-function onKeyDown(event: KeyboardEvent): void {
- // Modifier-only presses are not navigation — holding Shift before a click
- // must not turn that click into "keyboard".
- if (event.metaKey || event.altKey || event.ctrlKey) {
- return;
+function getStore(targetDocument: Document): InteractionModalityStore {
+ const singletonDocument = targetDocument as Document & {
+ [interactionModalityStoreKey]?: InteractionModalityStore;
+ };
+ const existingStore = singletonDocument[interactionModalityStoreKey];
+ if (existingStore != null) {
+ return existingStore;
}
- modality = 'keyboard';
+
+ // Default to keyboard: with no interaction yet, focus arrived
+ // programmatically or from the browser restoring it, and showing a ring is
+ // the safe error.
+ const store: InteractionModalityStore = {
+ modality: 'keyboard',
+ isListening: false,
+ onPointerDown: () => {
+ store.modality = 'pointer';
+ },
+ onKeyDown: event => {
+ // Modifier-only presses are not navigation — holding Shift before a
+ // click must not turn that click into "keyboard".
+ if (event.metaKey || event.altKey || event.ctrlKey) {
+ return;
+ }
+ store.modality = 'keyboard';
+ },
+ };
+ Object.defineProperty(singletonDocument, interactionModalityStoreKey, {
+ value: store,
+ });
+ return store;
}
-/**
- * Start tracking, once per document. Safe to call repeatedly and on the server
- * (where it does nothing).
- */
-export function trackInteractionModality(): void {
- if (isListening || typeof document === 'undefined') {
- return;
+function trackInteractionModality(): () => void {
+ if (typeof document === 'undefined') {
+ return () => {};
}
- isListening = true;
- document.addEventListener('pointerdown', onPointerDown, {
- capture: true,
- passive: true,
- });
- document.addEventListener('keydown', onKeyDown, {
- capture: true,
- passive: true,
- });
+
+ const targetDocument = document;
+ const store = getStore(targetDocument);
+ if (!store.isListening) {
+ store.isListening = true;
+ targetDocument.addEventListener('pointerdown', store.onPointerDown, {
+ capture: true,
+ passive: true,
+ });
+ targetDocument.addEventListener('keydown', store.onKeyDown, {
+ capture: true,
+ passive: 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(), []);
}
/** How the user last interacted with the page. */
export function getInteractionModality(): InteractionModality {
- return modality;
+ return typeof document === 'undefined'
+ ? 'keyboard'
+ : getStore(document).modality;
}
/** Test-only: restore the initial state between cases. */
export function __resetInteractionModalityForTest(): void {
- modality = 'keyboard';
+ if (typeof document !== 'undefined') {
+ getStore(document).modality = 'keyboard';
+ }
}
+
+/** Test-only: activate the tracker without rendering a hook. */
+export const __startInteractionModalityTrackingForTest =
+ trackInteractionModality;