An open source design system that's fully customizable and agent ready
TypeScript
fix(Dialog): when the first autofocus request is ineligible, the next eligible one takes initial focus (#10105)
Cindy Zhangc9c4932b300f
diff --git a/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md b/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.mdnew file mode 100644index 0000000000..204beecf6e--- /dev/null+++ b/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Dialog: when the first `data-autofocus` request is hidden, inert, `aria-hidden` or cannot take focus, the next eligible request takes initial focus. This also holds for a Dialog rendered inside an inert region of the page or in an iframe or Picture-in-Picture window (#4182)++@jiunshinndiff --git a/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md b/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.mdnew file mode 100644index 0000000000..d32bf4f2d4--- /dev/null+++ b/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: an internal entry reserved for Astryx's own packages exposes the Dialog's title id, inline state and `syncDefaultName()` (a header whose title renders after the dialog mounted asks the dialog to look for its name again), so Lab's upcoming DialogHeroHeader can name the dialog and request title focus the way DialogHeader does. A `data-autofocus="dialog-title"` request is tried after every explicit request, in preparation for that header; nothing a consumer sees changes (#4182)+@jiunshinndiff --git a/packages/core/package.json b/packages/core/package.jsonindex 5acf9891a2..b341d7baff 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -848,6 +848,11 @@"source": "./src/internal/calendar-system.ts","types": "./dist/internal/calendar-system.d.ts","default": "./dist/internal/calendar-system.js"+ },+ "./internal/dialog-context": {+ "source": "./src/internal/dialog-context.ts",+ "types": "./dist/internal/dialog-context.d.ts",+ "default": "./dist/internal/dialog-context.js"}},"files": [diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsxindex 9742761f43..8764f7e8ea 100644--- a/packages/core/src/Dialog/Dialog.test.tsx+++ b/packages/core/src/Dialog/Dialog.test.tsx@@ -9,7 +9,12 @@* SYNC: When Dialog.tsx changes, update tests to match new behavior*/-import {StrictMode, useState, type SyntheticEvent} from 'react';+import {+ StrictMode,+ useLayoutEffect,+ useState,+ type SyntheticEvent,+} from 'react';import {readFileSync} from 'node:fs';import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import type {MockInstance} from 'vitest';@@ -29,6 +34,7 @@ import {} from './Dialog';import {DialogHeader} from './DialogHeader';import {getFocusableElements, useFocusTrap} from '../hooks/useFocusTrap';+import {useDialogContext} from './DialogContext';import {defineTheme, generateThemeCSS} from '../theme';import {__resetInteractionModalityForTest,@@ -496,6 +502,91 @@ describe('Dialog', () => {expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();});+ it('skips a hidden or inert initial-focus request for the next eligible one', () => {+ render(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <div hidden>+ <button type="button" data-autofocus>+ Hidden+ </button>+ </div>+ <div inert>+ <button type="button" data-autofocus>+ Inert+ </button>+ </div>+ <button type="button" data-autofocus>+ Continue+ </button>+ </Dialog>,+ );++ expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();+ });++ it('honors its own initial-focus request inside an inert region of the page', () => {+ render(+ <div inert>+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <button type="button" data-autofocus>+ Continue+ </button>+ </Dialog>+ </div>,+ );++ expect(+ screen.getByRole('button', {name: 'Continue', hidden: true}),+ ).toHaveFocus();+ });++ it('falls through an initial-focus request that cannot take focus', () => {+ render(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <button type="button" disabled data-autofocus>+ Unavailable+ </button>+ <button type="button" data-autofocus>+ Continue+ </button>+ </Dialog>,+ );++ expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();+ });++ it("honors an explicit request before a header's title request", () => {+ render(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <h2 tabIndex={-1} data-autofocus="dialog-title">+ Hero title+ </h2>+ <button type="button" data-autofocus>+ Continue+ </button>+ </Dialog>,+ );++ expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();+ });++ it("focuses a header's title request when no explicit request is eligible", () => {+ render(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <h2 tabIndex={-1} data-autofocus="dialog-title">+ Hero title+ </h2>+ <div hidden>+ <button type="button" data-autofocus>+ Hidden+ </button>+ </div>+ </Dialog>,+ );++ expect(screen.getByRole('heading', {name: 'Hero title'})).toHaveFocus();+ });+describe('purpose: info (default)', () => {it('calls onOpenChange(false) when Escape is pressed', () => {const handleHide = vi.fn();@@ -900,6 +991,25 @@ describe('Dialog', () => {);}+ it("honors an explicit request before a header's title request", () => {+ render(+ createPortal(+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Review">+ <h2 tabIndex={-1} data-autofocus="dialog-title">+ Hero title+ </h2>+ <button type="button" data-autofocus>+ Continue+ </button>+ </Dialog>,+ secondDocument.body,+ ),+ );++ const continueButton = secondDocument.querySelector('button')!;+ expect(secondDocument.activeElement).toBe(continueButton);+ });+function SecondDocumentFieldDialog({isOpen}: {isOpen: boolean}) {return createPortal(<>@@ -1723,6 +1833,38 @@ describe('Dialog', () => {expect(dialog).toHaveAccessibleName('Rich dialog title');});+ it('names itself by a header title that renders after the dialog mounts', () => {+ // A composed header whose title arrives in a later commit asks the+ // dialog to check its default name again.+ function LateTitleHeader({isReady}: {isReady: boolean}) {+ const context = useDialogContext();+ const syncDefaultName = context?.syncDefaultName;+ useLayoutEffect(() => {+ syncDefaultName?.();+ }, [isReady, syncDefaultName]);+ return isReady ? <h2 id={context?.titleId}>Late title</h2> : null;+ }+ const {rerender} = render(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <LateTitleHeader isReady={false} />+ </Dialog>,+ );+ const dialog = screen.getByRole('dialog');+ expect(dialog).not.toHaveAttribute('aria-labelledby');+ rerender(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <LateTitleHeader isReady={true} />+ </Dialog>,+ );+ expect(dialog).toHaveAccessibleName('Late title');+ rerender(+ <Dialog isOpen={true} onOpenChange={() => {}}>+ <LateTitleHeader isReady={false} />+ </Dialog>,+ );+ expect(dialog).not.toHaveAttribute('aria-labelledby');+ });+it('prefers a consumer-provided aria-label over the header title', () => {render(<Dialog isOpen={true} onOpenChange={() => {}} aria-label="Custom name">diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex 288e178d18..7118e2faad 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -15,6 +15,8 @@* Fullscreen dialogs add safe-area protection to the default padding fallback* while preserving explicit prop/theme padding overrides, and fade in without* the centered-dialog translate/scale motion.+ * Initial focus is applied after showModal; an explicit descendant request+ * takes priority over a header's default title request.** Under reduced motion the entrance never travels or scales* (docs/design/reduced-motion.md): on a touch screen the dialog fades in@@ -541,11 +543,6 @@ export function Dialog({// would cost at the dialog level.const titleId = useId();- const dialogContextValue = useMemo(- () => ({isInline, titleId}),- [isInline, titleId],- );-// Consumer-provided labels always win over the DialogHeader default.const hasConsumerName =props['aria-label'] != null || props['aria-labelledby'] != null;@@ -575,6 +572,19 @@ export function Dialog({[titleId, hasConsumerName],);+ // A composed header whose title renders after the dialog mounted asks the+ // dialog to look for the title again.+ const syncDefaultName = useCallback(() => {+ if (dialogRef.current != null) {+ attachDialog(dialogRef.current);+ }+ }, [attachDialog]);++ const dialogContextValue = useMemo(+ () => ({isInline, titleId, syncDefaultName}),+ [isInline, titleId, syncDefaultName],+ );+// 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@@ -642,11 +652,34 @@ export function Dialog({dialog.showModal();// React's autoFocus calls .focus() during commit, before showModal()// makes the dialog visible, so the focus silently fails.- // Focus the first element with data-autofocus inside the dialog.- const autofocusTarget =- dialog.querySelector<HTMLElement>('[data-autofocus]');- if (autofocusTarget) {- focusForLastInput(autofocusTarget);+ // Explicit descendant intent takes priority over a header's default+ // title. Keep the marker private to the focus-owning components.+ const autofocusTargets = [+ ...dialog.querySelectorAll<HTMLElement>(+ '[data-autofocus]:not([data-autofocus="dialog-title"])',+ ),+ ...dialog.querySelectorAll<HTMLElement>(+ '[data-autofocus="dialog-title"]',+ ),+ ];+ for (const target of autofocusTargets) {+ // Only hiding inside the dialog makes a request ineligible: the+ // modal dialog is not part of an inert region around it.+ const hiddenAncestor = target.closest(+ '[hidden], [inert], [aria-hidden="true"]',+ );+ if (hiddenAncestor != null && dialog.contains(hiddenAncestor)) {+ continue;+ }+ // Disabled and CSS-hidden targets cannot receive focus in the+ // browser. If a request cannot land, try the next eligible request+ // and finally the title; otherwise preserve native initial focus.+ // The dialog's own document reports its focus, also when the dialog+ // renders in an iframe or a Picture-in-Picture window.+ focusForLastInput(target);+ if (target.ownerDocument.activeElement === target) {+ break;+ }}}// Under a coarse primary pointer, a tap or a drag during the entrancediff --git a/packages/core/src/Dialog/DialogContext.ts b/packages/core/src/Dialog/DialogContext.tsindex 9872e43d5f..600160df8d 100644--- a/packages/core/src/Dialog/DialogContext.ts+++ b/packages/core/src/Dialog/DialogContext.ts@@ -6,7 +6,8 @@* @file DialogContext.ts* @input React context* @output Internal dialog context for child focus behavior and default labelling- * @position Dialog internals; consumed by focus-managing children and DialogHeader+ * @position Dialog internals; consumed by focus-managing children and DialogHeader,+ * and by Lab's DialogHeroHeader through the internal/dialog-context entry*/import {createContext, use} from 'react';@@ -21,6 +22,12 @@ export interface DialogContextValue {* when the title actually rendered — never pointing at a nonexistent id.*/titleId?: string;+ /**+ * Checks the default aria-labelledby again. The dialog looks for its title+ * when it mounts; a composed header whose title element appears, changes,+ * or leaves after that calls this so the dialog's name follows it.+ */+ syncDefaultName?: () => void;}export const DialogContext = createContext<DialogContextValue | null>(null);diff --git a/packages/core/src/internal/dialog-context.test.ts b/packages/core/src/internal/dialog-context.test.tsnew file mode 100644index 0000000000..976496f876--- /dev/null+++ b/packages/core/src/internal/dialog-context.test.ts@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file dialog-context.test.ts+ * @input The internal `internal/dialog-context` entry and the Dialog module+ * @output Proof that the entry re-exports the same hook Dialog provides, by+ * name, and that the public Dialog barrel names no context+ * @position Unit tests of packages/core/src/internal/dialog-context.ts+ */+import {describe, expect, it} from 'vitest';++describe('internal/dialog-context', () => {+ it('re-exports the one Dialog context hook, the same value Dialog reads', async () => {+ const entry: Record<string, unknown> = await import('./dialog-context');+ const context = await import('../Dialog/DialogContext');+ expect(entry.useDialogContext).toBe(context.useDialogContext);+ // Named re-exports only, nothing else.+ expect(Object.keys(entry).sort()).toEqual(['useDialogContext']);+ });++ it('the public Dialog barrel exports no context surface', async () => {+ const pub: Record<string, unknown> = await import('../Dialog');+ expect(pub).not.toHaveProperty('DialogContext');+ expect(pub).not.toHaveProperty('useDialogContext');+ });+});diff --git a/packages/core/src/internal/dialog-context.ts b/packages/core/src/internal/dialog-context.tsnew file mode 100644index 0000000000..ddb4e7263a--- /dev/null+++ b/packages/core/src/internal/dialog-context.ts@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file dialog-context.ts+ * @input Dialog's internal context hook+ * @output `@astryxdesign/core/internal/dialog-context`: `useDialogContext`,+ * for Astryx's own packages+ * @position An internal entry reserved for Astryx's own packages:+ * undocumented, outside the public API and its compatibility promise,+ * versioned in lockstep with Core, and allowed only in Core and Lab by the+ * `@astryx/no-core-internal-import` lint rule. Lab's DialogHeroHeader reads+ * the Dialog's title id and inline state through it, so it names the dialog+ * and requests title focus the way DialogHeader does. Named re-exports only.+ *+ * SYNC: When modified, update dialog-context.test.ts and+ * scripts/sync-exports.js.+ */+export {useDialogContext} from '../Dialog/DialogContext';diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex abbcf7cf43..2b63f64225 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -242,6 +242,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = ['internal/selectable-card','internal/spinner-rotor','internal/calendar-system',+ 'internal/dialog-context',];/**