Skip to content

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

TypeScript

fix(Dialog): hide the focus ring on pointer-initiated focus moves in WebKit (#7313)

Harjoth Khara0818c4205d5e
diff --git a/.changeset/dialog-pointer-focus-ring.md b/.changeset/dialog-pointer-focus-ring.md
new file mode 100644
index 0000000000..2b9010a7be
--- /dev/null
+++ b/.changeset/dialog-pointer-focus-ring.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Dialog's initial focus and the focus it returns on close now follow the last input: the shared focus indicator is hidden after a mouse click or tap and shown after keyboard input, including focus returned after a keyboard open and a mouse close (#7306). Text fields keep their own focus treatment.
+
+@harjothkhara
diff --git a/apps/storybook/stories/DialogA11y.stories.tsx b/apps/storybook/stories/DialogA11y.stories.tsx
index 9d7ec88c63..85e2c7a82f 100644
--- a/apps/storybook/stories/DialogA11y.stories.tsx
+++ b/apps/storybook/stories/DialogA11y.stories.tsx
@@ -2,15 +2,23 @@
/**
* @file DialogA11y.stories.tsx
- * @input Uses Dialog's shared modal-dialog state inventory and render map
- * @output One checked-in browser reproduction story for every bound state
+ * @input Uses Dialog's shared modal-dialog state inventory and render map, and
+ * AlertDialog for the last-input focus fixture
+ * @output One checked-in browser reproduction story for every bound state, plus
+ * PointerFocusVisibility
* @position Stable real-browser fixtures required by AST-009 FR30 and AST-021.
*
+ * PointerFocusVisibility is the one fixture outside that inventory: it backs
+ * Dialog.a11y.browser.spec.ts, the Chromium and WebKit proof that Dialog's
+ * focus moves follow the last input (interaction-modality INV1).
+ *
* SYNC: A new row in Dialog.a11y.states.ts needs a named export here. The
* Chromium binding catches a missing or renamed story by its stable storyId.
*/
+import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
+import {AlertDialog} from '../../../packages/core/src/AlertDialog';
import {DIALOG_MODAL_BINDING_STATES} from '../../../packages/core/src/Dialog/__tests__/Dialog.a11y.states';
import {renderDialogModalState} from '../../../packages/core/src/Dialog/__tests__/Dialog.a11y.renders';
@@ -50,3 +58,29 @@ export const ConditionalContentFocusRestoration = storyFor(
'conditional-content-focus-restoration',
);
export const NoFocusableContent = storyFor('no-focusable-content');
+
+/**
+ * An AlertDialog opened from a button WebKit focuses on click. WebKit leaves a
+ * plain clicked button unfocused, so the explicit `tabIndex` is what lets both
+ * engines show where focus returns after a pointer close.
+ */
+export const PointerFocusVisibility: StoryObj = {
+ render: function PointerFocusVisibilityStory() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" tabIndex={0} onClick={() => setIsOpen(true)}>
+ Delete item
+ </button>
+ <AlertDialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ title="Delete item?"
+ description="This action cannot be undone."
+ actionLabel="Delete"
+ onAction={() => setIsOpen(false)}
+ />
+ </>
+ );
+ },
+};
diff --git a/packages/core/src/Dialog/Dialog.spec.md b/packages/core/src/Dialog/Dialog.spec.md
index 486e3f9812..22cea528cc 100644
--- a/packages/core/src/Dialog/Dialog.spec.md
+++ b/packages/core/src/Dialog/Dialog.spec.md
@@ -16,12 +16,14 @@ verified_by:
packages/core/src/Dialog/DialogHeader.test.tsx,
packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx,
packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts,
+ packages/core/src/Dialog/__tests__/Dialog.a11y.browser.spec.ts,
]
modules: [module:Dialog/DialogHeader]
families: [family:overlay-dismissal]
design_specs: []
architecture:
[
+ architecture:interaction-modality,
architecture:layer-runtime,
architecture:public-component-api,
architecture:react-component-runtime,
@@ -131,6 +133,9 @@ component design and theming owners.
Escape press affects only the topmost relevant layer.
- `architecture:layer-runtime` owns modal layer ordering and shared lifecycle.
- `architecture:react-component-runtime` owns node/resource replacement safety.
+- `architecture:interaction-modality` INV1 decides whether initial focus and the
+ focus returned on close show the shared focus indicator; Dialog's
+ `Dialog.a11y.browser.spec.ts` verifies both after pointer and keyboard input.
- This component owns the destination and return outcome for Dialog's modal focus
lifecycle.
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index b531f4373a..98061bead4 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -11,7 +11,8 @@
import {useState} from 'react';
import {readFileSync} from 'node:fs';
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import type {MockInstance} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {
Dialog,
@@ -20,6 +21,7 @@ import {
} from './Dialog';
import {DialogHeader} from './DialogHeader';
import {defineTheme, generateThemeCSS} from '../theme';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
function generateThemeTestCSS(
theme: Parameters<typeof generateThemeCSS>[0],
@@ -470,6 +472,288 @@ describe('Dialog', () => {
});
});
+ // jsdom draws no focus ring, so these prove only which focus call Dialog
+ // makes. Dialog.a11y.browser.spec.ts proves the rendered outcome.
+ describe('last-input focus visibility', () => {
+ function LastInputExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open dialog
+ </button>
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ aria-label="Review changes">
+ <button
+ type="button"
+ data-autofocus
+ onClick={() => setIsOpen(false)}>
+ Cancel
+ </button>
+ </Dialog>
+ </>
+ );
+ }
+
+ function focusCallsOn(
+ focus: MockInstance<HTMLElement['focus']>,
+ element: HTMLElement,
+ ): unknown[][] {
+ return focus.mock.calls.filter(
+ (_call, index) => focus.mock.contexts[index] === element,
+ );
+ }
+
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('hides the ring on both focus moves after pointer input', () => {
+ render(<LastInputExample />);
+ const invoker = screen.getByRole('button', {name: 'Open dialog'});
+ invoker.focus();
+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');
+
+ fireEvent.pointerDown(invoker);
+ fireEvent.click(invoker);
+ const cancel = screen.getByRole('button', {name: 'Cancel'});
+ expect(cancel).toHaveFocus();
+ expect(focusCallsOn(focus, cancel)).toEqual([[{focusVisible: false}]]);
+
+ fireEvent.pointerDown(cancel);
+ fireEvent.click(cancel);
+ expect(invoker).toHaveFocus();
+ expect(focusCallsOn(focus, invoker)).toEqual([[{focusVisible: false}]]);
+ });
+
+ it('keeps plain focus on both moves after keyboard input', () => {
+ render(<LastInputExample />);
+ const invoker = screen.getByRole('button', {name: 'Open dialog'});
+ invoker.focus();
+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');
+
+ fireEvent.keyDown(invoker, {key: 'Enter'});
+ fireEvent.click(invoker);
+ const cancel = screen.getByRole('button', {name: 'Cancel'});
+ expect(focusCallsOn(focus, cancel)).toEqual([[]]);
+
+ fireEvent.keyDown(cancel, {key: 'Enter'});
+ fireEvent.click(cancel);
+ expect(invoker).toHaveFocus();
+ expect(focusCallsOn(focus, invoker)).toEqual([[]]);
+ });
+
+ it('clears a ring the browser already drew before refocusing after pointer input', () => {
+ render(<LastInputExample />);
+ const invoker = screen.getByRole('button', {name: 'Open dialog'});
+ invoker.focus();
+ fireEvent.pointerDown(invoker);
+ fireEvent.click(invoker);
+
+ // WebKit's native close restores focus to the invoker with a ring before
+ // Dialog moves focus, and focusing the focused element is a no-op.
+ HTMLDialogElement.prototype.close = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.removeAttribute('open');
+ invoker.focus();
+ });
+ const matches = HTMLElement.prototype.matches;
+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (
+ this: HTMLElement,
+ selector: string,
+ ) {
+ return selector === ':focus-visible'
+ ? this === invoker
+ : matches.call(this, selector);
+ });
+ const blur = vi.spyOn(invoker, 'blur');
+ const focus = vi.spyOn(invoker, 'focus');
+
+ const cancel = screen.getByRole('button', {name: 'Cancel'});
+ fireEvent.pointerDown(cancel);
+ fireEvent.click(cancel);
+
+ expect(blur).toHaveBeenCalledTimes(1);
+ expect(focus.mock.calls.at(-1)).toEqual([{focusVisible: false}]);
+ expect(blur.mock.invocationCallOrder[0]).toBeLessThan(
+ focus.mock.invocationCallOrder.at(-1) ?? 0,
+ );
+ expect(invoker).toHaveFocus();
+ });
+
+ // Consumer focus callbacks see at most one extra blur and focus, and only
+ // where the browser already drew a ring on a non-text target after a
+ // pointer press. The mocks stand in for WebKit: showModal() and close()
+ // move focus themselves, and every focused element matches :focus-visible.
+ describe('consumer focus callbacks', () => {
+ type Counts = {focus: number; blur: number};
+ type Kind = 'button' | 'tabindex' | 'text';
+
+ function counter(): Counts & {
+ props: {onFocus: () => void; onBlur: () => void};
+ } {
+ const counts = {
+ focus: 0,
+ blur: 0,
+ props: {
+ onFocus: () => {
+ counts.focus += 1;
+ },
+ onBlur: () => {
+ counts.blur += 1;
+ },
+ },
+ };
+ return counts;
+ }
+
+ function Focusable({
+ kind,
+ label,
+ counts,
+ ...rest
+ }: {
+ kind: Kind;
+ label: string;
+ counts: ReturnType<typeof counter>;
+ onClick?: () => void;
+ 'data-autofocus'?: boolean;
+ }) {
+ if (kind === 'text') {
+ return <input aria-label={label} {...counts.props} {...rest} />;
+ }
+ return kind === 'tabindex' ? (
+ <div role="button" tabIndex={0} {...counts.props} {...rest}>
+ {label}
+ </div>
+ ) : (
+ <button type="button" {...counts.props} {...rest}>
+ {label}
+ </button>
+ );
+ }
+
+ function setup(invokerKind: Kind, targetKind: Kind) {
+ const invokerCounts = counter();
+ const targetCounts = counter();
+ function Example() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Focusable
+ kind={invokerKind}
+ label="Invoker"
+ counts={invokerCounts}
+ onClick={() => setIsOpen(true)}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ aria-label="Review changes">
+ <Focusable
+ kind={targetKind}
+ label="Target"
+ counts={targetCounts}
+ data-autofocus
+ />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Done
+ </button>
+ </Dialog>
+ </>
+ );
+ }
+ render(<Example />);
+ const invoker = screen.getByRole(
+ invokerKind === 'text' ? 'textbox' : 'button',
+ {name: 'Invoker'},
+ );
+ invoker.focus();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('[data-autofocus]')?.focus();
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.removeAttribute('open');
+ invoker.focus();
+ });
+ const matches = HTMLElement.prototype.matches;
+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (
+ this: HTMLElement,
+ selector: string,
+ ) {
+ return selector === ':focus-visible'
+ ? this === document.activeElement
+ : matches.call(this, selector);
+ });
+ const reset = () => {
+ for (const counts of [invokerCounts, targetCounts]) {
+ counts.focus = 0;
+ counts.blur = 0;
+ }
+ };
+ reset();
+ return {invoker, invokerCounts, targetCounts, reset};
+ }
+
+ function press(element: HTMLElement, modality: 'pointer' | 'keyboard') {
+ if (modality === 'pointer') {
+ fireEvent.pointerDown(element);
+ } else {
+ fireEvent.keyDown(element, {key: 'Enter'});
+ }
+ fireEvent.click(element);
+ }
+
+ function counts({focus, blur}: Counts): Counts {
+ return {focus, blur};
+ }
+
+ it.each([
+ ['button', 'pointer', {focus: 2, blur: 1}],
+ ['button', 'keyboard', {focus: 1, blur: 0}],
+ ['text', 'pointer', {focus: 1, blur: 0}],
+ ['text', 'keyboard', {focus: 1, blur: 0}],
+ ] as const)(
+ 'gives a %s autofocus target on a %s open %j',
+ (targetKind, modality, expected) => {
+ const {invoker, targetCounts} = setup('button', targetKind);
+ press(invoker, modality);
+ expect(counts(targetCounts)).toEqual(expected);
+ },
+ );
+
+ it.each([
+ ['button', 'pointer', {focus: 2, blur: 1}],
+ ['button', 'keyboard', {focus: 1, blur: 0}],
+ ['tabindex', 'pointer', {focus: 2, blur: 1}],
+ ['tabindex', 'keyboard', {focus: 1, blur: 0}],
+ ['text', 'pointer', {focus: 1, blur: 0}],
+ ] as const)(
+ 'gives a %s invoker on a %s close %j',
+ (invokerKind, modality, expected) => {
+ const {invoker, invokerCounts, reset} = setup(invokerKind, 'button');
+ press(invoker, 'keyboard');
+ reset();
+ press(screen.getByRole('button', {name: 'Done'}), modality);
+ expect(invoker).toHaveFocus();
+ expect(counts(invokerCounts)).toEqual(expected);
+ },
+ );
+ });
+ });
+
describe('variant: standard', () => {
it('renders with default variant', () => {
render(
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 91ed97e99d..91cc6fb997 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -5,7 +5,7 @@
/**
* @file Dialog.tsx
* @input Uses React, DialogHTMLAttributes, ReactNode, container (Layout), DialogContext, layerTextReset,
- * layerStructureReset, modalOutlet
+ * layerStructureReset, modalOutlet, interactionModality
* @output Exports Dialog component, DialogProps, DialogVariant, DialogPurpose types
* @position Core implementation; consumed by index.ts, tested by Dialog.test.tsx
*
@@ -16,6 +16,10 @@
* while preserving explicit prop/theme padding overrides, and fade in without
* the centered-dialog translate/scale motion.
*
+ * Initial focus and the focus returned on close follow the last input
+ * (docs/architecture/interaction-modality.md INV1): the shared focus indicator
+ * is hidden after a pointer press and shown after a key press.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Dialog/Dialog.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Dialog/Dialog.test.tsx (tests for new/changed behavior)
@@ -66,8 +70,38 @@ import {DialogContext} from './DialogContext';
import {themeProps} from '../utils/themeProps';
import type {DialogVariantMap} from './index';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
+import {
+ getInteractionModality,
+ useInteractionModalityTracking,
+} from '../utils/interactionModality';
import {useMergedRefs} from '../hooks/useMergedRefs';
+/**
+ * Move focus programmatically so its ring follows the last input. Dialog does
+ * not render the element that opened it or the consumer's autofocus target, so
+ * the browser's focus option is the one way to reach them.
+ */
+function focusForLastInput(element: HTMLElement): 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.
+ const isTextEntry =
+ element instanceof HTMLInputElement ||
+ element instanceof HTMLTextAreaElement ||
+ element instanceof HTMLSelectElement ||
+ element.isContentEditable;
+ if (isTextEntry || getInteractionModality() !== 'pointer') {
+ element.focus();
+ return;
+ }
+ // Focusing the element that already has focus does nothing, so a ring the
+ // browser already drew would stay. WebKit draws one when showModal() or its
+ // native close moves focus itself, so clear that focus first.
+ if (element.matches(':focus-visible')) {
+ element.blur();
+ }
+ element.focus({focusVisible: false});
+}
+
/**
* Calculate a directional translate offset for dialog entry animation.
* Returns a normalized vector from the trigger element toward the viewport
@@ -502,6 +536,8 @@ export function Dialog({
// for directional animation origin and focus restoration on close.
const triggerElementRef = useRef<HTMLElement | null>(null);
+ useInteractionModalityTracking();
+
// Derive dismissal behavior from purpose
const allowEscape = purpose !== 'required';
const allowBackdropClick = purpose === 'info';
@@ -540,7 +576,7 @@ export function Dialog({
const autofocusTarget =
dialog.querySelector<HTMLElement>('[data-autofocus]');
if (autofocusTarget) {
- autofocusTarget.focus();
+ focusForLastInput(autofocusTarget);
}
}
} else {
@@ -548,7 +584,9 @@ export function Dialog({
dialog.close();
}
// Return focus to the element that opened the dialog
- triggerElementRef.current?.focus();
+ if (triggerElementRef.current) {
+ focusForLastInput(triggerElementRef.current);
+ }
triggerElementRef.current = null;
}
}, [isOpen, isInline]);
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.browser.spec.ts b/packages/core/src/Dialog/__tests__/Dialog.a11y.browser.spec.ts
new file mode 100644
index 0000000000..b63d51508a
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.browser.spec.ts
@@ -0,0 +1,110 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dialog.a11y.browser.spec.ts
+ * @input Built Dialog stories and real Chromium/WebKit pointer and keyboard input
+ * @output Browser evidence that Dialog's initial and returning focus follow the
+ * last input (docs/architecture/interaction-modality.md INV1)
+ * @position Cross-browser proof; jsdom only proves which focus call Dialog makes.
+ *
+ * `:focus-visible` is the engine's own answer, so only a shipping engine can
+ * show whether a ring is drawn. WebKit is the engine that draws one after a
+ * pointer press, both on the focus Dialog moves into the modal and on the
+ * focus its native close restores to the invoker.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mount(page: Page, story: string): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-dialog-modal-pattern--${story}&viewMode=story`,
+ );
+}
+
+async function matchesFocusVisible(locator: Locator): Promise<boolean> {
+ return locator.evaluate(element => element.matches(':focus-visible'));
+}
+
+test('a pointer open draws no ring on the initial focus', async ({page}) => {
+ await mount(page, 'pointer-focus-visibility');
+ await page.getByRole('button', {name: 'Delete item', exact: true}).click();
+ const cancel = page.getByRole('button', {name: 'Cancel', exact: true});
+ await expect(cancel).toBeFocused();
+ expect(await matchesFocusVisible(cancel)).toBe(false);
+});
+
+test('a pointer close draws no ring on the returned focus', async ({page}) => {
+ await mount(page, 'pointer-focus-visibility');
+ const opener = page.getByRole('button', {name: 'Delete item', exact: true});
+ await opener.click();
+ await page.getByRole('button', {name: 'Cancel', exact: true}).click();
+ await expect(page.getByRole('alertdialog')).toBeHidden();
+ await expect(opener).toBeFocused();
+ expect(await matchesFocusVisible(opener)).toBe(false);
+});
+
+test('a keyboard open and Escape close keep both focus rings', async ({
+ page,
+}) => {
+ await mount(page, 'pointer-focus-visibility');
+ const opener = page.getByRole('button', {name: 'Delete item', exact: true});
+ await opener.focus();
+ await page.keyboard.press('Enter');
+ const cancel = page.getByRole('button', {name: 'Cancel', exact: true});
+ await expect(cancel).toBeFocused();
+ expect(await matchesFocusVisible(cancel)).toBe(true);
+
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('alertdialog')).toBeHidden();
+ await expect(opener).toBeFocused();
+ expect(await matchesFocusVisible(opener)).toBe(true);
+});
+
+test('the input that closes owns the returned ring', async ({page}) => {
+ await mount(page, 'pointer-focus-visibility');
+ const opener = page.getByRole('button', {name: 'Delete item', exact: true});
+ await opener.focus();
+ await page.keyboard.press('Enter');
+ await page.getByRole('button', {name: 'Cancel', exact: true}).click();
+ await expect(page.getByRole('alertdialog')).toBeHidden();
+ await expect(opener).toBeFocused();
+ expect(await matchesFocusVisible(opener)).toBe(false);
+});
+
+test('a pointer-opened form still shows where typing goes', async ({page}) => {
+ await mount(page, 'explicit-descendant-focus');
+ await page
+ .getByRole('button', {name: 'Open contract dialog', exact: true})
+ .click();
+ const field = page.getByRole('textbox', {name: 'Name', exact: true});
+ await expect(field).toBeFocused();
+ // The field paints its own focus treatment through `:focus-within` on its
+ // wrapper, so hiding the shared ring leaves it in place.
+ expect(
+ await field.evaluate(element => {
+ const wrapper = element.parentElement;
+ return (
+ wrapper != null &&
+ wrapper.matches(':focus-within') &&
+ getComputedStyle(wrapper).boxShadow !== 'none'
+ );
+ }),
+ ).toBe(true);
+ await page.keyboard.type('Ada');
+ await expect(field).toHaveValue('Ada');
+});