Skip to content

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

TypeScript

fix(field-label): forward description clicks to checkbox/switch without name pollution (#4574)

freddymeta921d3db31ae4
diff --git a/.changeset/field-label-clickable-description.md b/.changeset/field-label-clickable-description.md
new file mode 100644
index 0000000000..0f0fb7bcb0
--- /dev/null
+++ b/.changeset/field-label-clickable-description.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] CheckboxInput & Switch: clicking the field description now forwards to the control (the whole label area is one hit target), while clicks on interactive content inside a description (links, buttons) are left alone. No new prop or accessibility-tree change — the description stays a sibling of the label, so it isn't folded into the control's accessible name.
+
+@freddymeta
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
index d05ba298fd..9f511cf611 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
@@ -144,6 +144,39 @@ describe('CheckboxInput', () => {
expect(checkbox).toHaveAttribute('aria-describedby', description.id);
});
+ it('toggles when clicking on the description', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <CheckboxInput
+ label="Subscribe"
+ description="Receive weekly updates"
+ value={false}
+ onChange={handleChange}
+ />,
+ );
+ await user.click(screen.getByText('Receive weekly updates'));
+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));
+ });
+
+ it('does not fold the description into the checkbox accessible name', () => {
+ // The description stays a sibling of the <label>, so it must NOT become
+ // part of the checkbox's accessible name (which is computed from the
+ // associated label). It belongs in the accessible DESCRIPTION only
+ // (via aria-describedby) — otherwise screen readers announce it twice.
+ render(
+ <CheckboxInput
+ label="Email notifications"
+ description="We'll send weekly digests"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const checkbox = screen.getByRole('checkbox');
+ expect(checkbox).toHaveAccessibleName('Email notifications');
+ expect(checkbox).toHaveAccessibleDescription("We'll send weekly digests");
+ });
+
it('is disabled when isDisabled prop is true', () => {
render(
<CheckboxInput
diff --git a/packages/core/src/Field/FieldLabel.test.tsx b/packages/core/src/Field/FieldLabel.test.tsx
index 5d475a8631..c99f339bcd 100644
--- a/packages/core/src/Field/FieldLabel.test.tsx
+++ b/packages/core/src/Field/FieldLabel.test.tsx
@@ -11,6 +11,7 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {TestIcon} from '../__tests__/TestIcon';
import {InternationalizationProvider} from '../i18n';
import {FieldLabel} from './FieldLabel';
@@ -119,4 +120,81 @@ describe('FieldLabel', () => {
// Info icon should be present
expect(document.querySelector('svg')).toBeInTheDocument();
});
+
+ describe('description click forwarding', () => {
+ // Renders a real control with the target id so click-forwarding has
+ // something to hit, alongside the label whose description forwards clicks.
+ function renderWithControl(props: {
+ isGroupLabel?: boolean;
+ controlType?: string;
+ description?: React.ReactNode;
+ }) {
+ const {isGroupLabel, controlType = 'checkbox', description} = props;
+ const onClick = vi.fn();
+ render(
+ <>
+ <input id="ctrl" type={controlType} onClick={onClick} />
+ <FieldLabel
+ label="Notify"
+ inputID="ctrl"
+ description={description ?? "We'll email you"}
+ descriptionID="ctrl-desc"
+ isGroupLabel={isGroupLabel}
+ />
+ </>,
+ );
+ return onClick;
+ }
+
+ it('forwards a description click to a click-activatable control (checkbox)', async () => {
+ const user = userEvent.setup();
+ const onClick = renderWithControl({controlType: 'checkbox'});
+ await user.click(screen.getByText("We'll email you"));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('focuses (does not click) a text input on description click', async () => {
+ const user = userEvent.setup();
+ const onClick = renderWithControl({controlType: 'text'});
+ await user.click(screen.getByText("We'll email you"));
+ // Text inputs focus rather than click — matching native label behavior,
+ // so no synthetic click fires but the control receives focus.
+ expect(onClick).not.toHaveBeenCalled();
+ expect(document.getElementById('ctrl')).toHaveFocus();
+ });
+
+ it('does NOT forward description clicks for a group label', async () => {
+ const user = userEvent.setup();
+ const onClick = renderWithControl({isGroupLabel: true});
+ await user.click(screen.getByText("We'll email you"));
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('does NOT hijack clicks on interactive content inside the description', async () => {
+ const user = userEvent.setup();
+ const linkClick = vi.fn();
+ const onClick = renderWithControl({
+ description: (
+ <>
+ See our{' '}
+ <a href="#terms" onClick={linkClick}>
+ terms
+ </a>
+ </>
+ ),
+ });
+ await user.click(screen.getByRole('link', {name: 'terms'}));
+ // The nested link handles its own click; the control is not toggled.
+ expect(linkClick).toHaveBeenCalledTimes(1);
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('keeps the description a sibling of the label (not nested inside it)', () => {
+ renderWithControl({});
+ const description = screen.getByText("We'll email you");
+ // The description must not live inside the <label> — nesting it there
+ // would fold it into the control's accessible name.
+ expect(description.closest('label')).toBeNull();
+ });
+ });
});
diff --git a/packages/core/src/Field/FieldLabel.tsx b/packages/core/src/Field/FieldLabel.tsx
index 149a3e3d43..13cad23e81 100644
--- a/packages/core/src/Field/FieldLabel.tsx
+++ b/packages/core/src/Field/FieldLabel.tsx
@@ -15,7 +15,7 @@
* - /packages/core/locales/en.json (@astryx.field.required / @astryx.field.optional)
*/
-import type {ReactNode} from 'react';
+import {useMemo, useRef, type ReactNode, type RefObject} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import {mergeProps} from '../utils';
@@ -31,6 +31,7 @@ import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Tooltip} from '../Tooltip';
import {useTranslator} from '../i18n';
import {themeProps} from '../utils/themeProps';
+import {useInputContainer} from '../hooks';
const styles = stylex.create({
label: {
@@ -76,6 +77,11 @@ const styles = stylex.create({
fontWeight: fontWeightVars['--font-weight-normal'],
color: colorVars['--color-text-secondary'],
},
+ // When the description forwards clicks to a click-activatable control
+ // (checkbox/switch), it reads as part of the same hit target as the label.
+ descriptionClickable: {
+ cursor: 'pointer',
+ },
});
export interface FieldLabelProps extends BaseProps<HTMLLabelElement> {
@@ -194,6 +200,41 @@ export function FieldLabel({
// label styling and slots. The group references it via `aria-labelledby`.
const LabelElement = isGroupLabel ? 'span' : 'label';
+ // Clicking the description forwards to the associated control, so the whole
+ // label area (label text + description) is one hit target — mirroring native
+ // `<label>` click behavior, which the description can't get from `htmlFor`
+ // because it stays a sibling `<span>` (nesting it in the `<label>` would fold
+ // it into the control's accessible name and double-announce it alongside
+ // `aria-describedby`). A group label names a group, not one control, so it
+ // has nothing to forward to.
+ const forwardsDescriptionClick = !isGroupLabel && inputID != null;
+
+ // Reuse `useInputContainer` — the same hook input wrappers use to forward
+ // clicks on non-interactive chrome to their control. It skips nested
+ // interactive content (a link/button inside a ReactNode description) and
+ // guards against forwarding during text selection, so the description needs
+ // no bespoke click logic. The "input" is resolved from `inputID` lazily via
+ // a ref-shaped object, since FieldLabel points at the control by id rather
+ // than holding a ref to it.
+ const descriptionRef = useRef<HTMLSpanElement>(null);
+ const controlRef = useMemo<RefObject<HTMLElement | null>>(
+ () => ({
+ get current() {
+ return inputID == null
+ ? null
+ : (descriptionRef.current?.ownerDocument.getElementById(inputID) ??
+ null);
+ },
+ set current(_value) {},
+ }),
+ [inputID],
+ );
+ const descriptionClickProps = useInputContainer({
+ containerRef: descriptionRef,
+ inputRef: controlRef,
+ disabled: !forwardsDescriptionClick,
+ });
+
const labelContent = (
<>
{labelIcon && renderIconSlot(labelIcon, {size: 'sm', color: 'inherit'})}
@@ -236,8 +277,14 @@ export function FieldLabel({
</LabelElement>
{description && (
<span
+ ref={forwardsDescriptionClick ? descriptionRef : undefined}
id={descriptionID}
- {...stylex.props(styles.description, isLabelHidden && styles.srOnly)}>
+ {...(forwardsDescriptionClick ? descriptionClickProps : undefined)}
+ {...stylex.props(
+ styles.description,
+ forwardsDescriptionClick && styles.descriptionClickable,
+ isLabelHidden && styles.srOnly,
+ )}>
{description}
</span>
)}
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index cc6c9d49be..161fd7a96c 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -171,6 +171,40 @@ describe('Switch', () => {
expect(switchEl).toHaveAttribute('aria-describedby', description.id);
});
+ it('toggles when clicking on the description', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <Switch
+ label="Dark mode"
+ description="Switch to a darker color scheme"
+ value={false}
+ onChange={handleChange}
+ />,
+ );
+ await user.click(screen.getByText('Switch to a darker color scheme'));
+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));
+ });
+
+ it('does not fold the description into the switch accessible name', () => {
+ // Description stays a sibling of the <label>, so it must not become part
+ // of the switch's accessible name — it belongs in the accessible
+ // description (aria-describedby) only, to avoid double announcement.
+ render(
+ <Switch
+ label="Dark mode"
+ description="Switch to a darker color scheme"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const switchEl = screen.getByRole('switch');
+ expect(switchEl).toHaveAccessibleName('Dark mode');
+ expect(switchEl).toHaveAccessibleDescription(
+ 'Switch to a darker color scheme',
+ );
+ });
+
it('is disabled when isDisabled prop is true', () => {
render(
<Switch
diff --git a/packages/core/src/hooks/useInputContainer.test.tsx b/packages/core/src/hooks/useInputContainer.test.tsx
new file mode 100644
index 0000000000..f6dad3f815
--- /dev/null
+++ b/packages/core/src/hooks/useInputContainer.test.tsx
@@ -0,0 +1,180 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useInputContainer.test.tsx
+ * @input Uses React Testing Library, useInputContainer
+ * @output Unit tests for focus-vs-click forwarding on container click
+ */
+
+import {fireEvent, render} from '@testing-library/react';
+import {useRef} from 'react';
+import {describe, expect, it, vi} from 'vitest';
+import {useInputContainer} from './useInputContainer';
+
+/**
+ * Renders a container wired with useInputContainer around a single control.
+ * The control is described by `control`, which receives the ref to attach.
+ */
+function TestContainer({
+ renderControl,
+}: {
+ renderControl: (ref: React.RefObject<HTMLElement | null>) => React.ReactNode;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLElement | null>(null);
+ const {onClick, onMouseUp} = useInputContainer({
+ containerRef,
+ inputRef,
+ });
+ return (
+ <div ref={containerRef} onClick={onClick} onMouseUp={onMouseUp}>
+ <span data-testid="chrome">chrome</span>
+ {renderControl(inputRef)}
+ </div>
+ );
+}
+
+describe('useInputContainer', () => {
+ it('clicks (not focuses) a role="combobox" aria-haspopup="dialog" text input', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <input
+ ref={ref as React.RefObject<HTMLInputElement>}
+ data-testid="control"
+ type="text"
+ role="combobox"
+ aria-haspopup="dialog"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ // Click the non-interactive chrome so the container handler fires.
+ fireEvent.click(getByTestId('chrome'));
+
+ // A popup trigger must be activated via click, not merely focused —
+ // otherwise DateInput's calendar would never open.
+ expect(onControlClick).toHaveBeenCalledTimes(1);
+ expect(onFocus).not.toHaveBeenCalled();
+ });
+
+ it('clicks a control that only advertises aria-haspopup (no combobox role)', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <input
+ ref={ref as React.RefObject<HTMLInputElement>}
+ data-testid="control"
+ type="text"
+ aria-haspopup="menu"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ fireEvent.click(getByTestId('chrome'));
+
+ expect(onControlClick).toHaveBeenCalledTimes(1);
+ expect(onFocus).not.toHaveBeenCalled();
+ });
+
+ it('focuses (not clicks) a plain type="text" input', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <input
+ ref={ref as React.RefObject<HTMLInputElement>}
+ data-testid="control"
+ type="text"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ fireEvent.click(getByTestId('chrome'));
+
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onControlClick).not.toHaveBeenCalled();
+ });
+
+ it('focuses (not clicks) a plain type="number" input', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <input
+ ref={ref as React.RefObject<HTMLInputElement>}
+ data-testid="control"
+ type="number"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ fireEvent.click(getByTestId('chrome'));
+
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onControlClick).not.toHaveBeenCalled();
+ });
+
+ it('focuses (not clicks) a textarea', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <textarea
+ ref={ref as React.RefObject<HTMLTextAreaElement>}
+ data-testid="control"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ fireEvent.click(getByTestId('chrome'));
+
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onControlClick).not.toHaveBeenCalled();
+ });
+
+ it('clicks (not focuses) a checkbox — unchanged behavior', () => {
+ const onFocus = vi.fn();
+ const onControlClick = vi.fn();
+ const {getByTestId} = render(
+ <TestContainer
+ renderControl={ref => (
+ <input
+ ref={ref as React.RefObject<HTMLInputElement>}
+ data-testid="control"
+ type="checkbox"
+ onFocus={onFocus}
+ onClick={onControlClick}
+ />
+ )}
+ />,
+ );
+
+ fireEvent.click(getByTestId('chrome'));
+
+ expect(onControlClick).toHaveBeenCalledTimes(1);
+ expect(onFocus).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/hooks/useInputContainer.ts b/packages/core/src/hooks/useInputContainer.ts
index 9d5be466a2..4a89b7243c 100644
--- a/packages/core/src/hooks/useInputContainer.ts
+++ b/packages/core/src/hooks/useInputContainer.ts
@@ -35,6 +35,36 @@ const FOCUS_INPUT_TYPES = new Set([
'week',
]);
+/**
+ * `aria-haspopup` values that advertise a control opens a popup on activation.
+ * https://www.w3.org/TR/wai-aria-1.2/#aria-haspopup
+ */
+const HASPOPUP_VALUES = new Set([
+ 'true',
+ 'menu',
+ 'listbox',
+ 'tree',
+ 'grid',
+ 'dialog',
+]);
+
+/**
+ * Whether an element is a popup trigger — a combobox or any control that
+ * advertises `aria-haspopup`. Such controls activate their popup on *click*
+ * (e.g. DateInput's `<input type="text" role="combobox" aria-haspopup="dialog">`
+ * opens its calendar via `onClick`, with no `onFocus` opener). Forwarding a
+ * container click to `.focus()` would focus the control but leave the popup
+ * closed — so we `.click()` these instead. Plain text inputs (no popup) are
+ * unaffected and keep `.focus()`.
+ */
+function isPopupTrigger(el: HTMLElement): boolean {
+ if (el.getAttribute('role') === 'combobox') {
+ return true;
+ }
+ const haspopup = el.getAttribute('aria-haspopup');
+ return haspopup != null && HASPOPUP_VALUES.has(haspopup);
+}
+
export interface UseInputContainerOptions {
/** Ref to the outer container/wrapper element */
containerRef: RefObject<HTMLElement | null>;
@@ -83,7 +113,12 @@ export function useInputContainer({
if (input == null) {
return;
}
- if (
+ // Popup triggers (combobox / aria-haspopup) activate their popup on
+ // *click*, not focus — so check this BEFORE the type check, otherwise a
+ // `type="text"` combobox (DateInput) would `.focus()` and never open.
+ if (input instanceof HTMLElement && isPopupTrigger(input)) {
+ input.click();
+ } else if (
input instanceof HTMLInputElement &&
FOCUS_INPUT_TYPES.has(input.type)
) {