Skip to content

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

TypeScript

XDSCheckboxInput (#47)

Andrey Goderff617e9fb0be
diff --git a/apps/storybook/stories/CheckboxInput.stories.tsx b/apps/storybook/stories/CheckboxInput.stories.tsx
new file mode 100644
index 0000000000..8f74ce87ba
--- /dev/null
+++ b/apps/storybook/stories/CheckboxInput.stories.tsx
@@ -0,0 +1,156 @@
+import { useState } from 'react';
+import type { Meta, StoryObj } from '@storybook/react';
+import { XDSCheckboxInput } from '@xds/core/CheckboxInput';
+
+const meta: Meta<typeof XDSCheckboxInput> = {
+ title: 'Core/XDSCheckboxInput',
+ component: XDSCheckboxInput,
+ tags: ['autodocs'],
+ argTypes: {
+ label: {
+ control: 'text',
+ description: 'Label text (required)',
+ },
+ isLabelHidden: {
+ control: 'boolean',
+ description: 'Visually hide the label (still accessible to screen readers)',
+ },
+ description: {
+ control: 'text',
+ description: 'Description text displayed below the label',
+ },
+ value: {
+ control: 'select',
+ options: [true, false, 'indeterminate'],
+ description: 'Whether the checkbox is checked, unchecked, or indeterminate',
+ },
+ isDisabled: {
+ control: 'boolean',
+ description: 'Whether the checkbox is disabled',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCheckboxInput>;
+
+export const Default: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? false);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Accept terms and conditions',
+ },
+};
+
+export const Checked: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? true);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'I agree to the terms',
+ value: true,
+ },
+};
+
+export const WithDescription: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? false);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Subscribe to newsletter',
+ description: 'Receive weekly updates about new features and announcements.',
+ },
+};
+
+export const WithHiddenLabel: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? false);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Select row',
+ isLabelHidden: true,
+ },
+};
+
+export const Indeterminate: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? 'indeterminate');
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Select all items',
+ description: 'Some items are selected',
+ value: 'indeterminate',
+ },
+};
+
+export const Disabled: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? false);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Premium feature',
+ description: 'Upgrade to enable this option',
+ isDisabled: true,
+ },
+};
+
+export const DisabledChecked: Story = {
+ render: (args) => {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(args.value ?? true);
+ return <XDSCheckboxInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Feature enabled',
+ value: true,
+ isDisabled: true,
+ },
+};
+
+export const AllVariations: Story = {
+ render: () => {
+ const [value1, setValue1] = useState<boolean | 'indeterminate'>(false);
+ const [value2, setValue2] = useState<boolean | 'indeterminate'>(true);
+ const [value3, setValue3] = useState<boolean | 'indeterminate'>('indeterminate');
+ const [value4, setValue4] = useState<boolean | 'indeterminate'>(false);
+ const [value5, setValue5] = useState<boolean | 'indeterminate'>(true);
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px', maxWidth: '400px' }}>
+ <XDSCheckboxInput
+ label="Unchecked"
+ value={value1}
+ onChange={setValue1}
+ />
+ <XDSCheckboxInput
+ label="Checked"
+ value={value2}
+ onChange={setValue2}
+ />
+ <XDSCheckboxInput
+ label="Indeterminate"
+ description="Some items are selected"
+ value={value3}
+ onChange={setValue3}
+ />
+ <XDSCheckboxInput
+ label="Disabled unchecked"
+ value={value4}
+ onChange={setValue4}
+ isDisabled
+ />
+ <XDSCheckboxInput
+ label="Disabled checked"
+ value={value5}
+ onChange={setValue5}
+ isDisabled
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index a0b4577ace..30d1dd1ce8 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -27,6 +27,16 @@
"import": "./dist/Button/index.mjs",
"require": "./dist/Button/index.js"
},
+ "./CheckboxInput": {
+ "types": "./dist/CheckboxInput/index.d.ts",
+ "import": "./dist/CheckboxInput/index.mjs",
+ "require": "./dist/CheckboxInput/index.js"
+ },
+ "./Field": {
+ "types": "./dist/Field/index.d.ts",
+ "import": "./dist/Field/index.mjs",
+ "require": "./dist/Field/index.js"
+ },
"./Layout": {
"types": "./dist/Layout/index.d.ts",
"import": "./dist/Layout/index.mjs",
diff --git a/packages/core/src/CheckboxInput/README.md b/packages/core/src/CheckboxInput/README.md
new file mode 100644
index 0000000000..5a019964c6
--- /dev/null
+++ b/packages/core/src/CheckboxInput/README.md
@@ -0,0 +1,84 @@
+# /packages/core/src/CheckboxInput
+
+A checkbox input component for toggling boolean values.
+
+<!-- SYNC: When files in this directory change, update this document. -->
+
+## Features
+
+- **Accessible**: Always includes a label (can be visually hidden)
+- **Indeterminate state**: Supports indeterminate state for "select all" patterns
+- **Descriptions**: Optional description text below the label
+- **Custom styling**: Uses StyleX with XDS design tokens
+- **Disabled state**: Full support for disabled state styling
+
+## Usage
+
+```tsx
+import { XDSCheckboxInput } from '@xds/core/CheckboxInput';
+
+// Basic usage
+<XDSCheckboxInput
+ label="Accept terms and conditions"
+ value={accepted}
+ onChange={setAccepted}
+/>
+
+// With description
+<XDSCheckboxInput
+ label="Subscribe to newsletter"
+ description="Receive weekly updates about new features"
+ value={subscribed}
+ onChange={setSubscribed}
+/>
+
+// Indeterminate state (e.g., for "select all" when some items are selected)
+<XDSCheckboxInput
+ label="Select all items"
+ value="indeterminate"
+ onChange={setSelectAll}
+/>
+
+// Hidden label (still accessible)
+<XDSCheckboxInput
+ label="Select row"
+ isLabelHidden
+ value={selected}
+ onChange={setSelected}
+/>
+
+// Disabled
+<XDSCheckboxInput
+ label="Premium feature"
+ description="Upgrade to enable this option"
+ value={false}
+ onChange={() => {}}
+ isDisabled
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+|------|------|---------|-------------|
+| `label` | `string` | — | Label text for the checkbox (always rendered for accessibility) |
+| `isLabelHidden` | `boolean` | `false` | Whether to visually hide the label |
+| `description` | `string` | — | Description text displayed below the label |
+| `value` | `boolean \| 'indeterminate'` | — | Whether the checkbox is checked, unchecked, or indeterminate |
+| `onChange` | `(checked: boolean, e: ChangeEvent) => void` | — | Callback fired when the checkbox state changes |
+| `isDisabled` | `boolean` | `false` | Whether the checkbox is disabled |
+
+## Files
+
+| File | Role | Purpose |
+|------|------|---------|
+| `index.ts` | Entry | Exports component and types |
+| `XDSCheckboxInput.tsx` | Core | Component implementation |
+| `XDSCheckboxInput.test.tsx` | Test | Unit tests |
+
+## Implementation Notes
+
+- Uses a hidden native `<input type="checkbox">` for accessibility with a custom visual checkbox overlay
+- The visual checkbox responds to hover, focus, and checked states via sibling selectors in CSS
+- Label is clickable and properly associated with the input via `htmlFor`/`id`
+- Focus outline uses the standard XDS focus outline token
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.test.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.test.tsx
new file mode 100644
index 0000000000..c207d8a571
--- /dev/null
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.test.tsx
@@ -0,0 +1,192 @@
+/**
+ * @file XDSCheckboxInput.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSCheckboxInput component
+ * @output Unit tests for XDSCheckboxInput component behavior
+ * @position Testing; validates XDSCheckboxInput.tsx implementation
+ *
+ * SYNC: When XDSCheckboxInput.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSCheckboxInput} from './XDSCheckboxInput';
+
+describe('XDSCheckboxInput', () => {
+ it('renders with label', () => {
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByLabelText('Accept terms')).toBeInTheDocument();
+ });
+
+ it('renders as unchecked by default', () => {
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole('checkbox')).not.toBeChecked();
+ });
+
+ it('renders as checked when value prop is true', () => {
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={true}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ });
+
+ it('calls onChange with new checked state when clicked', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={handleChange}
+ />,
+ );
+
+ const checkbox = screen.getByRole('checkbox');
+ await user.click(checkbox);
+ expect(handleChange).toHaveBeenCalledTimes(1);
+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));
+ });
+
+ it('calls onChange with false when unchecking', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={true}
+ onChange={handleChange}
+ />,
+ );
+
+ const checkbox = screen.getByRole('checkbox');
+ await user.click(checkbox);
+ expect(handleChange).toHaveBeenCalledWith(false, expect.any(Object));
+ });
+
+ it('works when clicking on the label', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={handleChange}
+ />,
+ );
+
+ const label = screen.getByText('Accept terms');
+ await user.click(label);
+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));
+ });
+
+ it('renders description when provided', () => {
+ render(
+ <XDSCheckboxInput
+ label="Subscribe"
+ description="Receive weekly updates"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText('Receive weekly updates')).toBeInTheDocument();
+ });
+
+ it('associates description with checkbox via aria-describedby', () => {
+ render(
+ <XDSCheckboxInput
+ label="Subscribe"
+ description="Receive weekly updates"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const checkbox = screen.getByRole('checkbox');
+ const description = screen.getByText('Receive weekly updates');
+ expect(checkbox).toHaveAttribute('aria-describedby', description.id);
+ });
+
+ it('is disabled when isDisabled prop is true', () => {
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ });
+
+ it('does not call onChange when isDisabled', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={handleChange}
+ isDisabled
+ />,
+ );
+
+ const checkbox = screen.getByRole('checkbox');
+ await user.click(checkbox);
+ expect(handleChange).not.toHaveBeenCalled();
+ });
+
+ it('forwards ref correctly', () => {
+ const ref = vi.fn();
+ render(
+ <XDSCheckboxInput
+ ref={ref}
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+
+ it('visually hides label when isLabelHidden is true', () => {
+ render(
+ <XDSCheckboxInput
+ label="Select row"
+ isLabelHidden
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const label = screen.getByText('Select row');
+ expect(label).toBeInTheDocument();
+ // Label should still be accessible
+ expect(screen.getByLabelText('Select row')).toBeInTheDocument();
+ });
+
+ it('shows label visually by default', () => {
+ render(
+ <XDSCheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const label = screen.getByText('Accept terms');
+ expect(label).toBeVisible();
+ });
+});
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
new file mode 100644
index 0000000000..6df99ba4b1
--- /dev/null
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -0,0 +1,249 @@
+/**
+ * @file XDSCheckboxInput.tsx
+ * @input Uses React forwardRef, useId, ChangeEvent, XDSFieldLabel
+ * @output Exports XDSCheckboxInput component, XDSCheckboxInputProps
+ * @position Core implementation; consumed by index.ts, tested by XDSCheckboxInput.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/CheckboxInput/README.md (props table, features, implementation notes)
+ * - /packages/core/src/CheckboxInput/XDSCheckboxInput.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/CheckboxInput/index.ts (exports if types change)
+ * - /apps/storybook/stories/CheckboxInput.stories.tsx (storybook stories)
+ */
+
+import {forwardRef, useId, type ChangeEvent} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ transitionVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+import {XDSFieldLabel} from '../Field/XDSFieldLabel';
+
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: spacingVars['--spacing-2'],
+ },
+ checkboxWrapper: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ width: 24,
+ height: 24,
+ },
+ input: {
+ position: 'absolute',
+ width: 24,
+ height: 24,
+ margin: 0,
+ padding: 0,
+ opacity: 0,
+ cursor: 'pointer',
+ },
+ inputDisabled: {
+ cursor: 'not-allowed',
+ },
+ checkbox: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 22,
+ height: 22,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: colorVars['--color-divider-emphasized'],
+ borderRadius: radiusVars['--radius-content'],
+ backgroundColor: colorVars['--color-surface'],
+ transitionProperty: 'background-color, border-color',
+ transitionDuration: transitionVars['--transition-fast'],
+ },
+ checkboxHover: {
+ borderColor: colorVars['--color-divider-high-contrast'],
+ },
+ checkboxChecked: {
+ backgroundColor: colorVars['--color-accent'],
+ borderColor: colorVars['--color-accent'],
+ },
+ checkboxFocused: {
+ outline: `2px solid ${colorVars['--color-focus-outline']}`,
+ outlineOffset: 2,
+ },
+ checkboxDisabled: {
+ opacity: 0.5,
+ borderColor: colorVars['--color-divider'],
+ },
+ checkboxDisabledUnchecked: {
+ backgroundColor: colorVars['--color-deemphasized'],
+ },
+ checkmark: {
+ display: 'none',
+ width: 14,
+ height: 14,
+ fill: 'white',
+ },
+ checkmarkVisible: {
+ display: 'block',
+ },
+ indeterminateMark: {
+ display: 'none',
+ width: 12,
+ height: 2,
+ backgroundColor: 'white',
+ borderRadius: 1,
+ },
+ indeterminateMarkVisible: {
+ display: 'block',
+ },
+ labelWrapper: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ marginTop: 3,
+ },
+ description: {
+ fontFamily: typographyVars['--font-body'],
+ fontSize: '0.75rem',
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+export interface XDSCheckboxInputProps {
+ /**
+ * Label text for the checkbox (always rendered for accessibility).
+ */
+ label: string;
+ /**
+ * Whether to visually hide the label (still accessible to screen readers).
+ * @default false
+ */
+ isLabelHidden?: boolean;
+ /**
+ * Description text displayed below the label.
+ */
+ description?: string;
+ /**
+ * Callback fired when the checkbox state changes.
+ */
+ onChange: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;
+ /**
+ * Whether the checkbox is checked, unchecked, or indeterminate.
+ */
+ value: boolean | 'indeterminate';
+ /**
+ * Whether the checkbox is disabled.
+ * @default false
+ */
+ isDisabled?: boolean;
+}
+
+/**
+ * A checkbox input component for toggling boolean values.
+ *
+ * @example
+ * ```tsx
+ * <XDSCheckboxInput
+ * label="Accept terms"
+ * value={accepted}
+ * onChange={setAccepted}
+ * />
+ * <XDSCheckboxInput
+ * label="Subscribe"
+ * description="Receive weekly updates"
+ * value={subscribed}
+ * onChange={setSubscribed}
+ * />
+ * ```
+ */
+export const XDSCheckboxInput = forwardRef<
+ HTMLInputElement,
+ XDSCheckboxInputProps
+>(
+ (
+ {
+ label,
+ isLabelHidden = false,
+ description,
+ onChange,
+ value,
+ isDisabled = false,
+ },
+ ref,
+ ) => {
+ const id = useId();
+ const descriptionID = useId();
+
+ const isIndeterminate = value === 'indeterminate';
+ const isChecked = value === true;
+
+ return (
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.checkboxWrapper)}>
+ <input
+ ref={ref}
+ id={id}
+ type="checkbox"
+ checked={isChecked}
+ disabled={isDisabled}
+ onChange={e => onChange(e.target.checked, e)}
+ aria-describedby={description ? descriptionID : undefined}
+ {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
+ />
+ <div
+ aria-hidden="true"
+ {...stylex.props(
+ styles.checkbox,
+ (isChecked || isIndeterminate) && styles.checkboxChecked,
+ isDisabled && styles.checkboxDisabled,
+ isDisabled &&
+ !isChecked &&
+ !isIndeterminate &&
+ styles.checkboxDisabledUnchecked,
+ )}>
+ <svg
+ viewBox="0 0 10 10"
+ {...stylex.props(
+ styles.checkmark,
+ isChecked && styles.checkmarkVisible,
+ )}>
+ <path
+ d="M8.5 2.5L4 7.5L1.5 5"
+ stroke="white"
+ strokeWidth="1.5"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ <div
+ {...stylex.props(
+ styles.indeterminateMark,
+ isIndeterminate && styles.indeterminateMarkVisible,
+ )}
+ />
+ </div>
+ </div>
+ <div {...stylex.props(styles.labelWrapper)}>
+ <XDSFieldLabel
+ label={label}
+ inputID={id}
+ isLabelHidden={isLabelHidden}
+ isDisabled={isDisabled}
+ />
+ {description && (
+ <span id={descriptionID} {...stylex.props(styles.description)}>
+ {description}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+ },
+);
+
+XDSCheckboxInput.displayName = 'XDSCheckboxInput';
diff --git a/packages/core/src/CheckboxInput/index.ts b/packages/core/src/CheckboxInput/index.ts
new file mode 100644
index 0000000000..42022edebb
--- /dev/null
+++ b/packages/core/src/CheckboxInput/index.ts
@@ -0,0 +1,11 @@
+/**
+ * @file index.ts
+ * @input Imports XDSCheckboxInput component and types from XDSCheckboxInput.tsx
+ * @output Exports XDSCheckboxInput, XDSCheckboxInputProps
+ * @position Component entry point; re-exported by /packages/core/src/index.ts
+ *
+ * SYNC: When modified, update this header and /packages/core/src/CheckboxInput/README.md
+ */
+
+export { XDSCheckboxInput } from './XDSCheckboxInput';
+export type { XDSCheckboxInputProps } from './XDSCheckboxInput';
diff --git a/packages/core/src/Field/XDSField.test.tsx b/packages/core/src/Field/XDSField.test.tsx
index bc7a0051de..7a479ffcd0 100644
--- a/packages/core/src/Field/XDSField.test.tsx
+++ b/packages/core/src/Field/XDSField.test.tsx
@@ -96,25 +96,27 @@ describe('XDSField', () => {
expect(description).not.toHaveAttribute('id');
});
- it('renders Optional text when isOptional is true', () => {
+ it('renders Optional text when isOptional is set', () => {
render(
<XDSField label="Name" inputID="name-input" isOptional>
<input id="name-input" />
</XDSField>,
);
- expect(screen.getByText('Optional')).toBeInTheDocument();
+ expect(screen.getByText('Name')).toBeInTheDocument();
+ expect(screen.getByText(/Optional/)).toBeInTheDocument();
});
- it('renders Required text when isRequired is true', () => {
+ it('renders Required text when isRequired is set', () => {
render(
<XDSField label="Name" inputID="name-input" isRequired>
<input id="name-input" />
</XDSField>,
);
- expect(screen.getByText('Required')).toBeInTheDocument();
+ expect(screen.getByText('Name')).toBeInTheDocument();
+ expect(screen.getByText(/Required/)).toBeInTheDocument();
});
- it('renders description and Optional text separately', () => {
+ it('renders description and Optional text when both are set', () => {
render(
<XDSField
label="Name"
@@ -126,10 +128,10 @@ describe('XDSField', () => {
</XDSField>,
);
expect(screen.getByText('Enter your name')).toBeInTheDocument();
- expect(screen.getByText('Optional')).toBeInTheDocument();
+ expect(screen.getByText(/Optional/)).toBeInTheDocument();
});
- it('renders description and Required text separately', () => {
+ it('renders description and Required text when both are set', () => {
render(
<XDSField
label="Name"
@@ -141,17 +143,16 @@ describe('XDSField', () => {
</XDSField>,
);
expect(screen.getByText('This field is mandatory')).toBeInTheDocument();
- expect(screen.getByText('Required')).toBeInTheDocument();
+ expect(screen.getByText(/Required/)).toBeInTheDocument();
});
- it('renders Optional text next to label with bullet separator', () => {
+ it('renders Optional text with bullet separator', () => {
render(
<XDSField label="Name" inputID="name-input" isOptional>
<input id="name-input" />
</XDSField>,
);
- expect(screen.getByText('Optional')).toBeInTheDocument();
expect(screen.getByText('Name')).toBeInTheDocument();
- expect(screen.getByText('∙', {exact: false})).toBeInTheDocument();
+ expect(screen.getByText(/∙.*Optional/)).toBeInTheDocument();
});
});
diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsx
index e826177566..e5d0d2aeaf 100644
--- a/packages/core/src/Field/XDSField.tsx
+++ b/packages/core/src/Field/XDSField.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSField.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React forwardRef, HTMLAttributes, ReactNode, XDSFieldLabel
* @output Exports XDSField component, XDSFieldProps
* @position Core implementation; consumed by index.ts, tested by XDSField.test.tsx
*
@@ -13,6 +13,7 @@
import {forwardRef, type HTMLAttributes, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
+import {XDSFieldLabel} from './XDSFieldLabel';
import {colorVars, spacingVars, typographyVars} from '../theme/tokens.stylex';
const styles = stylex.create({
@@ -130,23 +131,14 @@ export const XDSField = forwardRef<HTMLDivElement, XDSFieldProps>(
) => {
return (
<div ref={ref} {...stylex.props(styles.container)} {...props}>
- <div {...stylex.props(styles.labelRow)}>
- <label
- htmlFor={inputID}
- {...stylex.props(
- styles.label,
- isLabelHidden && styles.labelHidden,
- )}>
- {label}
- </label>
- {isOptional || isRequired ? (
- <span {...stylex.props(styles.optionalRequired)}>
- <span aria-hidden="true">{'\u2219 '}</span>
- {isOptional ? 'Optional' : 'Required'}
- </span>
- ) : null}
- </div>
- {description != null && (
+ <XDSFieldLabel
+ label={label}
+ inputID={inputID}
+ isLabelHidden={isLabelHidden}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ />
+ {description && (
<span id={descriptionID} {...stylex.props(styles.description)}>
{description}
</span>
diff --git a/packages/core/src/Field/XDSFieldLabel.tsx b/packages/core/src/Field/XDSFieldLabel.tsx
new file mode 100644
index 0000000000..b59225835c
--- /dev/null
+++ b/packages/core/src/Field/XDSFieldLabel.tsx
@@ -0,0 +1,128 @@
+/**
+ * @file XDSFieldLabel.tsx
+ * @input Uses React forwardRef
+ * @output Exports XDSFieldLabel component, XDSFieldLabelProps
+ * @position Core label implementation; used by XDSField, XDSCheckboxInput
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Field/README.md (props table, features, implementation notes)
+ * - /packages/core/src/Field/index.ts (exports if types change)
+ */
+
+import {forwardRef} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars, typographyVars} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ label: {
+ fontFamily: typographyVars['--font-body'],
+ fontSize: '0.875rem',
+ fontWeight: 500,
+ color: colorVars['--color-text-primary'],
+ },
+ labelClickable: {
+ cursor: 'pointer',
+ },
+ labelDisabled: {
+ color: colorVars['--color-text-disabled'],
+ cursor: 'not-allowed',
+ },
+ labelHidden: {
+ borderStyle: 'none',
+ clip: 'rect(0, 0, 0, 0)',
+ height: 1,
+ left: 0,
+ margin: -1,
+ overflow: 'hidden',
+ padding: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: 0,
+ userSelect: 'none',
+ whiteSpace: 'nowrap',
+ width: 1,
+ },
+ optionalRequired: {
+ fontWeight: 400,
+ fontSize: '0.75rem',
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+export interface XDSFieldLabelProps {
+ /**
+ * Label text (always rendered for accessibility).
+ */
+ label: string;
+ /**
+ * ID of the input element this label is for.
+ */
+ inputID: string;
+ /**
+ * Whether to visually hide the label (still accessible to screen readers).
+ * @default false
+ */
+ isLabelHidden?: boolean;
+ /**
+ * Whether the associated input is disabled.
+ * @default false
+ */
+ isDisabled?: boolean;
+ /**
+ * Whether the field is optional. Mutually exclusive with isRequired.
+ * @default false
+ */
+ isOptional?: boolean;
+ /**
+ * Whether the field is required. Mutually exclusive with isOptional.
+ * @default false
+ */
+ isRequired?: boolean;
+}
+
+/**
+ * A label component for form fields with support for hidden and disabled states.
+ *
+ * @example
+ * ```tsx
+ * <XDSFieldLabel label="Email" inputID={inputId} />
+ * <XDSFieldLabel label="Hidden label" inputID={inputId} isLabelHidden />
+ * ```
+ */
+export const XDSFieldLabel = forwardRef<HTMLLabelElement, XDSFieldLabelProps>(
+ (
+ {
+ label,
+ inputID,
+ isLabelHidden = false,
+ isDisabled = false,
+ isOptional = false,
+ isRequired = false,
+ },
+ ref,
+ ) => {
+ const statusText = isOptional ? 'Optional' : isRequired ? 'Required' : null;
+
+ return (
+ <label
+ ref={ref}
+ htmlFor={inputID}
+ {...stylex.props(
+ styles.label,
+ !isDisabled && styles.labelClickable,
+ isDisabled && styles.labelDisabled,
+ isLabelHidden && styles.labelHidden,
+ )}>
+ {label}
+ {statusText && (
+ <span {...stylex.props(styles.optionalRequired)}>
+ {' '}
+ ∙ {statusText}
+ </span>
+ )}
+ </label>
+ );
+ },
+);
+
+XDSFieldLabel.displayName = 'XDSFieldLabel';
diff --git a/packages/core/src/Field/index.ts b/packages/core/src/Field/index.ts
index dfe52470b2..facedc443d 100644
--- a/packages/core/src/Field/index.ts
+++ b/packages/core/src/Field/index.ts
@@ -1,11 +1,13 @@
/**
* @file index.ts
- * @input Imports XDSField component and types from XDSField.tsx
- * @output Exports XDSField, XDSFieldProps
+ * @input Imports XDSField component and types from XDSField.tsx, XDSFieldLabel from XDSFieldLabel.tsx
+ * @output Exports XDSField, XDSFieldProps, XDSFieldLabel, XDSFieldLabelProps
* @position Component entry point; re-exported by /packages/core/src/index.ts
*
* SYNC: When modified, update this header and /packages/core/src/Field/README.md
*/
-export {XDSField} from './XDSField';
-export type {XDSFieldProps} from './XDSField';
+export { XDSField } from './XDSField';
+export type { XDSFieldProps } from './XDSField';
+export { XDSFieldLabel } from './XDSFieldLabel';
+export type { XDSFieldLabelProps } from './XDSFieldLabel';
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index b314008241..a6b478b63d 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -57,7 +57,7 @@ const styles = stylex.create({
disabled: {
cursor: 'not-allowed',
opacity: 0.5,
- borderColor: color.dividerEmphasized,
+ borderColor: colorVars['--color-divider-emphasized'],
},
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 460fee6711..33d130c1ca 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -10,6 +10,7 @@
// Components
export * from './Avatar';
export * from './Button';
+export * from './CheckboxInput';
export * from './Field';
export * from './TextInput';