Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
104 changes: 103 additions & 1 deletion packages/core/src/Dialog/Dialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';

Expand Down Expand Up @@ -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(
<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('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();
Expand Down Expand Up @@ -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 ? <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">
Expand Down
46 changes: 36 additions & 10 deletions packages/core/src/Dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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<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) {
if (target.closest('[hidden], [inert], [aria-hidden="true"]')) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This walks every ancestor, past the <dialog>. A modal dialog escapes an ancestor's inertness: Chromium focuses a button inside a modal <dialog> under <div inert>. A Dialog rendered in an inert region therefore skips its own eligible request and falls back to native focus, against component:Dialog FR2. Count a match only when it is inside the dialog:

const blocker = target.closest('[hidden], [inert], [aria-hidden="true"]');
if (blocker != null && dialog.contains(blocker)) {
  continue;
}

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

document is the page's document. For a Dialog rendered into an iframe or a Picture-in-Picture window this is never true, so the loop focuses every eligible request in turn and ends on the last one, which is the dialog-title request when there is one. Compare against the target's own document:

if (target.ownerDocument.activeElement === target) {
  break;
}

break;
}
}
}
} else {
Expand Down
9 changes: 8 additions & 1 deletion packages/core/src/Dialog/DialogContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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);
Expand Down
25 changes: 25 additions & 0 deletions packages/core/src/internal/dialog-context.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
19 changes: 19 additions & 0 deletions packages/core/src/internal/dialog-context.ts
Original file line number Diff line number Diff line change
@@ -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';
1 change: 1 addition & 0 deletions scripts/sync-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
// (architecture:react-component-runtime INV13).
'internal/touch',
'internal/tokenizer-presentation',
'internal/dialog-context',
];

/**
Expand Down
Loading