Skip to content

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

TypeScript

feat(CheckboxList): a required checkbox group needs one checked box (isRequired) (#9854)

Cindy Zhang6255d302217d
diff --git a/.changeset/checkbox-list-is-required.md b/.changeset/checkbox-list-is-required.md
new file mode 100644
index 0000000000..8f176cbf13
--- /dev/null
+++ b/.changeset/checkbox-list-is-required.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `CheckboxList` takes `isRequired`. The group label shows the required indicator by the same rules as every input field. While no box is checked, the first box that is neither disabled nor read-only carries native `required`, so the browser blocks submit and moves focus to it with its own message. Once any box is checked, the form submits. A disabled or read-only group requires nothing. Show your own error text through `status`.
+
+@cixzhang
diff --git a/apps/storybook/stories/CheckboxList.stories.tsx b/apps/storybook/stories/CheckboxList.stories.tsx
index 2dff2991c3..fe58d67731 100644
--- a/apps/storybook/stories/CheckboxList.stories.tsx
+++ b/apps/storybook/stories/CheckboxList.stories.tsx
@@ -350,6 +350,34 @@ export const Optional: Story = {
},
};
+export const Required: Story = {
+ render: args => {
+ const [value, setValue] = useState<string[]>([]);
+ const [submitted, setSubmitted] = useState(false);
+ const {value: _value, onChange: _onChange, ...restArgs} = args;
+ return (
+ <form
+ onSubmit={event => {
+ event.preventDefault();
+ setSubmitted(true);
+ }}>
+ <CheckboxList {...restArgs} value={value} onChange={setValue}>
+ <CheckboxListItem label="Design" value="design" />
+ <CheckboxListItem label="Engineering" value="eng" />
+ <CheckboxListItem label="Research" value="research" />
+ </CheckboxList>
+ <button type="submit">Submit</button>
+ {submitted ? <p>Submitted</p> : null}
+ </form>
+ );
+ },
+ args: {
+ label: 'Topics',
+ description: 'Choose at least one.',
+ isRequired: true,
+ },
+};
+
export const WithErrorStatus: Story = {
render: args => {
const [value, setValue] = useState<string[]>([]);
diff --git a/docs/specs/components/CheckboxList/CheckboxList.spec.md b/docs/specs/components/CheckboxList/CheckboxList.spec.md
index f474466992..dee7b83862 100644
--- a/docs/specs/components/CheckboxList/CheckboxList.spec.md
+++ b/docs/specs/components/CheckboxList/CheckboxList.spec.md
@@ -31,6 +31,7 @@ verified_by:
packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
packages/core/src/CheckboxList/CheckboxList.fr10.test.tsx,
+ packages/core/src/CheckboxList/CheckboxList.required.test.tsx,
scripts/check-knowledge.mjs,
]
modules: []
@@ -57,7 +58,7 @@ system_specs: [spec:AST-011, spec:AST-021, spec:AST-038, spec:AST-085]
| Behavior | The group names and describes its options, tracks every value whose `changeAction` is pending so each saving option stays busy while the others stay interactive, and applies disabled, read-only, and status to every option. |
| End-user impact | People can identify the group, operate every option by pointer, touch, and keyboard, learn why a group is unavailable, and see which options are still saving. |
| Builder impact | Builders choose collection mode by passing `value`, and then supply stable item `value`s. The rendering of a status without a message stays an open question here (OQ3); per-option open questions are in `component:CheckboxListItem`. |
-| Compatibility/readiness | Adds `isOptional` (FR16), default `false`. Each checkbox gains `aria-invalid` under an error status; no other API, default, or DOM change. |
+| Compatibility/readiness | Adds `isOptional` (FR16) and `isRequired` (FR17), each default `false`. Each checkbox gains `aria-invalid` under an error status; no other API, default, or DOM change. |
| Review checks | Reject a pending value that loses its busy state or re-toggle guard when another option is toggled, dropped group naming or description ids, a toggle while the group is disabled or read-only, or new target or state API introduced without an owner decision. Per-option checks are in `component:CheckboxListItem`. |
| Governing rules | `architecture:public-component-api/INV1–INV9`; `architecture:component-theming-surface/INV3–INV6`; `architecture:interaction-modality/INV1–INV5`; `architecture:component-test-sufficiency/INV1–INV7`; `architecture:knowledge-contracts/INV2`; `spec:AST-021/FR8–FR10`; `spec:AST-038/FR7`; `spec:AST-085/FR1, FR7`; `family:input-fields/FR10`; WCAG 2.2 1.3.1, 2.1.1, 4.1.2. |
@@ -72,8 +73,8 @@ touch, keyboard, and assistive technology.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: additive `isOptional` (FR16), default `false`; no other
- public prop, default, or export change; each checkbox gains `aria-invalid`
+- Compatibility class: additive `isOptional` (FR16) and `isRequired` (FR17),
+ each default `false`; no other public prop, default, or export change; each checkbox gains `aria-invalid`
under an error status
- Controlled/uncontrolled behavior: collection mode is controlled by `value`;
standalone items follow `component:CheckboxListItem`; no uncontrolled mode
@@ -115,7 +116,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
| ---------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------- | ---------------------- | -------------------------------------- | ------------------------------------------------------------ |
| group naming | `label`, `isLabelHidden`, `description` | Names and describes the `role="group"`; a hidden label still names it. | All states. | label required; visible | caller and Field | stable | rejected by the public type |
-| optionality | `isOptional` | Shows Field's optional indicator after the group label. | All states. | false | caller and Field | stable | boolean only |
+| optionality | `isOptional`, `isRequired` | Shows Field's optional or required indicator after the group label; `isRequired` also needs one checked box (FR17). | All states. | false | caller and Field | stable | boolean only |
| collection value | `value` array present or absent | Present: the group owns checked membership and change handling for its items. Absent: its items are standalone. | All states. | absent | caller and component | stable | an item without `value` in collection mode throws (item FR4) |
| change path | `onChange`, `changeAction`, both, neither | Reports the next value array; `changeAction` runs after `onChange` in a transition with an optimistic value. | Collection mode. | neither | caller and component | shipped; handlerless meaning unsettled | no handler means no component-owned mutation |
| availability | enabled, `isDisabled`, `isDisabled` with `disabledMessage` | Blocks toggling on every item, which stays focusable through `aria-disabled`; a reason adds a group tooltip. | Reason applies only with `isDisabled`. | enabled | component | stable | a reason without `isDisabled` renders nothing |
@@ -131,19 +132,20 @@ of `component:CheckboxListItem`.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
-| FR1 | The render MUST place CheckboxListItem children inside a List within a `role="group"` named by the group label through `aria-labelledby`; its `aria-describedby` MUST list any caller description, then the description, status message, and disabled-reason tooltip that are present, in that order. | shipped source; focused tests; WCAG 1.3.1 and 4.1.2 |
-| FR2 | The CheckboxList root MUST carry the current `checkbox-list` target. | shipped source and public docs |
-| FR4 | A status message MUST render through a detached FieldStatus after the list. | shipped source, focused tests, and the Chromium accessibility suite |
-| FR6 | With a `value` array, the group MUST provide membership to its items, call `onChange` with the next array an item proposes (`component:CheckboxListItem` FR4), and then run `changeAction` with the same array in a transition with an optimistic value. | shipped source and focused tests |
-| FR7 | The group MUST track every value whose `changeAction` is pending and expose it to its items, each of which renders busy (`component:CheckboxListItem` FR7); toggling another item MUST NOT clear an earlier pending value. Concurrent pending values settle together, after which every busy state clears. | shipped public `changeAction` promise; focused regression test; the Chromium accessibility suite |
-| FR9 | Group `isDisabled` MUST make every checkbox focusable-disabled through `aria-disabled` (`component:CheckboxInput` FR4) and refuse toggling, and MUST set `aria-disabled="true"` on the `role="group"` element, as `component:ButtonGroup` FR1 does. With `disabledMessage`, the reason tooltip opens on group hover and keyboard focus, and the reason MUST describe each focusable checkbox (`spec:AST-085` FR5, FR7). Implementation gap: the reason describes only the `role="group"`, so a focused checkbox is not described by it. | `spec:AST-085` FR1, FR7; shipped source, focused tests, and shared checkbox binding |
-| FR10 | Group `isReadOnly` MUST make every item in the group read-only (`component:CheckboxListItem` FR8 and FR10). | shipped source; shared checkbox binding; `spec:AST-011` read-only vocabulary |
-| FR13 | `density` MUST reach the List and its rows (the checkbox size follows `component:CheckboxListItem` FR11); `hasDividers` MUST separate rows without a divider after the last row; `width` MUST size the label, list, and status together. | shipped source, docs, and the Chromium accessibility suite |
-| FR14 | An error `status` with a message renders it (FR4), and an error `status` makes every checkbox `aria-invalid="true"`, so a screen reader announces the invalid state as each checkbox takes focus. Implementation gap: a status without a message renders nothing; its meaning is OQ3. | shipped source; `spec:AST-002/FR15` |
-| FR15 | Base props, including ARIA and `ref`, MUST reach the `role="group"`; a caller `aria-labelledby` joins the group label and a caller `aria-describedby` comes first. `container*` MUST reach the Field box where one renders (in a `horizontal-labels` FormLayout none renders, and `container*` has no effect and warns), and `control*` the group element; root `xstyle`, `className`, and `style` are not accepted. | `family:input-fields` FR10; `CheckboxList.fr10.test.tsx` |
-| FR16 | `isOptional` MUST reach the group's Field as `isOptional`, so the group label shows the optional indicator unless the nearest `FormLayout` defaults fields to optional (`component:FormLayout` FR5). An empty selection is an answer, so a checkbox group takes no required state from a form default (`component:FormLayout` FR5's exception): with or without `isOptional`, its checkboxes carry no `aria-required` from it, and the group sets no native `required`. | CheckboxInput and RadioList parity; WAI-ARIA 1.2 `group` has no `aria-required`, and `aria-required` on each checkbox would require every option |
+| ID | Invariant | Basis |
+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
+| FR1 | The render MUST place CheckboxListItem children inside a List within a `role="group"` named by the group label through `aria-labelledby`; its `aria-describedby` MUST list any caller description, then the description, status message, and disabled-reason tooltip that are present, in that order. | shipped source; focused tests; WCAG 1.3.1 and 4.1.2 |
+| FR2 | The CheckboxList root MUST carry the current `checkbox-list` target. | shipped source and public docs |
+| FR4 | A status message MUST render through a detached FieldStatus after the list. | shipped source, focused tests, and the Chromium accessibility suite |
+| FR6 | With a `value` array, the group MUST provide membership to its items, call `onChange` with the next array an item proposes (`component:CheckboxListItem` FR4), and then run `changeAction` with the same array in a transition with an optimistic value. | shipped source and focused tests |
+| FR7 | The group MUST track every value whose `changeAction` is pending and expose it to its items, each of which renders busy (`component:CheckboxListItem` FR7); toggling another item MUST NOT clear an earlier pending value. Concurrent pending values settle together, after which every busy state clears. | shipped public `changeAction` promise; focused regression test; the Chromium accessibility suite |
+| FR9 | Group `isDisabled` MUST make every checkbox focusable-disabled through `aria-disabled` (`component:CheckboxInput` FR4) and refuse toggling, and MUST set `aria-disabled="true"` on the `role="group"` element, as `component:ButtonGroup` FR1 does. With `disabledMessage`, the reason tooltip opens on group hover and keyboard focus, and the reason MUST describe each focusable checkbox (`spec:AST-085` FR5, FR7). Implementation gap: the reason describes only the `role="group"`, so a focused checkbox is not described by it. | `spec:AST-085` FR1, FR7; shipped source, focused tests, and shared checkbox binding |
+| FR10 | Group `isReadOnly` MUST make every item in the group read-only (`component:CheckboxListItem` FR8 and FR10). | shipped source; shared checkbox binding; `spec:AST-011` read-only vocabulary |
+| FR13 | `density` MUST reach the List and its rows (the checkbox size follows `component:CheckboxListItem` FR11); `hasDividers` MUST separate rows without a divider after the last row; `width` MUST size the label, list, and status together. | shipped source, docs, and the Chromium accessibility suite |
+| FR14 | An error `status` with a message renders it (FR4), and an error `status` makes every checkbox `aria-invalid="true"`, so a screen reader announces the invalid state as each checkbox takes focus. Implementation gap: a status without a message renders nothing; its meaning is OQ3. | shipped source; `spec:AST-002/FR15` |
+| FR15 | Base props, including ARIA and `ref`, MUST reach the `role="group"`; a caller `aria-labelledby` joins the group label and a caller `aria-describedby` comes first. `container*` MUST reach the Field box where one renders (in a `horizontal-labels` FormLayout none renders, and `container*` has no effect and warns), and `control*` the group element; root `xstyle`, `className`, and `style` are not accepted. | `family:input-fields` FR10; `CheckboxList.fr10.test.tsx` |
+| FR16 | `isOptional` MUST reach the group's Field as `isOptional`, so the group label shows the optional indicator unless the nearest `FormLayout` defaults fields to optional (`component:FormLayout` FR5). An empty selection is an answer, so a checkbox group takes no required state from a form default (`component:FormLayout` FR5's exception): with or without `isOptional`, its checkboxes carry no `aria-required` from it, and the form default puts no native `required` on them. | CheckboxInput and RadioList parity; WAI-ARIA 1.2 `group` has no `aria-required`, and `aria-required` on each checkbox would require every option |
+| FR17 | `isRequired` marks the group required. Its name shows the input fields' required marker by the same rules every input field follows (`family:input-fields`), so where a form's default already marks fields required, no marker shows, as for any field. While no checkbox is checked, the first checkbox that is neither disabled nor read-only carries native `required`, so the browser blocks submit and focuses it with its own message; once any box is checked, no box carries `required`. An empty group is missing; the app's `status` stays the visible error text, and Astryx adds no message of its own. | Owner decision; `family:input-fields`; HTML constraint validation |
Per-option requirements are owned by `component:CheckboxListItem`
(`architecture:knowledge-contracts/INV2`).
@@ -182,7 +184,10 @@ Option variation is `component:CheckboxListItem` AV1–AV3.
### Performance and resources
- **PR1 — Bounded resources.** The component owns no observer or global
- listener. Tooltip listeners are scoped to the group element and its lifetime.
+ listener of its own. Tooltip listeners are scoped to the group element and
+ its lifetime. A required group (FR17) registers its options with Core's
+ shared mutation observer for its lifetime, so a reorder updates which box
+ carries `required`.
Current measurements belong in the audit record; this subsection owns only
durable constraints and their verification target.
@@ -291,18 +296,19 @@ row surface, but not a checked-row state (`component:CheckboxListItem` FR15).
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- |
-| FR1, AR1 | `CheckboxList.test.tsx` group-role, group-description, and disabledMessage cases | Named group; description plus status; disabled reason | A missing group name, or a description and status out of order, fails. Evidence gap: no test asserts the caller description first or the disabled reason last. | `audit:CheckboxList/accessibility` |
-| FR2, FR15 | `CheckboxList.test.tsx` ref and container case; `CheckboxList.fr10.test.tsx` | Standalone; `horizontal-labels` FormLayout | A ref off the group, `container*` off the Field box, or a base prop off the group fails. | `audit:CheckboxList/api` |
-| FR4, FR14 | `CheckboxList.test.tsx` error-status cases, including every checkbox's `aria-invalid`; `CheckboxListErrorStatus.a11y.chromium.spec.ts` | Error with message | A missing status message fails. Evidence gap: no test asserts the empty render without a message. | `audit:CheckboxList/accessibility` |
-| FR6, FR7 | `CheckboxList.test.tsx` add, remove, and pending cases; `CheckboxList.a11y.chromium.spec.ts` `pending-single`, `pending-concurrent`, and `pending-settled` cases | Add; remove; one and two pending values; settled | A wrong array, a cleared earlier pending value, or a busy state that outlives settlement fails. | `audit:CheckboxList/behavior` |
-| FR9, FR10, AR4 | `CheckboxList.test.tsx` group-disabled (including the group's `aria-disabled`), disabledMessage, and read-only cases; `ListGroupDisabled.a11y.chromium.spec.ts`; shared checkbox bindings | Group disabled; with reason; read-only item | A lost tab stop, a toggle while disabled, or a read-only toggle fails. Evidence gap: no test asserts that a focused checkbox is not described by the reason. | `audit:CheckboxList/accessibility` |
-| FR13 | `CheckboxList.test.tsx` density cases; `CheckboxList.a11y.chromium.spec.ts` density, divider, 320-pixel, and RTL cases | Compact, balanced, spacious; dividers; narrow; RTL | A density, divider, overflow, or direction sensor fails. Evidence gap: no test asserts `width` sizing the label, list, and status together. | `audit:CheckboxList/layout` |
-| FR16 | `CheckboxList.test.tsx` optional-indicator and FormLayout-default cases | `isOptional`; unmarked and optional groups under a required default; optional default; toggled with focus | Dropping `isOptional` from the Field, showing it under an optional default, a group checkbox with `aria-required` under a required default, or remounting rows when `isOptional` changes, fails. | `audit:CheckboxList/accessibility` |
-| ORD1–ORD3, PR1 | ORD1 and ORD2 are covered by the FR6 and FR7 rows, ORD3 by the FR9 and FR10 rows. Evidence gap: no test asserts the absence of observers or global listeners | — | — | `audit:CheckboxList/behavior` |
-| Local target source | `themingTargets.test.ts`; `CheckboxList.test.tsx` ref and container case | `checkbox-list` | A rendered class absent from the documented targets, or a missing `astryx-checkbox-list` on the Field root, fails. | `audit:CheckboxList/theming` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails validation. | `audit:CheckboxList/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- |
+| FR1, AR1 | `CheckboxList.test.tsx` group-role, group-description, and disabledMessage cases | Named group; description plus status; disabled reason | A missing group name, or a description and status out of order, fails. Evidence gap: no test asserts the caller description first or the disabled reason last. | `audit:CheckboxList/accessibility` |
+| FR2, FR15 | `CheckboxList.test.tsx` ref and container case; `CheckboxList.fr10.test.tsx` | Standalone; `horizontal-labels` FormLayout | A ref off the group, `container*` off the Field box, or a base prop off the group fails. | `audit:CheckboxList/api` |
+| FR4, FR14 | `CheckboxList.test.tsx` error-status cases, including every checkbox's `aria-invalid`; `CheckboxListErrorStatus.a11y.chromium.spec.ts` | Error with message | A missing status message fails. Evidence gap: no test asserts the empty render without a message. | `audit:CheckboxList/accessibility` |
+| FR6, FR7 | `CheckboxList.test.tsx` add, remove, and pending cases; `CheckboxList.a11y.chromium.spec.ts` `pending-single`, `pending-concurrent`, and `pending-settled` cases | Add; remove; one and two pending values; settled | A wrong array, a cleared earlier pending value, or a busy state that outlives settlement fails. | `audit:CheckboxList/behavior` |
+| FR9, FR10, AR4 | `CheckboxList.test.tsx` group-disabled (including the group's `aria-disabled`), disabledMessage, and read-only cases; `ListGroupDisabled.a11y.chromium.spec.ts`; shared checkbox bindings | Group disabled; with reason; read-only item | A lost tab stop, a toggle while disabled, or a read-only toggle fails. Evidence gap: no test asserts that a focused checkbox is not described by the reason. | `audit:CheckboxList/accessibility` |
+| FR13 | `CheckboxList.test.tsx` density cases; `CheckboxList.a11y.chromium.spec.ts` density, divider, 320-pixel, and RTL cases | Compact, balanced, spacious; dividers; narrow; RTL | A density, divider, overflow, or direction sensor fails. Evidence gap: no test asserts `width` sizing the label, list, and status together. | `audit:CheckboxList/layout` |
+| FR16 | `CheckboxList.test.tsx` optional-indicator and FormLayout-default cases | `isOptional`; unmarked and optional groups under a required default; optional default; toggled with focus | Dropping `isOptional` from the Field, showing it under an optional default, a group checkbox with `aria-required` under a required default, or remounting rows when `isOptional` changes, fails. | `audit:CheckboxList/accessibility` |
+| FR17 | `CheckboxList.required.test.tsx` | Marker; required-default form; no box checked; one checked; last box unchecked; disabled first box; disabled group; read-only group; standalone items; keyed reorder; item removed | A missing marker, a marker under a required default, a submit with no box checked, a blocked submit with one checked, or `required` on more than one box, fails. | `audit:CheckboxList/accessibility` |
+| ORD1–ORD3, PR1 | ORD1 and ORD2 are covered by the FR6 and FR7 rows, ORD3 by the FR9 and FR10 rows. Evidence gap: no test asserts the absence of observers or global listeners | — | — | `audit:CheckboxList/behavior` |
+| Local target source | `themingTargets.test.ts`; `CheckboxList.test.tsx` ref and container case | `checkbox-list` | A rendered class absent from the documented targets, or a missing `astryx-checkbox-list` on the Field root, fails. | `audit:CheckboxList/theming` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails validation. | `audit:CheckboxList/theming` |
Per-option verification is owned by `component:CheckboxListItem`'s
verification map. No current repository check resolves `delegatesTo`
@@ -316,6 +322,7 @@ CheckboxInput, Spinner, and FieldStatus targets.
against `spec:AST-085` FR5 and FR7.
- **Status without a message (FR14).** A status without a message renders
nothing; its meaning is OQ3.
+- **Required announcement (FR17).** `role="group"` cannot carry `aria-required`, and browsers expose an unchecked `required` checkbox as invalid rather than required, so while the group is empty its first checkbox alone reports that state, as a `CheckboxInput` with `isRequired` does today; a required `RadioList` keeps each radio's invalid state on its status instead (`component:RadioList` FR6).
## Decision log
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 69f2982394..8be8627ae7 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -572,6 +572,7 @@ component CheckboxList(props: CheckboxListProps)
prop isLabelHidden?: boolean = false
prop isOptional?: boolean = false
prop isReadOnly?: boolean = false
+ prop isRequired?: boolean = false
prop label: string
prop onChange?: (values: string[]) => void
prop ref?: React.Ref<HTMLDivElement>
diff --git a/packages/core/src/CheckboxList/CheckboxList.doc.mjs b/packages/core/src/CheckboxList/CheckboxList.doc.mjs
index 8165761354..5af6a76370 100644
--- a/packages/core/src/CheckboxList/CheckboxList.doc.mjs
+++ b/packages/core/src/CheckboxList/CheckboxList.doc.mjs
@@ -134,6 +134,13 @@ export const docs = {
'Whether the group is optional. Shows the optional indicator after the group label, unless a surrounding FormLayout already makes fields optional by default.',
default: 'false',
},
+ {
+ name: 'isRequired',
+ type: 'boolean',
+ description:
+ 'Whether the group needs at least one checked box. Shows the required indicator after the group label by the same rules as every input field. While no box is checked, the browser blocks submit and moves focus to the first box that is neither disabled nor read-only, with its own message. A disabled or read-only group requires nothing. Show your own error text through status. Mutually exclusive with isOptional.',
+ default: 'false',
+ },
{
name: 'density',
type: "'compact' | 'balanced' | 'spacious'",
diff --git a/packages/core/src/CheckboxList/CheckboxList.required.test.tsx b/packages/core/src/CheckboxList/CheckboxList.required.test.tsx
new file mode 100644
index 0000000000..65481aa1a4
--- /dev/null
+++ b/packages/core/src/CheckboxList/CheckboxList.required.test.tsx
@@ -0,0 +1,217 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CheckboxList.required.test.tsx
+ * @input vitest (jsdom), React Testing Library, CheckboxList, FormLayout
+ * @output Checks an `isRequired` CheckboxList: the label marker follows the
+ * input fields' rules; while no box is checked the first enabled box carries
+ * native `required`, so the form does not submit; once a box is checked, no
+ * box is required and the form submits
+ * @position Testing; validates the CheckboxList record's isRequired rule
+ */
+
+import {useState, type ReactElement} from 'react';
+import {describe, expect, it, vi} from 'vitest';
+import {act, fireEvent, render, screen, within} from '@testing-library/react';
+import {CheckboxList} from './CheckboxList';
+import {CheckboxListItem} from './CheckboxListItem';
+import {FormLayout} from '../FormLayout/FormLayout';
+
+const NONE: string[] = [];
+
+function RequiredForm({
+ onSubmit,
+ initial = NONE,
+ disabledValue,
+ isGroupDisabled = false,
+}: {
+ onSubmit: () => void;
+ initial?: string[];
+ disabledValue?: string;
+ isGroupDisabled?: boolean;
+}): ReactElement {
+ const [value, setValue] = useState<string[]>(initial);
+ return (
+ <form
+ aria-label="Signup"
+ onSubmit={event => {
+ event.preventDefault();
+ onSubmit();
+ }}>
+ <CheckboxList
+ label="Topics"
+ isRequired
+ isDisabled={isGroupDisabled}
+ value={value}
+ onChange={setValue}>
+ <CheckboxListItem
+ label="Design"
+ value="design"
+ isDisabled={disabledValue === 'design'}
+ />
+ <CheckboxListItem label="Engineering" value="eng" />
+ <CheckboxListItem label="Research" value="research" />
+ </CheckboxList>
+ <button type="submit">Submit</button>
+ </form>
+ );
+}
+
+const box = (name: string) => screen.getByRole('checkbox', {name});
+const form = () => screen.getByRole<HTMLFormElement>('form', {name: 'Signup'});
+
+describe('CheckboxList isRequired', () => {
+ it('shows the required marker after the group label', () => {
+ render(
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ </CheckboxList>,
+ );
+ expect(
+ within(screen.getByText('Topics')).getByText('Required'),
+ ).toBeInTheDocument();
+ });
+
+ it('shows no marker where the form already makes fields required, as for every field', () => {
+ render(
+ <FormLayout defaultOptionality="required">
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ </CheckboxList>
+ </FormLayout>,
+ );
+ expect(screen.queryByText('Required')).not.toBeInTheDocument();
+ expect(box('Design')).toBeRequired();
+ });
+
+ it('with no box checked, requires the first box only and blocks submit', () => {
+ const onSubmit = vi.fn();
+ render(<RequiredForm onSubmit={onSubmit} />);
+ expect(box('Design')).toBeRequired();
+ expect(box('Engineering')).not.toBeRequired();
+ expect(box('Research')).not.toBeRequired();
+ expect(form().checkValidity()).toBe(false);
+ form().requestSubmit();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('with one box checked, requires no box and submits', () => {
+ const onSubmit = vi.fn();
+ render(<RequiredForm onSubmit={onSubmit} />);
+ fireEvent.click(box('Research'));
+ for (const name of ['Design', 'Engineering', 'Research']) {
+ expect(box(name)).not.toBeRequired();
+ }
+ form().requestSubmit();
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ });
+
+ it('requires the first box again when the last checked box is unchecked', () => {
+ render(<RequiredForm onSubmit={() => {}} initial={['eng']} />);
+ expect(box('Design')).not.toBeRequired();
+ fireEvent.click(box('Engineering'));
+ expect(box('Design')).toBeRequired();
+ });
+
+ it('skips a disabled box: the first enabled box is required', () => {
+ render(<RequiredForm onSubmit={() => {}} disabledValue="design" />);
+ expect(box('Design')).not.toBeRequired();
+ expect(box('Engineering')).toBeRequired();
+ });
+
+ it('requires no box in a disabled group, which the user cannot fill', () => {
+ const onSubmit = vi.fn();
+ render(<RequiredForm onSubmit={onSubmit} isGroupDisabled />);
+ for (const name of ['Design', 'Engineering', 'Research']) {
+ expect(box(name)).not.toBeRequired();
+ }
+ form().requestSubmit();
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ });
+
+ it('works for standalone items that own their checked state', () => {
+ function Standalone() {
+ const [a, setA] = useState(false);
+ const [b, setB] = useState(false);
+ return (
+ <CheckboxList label="Consent" isRequired>
+ <CheckboxListItem label="Terms" isChecked={a} onCheck={setA} />
+ <CheckboxListItem label="Privacy" isChecked={b} onCheck={setB} />
+ </CheckboxList>
+ );
+ }
+ render(<Standalone />);
+ expect(box('Terms')).toBeRequired();
+ fireEvent.click(box('Privacy'));
+ expect(box('Terms')).not.toBeRequired();
+ expect(box('Privacy')).not.toBeRequired();
+ });
+
+ it('requires no box once isRequired is removed', () => {
+ const {rerender} = render(
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ </CheckboxList>,
+ );
+ expect(box('Design')).toBeRequired();
+ rerender(
+ <CheckboxList label="Topics" value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ </CheckboxList>,
+ );
+ expect(box('Design')).not.toBeRequired();
+ });
+
+ it('moves required to the new first box after a keyed reorder', async () => {
+ const items = [
+ {label: 'Design', value: 'design'},
+ {label: 'Engineering', value: 'eng'},
+ ];
+ const list = (order: typeof items) => (
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ {order.map(item => (
+ <CheckboxListItem
+ key={item.value}
+ label={item.label}
+ value={item.value}
+ />
+ ))}
+ </CheckboxList>
+ );
+ const {rerender} = render(list(items));
+ expect(box('Design')).toBeRequired();
+ rerender(list([...items].reverse()));
+ await act(async () => {});
+ expect(box('Engineering')).toBeRequired();
+ expect(box('Design')).not.toBeRequired();
+ });
+
+ it('skips a read-only group: no box is required', () => {
+ render(
+ <CheckboxList
+ label="Topics"
+ isRequired
+ isReadOnly
+ value={[]}
+ onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ </CheckboxList>,
+ );
+ expect(box('Design')).not.toBeRequired();
+ });
+
+ it('moves required to the new first box when the first item is removed', () => {
+ const {rerender} = render(
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Design" value="design" />
+ <CheckboxListItem label="Engineering" value="eng" />
+ </CheckboxList>,
+ );
+ rerender(
+ <CheckboxList label="Topics" isRequired value={[]} onChange={() => {}}>
+ <CheckboxListItem label="Engineering" value="eng" />
+ </CheckboxList>,
+ );
+ expect(box('Engineering')).toBeRequired();
+ });
+});
diff --git a/packages/core/src/CheckboxList/CheckboxList.tsx b/packages/core/src/CheckboxList/CheckboxList.tsx
index aa0b5605b3..c184b31d6d 100644
--- a/packages/core/src/CheckboxList/CheckboxList.tsx
+++ b/packages/core/src/CheckboxList/CheckboxList.tsx
@@ -4,7 +4,7 @@
/**
* @file CheckboxList.tsx
- * @input Uses React, useId, useOptimistic, useTransition, Field, List, CheckboxListContext
+ * @input Uses React, useId, useOptimistic, useTransition, Field, List, CheckboxListContext, requiredGroup
* @output Exports CheckboxList component, CheckboxListProps
* @position Core implementation; consumed by index.ts, tested by CheckboxList.test.tsx
*
@@ -43,6 +43,7 @@ import {
CheckboxListContext,
type CheckboxListContextValue,
} from './CheckboxListContext';
+import {createRequiredGroup} from './requiredGroup';
const EMPTY_ARRAY: string[] = [];
@@ -72,6 +73,17 @@ export interface CheckboxListProps extends Omit<
* @default false
*/
isOptional?: boolean;
+ /**
+ * Whether the group needs at least one checked box. Shows the required
+ * indicator after the group label by the same rules as every input field.
+ * While no box is checked, the browser blocks submit and moves focus to
+ * the first box that is neither disabled nor read-only. A disabled or
+ * read-only group requires nothing. Show your own error text through
+ * `status`.
+ * Mutually exclusive with isOptional.
+ * @default false
+ */
+ isRequired?: boolean;
/**
* Status indicator for the checkbox group.
* When set with a message, displays a colored message box below the group.
@@ -161,6 +173,7 @@ export function CheckboxList({
isLabelHidden = false,
description,
isOptional = false,
+ isRequired = false,
status,
value,
onChange,
@@ -193,6 +206,18 @@ export function CheckboxList({
const descriptionID = useId();
const statusMessageID = useId();
+ const requiredGroup = useMemo(
+ () => (isRequired ? createRequiredGroup() : undefined),
+ [isRequired],
+ );
+ const observeRequiredGroup = useCallback(
+ (container: HTMLDivElement | null) =>
+ container != null && requiredGroup != null
+ ? requiredGroup.observe(container)
+ : undefined,
+ [requiredGroup],
+ );
+
const [, startTransition] = useTransition();
const isCollectionMode = value !== undefined;
const effectiveValue = value ?? EMPTY_ARRAY;
@@ -256,6 +281,7 @@ export function CheckboxList({
isReadOnly,
isInvalid: status?.type === 'error',
loadingValues,
+ requiredGroup,
}),
[
isCollectionMode,
@@ -267,6 +293,7 @@ export function CheckboxList({
isReadOnly,
status?.type,
loadingValues,
+ requiredGroup,
],
);
@@ -279,6 +306,7 @@ export function CheckboxList({
labelID={labelID}
isGroupLabel
isOptional={isOptional}
+ isRequired={isRequired}
descriptionID={description ? descriptionID : undefined}
isDisabled={isDisabled}
status={
@@ -302,7 +330,11 @@ export function CheckboxList({
{...rest}
// The disabled-message tooltip anchors here; its handlers are gated
// internally by isEnabled, so attaching unconditionally is safe.
- ref={useMergedRefs(ref, disabledMessageTooltip.ref)}
+ ref={useMergedRefs(
+ ref,
+ disabledMessageTooltip.ref,
+ observeRequiredGroup,
+ )}
{...mergeProps(
stylex.props(controlXstyle),
controlClassName,
diff --git a/packages/core/src/CheckboxList/CheckboxListContext.tsx b/packages/core/src/CheckboxList/CheckboxListContext.tsx
index 9609bd94ce..d572d5f81d 100644
--- a/packages/core/src/CheckboxList/CheckboxListContext.tsx
+++ b/packages/core/src/CheckboxList/CheckboxListContext.tsx
@@ -4,12 +4,14 @@
/**
* @file CheckboxListContext.tsx
- * @input Uses the private layer-scoped context factory
+ * @input Uses the private layer-scoped context factory and the RequiredGroup
+ * type
* @output Exports CheckboxListContext for parent-child communication
* @position Internal context; consumed by CheckboxList.tsx and CheckboxListItem.tsx
*/
import {createLayerScopedContext} from '../Layer/layerScopedContext';
+import type {RequiredGroup} from './requiredGroup';
export interface CheckboxListContextValue {
value?: string[];
@@ -49,6 +51,12 @@ export interface CheckboxListContextValue {
* when idle.
*/
loadingValues?: ReadonlyArray<string>;
+ /**
+ * Present when the list is `isRequired`. Each item registers its checkbox,
+ * so that while no box is checked the first enabled box carries native
+ * `required`.
+ */
+ requiredGroup?: RequiredGroup;
}
export const CheckboxListContext =
diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsx
index caf171e1a0..836dd2c4dd 100644
--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx
+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx
@@ -17,7 +17,7 @@
* - /packages/cli/assets/templates/blocks/components/CheckboxList/ (showcase blocks)
*/
-import {use, useId, useRef, type ReactNode} from 'react';
+import {use, useCallback, useId, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
@@ -30,6 +30,7 @@ import {ListContext} from '../List/ListContext';
import {CheckboxListContext} from './CheckboxListContext';
import {ItemDescriptionContext} from '../Item/ItemDescriptionContext';
import {joinAriaIDs} from '../utils/inputAria';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {ItemAlign} from '../Item';
import {
registerEnglishFallback,
@@ -284,6 +285,26 @@ export function CheckboxListItem({
const checkboxRef = useRef<HTMLInputElement | null>(null);
const hasRowInteraction = isInteractive || onClickProp != null;
+ // A required group decides which box carries native `required` from the
+ // state of every box. A change to this box's state registers it again.
+ const requiredGroup = ctx?.requiredGroup;
+ const isBoxChecked = resolvedChecked === true;
+ const isBoxEnabled = !effectiveDisabled && !effectiveReadOnly;
+ const registerWithRequiredGroup = useCallback(
+ (input: HTMLInputElement | null) =>
+ input != null && requiredGroup != null
+ ? requiredGroup.register(input, {
+ isChecked: isBoxChecked,
+ isEnabled: isBoxEnabled,
+ })
+ : undefined,
+ [requiredGroup, isBoxChecked, isBoxEnabled],
+ );
+ const checkboxInputRef = useMergedRefs(
+ checkboxRef,
+ registerWithRequiredGroup,
+ );
+
// A read-only checkbox carries aria-readonly, which the row's clickable
// container treats as a non-interactive target, so a click on it would be
// delegated straight back to the checkbox without end. Stop that click at
@@ -349,7 +370,7 @@ export function CheckboxListItem({
style={style}
startContent={
<DescribedCheckboxInput
- ref={checkboxRef}
+ ref={checkboxInputRef}
label={checkboxLabel}
aria-labelledby={namesFromVisibleLabel ? labelID : undefined}
isLabelHidden
diff --git a/packages/core/src/CheckboxList/requiredGroup.ts b/packages/core/src/CheckboxList/requiredGroup.ts
new file mode 100644
index 0000000000..b0846fa038
--- /dev/null
+++ b/packages/core/src/CheckboxList/requiredGroup.ts
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file requiredGroup.ts
+ * @input The checkbox inputs of a required CheckboxList and each box's state;
+ * Core's shared mutation observer
+ * @output Exports createRequiredGroup, RequiredGroup, and RequiredGroupBox
+ * @position Internal to CheckboxList; CheckboxList creates one for an
+ * `isRequired` group and CheckboxListItem registers its checkbox with it
+ *
+ * The browser has no required state for a group of checkboxes. While no box
+ * is checked, the first enabled box carries native `required`. The browser
+ * then blocks submit and moves focus to that box with its own message. Once
+ * any box is checked, no box carries `required`.
+ */
+
+import {observeMutations} from '../utils/sharedMutationObserver';
+
+/** The state of one box that decides which box carries `required`. */
+export interface RequiredGroupBox {
+ isChecked: boolean;
+ /** False for a disabled or read-only box, which the user cannot check. */
+ isEnabled: boolean;
+}
+
+export interface RequiredGroup {
+ /**
+ * Adds a checkbox with its state and updates `required` on every box.
+ * Returns a function that removes the checkbox, clears its `required`, and
+ * updates the rest. An item registers again when its state changes.
+ */
+ register: (input: HTMLInputElement, box: RequiredGroupBox) => () => void;
+ /**
+ * Updates `required` when the group's options move, for example after a
+ * keyed reorder, which registers no box again. Returns a function that
+ * stops it.
+ */
+ observe: (container: HTMLElement) => () => void;
+}
+
+const MOVE_OPTIONS: MutationObserverInit = {childList: true, subtree: true};
+
+function byDocumentOrder(a: HTMLInputElement, b: HTMLInputElement): number {
+ return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING
+ ? -1
+ : 1;
+}
+
+export function createRequiredGroup(): RequiredGroup {
+ const boxes = new Map<HTMLInputElement, RequiredGroupBox>();
+
+ function update() {
+ const ordered = [...boxes.keys()].sort(byDocumentOrder);
+ const isEmpty = ![...boxes.values()].some(box => box.isChecked);
+ const target = isEmpty
+ ? ordered.find(input => boxes.get(input)?.isEnabled === true)
+ : undefined;
+ for (const input of ordered) {
+ input.required = input === target;
+ }
+ }
+
+ return {
+ register(input, box) {
+ boxes.set(input, box);
+ update();
+ return () => {
+ boxes.delete(input);
+ input.required = false;
+ update();
+ };
+ },
+ observe(container) {
+ return observeMutations(container, MOVE_OPTIONS, update);
+ },
+ };
+}
diff --git a/packages/core/src/utils/sharedMutationObserver.ts b/packages/core/src/utils/sharedMutationObserver.ts
index a58ecb24de..c9b9526b84 100644
--- a/packages/core/src/utils/sharedMutationObserver.ts
+++ b/packages/core/src/utils/sharedMutationObserver.ts
@@ -8,7 +8,8 @@
* @output Exports observeMutations (one shared observer per set of options)
* and observeContent, its text-and-children form
* @position Internal utility; consumed by useTruncation, hitArea, AppShell's
- * main-overflow observer and ModalAnnounceProvider's presentation watch. The mutation counterpart of sharedResizeObserver:
+ * main-overflow observer, ModalAnnounceProvider's presentation watch and
+ * CheckboxList's required group. The mutation counterpart of sharedResizeObserver:
* one observer for every element observed with the same options, so a
* repeated cell, row or region does not create one observer per instance.
*/