Skip to content

Commit 7c0f6d2

Browse files
jiunshinncixzhang
authored andcommitted
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.
1 parent af7037b commit 7c0f6d2

9 files changed

Lines changed: 214 additions & 12 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[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)
6+
@jiunshinn
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[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)
6+
@jiunshinn

‎packages/core/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -848,6 +848,11 @@
848848
"source": "./src/internal/calendar-system.ts",
849849
"types": "./dist/internal/calendar-system.d.ts",
850850
"default": "./dist/internal/calendar-system.js"
851+
},
852+
"./internal/dialog-context": {
853+
"source": "./src/internal/dialog-context.ts",
854+
"types": "./dist/internal/dialog-context.d.ts",
855+
"default": "./dist/internal/dialog-context.js"
851856
}
852857
},
853858
"files": [

‎packages/core/src/Dialog/Dialog.test.tsx‎

Lines changed: 108 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99
* SYNC: When Dialog.tsx changes, update tests to match new behavior
1010
*/
1111

12-
import {StrictMode, useState, type SyntheticEvent} from 'react';
12+
import {
13+
StrictMode,
14+
useLayoutEffect,
15+
useState,
16+
type SyntheticEvent,
17+
} from 'react';
1318
import {readFileSync} from 'node:fs';
1419
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
1520
import type {MockInstance} from 'vitest';
@@ -29,6 +34,7 @@ import {
2934
} from './Dialog';
3035
import {DialogHeader} from './DialogHeader';
3136
import {getFocusableElements, useFocusTrap} from '../hooks/useFocusTrap';
37+
import {useDialogContext} from './DialogContext';
3238
import {defineTheme, generateThemeCSS} from '../theme';
3339
import {
3440
__resetInteractionModalityForTest,
@@ -496,6 +502,75 @@ describe('Dialog', () => {
496502
expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();
497503
});
498504

505+
it('skips a hidden or inert initial-focus request for the next eligible one', () => {
506+
render(
507+
<Dialog isOpen={true} onOpenChange={() => {}}>
508+
<div hidden>
509+
<button type="button" data-autofocus>
510+
Hidden
511+
</button>
512+
</div>
513+
<div inert>
514+
<button type="button" data-autofocus>
515+
Inert
516+
</button>
517+
</div>
518+
<button type="button" data-autofocus>
519+
Continue
520+
</button>
521+
</Dialog>,
522+
);
523+
524+
expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();
525+
});
526+
527+
it('falls through an initial-focus request that cannot take focus', () => {
528+
render(
529+
<Dialog isOpen={true} onOpenChange={() => {}}>
530+
<button type="button" disabled data-autofocus>
531+
Unavailable
532+
</button>
533+
<button type="button" data-autofocus>
534+
Continue
535+
</button>
536+
</Dialog>,
537+
);
538+
539+
expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();
540+
});
541+
542+
it("honors an explicit request before a header's title request", () => {
543+
render(
544+
<Dialog isOpen={true} onOpenChange={() => {}}>
545+
<h2 tabIndex={-1} data-autofocus="dialog-title">
546+
Hero title
547+
</h2>
548+
<button type="button" data-autofocus>
549+
Continue
550+
</button>
551+
</Dialog>,
552+
);
553+
554+
expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();
555+
});
556+
557+
it("focuses a header's title request when no explicit request is eligible", () => {
558+
render(
559+
<Dialog isOpen={true} onOpenChange={() => {}}>
560+
<h2 tabIndex={-1} data-autofocus="dialog-title">
561+
Hero title
562+
</h2>
563+
<div hidden>
564+
<button type="button" data-autofocus>
565+
Hidden
566+
</button>
567+
</div>
568+
</Dialog>,
569+
);
570+
571+
expect(screen.getByRole('heading', {name: 'Hero title'})).toHaveFocus();
572+
});
573+
499574
describe('purpose: info (default)', () => {
500575
it('calls onOpenChange(false) when Escape is pressed', () => {
501576
const handleHide = vi.fn();
@@ -1723,6 +1798,38 @@ describe('Dialog', () => {
17231798
expect(dialog).toHaveAccessibleName('Rich dialog title');
17241799
});
17251800

1801+
it('names itself by a header title that renders after the dialog mounts', () => {
1802+
// A composed header whose title arrives in a later commit asks the
1803+
// dialog to check its default name again.
1804+
function LateTitleHeader({isReady}: {isReady: boolean}) {
1805+
const context = useDialogContext();
1806+
const syncDefaultName = context?.syncDefaultName;
1807+
useLayoutEffect(() => {
1808+
syncDefaultName?.();
1809+
}, [isReady, syncDefaultName]);
1810+
return isReady ? <h2 id={context?.titleId}>Late title</h2> : null;
1811+
}
1812+
const {rerender} = render(
1813+
<Dialog isOpen={true} onOpenChange={() => {}}>
1814+
<LateTitleHeader isReady={false} />
1815+
</Dialog>,
1816+
);
1817+
const dialog = screen.getByRole('dialog');
1818+
expect(dialog).not.toHaveAttribute('aria-labelledby');
1819+
rerender(
1820+
<Dialog isOpen={true} onOpenChange={() => {}}>
1821+
<LateTitleHeader isReady={true} />
1822+
</Dialog>,
1823+
);
1824+
expect(dialog).toHaveAccessibleName('Late title');
1825+
rerender(
1826+
<Dialog isOpen={true} onOpenChange={() => {}}>
1827+
<LateTitleHeader isReady={false} />
1828+
</Dialog>,
1829+
);
1830+
expect(dialog).not.toHaveAttribute('aria-labelledby');
1831+
});
1832+
17261833
it('prefers a consumer-provided aria-label over the header title', () => {
17271834
render(
17281835
<Dialog isOpen={true} onOpenChange={() => {}} aria-label="Custom name">

‎packages/core/src/Dialog/Dialog.tsx‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
* Fullscreen dialogs add safe-area protection to the default padding fallback
1616
* while preserving explicit prop/theme padding overrides, and fade in without
1717
* the centered-dialog translate/scale motion.
18+
* Initial focus is applied after showModal; an explicit descendant request
19+
* takes priority over a header's default title request.
1820
*
1921
* Under reduced motion the entrance never travels or scales
2022
* (docs/design/reduced-motion.md): on a touch screen the dialog fades in
@@ -541,11 +543,6 @@ export function Dialog({
541543
// would cost at the dialog level.
542544
const titleId = useId();
543545

544-
const dialogContextValue = useMemo(
545-
() => ({isInline, titleId}),
546-
[isInline, titleId],
547-
);
548-
549546
// Consumer-provided labels always win over the DialogHeader default.
550547
const hasConsumerName =
551548
props['aria-label'] != null || props['aria-labelledby'] != null;
@@ -575,6 +572,19 @@ export function Dialog({
575572
[titleId, hasConsumerName],
576573
);
577574

575+
// A composed header whose title renders after the dialog mounted asks the
576+
// dialog to look for the title again.
577+
const syncDefaultName = useCallback(() => {
578+
if (dialogRef.current != null) {
579+
attachDialog(dialogRef.current);
580+
}
581+
}, [attachDialog]);
582+
583+
const dialogContextValue = useMemo(
584+
() => ({isInline, titleId, syncDefaultName}),
585+
[isInline, titleId, syncDefaultName],
586+
);
587+
578588
// Input in a second document (a same-origin iframe, a Document
579589
// Picture-in-Picture window) never reaches the page's listeners, so the
580590
// dialog's own document keeps its own last input for the focus return while
@@ -642,11 +652,27 @@ export function Dialog({
642652
dialog.showModal();
643653
// React's autoFocus calls .focus() during commit, before showModal()
644654
// makes the dialog visible, so the focus silently fails.
645-
// Focus the first element with data-autofocus inside the dialog.
646-
const autofocusTarget =
647-
dialog.querySelector<HTMLElement>('[data-autofocus]');
648-
if (autofocusTarget) {
649-
focusForLastInput(autofocusTarget);
655+
// Explicit descendant intent takes priority over a header's default
656+
// title. Keep the marker private to the focus-owning components.
657+
const autofocusTargets = [
658+
...dialog.querySelectorAll<HTMLElement>(
659+
'[data-autofocus]:not([data-autofocus="dialog-title"])',
660+
),
661+
...dialog.querySelectorAll<HTMLElement>(
662+
'[data-autofocus="dialog-title"]',
663+
),
664+
];
665+
for (const target of autofocusTargets) {
666+
if (target.closest('[hidden], [inert], [aria-hidden="true"]')) {
667+
continue;
668+
}
669+
// Disabled and CSS-hidden targets cannot receive focus in the
670+
// browser. If a request cannot land, try the next eligible request
671+
// and finally the title; otherwise preserve native initial focus.
672+
focusForLastInput(target);
673+
if (document.activeElement === target) {
674+
break;
675+
}
650676
}
651677
}
652678
// Under a coarse primary pointer, a tap or a drag during the entrance

‎packages/core/src/Dialog/DialogContext.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
* @file DialogContext.ts
77
* @input React context
88
* @output Internal dialog context for child focus behavior and default labelling
9-
* @position Dialog internals; consumed by focus-managing children and DialogHeader
9+
* @position Dialog internals; consumed by focus-managing children and DialogHeader,
10+
* and by Lab's DialogHeroHeader through the internal/dialog-context entry
1011
*/
1112

1213
import {createContext, use} from 'react';
@@ -21,6 +22,12 @@ export interface DialogContextValue {
2122
* when the title actually rendered — never pointing at a nonexistent id.
2223
*/
2324
titleId?: string;
25+
/**
26+
* Checks the default aria-labelledby again. The dialog looks for its title
27+
* when it mounts; a composed header whose title element appears, changes,
28+
* or leaves after that calls this so the dialog's name follows it.
29+
*/
30+
syncDefaultName?: () => void;
2431
}
2532

2633
export const DialogContext = createContext<DialogContextValue | null>(null);
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
/**
3+
* @file dialog-context.test.ts
4+
* @input The internal `internal/dialog-context` entry and the Dialog module
5+
* @output Proof that the entry re-exports the same hook Dialog provides, by
6+
* name, and that the public Dialog barrel names no context
7+
* @position Unit tests of packages/core/src/internal/dialog-context.ts
8+
*/
9+
import {describe, expect, it} from 'vitest';
10+
11+
describe('internal/dialog-context', () => {
12+
it('re-exports the one Dialog context hook, the same value Dialog reads', async () => {
13+
const entry: Record<string, unknown> = await import('./dialog-context');
14+
const context = await import('../Dialog/DialogContext');
15+
expect(entry.useDialogContext).toBe(context.useDialogContext);
16+
// Named re-exports only, nothing else.
17+
expect(Object.keys(entry).sort()).toEqual(['useDialogContext']);
18+
});
19+
20+
it('the public Dialog barrel exports no context surface', async () => {
21+
const pub: Record<string, unknown> = await import('../Dialog');
22+
expect(pub).not.toHaveProperty('DialogContext');
23+
expect(pub).not.toHaveProperty('useDialogContext');
24+
});
25+
});
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file dialog-context.ts
5+
* @input Dialog's internal context hook
6+
* @output `@astryxdesign/core/internal/dialog-context`: `useDialogContext`,
7+
* for Astryx's own packages
8+
* @position An internal entry reserved for Astryx's own packages:
9+
* undocumented, outside the public API and its compatibility promise
10+
* (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in
11+
* Core and Lab by the `@astryx/no-core-internal-import` lint rule
12+
* (architecture:react-component-runtime INV13). Lab's DialogHeroHeader reads
13+
* the Dialog's title id and inline state through it, so it names the dialog
14+
* and requests title focus the way DialogHeader does. Named re-exports only.
15+
*
16+
* SYNC: When modified, update dialog-context.test.ts and
17+
* scripts/sync-exports.js.
18+
*/
19+
export {useDialogContext} from '../Dialog/DialogContext';

‎scripts/sync-exports.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
242242
'internal/selectable-card',
243243
'internal/spinner-rotor',
244244
'internal/calendar-system',
245+
'internal/dialog-context',
245246
];
246247

247248
/**

0 commit comments

Comments
 (0)