From 2b4795f32a8777b6c15ee55ab9f7bb6583099941 Mon Sep 17 00:00:00 2001 From: jiunshinn Date: Wed, 28 Oct 2026 18:54:25 +0900 Subject: [PATCH] fix(Dialog): an explicit autofocus request wins over a header's title, and Lab can read the Dialog context through an internal entry Dialog now honors only eligible initial-focus requests (component:Dialog FR2): a request inside a hidden or inert subtree is skipped, and a request that cannot take focus falls through to the next one. A header's default title request (data-autofocus="dialog-title") comes after every explicit request. The Dialog context gains syncDefaultName(), so a composed header whose title renders after mount can ask Dialog to check its default name again. @astryxdesign/core/internal/dialog-context re-exports useDialogContext for Astryx's own packages only (spec:AST-017 FR21), the same shape as internal/tokenizer-presentation. Part of #4182. Split out of #5105. --- ...e-opening-dialog-s-first-data-auto-wr66.md | 6 + ...-dialogheroheader-reads-the-dialog-ctse.md | 6 + packages/core/package.json | 5 + packages/core/src/Dialog/Dialog.test.tsx | 104 +++++++++++++++++- packages/core/src/Dialog/Dialog.tsx | 46 ++++++-- packages/core/src/Dialog/DialogContext.ts | 9 +- .../core/src/internal/dialog-context.test.ts | 25 +++++ packages/core/src/internal/dialog-context.ts | 19 ++++ scripts/sync-exports.js | 1 + 9 files changed, 209 insertions(+), 12 deletions(-) create mode 100644 .changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md create mode 100644 .changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md create mode 100644 packages/core/src/internal/dialog-context.test.ts create mode 100644 packages/core/src/internal/dialog-context.ts 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.md new file mode 100644 index 0000000000000..115b0fc049f3e --- /dev/null +++ b/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md @@ -0,0 +1,6 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Dialog: when the opening Dialog's first data-autofocus request is hidden, inert, or cannot take focus, the next request takes it; a header's default title request comes after every explicit request (#4182) +@jiunshinn diff --git a/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md b/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md new file mode 100644 index 0000000000000..23103c514ad46 --- /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 and inline state, so Lab's upcoming DialogHeroHeader can name the dialog and request title focus the way DialogHeader does; nothing a consumer sees changes (#4182) +@jiunshinn diff --git a/packages/core/package.json b/packages/core/package.json index 295c3d98433c4..dd119a33b384c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -828,6 +828,11 @@ "source": "./src/internal/tokenizer-presentation.ts", "types": "./dist/internal/tokenizer-presentation.d.ts", "default": "./dist/internal/tokenizer-presentation.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.tsx index b676be021577d..731a728d0d379 100644 --- a/packages/core/src/Dialog/Dialog.test.tsx +++ b/packages/core/src/Dialog/Dialog.test.tsx @@ -9,7 +9,7 @@ * SYNC: When Dialog.tsx changes, update tests to match new behavior */ -import {useState, type SyntheticEvent} from 'react'; +import {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'; @@ -20,6 +20,7 @@ import { resolveDialogPositionOffsets, } from './Dialog'; import {DialogHeader} from './DialogHeader'; +import {useDialogContext} from './DialogContext'; import {defineTheme, generateThemeCSS} from '../theme'; import {__resetInteractionModalityForTest} from '../utils/interactionModality'; @@ -207,6 +208,75 @@ describe('Dialog', () => { expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus(); }); + it('skips a hidden or inert initial-focus request for the next eligible one', () => { + render( + {}}> + +
+ +
+ +
, + ); + + expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus(); + }); + + it('falls through an initial-focus request that cannot take focus', () => { + render( + {}}> + + + , + ); + + expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus(); + }); + + it("honors an explicit request before a header's title request", () => { + render( + {}}> +

+ Hero title +

+ +
, + ); + + expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus(); + }); + + it("focuses a header's title request when no explicit request is eligible", () => { + render( + {}}> +

+ Hero title +

+ +
, + ); + + expect(screen.getByRole('heading', {name: 'Hero title'})).toHaveFocus(); + }); + describe('purpose: info (default)', () => { it('calls onOpenChange(false) when Escape is pressed', () => { const handleHide = vi.fn(); @@ -1218,6 +1288,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 ?

Late title

: null; + } + const {rerender} = render( + {}}> + + , + ); + const dialog = screen.getByRole('dialog'); + expect(dialog).not.toHaveAttribute('aria-labelledby'); + rerender( + {}}> + + , + ); + expect(dialog).toHaveAccessibleName('Late title'); + rerender( + {}}> + + , + ); + expect(dialog).not.toHaveAttribute('aria-labelledby'); + }); + it('prefers a consumer-provided aria-label over the header title', () => { render( {}} aria-label="Custom name"> diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx index 2f1e5806bddb0..04af612319248 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 @@ -495,11 +497,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; @@ -526,6 +523,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], + ); + const mergedDialogRef = useMergedRefs(ref, attachDialog); // Capture the element that was focused when the dialog opened, for @@ -580,11 +590,27 @@ 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('[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( + '[data-autofocus]:not([data-autofocus="dialog-title"])', + ), + ...dialog.querySelectorAll( + '[data-autofocus="dialog-title"]', + ), + ]; + for (const target of autofocusTargets) { + if (target.closest('[hidden], [inert], [aria-hidden="true"]')) { + 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. + focusForLastInput(target); + if (document.activeElement === target) { + break; + } } } } else { diff --git a/packages/core/src/Dialog/DialogContext.ts b/packages/core/src/Dialog/DialogContext.ts index 9872e43d5fe59..600160df8d0c1 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(null); diff --git a/packages/core/src/internal/dialog-context.test.ts b/packages/core/src/internal/dialog-context.test.ts new file mode 100644 index 0000000000000..976496f876b24 --- /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 = 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 = 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.ts new file mode 100644 index 0000000000000..aaf9ca18b4b55 --- /dev/null +++ b/packages/core/src/internal/dialog-context.ts @@ -0,0 +1,19 @@ +// 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 + * (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in + * Core and Lab by the `@astryx/no-core-internal-import` lint rule + * (architecture:react-component-runtime INV13). 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.js index ee5316c7916a1..ec61b3c86cb0a 100644 --- a/scripts/sync-exports.js +++ b/scripts/sync-exports.js @@ -239,6 +239,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [ // (architecture:react-component-runtime INV13). 'internal/touch', 'internal/tokenizer-presentation', + 'internal/dialog-context', ]; /**