Skip to content

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

TypeScript

fix(checkbox-list): make loading per-item with in-checkbox spinner (#2929)

Cindy Zhangec935500b398
diff --git a/.changeset/checkbox-list-item-loading-spinner.md b/.changeset/checkbox-list-item-loading-spinner.md
new file mode 100644
index 0000000000..ddd0024f4d
--- /dev/null
+++ b/.changeset/checkbox-list-item-loading-spinner.md
@@ -0,0 +1,9 @@
+---
+'@xds/core': patch
+---
+
+`XDSCheckboxList` loading is now per-item. The group-level `isLoading` prop on `XDSCheckboxList` (which dimmed every item) has been removed in favor of an `isLoading` prop on `XDSCheckboxListItem`. A loading item renders a spinner **inside its checkbox** (using `XDSSpinner`'s `inherit` shade so the ring matches the box's resolved foreground in both checked and unchecked states) and blocks interaction on that item only.
+
+In collection mode this is also driven automatically: when `XDSCheckboxList` has a `changeAction`, the item the user just toggled shows its spinner while that promise is pending — no value-array diffing required, since the toggled value is passed up directly.
+
+`XDSCheckboxInput`'s built-in loading spinner now uses the `inherit` shade as well, for consistent contrast across themes.
diff --git a/.changeset/checkbox-list-loading-visual.md b/.changeset/checkbox-list-loading-visual.md
deleted file mode 100644
index c552323de2..0000000000
--- a/.changeset/checkbox-list-loading-visual.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-'@xds/core': patch
----
-
-`XDSCheckboxList` now gives visual feedback while loading. When `isLoading` is set (or a `changeAction` promise is pending), items are dimmed (reduced opacity) in addition to the existing `aria-busy` and blocked interaction. Previously the loading state was only conveyed to assistive tech, with no visible change. JSDoc and component docs were corrected to match the implemented behavior.
diff --git a/apps/storybook/stories/CheckboxList.stories.tsx b/apps/storybook/stories/CheckboxList.stories.tsx
index e50102a498..5675330446 100644
--- a/apps/storybook/stories/CheckboxList.stories.tsx
+++ b/apps/storybook/stories/CheckboxList.stories.tsx
@@ -220,20 +220,46 @@ export const Disabled: Story = {
};
export const Loading: Story = {
- render: args => {
+ render: () => {
const [value, setValue] = useState<string[]>(['email']);
- const {value: _value, onChange: _onChange, ...restArgs} = args;
return (
- <XDSCheckboxList {...restArgs} value={value} onChange={setValue}>
+ <XDSCheckboxList
+ label="Notification preferences"
+ value={value}
+ onChange={setValue}>
<XDSCheckboxListItem label="Email" value="email" />
- <XDSCheckboxListItem label="SMS" value="sms" />
+ <XDSCheckboxListItem label="SMS" value="sms" isLoading />
<XDSCheckboxListItem label="Push notification" value="push" />
</XDSCheckboxList>
);
},
- args: {
- label: 'Notification preferences',
- isLoading: true,
+};
+
+export const ChangeAction: Story = {
+ render: () => {
+ const [value, setValue] = useState<string[]>(['email']);
+ // Simulates persisting the new selection to a server. While the promise
+ // is pending, the toggled item shows a spinner inside its checkbox and
+ // blocks re-toggling; the other items stay interactive.
+ const persist = (next: string[]) =>
+ new Promise<void>(resolve => {
+ setTimeout(() => {
+ setValue(next);
+ resolve();
+ }, 1500);
+ });
+ return (
+ <XDSCheckboxList
+ label="Notification preferences"
+ description="Toggle an option — it spins while saving"
+ value={value}
+ changeAction={persist}
+ hasDividers>
+ <XDSCheckboxListItem label="Email" value="email" />
+ <XDSCheckboxListItem label="SMS" value="sms" />
+ <XDSCheckboxListItem label="Push notification" value="push" />
+ </XDSCheckboxList>
+ );
},
};
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
index 3e33b1d983..df83739794 100644
--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -102,6 +102,9 @@ const styles = stylex.create({
},
// State-dependent colors with ancestor hover behavior
checkboxUnchecked: {
+ // Foreground for the inherit-shade loading spinner (reads currentColor):
+ // brand accent on the light surface fill.
+ color: colorVars['--color-accent'],
borderColor: {
default: colorVars['--color-border-emphasized'],
[stylex.when.ancestor(':hover', checkboxScope)]: {
@@ -116,6 +119,9 @@ const styles = stylex.create({
},
},
checkboxChecked: {
+ // Foreground for the inherit-shade loading spinner (reads currentColor):
+ // on-accent color against the accent fill.
+ color: colorVars['--color-on-accent'],
borderColor: {
default: colorVars['--color-accent'],
[stylex.when.ancestor(':hover', checkboxScope)]: {
@@ -454,10 +460,7 @@ export function XDSCheckboxInput({
),
)}>
{isBusy ? (
- <XDSSpinner
- size="sm"
- shade={isCheckedOrIndeterminate ? 'onMedia' : 'default'}
- />
+ <XDSSpinner size="sm" shade="inherit" />
) : (
<>
<svg
diff --git a/packages/core/src/CheckboxList/CheckboxList.doc.mjs b/packages/core/src/CheckboxList/CheckboxList.doc.mjs
index b869129ce1..e814c5a139 100644
--- a/packages/core/src/CheckboxList/CheckboxList.doc.mjs
+++ b/packages/core/src/CheckboxList/CheckboxList.doc.mjs
@@ -45,14 +45,8 @@ export const docs = {
{
name: 'changeAction',
type: '(values: string[]) => void | Promise<void>',
- description: 'Async action on change with optimistic updates.',
- },
- {
- name: 'isLoading',
- type: 'boolean',
description:
- 'External loading state. Dims items (reduced opacity), marks them aria-busy, and blocks interaction.',
- default: 'false',
+ 'Async action on change with optimistic updates. While the promise is pending, the toggled item shows a spinner inside its checkbox and is marked aria-busy.',
},
{
name: 'isLabelHidden',
diff --git a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs
index e55fbc1f3f..a21c43921e 100644
--- a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs
+++ b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs
@@ -51,6 +51,13 @@ export const docs = {
description: 'Whether this individual item is disabled.',
default: 'false',
},
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description:
+ 'Whether this item is loading. Shows a spinner inside the checkbox and blocks interaction on this item. In collection mode, the toggled item also shows this automatically while the parent changeAction is pending.',
+ default: 'false',
+ },
{
name: 'isChecked',
type: "boolean | 'indeterminate'",
@@ -97,6 +104,13 @@ export const docsZh = {
description: '是否禁用此单个选项。',
default: 'false',
},
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description:
+ '此选项是否处于加载状态。在复选框内显示加载旋转器并阻止该选项的交互。在集合模式下,当父级 changeAction 处于待定状态时,被切换的选项会自动显示此状态。',
+ default: 'false',
+ },
{
name: 'isChecked',
type: "boolean | 'indeterminate'",
@@ -121,6 +135,8 @@ export const docsDense = {
description: 'Secondary text below label.',
endContent: 'Content rendered after label area.',
isDisabled: 'Whether this individual item disabled.',
+ isLoading:
+ 'Item loading: spinner inside checkbox + blocks interaction. Auto-set on toggled item while parent changeAction pending.',
isChecked: 'Direct checked state (standalone mode only).',
onCheck: 'Direct check handler (standalone mode only).',
},
diff --git a/packages/core/src/CheckboxList/XDSCheckboxList.test.tsx b/packages/core/src/CheckboxList/XDSCheckboxList.test.tsx
index aabba8c2bd..16be519d62 100644
--- a/packages/core/src/CheckboxList/XDSCheckboxList.test.tsx
+++ b/packages/core/src/CheckboxList/XDSCheckboxList.test.tsx
@@ -10,7 +10,7 @@
*/
import {describe, it, expect, vi} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {render, screen, fireEvent, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {XDSCheckboxList} from './XDSCheckboxList';
import {XDSCheckboxListItem} from './XDSCheckboxListItem';
@@ -406,65 +406,84 @@ describe('XDSCheckboxListItem ARIA props', () => {
expect(item).toHaveAttribute('aria-checked', 'mixed');
});
- it('sets aria-busy during async actions', () => {
- // Render with a pending async action by providing changeAction
- // that returns a promise that never resolves
+ it('does not mark items aria-busy when idle', () => {
render(
<XDSCheckboxList label="Prefs" value={['a']} onChange={() => {}}>
<XDSCheckboxListItem label="Option A" value="a" />
</XDSCheckboxList>,
);
- // By default isBusy is false, so aria-busy should not be present
const item = screen.getByRole('listitem');
expect(item).not.toHaveAttribute('aria-busy');
});
- it('marks items aria-busy when isLoading is set', () => {
+ it('marks the item aria-busy when item-level isLoading is set', () => {
render(
- <XDSCheckboxList
- label="Prefs"
- value={['a']}
- onChange={() => {}}
- isLoading>
- <XDSCheckboxListItem label="Option A" value="a" />
+ <XDSCheckboxList label="Prefs" value={['a']} onChange={() => {}}>
+ <XDSCheckboxListItem label="Option A" value="a" isLoading />
+ <XDSCheckboxListItem label="Option B" value="b" />
</XDSCheckboxList>,
);
- const item = screen.getByRole('listitem');
- expect(item).toHaveAttribute('aria-busy', 'true');
+ const [itemA, itemB] = screen.getAllByRole('listitem');
+ expect(itemA).toHaveAttribute('aria-busy', 'true');
+ // Loading is per-item — sibling items are unaffected.
+ expect(itemB).not.toHaveAttribute('aria-busy');
});
- it('dims items visually when isLoading is set', () => {
- const {rerender} = render(
+ it('renders a spinner inside the checkbox when item isLoading is set', () => {
+ render(
<XDSCheckboxList label="Prefs" value={['a']} onChange={() => {}}>
- <XDSCheckboxListItem label="Option A" value="a" />
+ <XDSCheckboxListItem label="Option A" value="a" isLoading />
</XDSCheckboxList>,
);
- const idleClass = screen.getByRole('listitem').getAttribute('class');
+ // The spinner is decorative — it lives inside the checkbox's
+ // aria-hidden visual box, so query with hidden:true. The accessible
+ // loading signal is `aria-busy` on the item (asserted above).
+ expect(screen.getByRole('status', {hidden: true})).toBeInTheDocument();
+ });
- rerender(
- <XDSCheckboxList
- label="Prefs"
- value={['a']}
- onChange={() => {}}
- isLoading>
- <XDSCheckboxListItem label="Option A" value="a" />
+ it('does not toggle when item-level isLoading is set', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSCheckboxList label="Prefs" value={[]} onChange={onChange}>
+ <XDSCheckboxListItem label="Option A" value="a" isLoading />
</XDSCheckboxList>,
);
- const busyClass = screen.getByRole('listitem').getAttribute('class');
-
- // Loading applies an additional style class for the dimmed appearance.
- expect(busyClass).not.toBe(idleClass);
+ fireEvent.click(screen.getByRole('checkbox'));
+ expect(onChange).not.toHaveBeenCalled();
});
- it('does not toggle when isLoading is set', () => {
- const onChange = vi.fn();
+ it('shows a spinner only on the toggled item while changeAction is pending', async () => {
+ // changeAction returns a promise that never resolves, so the pending
+ // (loading) state persists for assertions.
+ const changeAction = vi.fn(async () => {
+ await new Promise<void>(() => {});
+ });
render(
- <XDSCheckboxList label="Prefs" value={[]} onChange={onChange} isLoading>
+ <XDSCheckboxList
+ label="Prefs"
+ value={[]}
+ onChange={() => {}}
+ changeAction={changeAction}>
<XDSCheckboxListItem label="Option A" value="a" />
+ <XDSCheckboxListItem label="Option B" value="b" />
</XDSCheckboxList>,
);
- fireEvent.click(screen.getByRole('checkbox'));
- expect(onChange).not.toHaveBeenCalled();
+
+ const [itemA, itemB] = screen.getAllByRole('listitem');
+ // Toggle Option A.
+ fireEvent.click(within(itemA).getByRole('checkbox'));
+
+ // The toggled item becomes busy and shows a spinner; the sibling stays idle.
+ // The spinner is decorative (inside the aria-hidden box), so query hidden.
+ expect(
+ await within(itemA).findByRole('status', {hidden: true}),
+ ).toBeInTheDocument();
+ expect(itemA).toHaveAttribute('aria-busy', 'true');
+ expect(itemB).not.toHaveAttribute('aria-busy');
+ expect(
+ within(itemB).queryByRole('status', {hidden: true}),
+ ).not.toBeInTheDocument();
+ expect(changeAction).toHaveBeenCalledWith(['a']);
});
it('forwards arbitrary aria attributes to the list item DOM element', () => {
diff --git a/packages/core/src/CheckboxList/XDSCheckboxList.tsx b/packages/core/src/CheckboxList/XDSCheckboxList.tsx
index 3f31c3de61..1315217c8d 100644
--- a/packages/core/src/CheckboxList/XDSCheckboxList.tsx
+++ b/packages/core/src/CheckboxList/XDSCheckboxList.tsx
@@ -72,17 +72,11 @@ export interface XDSCheckboxListProps extends Omit<
onChange?: (values: string[]) => void;
/**
* Async action on change. Fires after onChange.
- * While the returned promise is pending, items are dimmed (reduced
- * opacity) and marked `aria-busy`, and interaction is blocked.
+ * While the returned promise is pending, the toggled item shows a spinner
+ * inside its checkbox and is marked `aria-busy`, and re-toggling it is
+ * blocked. Other items remain interactive.
*/
changeAction?: (values: string[]) => void | Promise<void>;
- /**
- * Whether the checkbox group is in an external loading state.
- * While loading, items are dimmed (reduced opacity) and marked
- * `aria-busy`, and interaction is blocked.
- * @default false
- */
- isLoading?: boolean;
/**
* Spacing density for list items.
* @default 'balanced'
@@ -137,7 +131,6 @@ export function XDSCheckboxList({
value,
onChange,
changeAction,
- isLoading = false,
density = 'balanced',
hasDividers = false,
isDisabled = false,
@@ -157,19 +150,30 @@ export function XDSCheckboxList({
const isCollectionMode = value !== undefined;
const effectiveValue = value ?? EMPTY_ARRAY;
const [optimisticValue, setOptimisticValue] = useOptimistic(effectiveValue);
- const isBusy = isLoading || optimisticValue !== effectiveValue;
+ // Tracks which item has a pending `changeAction`. Auto-reverts to null when
+ // the transition settles, so the spinner clears without manual cleanup.
+ const [loadingValue, setLoadingValue] = useOptimistic<string | null>(null);
const handleChange = useCallback(
- (newValues: string[]) => {
+ (newValues: string[], toggledValue?: string) => {
onChange?.(newValues);
if (changeAction) {
startTransition(async () => {
setOptimisticValue(newValues);
+ if (toggledValue !== undefined) {
+ setLoadingValue(toggledValue);
+ }
await changeAction(newValues);
});
}
},
- [onChange, changeAction, startTransition, setOptimisticValue],
+ [
+ onChange,
+ changeAction,
+ startTransition,
+ setOptimisticValue,
+ setLoadingValue,
+ ],
);
const contextValue = useMemo<XDSCheckboxListContextValue>(
@@ -178,7 +182,7 @@ export function XDSCheckboxList({
onChange: isCollectionMode ? handleChange : undefined,
isDisabled,
isReadOnly,
- isBusy,
+ loadingValue,
}),
[
isCollectionMode,
@@ -186,7 +190,7 @@ export function XDSCheckboxList({
handleChange,
isDisabled,
isReadOnly,
- isBusy,
+ loadingValue,
],
);
diff --git a/packages/core/src/CheckboxList/XDSCheckboxListContext.tsx b/packages/core/src/CheckboxList/XDSCheckboxListContext.tsx
index e522b254bd..207c6a418a 100644
--- a/packages/core/src/CheckboxList/XDSCheckboxListContext.tsx
+++ b/packages/core/src/CheckboxList/XDSCheckboxListContext.tsx
@@ -13,10 +13,20 @@ import {createContext} from 'react';
export interface XDSCheckboxListContextValue {
value?: string[];
- onChange?: (values: string[]) => void;
+ /**
+ * Collection-mode change handler. `toggledValue` is the value of the item
+ * the user just toggled, so the list can show a loading spinner on that
+ * specific item while a `changeAction` promise is pending — no diffing
+ * of the value array required.
+ */
+ onChange?: (values: string[], toggledValue?: string) => void;
isDisabled: boolean;
isReadOnly: boolean;
- isBusy: boolean;
+ /**
+ * The value of the item with a pending `changeAction`, or null when idle.
+ * The matching item renders an in-checkbox spinner and blocks re-toggling.
+ */
+ loadingValue?: string | null;
}
export const XDSCheckboxListContext =
diff --git a/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx b/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
index 20f0227c61..336a93652b 100644
--- a/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
+++ b/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
@@ -34,11 +34,6 @@ const styles = stylex.create({
selected: {
backgroundColor: colorVars['--color-accent-muted'],
},
- // Loading/pending state: dim like disabled content (opacity 0.5).
- busy: {
- opacity: 0.5,
- cursor: 'progress',
- },
});
// =============================================================================
@@ -72,6 +67,16 @@ export interface XDSCheckboxListItemProps extends XDSBaseProps<HTMLLIElement> {
* @default false
*/
isDisabled?: boolean;
+ /**
+ * Whether this item is in a loading state. Renders a spinner inside the
+ * checkbox and blocks interaction on this item only.
+ *
+ * In collection mode, this is also driven automatically: when the parent
+ * `XDSCheckboxList` has a `changeAction`, the toggled item shows its
+ * spinner while that promise is pending.
+ * @default false
+ */
+ isLoading?: boolean;
/**
* Direct checked state (standalone mode only).
* Ignored when inside XDSCheckboxList.
@@ -116,6 +121,7 @@ export function XDSCheckboxListItem({
description,
endContent,
isDisabled: isItemDisabled = false,
+ isLoading: isItemLoading = false,
isChecked,
onCheck,
ref,
@@ -140,7 +146,13 @@ export function XDSCheckboxListItem({
// Disabled: parent-level OR item-level
const effectiveDisabled = (ctx?.isDisabled ?? false) || isItemDisabled;
const effectiveReadOnly = ctx?.isReadOnly ?? false;
- const isBusy = ctx?.isBusy ?? false;
+ // Loading is per-item: explicit item prop OR (collection mode) the item
+ // whose `changeAction` is currently pending in the parent.
+ const isBusy =
+ isItemLoading ||
+ (ctx?.loadingValue != null && value !== undefined
+ ? ctx.loadingValue === value
+ : false);
// Resolve checked state:
// 1. Collection mode (inside XDSCheckboxList with value[])
@@ -162,12 +174,16 @@ export function XDSCheckboxListItem({
}
if (ctx && ctx.value !== undefined && value !== undefined) {
- // Collection mode
+ // Collection mode — pass the toggled value up so the list can show a
+ // spinner on this item while a changeAction is pending.
const currentlyChecked = ctx.value.includes(value);
if (currentlyChecked) {
- ctx.onChange?.(ctx.value.filter(v => v !== value));
+ ctx.onChange?.(
+ ctx.value.filter(v => v !== value),
+ value,
+ );
} else {
- ctx.onChange?.([...ctx.value, value]);
+ ctx.onChange?.([...ctx.value, value], value);
}
} else {
// Standalone mode
@@ -195,8 +211,6 @@ export function XDSCheckboxListItem({
!effectiveDisabled &&
!effectiveReadOnly &&
styles.selected,
- // Dim while busy; disabled items already dim themselves.
- isBusy && !effectiveDisabled && styles.busy,
xstyle,
] as StyleXStyles
}
@@ -210,6 +224,7 @@ export function XDSCheckboxListItem({
onChange={() => handleToggle()}
isDisabled={effectiveDisabled}
isReadOnly={effectiveReadOnly}
+ isLoading={isBusy}
size={checkboxSize}
/>
}