Skip to content

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

TypeScript

fix(core): label Dialog from its header title via aria-labelledby (#4000)

Baraa Hamodi65f7202173a2
diff --git a/.changeset/dialog-default-labelledby.md b/.changeset/dialog-default-labelledby.md
new file mode 100644
index 0000000000..6a9748187d
--- /dev/null
+++ b/.changeset/dialog-default-labelledby.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Dialog: modals are now automatically labelled by their DialogHeader title via aria-labelledby, matching AlertDialog. Unnamed open dialogs warn in development.
+
+@bhamodi
diff --git a/packages/core/src/Dialog/Dialog.doc.mjs b/packages/core/src/Dialog/Dialog.doc.mjs
index 1d8fbeea7e..a3d1f892d7 100644
--- a/packages/core/src/Dialog/Dialog.doc.mjs
+++ b/packages/core/src/Dialog/Dialog.doc.mjs
@@ -111,7 +111,7 @@ export const docs = {
{ guidance: false, description: 'Use the fullscreen variant for simple confirmations; it is meant for complex content like editors or long forms.' },
],
anatomy: [
- {name: 'Header', required: true, description: 'Title, optional subtitle, and close button. The title receives focus on open for accessibility.'},
+ {name: 'Header', required: true, description: 'Title, optional subtitle, and close button. The title receives focus on open and labels the dialog via aria-labelledby.'},
{name: 'Body', required: true, description: 'The main content area: text, forms, lists, or any layout.'},
{name: 'Footer', required: false, description: 'Action buttons like Save/Cancel or Accept/Decline, aligned to the end.'},
{name: 'Backdrop', required: true, description: 'Semi-transparent overlay behind the dialog that blocks page interaction.'},
@@ -133,7 +133,7 @@ export const docsZh = {
{ guidance: false, description: 'Use the fullscreen variant for simple confirmations; it is meant for complex content like editors or long forms.' },
],
anatomy: [
- {name: 'Header', required: true, description: 'Title, optional subtitle, and close button. The title receives focus on open for accessibility.'},
+ {name: 'Header', required: true, description: 'Title, optional subtitle, and close button. The title receives focus on open and labels the dialog via aria-labelledby.'},
{name: 'Body', required: true, description: 'The main content area: text, forms, lists, or any layout.'},
{name: 'Footer', required: false, description: 'Action buttons like Save/Cancel or Accept/Decline, aligned to the end.'},
{name: 'Backdrop', required: true, description: 'Semi-transparent overlay behind the dialog that blocks page interaction.'},
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index 988e141cad..fc5854309b 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -212,10 +212,7 @@ describe('Dialog', () => {
it('forwards additional props to dialog element', () => {
render(
- <Dialog
- isOpen={true}
- onOpenChange={() => {}}
- data-testid="custom-dialog">
+ <Dialog isOpen={true} onOpenChange={() => {}} data-testid="custom-dialog">
Content
</Dialog>,
);
@@ -267,6 +264,82 @@ describe('Dialog', () => {
});
});
+ describe('accessible name', () => {
+ it('is labelled by the DialogHeader title by default', () => {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}}>
+ <DialogHeader title="Dialog title" />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog');
+ const heading = screen.getByRole('heading', {name: 'Dialog title'});
+ expect(heading.id).not.toBe('');
+ expect(dialog).toHaveAttribute('aria-labelledby', heading.id);
+ expect(dialog).toHaveAccessibleName('Dialog title');
+ });
+
+ it('prefers a consumer-provided aria-label over the header title', () => {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Custom name">
+ <DialogHeader title="Dialog title" />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog');
+ expect(dialog).not.toHaveAttribute('aria-labelledby');
+ expect(dialog).toHaveAccessibleName('Custom name');
+ });
+
+ it('prefers a consumer-provided aria-labelledby over the header title', () => {
+ render(
+ <>
+ <span id="external-label">External name</span>
+ <Dialog
+ isOpen={true}
+ onOpenChange={() => {}}
+ aria-labelledby="external-label">
+ <DialogHeader title="Dialog title" />
+ </Dialog>
+ </>,
+ );
+ const dialog = screen.getByRole('dialog');
+ expect(dialog).toHaveAttribute('aria-labelledby', 'external-label');
+ expect(dialog).toHaveAccessibleName('External name');
+ });
+
+ it('omits aria-labelledby and warns when open with no name source', () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}}>
+ Content
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog');
+ expect(dialog).not.toHaveAttribute('aria-labelledby');
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('accessible name'),
+ );
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
+ it('does not warn when the header provides a title', () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}}>
+ <DialogHeader title="Dialog title" />
+ </Dialog>,
+ );
+ expect(warnSpy).not.toHaveBeenCalled();
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+ });
+
describe('inner flex wrapper', () => {
it('wraps children in a flex container for scroll support', () => {
render(
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 203e6688a9..d4c2695b55 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -16,7 +16,14 @@
* - /packages/cli/templates/blocks/components/Dialog/ (showcase blocks)
*/
-import {useEffect, useMemo, useRef, type ReactNode} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ type ReactNode,
+} from 'react';
import type {BaseProps} from '../BaseProps';
import * as stylex from '@stylexjs/stylex';
import {useScrollLock} from '../hooks/useScrollLock';
@@ -318,6 +325,9 @@ export interface DialogProps extends BaseProps<HTMLDialogElement> {
*
* Designed to be used with Layout as its child for structured content.
* Uses the browser's built-in modal behavior for optimal accessibility.
+ * When a DialogHeader is rendered inside, its title automatically names the
+ * dialog via aria-labelledby; pass `aria-label` or `aria-labelledby` to
+ * override.
*
* @example
* ```
@@ -354,10 +364,47 @@ export function Dialog({
const paddingToken = spacingStepToToken[effectivePadding] as SpacingToken;
const isFullscreen = variant === 'fullscreen';
- const dialogContextValue = useMemo(() => ({isInline}), [isInline]);
+
+ // Default accessible name: publish a title id through DialogContext so a
+ // DialogHeader applies it to its heading (mirrors AlertDialog's explicit
+ // useId wiring). Whether to emit the default aria-labelledby is decided
+ // imperatively in the callback ref below by checking whether the title
+ // element actually rendered — so a dialog with no header never points at a
+ // missing id, and we avoid the extra render a registration-via-state effect
+ // 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;
const dialogRef = useRef<HTMLDialogElement>(null);
+ // Callback ref on the <dialog>: sync the default aria-labelledby from the
+ // DialogHeader title (if one rendered) in the same commit, with no second
+ // render. Consumer aria-label/aria-labelledby win — when present we leave
+ // the attribute to the {...safeProps} spread and never touch it here.
+ const attachDialog = useCallback(
+ (node: HTMLDialogElement | null) => {
+ dialogRef.current = node;
+ if (!node || hasConsumerName) {
+ return;
+ }
+ const hasTitle = node.querySelector(`#${CSS.escape(titleId)}`) != null;
+ if (hasTitle) {
+ node.setAttribute('aria-labelledby', titleId);
+ } else {
+ node.removeAttribute('aria-labelledby');
+ }
+ },
+ [titleId, hasConsumerName],
+ );
+
// Capture the element that was focused when the dialog opened,
// for directional animation origin and focus restoration on close.
const triggerElementRef = useRef<HTMLElement | null>(null);
@@ -446,6 +493,28 @@ export function Dialog({
return () => dialog.removeEventListener('keydown', handleKeyDown);
}, [isOpen, isInline, allowEscape, onOpenChange]);
+ // Dev-time guardrail: an open modal should always have an accessible name.
+ // Warn once per component instance (in an effect) rather than on every
+ // render — mirrors the unnamed-dialog warning in usePopover.
+ const warnedUnnamedDialogRef = useRef(false);
+ useEffect(() => {
+ const hasHeaderTitle =
+ dialogRef.current?.querySelector(`#${CSS.escape(titleId)}`) != null;
+ if (
+ isOpen &&
+ !isInline &&
+ !hasConsumerName &&
+ !hasHeaderTitle &&
+ !warnedUnnamedDialogRef.current
+ ) {
+ warnedUnnamedDialogRef.current = true;
+ console.warn(
+ 'Dialog: open dialog has no accessible name. Add a DialogHeader ' +
+ 'with a `title`, or pass `aria-label`/`aria-labelledby`.',
+ );
+ }
+ }, [isOpen, isInline, hasConsumerName, titleId]);
+
// Handle backdrop click — when the user clicks the ::backdrop pseudo-element,
// the event target is the <dialog> element itself; clicks on child content
// always target the child. This avoids false positives from native browser
@@ -551,7 +620,7 @@ export function Dialog({
return (
<dialog
- ref={mergeRefs(ref, dialogRef)}
+ ref={mergeRefs(ref, attachDialog)}
{...safeProps}
{...mergeProps(
themeProps('dialog', {variant}),
@@ -576,6 +645,9 @@ export function Dialog({
onClick={handleClick}
onCancel={handleCancel}
aria-modal="true"
+ // The default aria-labelledby (from a DialogHeader title) is set
+ // imperatively in `attachDialog`; a consumer-provided aria-labelledby
+ // flows through {...safeProps} above and wins.
{...(purpose === 'required' ? {role: 'alertdialog'} : undefined)}>
{innerContent}
</dialog>
diff --git a/packages/core/src/Dialog/DialogContext.ts b/packages/core/src/Dialog/DialogContext.ts
index 8392062ea7..9872e43d5f 100644
--- a/packages/core/src/Dialog/DialogContext.ts
+++ b/packages/core/src/Dialog/DialogContext.ts
@@ -5,8 +5,8 @@
/**
* @file DialogContext.ts
* @input React context
- * @output Internal dialog context for child focus behavior
- * @position Dialog internals; consumed by focus-managing children
+ * @output Internal dialog context for child focus behavior and default labelling
+ * @position Dialog internals; consumed by focus-managing children and DialogHeader
*/
import {createContext, use} from 'react';
@@ -14,6 +14,13 @@ import {createContext, use} from 'react';
export interface DialogContextValue {
/** Whether the dialog is rendered inline for docs/showcases. */
isInline: boolean;
+ /**
+ * Id the DialogHeader title should render with so the dialog can name
+ * itself via aria-labelledby. The dialog detects the title element's
+ * presence directly (via a callback ref), so it only emits aria-labelledby
+ * when the title actually rendered — never pointing at a nonexistent id.
+ */
+ titleId?: string;
}
export const DialogContext = createContext<DialogContextValue | null>(null);
diff --git a/packages/core/src/Dialog/DialogHeader.doc.mjs b/packages/core/src/Dialog/DialogHeader.doc.mjs
index 5899acc6fb..3b53bc34b9 100644
--- a/packages/core/src/Dialog/DialogHeader.doc.mjs
+++ b/packages/core/src/Dialog/DialogHeader.doc.mjs
@@ -12,7 +12,7 @@ export const docs = {
{
name: 'title',
type: 'string',
- description: 'Dialog title (receives focus on open).',
+ description: 'Dialog title (receives focus on open and labels the dialog via aria-labelledby).',
},
{
name: 'subtitle',
@@ -158,7 +158,7 @@ export const docsDense = {
displayName: 'Dialog Header',
description: 'dialog header w/ title, optional subtitle, close button, start/end content slots',
propDescriptions: {
- title: 'dialog title (receives focus on open)',
+ title: 'dialog title (focused on open; labels dialog via aria-labelledby)',
subtitle: 'subtitle below title',
onOpenChange: 'close button callback (omit=no button)',
startContent: 'content before title (e.g. back button)',
diff --git a/packages/core/src/Dialog/DialogHeader.tsx b/packages/core/src/Dialog/DialogHeader.tsx
index a6fcb2a16a..7598550c0b 100644
--- a/packages/core/src/Dialog/DialogHeader.tsx
+++ b/packages/core/src/Dialog/DialogHeader.tsx
@@ -65,7 +65,9 @@ export interface DialogHeaderProps extends BaseProps<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
/**
* The title of the dialog.
- * This title receives focus when the dialog opens for screen reader accessibility.
+ * This title receives focus when the dialog opens for screen reader
+ * accessibility, and names the parent Dialog via aria-labelledby unless the
+ * consumer passes an explicit aria-label/aria-labelledby to the Dialog.
*/
title: string;
@@ -105,7 +107,8 @@ export interface DialogHeaderProps extends BaseProps<HTMLDivElement> {
* Renders a title that receives focus when a modal dialog opens (for screen reader accessibility)
* and an optional close button. Inline documentation previews suppress this autofocus.
* The title is an h2 element with tabIndex={-1} so it can be programmatically focused but
- * doesn't appear in the tab order.
+ * doesn't appear in the tab order. The title also names the parent Dialog via
+ * aria-labelledby (unless the Dialog receives an explicit aria-label/aria-labelledby).
*
* Uses LayoutHeader internally for consistent styling with other layout headers.
*
@@ -137,10 +140,13 @@ export function DialogHeader({
const titleRef = useRef<HTMLHeadingElement>(null);
const dialogContext = useDialogContext();
const shouldAutoFocus = dialogContext?.isInline !== true;
+ const titleId = dialogContext?.titleId;
// Auto-focus the title when mounted for screen reader accessibility.
// Inline dialogs are documentation/showcase previews, so suppress focus to
// avoid stealing scroll position from the surrounding page.
+ // The parent Dialog detects this title (by `titleId`) via a callback ref to
+ // set its default aria-labelledby — no registration handshake needed here.
useEffect(() => {
if (shouldAutoFocus && titleRef.current) {
titleRef.current.focus();
@@ -162,6 +168,7 @@ export function DialogHeader({
<div {...stylex.props(styles.titleWrapper)}>
<Heading
ref={titleRef}
+ id={titleId}
level={2}
tabIndex={-1}
xstyle={styles.titleFocusable}>