Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
7 changes: 7 additions & 0 deletions .changeset/dropdown-menu-labelledby-trigger-name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[fix] DropdownMenu: a custom trigger (`renderTrigger`) named by `aria-labelledby` now names its open menu too. The menu points at the same ids, so a screen reader announces "Project actions menu" instead of an unnamed menu.

@cixzhang
4 changes: 3 additions & 1 deletion docs/specs/components/DropdownMenu/DropdownMenu.spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,9 @@ visibility helper.
- **AR1 — A custom trigger still names the menu.** With `renderTrigger`, the
menu carries `aria-labelledby` pointing at the control's `id` (the Button path
keeps `aria-label`), and the control carries `aria-haspopup="menu"`,
`aria-expanded` and `aria-controls`.
`aria-expanded` and `aria-controls`. When the control names itself by
`aria-labelledby`, the open menu points at the same ids, because a name
reference does not follow a second reference.
- **AR2 — A row that navigates is a link element.** A row with an `href` is
the anchor itself: in the pointer menu it keeps `role="menuitem"` so the menu
stays one menu, while a modified click or Enter keeps the browser's link
Expand Down
51 changes: 51 additions & 0 deletions packages/core/src/DropdownMenu/DropdownMenu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4247,6 +4247,57 @@ describe('DropdownMenu custom trigger', () => {
);
});

it('a custom trigger named by aria-labelledby names the open menu by the same ids (FR9, AR1)', async () => {
const user = userEvent.setup();
render(
<>
<h2 id="project-heading">Project actions</h2>
<DropdownMenu
renderTrigger={props => (
<button type="button" {...props} aria-labelledby="project-heading">
<span aria-hidden="true">⋯</span>
</button>
)}>
<DropdownMenuItem label="Rename" onClick={() => {}} />
</DropdownMenu>
</>,
);
const trigger = screen.getByRole('button', {name: 'Project actions'});
await user.click(trigger);
await waitFor(() =>
expect(trigger).toHaveAttribute('aria-expanded', 'true'),
);
const menu = screen.getByRole('menu', {
name: 'Project actions',
hidden: true,
});
expect(menu).toHaveAttribute('aria-labelledby', 'project-heading');
});

it('a custom trigger whose aria-labelledby resolves to nothing still names the menu by its own text', async () => {
const user = userEvent.setup();
render(
<DropdownMenu
renderTrigger={props => (
<button type="button" {...props} aria-labelledby="missing">
Project actions
</button>
)}>
<DropdownMenuItem label="Rename" onClick={() => {}} />
</DropdownMenu>,
);
const trigger = screen.getByRole('button', {name: 'Project actions'});
await user.click(trigger);
await waitFor(() =>
expect(trigger).toHaveAttribute('aria-expanded', 'true'),
);
const menu = screen.getByRole('menu', {
name: 'Project actions',
hidden: true,
});
expect(menu).toHaveAttribute('aria-labelledby', trigger.id);
});

