An open source design system that's fully customizable and agent ready
TypeScript
fix(CheckboxListItem): name the checkbox from a rich label's visible text (#6178)
홍규진029368bde880
diff --git a/.changeset/checkbox-list-item-rich-label-name.md b/.changeset/checkbox-list-item-rich-label-name.mdnew file mode 100644index 0000000000..d7200ebe1a--- /dev/null+++ b/.changeset/checkbox-list-item-rich-label-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] CheckboxListItem: a ReactNode `label` now names the checkbox from its visible text through `aria-labelledby`, the way RadioListItem already does, instead of falling back to the generic name "Checkbox". `aria-label` still replaces that name; a rich label with no text at all needs it, as it does for RadioListItem. The dev-time warning that asked for `aria-label` on every rich label is gone.++@Kyujeniusdiff --git a/apps/storybook/stories/CheckboxA11y.stories.tsx b/apps/storybook/stories/CheckboxA11y.stories.tsxindex 187f436a53..60416b8214 100644--- a/apps/storybook/stories/CheckboxA11y.stories.tsx+++ b/apps/storybook/stories/CheckboxA11y.stories.tsx@@ -59,8 +59,8 @@ export const ListItemUnchecked = storyFor('list-item-unchecked');export const ListItemChecked = storyFor('list-item-checked');export const ListItemMixed = storyFor('list-item-mixed');export const ListItemDescribed = storyFor('list-item-described');-export const ListItemRichLabelMissingName = storyFor(- 'list-item-rich-label-missing-name',+export const ListItemRichLabelVisibleName = storyFor(+ 'list-item-rich-label-visible-name',);export const ListItemDisabled = storyFor('list-item-disabled');export const ListItemLoading = storyFor('list-item-loading');diff --git a/apps/storybook/stories/CheckboxList.stories.tsx b/apps/storybook/stories/CheckboxList.stories.tsxindex f5a7c5fdc6..57995cc21c 100644--- a/apps/storybook/stories/CheckboxList.stories.tsx+++ b/apps/storybook/stories/CheckboxList.stories.tsx@@ -109,7 +109,6 @@ export const RichDescriptions: Story = {Analytics <Link href="#analytics-details">details</Link></>}- aria-label="Analytics"value="analytics"description={<>diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 2368d7019c..87df859ae8 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -377,7 +377,7 @@},"@astryx.checkboxList.item.checkbox": {"defaultMessage": "Checkbox",- "description": "Screen-reader-only last-ditch fallback name for a checkbox inside a list item when no label is provided. Should almost never render — consumers should supply a real label."+ "description": "Localized hidden text used internally when a rich visible label names the checkbox through aria-labelledby. It does not become the computed name; callers must provide aria-label when rich content has no text."},"@astryx.commandPalette.emptySearch": {"defaultMessage": "No results",diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.tsindex ab4b063b00..364a8d6a89 100644--- a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts@@ -38,19 +38,6 @@ export const CHECKBOX_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [reason:'This is the accessibility-tree face of the missing relationship recorded above. It is separate because each known failure names exactly one expectation and layer.',},- {- expectation: 'checkbox.name.matches-visible-label',- binding: 'CheckboxListItem',- state: 'list-item-rich-label-missing-name',- evidenceLayer: 'accessibility-tree',- failureEquals:- 'the visible label reads "Pro plan" but the browser computes the accessible name as "Checkbox", so speaking the visible label does not reach this control',- standardsReference: 'WCAG 2.2 2.5.3 Label in Name (Level A)',- userImpact:- 'The browser exposes every rich-label item without an aria-label under the generic name "Checkbox", so speech input cannot address the item by the visible words.',- reason:- 'The public API permits a ReactNode label without an equivalent plain-text name. The migration records that supported branch without changing the component API.',- },{expectation: 'checkbox.readonly.declared',binding: 'CheckboxInput',diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsxindex 28ccb18a46..fdd3c3f8cd 100644--- a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx@@ -281,7 +281,7 @@ export const CHECKBOX_STATE_RENDERS: Record<description="Receive notifications by email"/>),- 'list-item-rich-label-missing-name': () => (+ 'list-item-rich-label-visible-name': () => (<StandaloneListItem initial={false} label="Pro plan" omitAriaLabel />),'list-item-disabled': () => (diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.tsindex 8be921414e..e22aadc82d 100644--- a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts@@ -260,14 +260,13 @@ export const CHECKBOX_BINDING_STATES = [],},{- id: 'list-item-rich-label-missing-name',+ id: 'list-item-rich-label-visible-name',binding: 'CheckboxListItem',- summary:- 'a rich-label list item with no equivalent plain-text accessible name',+ summary: 'a rich-label list item named from its visible text',facts: facts(),visibleLabel: 'Pro plan',visibleLabelSelector: '[data-a11y-visible-label]',- storyId: 'a11y-checkbox-pattern--list-item-rich-label-missing-name',+ storyId: 'a11y-checkbox-pattern--list-item-rich-label-visible-name',},{id: 'list-item-disabled',diff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsxindex 16433316bd..1b14c4a870 100644--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx@@ -369,12 +369,14 @@ describe('CheckboxList', () => {Pro plan <a href="#pricing">pricing details</a></>}- aria-label="Pro plan"+ aria-label="Pro plan pricing details"value="pro"/></CheckboxList>,);- const checkbox = screen.getByRole('checkbox', {name: 'Pro plan'});+ const checkbox = screen.getByRole('checkbox', {+ name: 'Pro plan pricing details',+ });const link = screen.getByRole('link', {name: 'pricing details'});await user.tab();expect(checkbox).toHaveFocus();@@ -596,8 +598,7 @@ describe('CheckboxListItem accessible name', () => {).toBeInTheDocument();});- it('names the checkbox from aria-label when the label is a ReactNode', () => {- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ it('names the checkbox from a conforming aria-label when the label is a ReactNode', () => {render(<CheckboxList label="Plans" value={[]} onChange={() => {}}><CheckboxListItem@@ -606,46 +607,49 @@ describe('CheckboxListItem accessible name', () => {Pro plan <em>(recommended)</em></span>}- aria-label="Pro plan"+ aria-label="Pro plan (recommended) option"value="pro"/></CheckboxList>,);expect(- screen.getByRole('checkbox', {name: 'Pro plan'}),+ screen.getByRole('checkbox', {name: 'Pro plan (recommended) option'}),).toBeInTheDocument();- // A named checkbox needs no dev guidance.- expect(warnSpy).not.toHaveBeenCalled();- warnSpy.mockRestore();});- it('warns once when a ReactNode label has no aria-label', () => {- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});- const richLabel = (- <span>- Pro plan <em>(recommended)</em>- </span>- );- const {rerender} = render(+ it('links a ReactNode label to the checkbox control', () => {+ render(<CheckboxList label="Plans" value={[]} onChange={() => {}}>- <CheckboxListItem label={richLabel} value="pro" />+ <CheckboxListItem+ label={+ <span>+ Pro plan <em>(recommended)</em>+ </span>+ }+ value="pro"+ /></CheckboxList>,);- // Falls back to the generic name, and tells the developer how to fix it.- expect(- screen.getByRole('checkbox', {name: 'Checkbox'}),- ).toBeInTheDocument();- expect(warnSpy).toHaveBeenCalledTimes(1);- expect(String(warnSpy.mock.calls[0]?.[0])).toContain('aria-label');+ const checkbox = screen.getByRole('checkbox');+ const labelledBy = checkbox.getAttribute('aria-labelledby');+ expect(labelledBy).toBeTruthy();+ expect(document.getElementById(labelledBy!)).toHaveTextContent(+ 'Pro plan (recommended)',+ );+ });- // Warn once per item instance — re-renders don't repeat it.- rerender(- <CheckboxList label="Plans" value={['pro']} onChange={() => {}}>- <CheckboxListItem label={richLabel} value="pro" />+ it('does not reference the visible label when a conforming aria-label is given', () => {+ render(+ <CheckboxList label="Plans" value={[]} onChange={() => {}}>+ <CheckboxListItem+ label={<span>Pro plan</span>}+ aria-label="Pro plan option"+ value="pro"+ /></CheckboxList>,);- expect(warnSpy).toHaveBeenCalledTimes(1);- warnSpy.mockRestore();+ const checkbox = screen.getByRole('checkbox', {name: 'Pro plan option'});+ expect(checkbox).not.toHaveAttribute('aria-labelledby');});});@@ -785,7 +789,7 @@ describe('CheckboxListItem ARIA props', () => {<CheckboxListItemlabel="Custom aria"aria-describedby="help-text"- aria-label="custom label"+ aria-label="Custom aria label"/></List>,);@@ -795,7 +799,7 @@ describe('CheckboxListItem ARIA props', () => {// ...but aria-label names the checkbox control, not the row.expect(item).not.toHaveAttribute('aria-label');expect(- screen.getByRole('checkbox', {name: 'custom label'}),+ screen.getByRole('checkbox', {name: 'Custom aria label'}),).toBeInTheDocument();});diff --git a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjsindex 92e1b27d53..7d03534bf9 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs+++ b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs@@ -14,14 +14,14 @@ export const docs = {name: 'label',type: 'ReactNode',description:- 'Primary text label for the item. Rich labels may contain links or buttons, which keep their own behavior without toggling the item. Pair a ReactNode label with aria-label so screen readers get a concise checkbox name.',+ 'Primary text label for the item. Rich labels may contain links or buttons, which keep their own behavior without toggling the item. A ReactNode label names the checkbox from its visible text; pass aria-label only when that text is absent, or include all visible label words in the override.',required: true,},{name: 'aria-label',type: 'string',description:- 'Plain-text accessible name for the checkbox when label is a ReactNode. Applied to the checkbox control. Without it, rich-label items all announce as the generic "Checkbox" to screen readers.',+ 'Plain-text accessible name for the checkbox, replacing the one derived from label. Applied to the checkbox control. Use it when a rich label has no visible text; otherwise the value must retain every visible label word.',},{name: 'value',@@ -79,10 +79,10 @@ export const docs = {],examples: [{- label: 'Rich label with an accessible name',+ label: 'Rich label with an overriding aria-label',code: `<CheckboxListItemlabel={<span>Pro plan <Badge label="Recommended" /></span>}- aria-label="Pro plan"+ aria-label="Pro plan Recommended option"value="pro"/>`,},@@ -100,14 +100,14 @@ export const docsZh = {name: 'label',type: 'ReactNode',description:- '选项的主标签。富内容标签可包含链接或按钮,它们保留自身行为且不会切换该选项。ReactNode 标签应同时传入 aria-label,为屏幕阅读器提供简洁的复选框名称。',+ '选项的主标签。富内容标签可包含链接或按钮,它们保留自身行为且不会切换该选项。ReactNode 标签会以其可见文本为复选框命名;仅当可见文本缺失时使用 aria-label,否则覆盖值必须保留全部可见文字。',required: true,},{name: 'aria-label',type: 'string',description:- '当 label 是 ReactNode 时,复选框的纯文本无障碍名称。缺少它时,富标签选项都会向屏幕阅读器播报为通用的 "Checkbox"。',+ '复选框的纯文本无障碍名称,会替换由 label 推导出的名称。仅当富标签没有可见文本时才完全替代;否则必须保留全部可见文字。',},{name: 'value',@@ -158,9 +158,9 @@ export const docsDense = {'Individual checkbox item w/ label, description, end content slot.',propDescriptions: {label:- 'Primary label. String or ReactNode; nested controls keep their behavior.',+ 'Primary label. String or ReactNode; nested controls keep their behavior. A ReactNode names the checkbox from its visible text.','aria-label':- 'Plain-text checkbox name when label is a ReactNode. Without it, rich-label items all announce as "Checkbox".',+ 'Plain-text checkbox name replacing the one derived from label. Use when visible text is absent; otherwise retain every visible label word.',value: 'Identity key (required inside CheckboxList).',description: 'Secondary content below label. String or ReactNode.',endContent: 'Content rendered after label area.',diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsxindex 72368ffc32..d9281d778b 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx@@ -16,12 +16,11 @@* - /packages/cli/assets/templates/blocks/components/CheckboxList/ (showcase blocks)*/-import {use, useRef, type ReactNode} from 'react';+import {use, useId, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';-import {useDevWarning} from '../hooks/useDevWarning';import {CheckboxInput} from '../CheckboxInput/CheckboxInput';import {ListItem} from '../List/ListItem';import {ListContext} from '../List/ListContext';@@ -51,22 +50,29 @@ export interface CheckboxListItemProps extends BaseProps<HTMLLIElement> {* child components control their own text behavior). Links and buttons in* the label keep their own behavior; only non-interactive row clicks* delegate to the checkbox.+ *+ * A string names the checkbox directly. A ReactNode names it from its+ * visible text through `aria-labelledby`; if that text is absent, pass+ * `aria-label`. When visible text is present, an override must retain every+ * visible word so speech-input users can say what they see.*/label: ReactNode;/**- * Plain-text accessible name for the checkbox when `label` is a ReactNode.+ * Plain-text accessible name for the checkbox, replacing the one derived+ * from `label`.*- * A string `label` names the checkbox automatically. A rich (ReactNode)- * `label` cannot, so pass a concise string equivalent via the standard- * `aria-label` — otherwise the checkbox falls back to the generic name- * "Checkbox" and every rich-label item in a list announces identically to- * screen readers. Applied to the checkbox control, not the row.+ * A string `label` names the checkbox directly, and a rich (ReactNode)+ * `label` names it from its visible text through `aria-labelledby`. Pass+ * `aria-label` when that text is absent. When visible text is present, the+ * override must retain every visible word so speech-input users can say what+ * they see. It replaces the derived name and applies to the checkbox control,+ * not the row.** @example* ```* <CheckboxListItem* label={<span>Pro plan <Badge label="Recommended" /></span>}- * aria-label="Pro plan"+ * aria-label="Pro plan Recommended option"* value="pro"* />* ```@@ -164,24 +170,19 @@ export function CheckboxListItem({);}- // Accessible name for the (visually hidden) checkbox label. A string- // `label` names it directly; a rich label needs `aria-label`.+ // Accessible name for the checkbox. A string `label` (or an explicit+ // `aria-label`) becomes the text of CheckboxInput's visually hidden+ // `<label>`, which only accepts a string. A rich label instead names the+ // checkbox from the visible label element through `aria-labelledby`, as+ // RadioListItem does; the hidden label then carries only the generic word,+ // which `aria-labelledby` outranks. Strings are left unwrapped on purpose:+ // Item single-line-truncates a raw string label but not a node.+ const isRichLabel = typeof label !== 'string';+ const labelID = useId();+ const namesFromVisibleLabel = isRichLabel && ariaLabel == null;const checkboxLabel =ariaLabel ??- (typeof label === 'string'- ? label- : t('@astryx.checkboxList.item.checkbox'));-- // Dev-time guardrail: a rich label without `aria-label` leaves the- // checkbox with the generic name "Checkbox".- useDevWarning(- 'CheckboxListItem',- '`label` is a ReactNode, so the checkbox falls ' +- 'back to the generic accessible name "Checkbox". Pass ' +- '`aria-label` with a concise string equivalent of the visible ' +- 'label so screen readers can tell items apart.',- typeof label !== 'string' && ariaLabel == null,- );+ (isRichLabel ? t('@astryx.checkboxList.item.checkbox') : label);// Density from list context for checkbox sizingconst listCtx = use(ListContext);@@ -249,7 +250,7 @@ export function CheckboxListItem({<ListItem{...restProps}ref={ref}- label={label}+ label={namesFromVisibleLabel ? <span id={labelID}>{label}</span> : label}description={description}endContent={endContent}isDisabled={effectiveDisabled}@@ -275,6 +276,7 @@ export function CheckboxListItem({<CheckboxInputref={checkboxRef}label={checkboxLabel}+ aria-labelledby={namesFromVisibleLabel ? labelID : undefined}isLabelHiddenvalue={resolvedChecked}onChange={() => handleToggle()}diff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsxindex 6cd84f7505..84049903bf 100644--- a/packages/core/src/RadioList/RadioList.test.tsx+++ b/packages/core/src/RadioList/RadioList.test.tsx@@ -682,13 +682,13 @@ describe('RadioList', () => {label="Option A"value="a"data-testid="item-a"- aria-label="First option"+ aria-label="Option A, first option"/></RadioList>,);expect(screen.getByTestId('item-a')).not.toHaveAttribute('aria-label');expect(- screen.getByRole('radio', {name: 'First option'}),+ screen.getByRole('radio', {name: 'Option A, first option'}),).toBeInTheDocument();});});@@ -708,8 +708,7 @@ describe('RadioList', () => {</RadioList>,);// The radio points at its visible label, so the name is computed from- // the rich node's own text — unlike CheckboxListItem, whose control has- // a separate hidden label and needs aria-label to say anything useful.+ // the rich node's own text.expect(screen.getByRole('radio', {name: 'Pro plan (recommended)'}),).toBeInTheDocument();@@ -724,12 +723,14 @@ describe('RadioList', () => {Pro plan <em>(recommended)</em></span>}- aria-label="Pro plan"+ aria-label="Pro plan (recommended) option"value="pro"/></RadioList>,);- expect(screen.getByRole('radio', {name: 'Pro plan'})).toBeInTheDocument();+ expect(+ screen.getByRole('radio', {name: 'Pro plan (recommended) option'}),+ ).toBeInTheDocument();});it('selects the option when a ReactNode label is clicked', async () => {@@ -755,12 +756,14 @@ describe('RadioList', () => {Pro plan <a href="#pricing">pricing details</a></>}- aria-label="Pro plan"+ aria-label="Pro plan pricing details"value="pro"/></RadioList>,);- const radio = screen.getByRole('radio', {name: 'Pro plan'});+ const radio = screen.getByRole('radio', {+ name: 'Pro plan pricing details',+ });const link = screen.getByRole('link', {name: 'pricing details'});await user.tab();expect(radio).toHaveFocus();diff --git a/packages/core/src/RadioList/RadioListItem.doc.mjs b/packages/core/src/RadioList/RadioListItem.doc.mjsindex c22ec31b68..b664130a15 100644--- a/packages/core/src/RadioList/RadioListItem.doc.mjs+++ b/packages/core/src/RadioList/RadioListItem.doc.mjs@@ -22,14 +22,14 @@ export const docs = {name: 'label',type: 'ReactNode',description:- 'Primary label for the radio item. Rich labels may contain links or buttons, which keep their own behavior without selecting the item. The label text names the radio; pair it with aria-label when that text does not read well on its own.',+ 'Primary label for the radio item. Rich labels may contain links or buttons, which keep their own behavior without selecting the item. The label text names the radio; use aria-label only when that text is absent, or retain every visible label word in the override.',required: true,},{name: 'aria-label',type: 'string',description:- 'Plain-text accessible name for the radio, applied to the control rather than the row. It overrides whatever the label element computes — a plain string label included — so reach for it when a rich label\u2019s own text is absent or reads badly.',+ 'Plain-text accessible name for the radio, applied to the control rather than the row. It overrides the name derived from the label. Use it when a rich label has no visible text; otherwise retain every visible label word.',},{name: 'value',@@ -96,14 +96,14 @@ export const docsZh = {name: 'label',type: 'ReactNode',description:- '单选选项的主标签。富内容标签可包含链接或按钮,它们保留自身行为且不会选中该选项。标签文本用于命名单选框;若朗读效果不佳,请同时传入 aria-label。',+ '单选选项的主标签。富内容标签可包含链接或按钮,它们保留自身行为且不会选中该选项。标签文本用于命名单选框;仅当可见文本缺失时使用 aria-label,否则覆盖值必须保留全部可见文字。',required: true,},{name: 'aria-label',type: 'string',description:- '单选框的纯文本无障碍名称,应用于控件本身而非整行。它会覆盖标签元素计算出的名称(包括纯字符串标签),因此仅在富文本标签自身缺少文本或朗读效果不佳时使用。',+ '单选框的纯文本无障碍名称,应用于控件本身而非整行。它会覆盖由标签推导出的名称。仅当富标签没有可见文本时才完全替代;否则必须保留全部可见文字。',},{name: 'value',@@ -144,7 +144,8 @@ export const docsDense = {propDescriptions: {label:'Primary label. String or ReactNode; nested controls keep their behavior.',- 'aria-label': 'Plain-text radio name; overrides any label.',+ 'aria-label':+ 'Plain-text radio name replacing the derived label. Use when visible text is absent; otherwise retain every visible label word.',value: 'Value of this radio item.',description: 'Secondary content below label. String or ReactNode.',isDisabled: 'Whether this individual radio item disabled.',diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 8faf9145a3..aa33555e5b 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -105,21 +105,23 @@ export interface RadioListItemProps extends BaseProps<HTMLDivElement> {* Accepts a plain string or a ReactNode for rich content. Links and buttons* in the label keep their own behavior; only non-interactive row clicks* delegate to the radio. The radio points at the rendered label for its- * accessible name, so a rich label still names it from its own text — pass- * `aria-label` when that text is absent or too noisy to announce.+ * accessible name, so a rich label still names it from its own text. Pass+ * `aria-label` when that text is absent. When visible text is present, the+ * override must retain every visible word so speech-input users can say what+ * they see.*/label: ReactNode;/*** Plain-text accessible name for the radio, applied to the control rather- * than the row. It replaces the name the label would otherwise supply — a- * plain string label included — so reach for it when a rich label's own- * text is absent or reads badly, not as a routine addition.+ * than the row. It replaces the name the label would otherwise supply. Use+ * it when a rich label has no visible text; otherwise the value must retain+ * every visible word.** @example* ```* <RadioListItem* label={<span>Pro plan <Badge label="Recommended" /></span>}- * aria-label="Pro plan"+ * aria-label="Pro plan Recommended option"* value="pro"* />* ```