it('a disabled custom trigger never opens the bottom sheet', async () => {
const user = userEvent.setup();
render(
Expand Down
29 changes: 26 additions & 3 deletions packages/core/src/DropdownMenu/DropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import React, {
type ReactNode,
} from 'react';
import {useCommittedRefInto} from '../hooks/useCommittedRef';
import {readAccessibleName} from '../utils/accessibleName';
import {labelledByText, readAccessibleName} from '../utils/accessibleName';
import * as stylex from '@stylexjs/stylex';
import {usePopoverInternal} from '../Popover/usePopover';
import {holdEntranceInput} from '../Layer/holdEntranceInput';
Expand Down Expand Up @@ -394,7 +394,11 @@ export type DropdownMenuPresentation = AdaptivePresentation;
export interface DropdownMenuTriggerProps {
/** Attaches the control as the menu's anchor and focus-return target. */
ref: (element: HTMLElement | null) => void;
/** The menu points at this id with `aria-labelledby`. */
/**
* The menu points at this id with `aria-labelledby`. When the trigger names
* itself by its own `aria-labelledby` and those ids resolve to text, the
* menu points at those ids instead.
*/
id: string;
onClick: (event: React.MouseEvent<HTMLElement>) => void;
onClickCapture: (event: React.MouseEvent<HTMLElement>) => void;
Expand Down Expand Up @@ -571,11 +575,24 @@ function holdInvokerThroughPress(
doc.addEventListener('pointercancel', onPressEnd, true);
}

/**
* The ids an element names itself by with `aria-labelledby`, when they resolve
* to non-empty text. A dangling or empty reference names nothing, so the
* element keeps the name it has from elsewhere.
*/
function readNameReference(element: HTMLElement | null): string | undefined {
if (element == null || labelledByText(element) == null) {
return undefined;
}
return element.getAttribute('aria-labelledby')?.trim();
}

/**
* The name of a menu opened from a custom trigger: the caller's `aria-label`
* when it is a non-empty string, else the trigger's own accessible name. The
* popover and the bottom sheet both name the menu through this.
*/

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.

Nit: moving the helper left this blank line between resolveCustomTriggerMenuName's doc comment and the function. Drop it so the comment sits directly on the function it documents.

function resolveCustomTriggerMenuName(
callerLabel: unknown,
triggerName: string | undefined,
Expand Down Expand Up @@ -972,6 +989,11 @@ function DropdownMenuPopover({

// The name a custom trigger gives the menu, read off it as the menu opens.
const [triggerName, setTriggerName] = useState<string | undefined>(undefined);
// The ids a custom trigger names itself by. A name reference does not follow
// a second reference, so the menu points at these ids, not at the trigger.
const [triggerLabelledBy, setTriggerLabelledBy] = useState<
string | undefined
>(undefined);

// Open state
const [internalIsOpen, setInternalIsOpen] = useState(false);
Expand Down Expand Up @@ -1152,6 +1174,7 @@ function DropdownMenuPopover({
resetFocusReturn();
if (renderTrigger != null) {
setTriggerName(readAccessibleName(buttonRef.current));
setTriggerLabelledBy(readNameReference(buttonRef.current));
}
if (notifyClickOnShowRef.current) {
notifyClickOnShowRef.current = false;
Expand Down Expand Up @@ -1927,7 +1950,7 @@ function DropdownMenuPopover({
isDrilled
? undefined
: renderTrigger != null && rest['aria-label'] == null
? triggerId
? (triggerLabelledBy ?? triggerId)
: (rest['aria-labelledby'] as string | undefined)
}
onKeyDown={listKeyDown}
Expand Down
35 changes: 23 additions & 12 deletions packages/core/src/utils/accessibleName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ export function visibleText(element: Element): string {
return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();
}

/**
* The text of the elements `element` names itself by with `aria-labelledby`,
* or `undefined` when no id resolves to non-empty text.
*/
export function labelledByText(element: HTMLElement): string | undefined {
const labelledBy = element.getAttribute('aria-labelledby');
if (labelledBy == null || labelledBy.trim() === '') {
return undefined;
}
const text = labelledBy
.trim()
.split(/\s+/)
.map(id => element.ownerDocument.getElementById(id))
.filter((node): node is HTMLElement => node != null)
.map(visibleText)
.join(' ')
.trim();
return text === '' ? undefined : text;
}

/**
* The accessible name of `element`: its own `aria-labelledby` targets, its
* `aria-label`, its labels, an input button's value, its text, or its
Expand All @@ -44,18 +64,9 @@ export function readAccessibleName(
if (element == null) {
return undefined;
}
const labelledBy = element.getAttribute('aria-labelledby');
if (labelledBy != null && labelledBy.trim() !== '') {
const text = labelledBy
.split(/\s+/)
.map(id => element.ownerDocument.getElementById(id))
.filter((node): node is HTMLElement => node != null)
.map(visibleText)
.join(' ')
.trim();
if (text !== '') {
return text;
}
const labelledBy = labelledByText(element);
if (labelledBy != null) {
return labelledBy;
}
const label = element.getAttribute('aria-label')?.trim();
if (label) {
Expand Down
Loading